<commit_before>window.c.h = ((m, moment) => {
    //Date Helpers
    const setMomentifyLocale = () => {
        moment.locale('pt', {
            monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_')
        });
    },

          momentify = (date, format) => {
              format = format || 'DD/MM/YYYY';
              return date ? moment(date).locale('pt').format(format) : 'no date';
          },

          storeAction = (action) => {
              if (!sessionStorage.getItem(action)) {
                  return sessionStorage.setItem(action, action);
              }
          },

          callStoredAction = (action, func) => {
              if (sessionStorage.getItem(action)) {
                  func.call();
                  return sessionStorage.removeItem(action);
              }
          },

          momentFromString = (date, format) => {
              const european = moment(date, format || 'DD/MM/YYYY');
              return european.isValid() ? european : moment(date);
          },

          //Object manipulation helpers
          generateRemaingTime = (project) => {
              const remainingTextObj = m.prop({}),
                    remainingTime = project.remaining_time.total,
                    translatedTime = {
                        days: 'dias',
                        minutes: 'minutos',
                        hours: 'horas',
                        seconds: 'segundos'
                    },
                    unit = () => {
                        const projUnit = translatedTime[project.remaining_time.unit || 'seconds'];

                        return (remainingTime <= 1) ? projUnit.slice(0, -1) : projUnit;
                    };

              remainingTextObj({
                  unit: unit(),
                  total: remainingTime
              });

              return remainingTextObj;
          },

          //Number formatting helpers
          generateFormatNumber = (s, c) => {
              return (number, n, x) => {
                  if (number === null || number === undefined) {
                      return null;
                  }

                  const re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
                        num = number.toFixed(Math.max(0, ~~n));
                  return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
              };
          },
          formatNumber = generateFormatNumber('.', ','),

          toggleProp = (defaultState, alternateState) => {
              const p = m.prop(defaultState);
              p.toggle = () => {
                  p(((p() === alternateState) ? defaultState : alternateState));
              };

              return p;
          },

          idVM = m.postgrest.filtersVM({
              id: 'eq'
          }),

          getUser = () => {
              const body = document.getElementsByTagName('body'),
                    data = _.first(body).getAttribute('data-user');
              if (data) {
                  return JSON.parse(data);
              } else {
                  return false;
              }
          },

          hashMatch = (str) => {
              return window.location.hash === str;
          },

          locationActionMatch = (action) => {
              const act = window.location.pathname.split('/').slice(-1)[0];
              return action === act;
          },

          useAvatarOrDefault = (avatarPath) => {
              return avatarPath || '/assets/catarse_bootstrap/user.jpg';
          },

          //Templates
          loader = () => {
              return m('.u-text-center.u-margintop-30 u-marginbottom-30', [
                  m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
              ]);
          },

          fbParse = () => {
              const tryParse = () => {
                  try {
                      window.FB.XFBML.parse();
                  } catch (e) {
                      console.log(e);
                  }
              };

              return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
          },

          pluralize = (count, s, p) => {
              return (count > 1 ? count + p : count + s);
          },

          simpleFormat = (str = '') => {
              str = str.replace(/\r\n?/, '\n');
              if (str.length > 0) {
                  str = str.replace(/\n\n+/g, '

');
                  str = str.replace(/\n/g, '
');
                  str = '
' + str + '
';
              }
              return str;
          },

          rewardSouldOut = (reward) => {
              return (reward.maximum_contributions > 0 ?
                      (reward.paid_count + reward.waiting_payment_count >= reward.maximum_contributions) : false);
          },

          rewardRemaning = (reward) => {
              return reward.maximum_contributions - (reward.paid_count + reward.waiting_payment_count);
          },

          parseUrl = (href) => {
              const l = document.createElement('a');
              l.href = href;
              return l;
          },

          mixpanelTrack = () => {
              return (el, isInitialized) => {
                  if (!isInitialized) {
                      window.CatarseMixpanel.activate();
                  }
              };
          },

          UIHelper = () => {
              return (el, isInitialized) => {
                  if (!isInitialized && $) {
                      window.UIHelper.setupResponsiveIframes($(el));
                  }
              };
          },

          navigateToDevise = () => {
              window.location.href = '/pt/login';
              return false;
          };

    setMomentifyLocale();

    return {
        momentify: momentify,
        momentFromString: momentFromString,
        formatNumber: formatNumber,
        idVM: idVM,
        getUser: getUser,
        toggleProp: toggleProp,
        loader: loader,
        fbParse: fbParse,
        pluralize: pluralize,
        simpleFormat: simpleFormat,
        generateRemaingTime: generateRemaingTime,
        rewardSouldOut: rewardSouldOut,
        rewardRemaning: rewardRemaning,
        parseUrl: parseUrl,
        hashMatch: hashMatch,
        useAvatarOrDefault: useAvatarOrDefault,
        locationActionMatch: locationActionMatch,
        mixpanelTrack: mixpanelTrack,
        navigateToDevise: navigateToDevise,
        storeAction: storeAction,
        callStoredAction: callStoredAction,
        UIHelper: UIHelper
    };
}(window.m, window.moment));
<commit_msg>adds disqus helper<commit_after>window.c.h = ((m, moment) => {
    //Date Helpers
    const setMomentifyLocale = () => {
        moment.locale('pt', {
            monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_')
        });
    },

          momentify = (date, format) => {
              format = format || 'DD/MM/YYYY';
              return date ? moment(date).locale('pt').format(format) : 'no date';
          },

          storeAction = (action) => {
              if (!sessionStorage.getItem(action)) {
                  return sessionStorage.setItem(action, action);
              }
          },

          callStoredAction = (action, func) => {
              if (sessionStorage.getItem(action)) {
                  func.call();
                  return sessionStorage.removeItem(action);
              }
          },

          discuss = (page, identifier) => {
            const d = document, s = d.createElement('script');
            window.disqus_config = function() {
              this.page.url = page;
              this.page.identifier = identifier;
            };
            s.src = '//catarseflex.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
            return m('#disqus_thread');
          },

          momentFromString = (date, format) => {
              const european = moment(date, format || 'DD/MM/YYYY');
              return european.isValid() ? european : moment(date);
          },

          //Object manipulation helpers
          generateRemaingTime = (project) => {
              const remainingTextObj = m.prop({}),
                    remainingTime = project.remaining_time.total,
                    translatedTime = {
                        days: 'dias',
                        minutes: 'minutos',
                        hours: 'horas',
                        seconds: 'segundos'
                    },
                    unit = () => {
                        const projUnit = translatedTime[project.remaining_time.unit || 'seconds'];

                        return (remainingTime <= 1) ? projUnit.slice(0, -1) : projUnit;
                    };

              remainingTextObj({
                  unit: unit(),
                  total: remainingTime
              });

              return remainingTextObj;
          },

          //Number formatting helpers
          generateFormatNumber = (s, c) => {
              return (number, n, x) => {
                  if (number === null || number === undefined) {
                      return null;
                  }

                  const re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
                        num = number.toFixed(Math.max(0, ~~n));
                  return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
              };
          },
          formatNumber = generateFormatNumber('.', ','),

          toggleProp = (defaultState, alternateState) => {
              const p = m.prop(defaultState);
              p.toggle = () => {
                  p(((p() === alternateState) ? defaultState : alternateState));
              };

              return p;
          },

          idVM = m.postgrest.filtersVM({
              id: 'eq'
          }),

          getUser = () => {
              const body = document.getElementsByTagName('body'),
                    data = _.first(body).getAttribute('data-user');
              if (data) {
                  return JSON.parse(data);
              } else {
                  return false;
              }
          },

          hashMatch = (str) => {
              return window.location.hash === str;
          },

          locationActionMatch = (action) => {
              const act = window.location.pathname.split('/').slice(-1)[0];
              return action === act;
          },

          useAvatarOrDefault = (avatarPath) => {
              return avatarPath || '/assets/catarse_bootstrap/user.jpg';
          },

          //Templates
          loader = () => {
              return m('.u-text-center.u-margintop-30 u-marginbottom-30', [
                  m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
              ]);
          },

          fbParse = () => {
              const tryParse = () => {
                  try {
                      window.FB.XFBML.parse();
                  } catch (e) {
                      console.log(e);
                  }
              };

              return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
          },

          pluralize = (count, s, p) => {
              return (count > 1 ? count + p : count + s);
          },

          simpleFormat = (str = '') => {
              str = str.replace(/\r\n?/, '\n');
              if (str.length > 0) {
                  str = str.replace(/\n\n+/g, '

');
                  str = str.replace(/\n/g, '
');
                  str = '
' + str + '
';
              }
              return str;
          },

          rewardSouldOut = (reward) => {
              return (reward.maximum_contributions > 0 ?
                      (reward.paid_count + reward.waiting_payment_count >= reward.maximum_contributions) : false);
          },

          rewardRemaning = (reward) => {
              return reward.maximum_contributions - (reward.paid_count + reward.waiting_payment_count);
          },

          parseUrl = (href) => {
              const l = document.createElement('a');
              l.href = href;
              return l;
          },

          mixpanelTrack = () => {
              return (el, isInitialized) => {
                  if (!isInitialized) {
                      window.CatarseMixpanel.activate();
                  }
              };
          },

          UIHelper = () => {
              return (el, isInitialized) => {
                  if (!isInitialized && $) {
                      window.UIHelper.setupResponsiveIframes($(el));
                  }
              };
          },

          navigateToDevise = () => {
              window.location.href = '/pt/login';
              return false;
          };

    setMomentifyLocale();

    return {
        discuss: discuss,
        momentify: momentify,
        momentFromString: momentFromString,
        formatNumber: formatNumber,
        idVM: idVM,
        getUser: getUser,
        toggleProp: toggleProp,
        loader: loader,
        fbParse: fbParse,
        pluralize: pluralize,
        simpleFormat: simpleFormat,
        generateRemaingTime: generateRemaingTime,
        rewardSouldOut: rewardSouldOut,
        rewardRemaning: rewardRemaning,
        parseUrl: parseUrl,
        hashMatch: hashMatch,
        useAvatarOrDefault: useAvatarOrDefault,
        locationActionMatch: locationActionMatch,
        mixpanelTrack: mixpanelTrack,
        navigateToDevise: navigateToDevise,
        storeAction: storeAction,
        callStoredAction: callStoredAction,
        UIHelper: UIHelper
    };
}(window.m, window.moment));
<|endoftext|>


<commit_before>// Load in dependencies
var windowInfo = require('../lib/windowInfo'),
    exec = require('../lib/utils').exec,
    expect = require('chai').expect;

// Set up test global
var WINDOW_ID = '0x1600093';
describe('windowInfo', function () {
  // Before anything, resize the window
  before(function () {
    // Sorry, tests are designed for 1920 x 1080 (x2) setup
    // Left, top, width, height
    exec('wmctrl -r ' + WINDOW_ID + ' -e 0,2800,30,1000,1100');
  });

  // Grab the window dimentsions
  before(function () {
    this.win = windowInfo(WINDOW_ID);
  });

  it('returns proper window size', function () {
    console.log(this.win);
    expect(this.win).to.deep.equal({
      left: 2800,
      top: 30,
      width: 1000,
      height: 1100
    });
  });
});<commit_msg>Got resize working but dimensions seem off by border<commit_after>// Load in dependencies
var windowInfo = require('../lib/windowInfo'),
    exec = require('../lib/utils').exec,
    expect = require('chai').expect;

// Set up test global
var WINDOW_ID = '0x01600093',
    COMMON_NAME = exec('wmctrl -l | grep ' + WINDOW_ID + ' | cut --delimiter " " --fields 5');
console.log(COMMON_NAME);
describe('windowInfo', function () {
  // Before anything, resize the window
  before(function () {
    // Sorry, tests are designed for 1920 x 1080 (x2) setup
    // Left, top, width, height
    exec('wmctrl -r ' + COMMON_NAME + ' -e 0,2800,30,1000,900');
  });

  // Grab the window dimentsions
  before(function () {
    this.win = windowInfo(WINDOW_ID);
  });

  it('returns proper window size', function () {
    console.log(this.win);
    expect(this.win).to.deep.equal({
      left: 2800,
      top: 30,
      width: 1000,
      height: 900
    });
  });
});<|endoftext|>


<commit_before>//import path from 'path';
//import webpack from 'webpack';
const path = require('path');
const webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

//export default {
//removed from entry: app: 'webpack/hot/dev-server','webpack-hot-middleware/client'
module.exports = {
    devtool: 'source-map',
    entry: {
        app: ["babel-polyfill", path.join(__dirname, 'index.js')],
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
        }, ],
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js',
        publicPath: '/ptravels', //this is basically the webroot
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './index.html', //changed from /.src/index.html but broke npm run dev
            title: 'Your website'
          }),
        new webpack.LoaderOptionsPlugin({
            debug: true,
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('development'),
            },
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.HotModuleReplacementPlugin(),
    ],
    // devServer: {
    //     contentBase: __dirname,
    //     historyApiFallback: true,
    //     hot: true,
    //     inline: true,
    //     port: 3001,
    //     stats: {
    //         cached: false,
    //     },
    // },
    node: { fs: "empty", net: "empty", tls: "empty" }
};<commit_msg>updating public path<commit_after>//import path from 'path';
//import webpack from 'webpack';
const path = require('path');
const webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

//export default {
//removed from entry: app: 'webpack/hot/dev-server','webpack-hot-middleware/client'
module.exports = {
    devtool: 'source-map',
    entry: {
        app: ["babel-polyfill", path.join(__dirname, 'index.js')],
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
        }, ],
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js',
        publicPath: '/', //this is basically the webroot
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './index.html', //changed from /.src/index.html but broke npm run dev
            title: 'Your website'
          }),
        new webpack.LoaderOptionsPlugin({
            debug: true,
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('development'),
            },
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.HotModuleReplacementPlugin(),
    ],
    // devServer: {
    //     contentBase: __dirname,
    //     historyApiFallback: true,
    //     hot: true,
    //     inline: true,
    //     port: 3001,
    //     stats: {
    //         cached: false,
    //     },
    // },
    node: { fs: "empty", net: "empty", tls: "empty" }
};<|endoftext|>


<commit_before>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

'use strict';

/* global _ */

define(['records', 'utils', 'file', 'widgets', './ext/eo-graph'], function(records, utils, file, widgets, EOGraph) { // jshint ignore:line
    var dgroup, dtype;
    var eoGraph;
    var asAForm = false; // Flag to ignore the records.EVT_EDIT_ANNOTATION event

    var onFinishDtree;

    var pluginRoot = 'plugins/decision-tree/';

    var dtreeId = 'fieldcontain-dtree-1';

    var fieldsetWidget = _.template(
        '<fieldset data-role="controlgroup" data-theme="b">' +
            '<legend><%- question %></legend>' +
            '<%= fields %>' +
        '</fieldset>' +
        '<%= buttons %>'
    );

    var radioWidget = _.template(
        '<label for="radio-<%- id %>"><%- label %>' +
        '<input ' +
            'name="<%= name %>" ' +
            'id="radio-<%= id %>" ' +
            'value="<%= value %>" ' +
            'type="radio" ' +
            '<% if (required === true) { %>required="required"<% } %> ' +
            '<% if (checked === true) { %>checked="checked"<% } %> ' +
        '>'
    );

    var rangeWidget = _.template(
        '<label for="slider-<%- id %>">Input slider:' +
        '<input type="range" name="<%= name %>" id="slider-<%- id %>" value="<%- value %>" min="<%- min %>" max="<%- max %>">'
    );

    var controlButtons = _.template(
        '<% if (previous === true) { %>' +
        '<< Prev' +
        '<% } %>' +
        '<% if (next === true) { %>' +
        'Next >>' +
        '<% } else { %>' +
        'Done.' +
        '<% } %>'
    );

    var inputValue = _.template(
        '
' +
            '
' +
                '<input type="text" ' +
                       'id="dtree-value"' +
                       'value="<%= value %>" ' +
                       'data-dtree-value="<%= dtree %>" ' +
                       'readonly >' +
            '
' +
            '
' +
                '' +
            '
' +
        '
'
    );

    var formatEdge = function(edge) {
        return {
            id: edge.nodeId,
            answer: {
                value: edge.value,
                id: edge.edgeId
            }
        };
    };

    var getReprAndValue = function(graph) {
        var repr;
        var value;

        value = graph.edges().map(formatEdge);
        repr = graph.values().join(', ');

        return {
            repr: repr,
            value: value
        };
    };

    var addRecordTreeAnswers = function(e, annotation) {
        var field;
        var graph;

        field = {
            id: dtreeId,
            label: 'Decision tree'
        };

        if (eoGraph !== undefined && asAForm) {
            graph = getReprAndValue(eoGraph);
            field.repr = graph.repr;
            field.val = [graph.repr];

            annotation.record.properties.fields.push(field);
        }
    };

    var renderFieldsToString = function(name, edges) {
        var elementType;
        var fields = '';
        var edge;
        edges = edges || [];

        for (var i = 0, len = edges.length; i < len; i++) {
            edge = edges[i];
            if (edge.element) {
                elementType = edge.element.type;
            }
            else {
                elementType = 'radio';
            }

            switch (elementType) {
                case 'slider':
                    fields += rangeWidget({
                        id: i,
                        name: name,
                        label: edge.label,
                        min: edge.element.options.min,
                        max: edge.element.options.max,
                        value: edge.element.options.value
                    });
                break;
                default:
                    fields += radioWidget({
                        id: i,
                        name: name,
                        label: edge.label,
                        required: false,
                        checked: false,
                        value: edge.value
                    });
            }
        }

        return fields;
    };

    var renderFieldSetToString = function(node) {
        var buttons = {
            previous: eoGraph.hasPrevious(),
            next: eoGraph.hasNext()
        };

        // Move this to a better place
        toggleLongButtons(buttons);

        return fieldsetWidget({
            question: node.label,
            fields: renderFieldsToString(node.name, node.edges),
            buttons: ''
            // buttons: controlButtons(buttons)
        });
    };

    var renderPage = function() {
        var node;
        var html;
        console.debug('render');

        node = eoGraph.current();

        html = renderFieldSetToString(node);
        $('#dtree-form')
            .html(html)
            .parent()
            .trigger('create');
    };

    /* popup a msg */
    var popup = function(msg) {
        $('#popup-text').html(msg);
        $('#dtree-message')
            .html(msg)
            .slideDown()
            .delay(2000)
            .slideUp();
        $('#dtree-popup').popup('open');
    };

    /**
     * function for initializing DecisionTree
     * download data and start questionnaire
     */
    var loadDtree = function(group, type, callback) {
        var url;

        if (group ===  records.EDITOR_GROUP.DEFAULT) {
            url = 'editors/' + type.replace(/.edtr$/, '.json');
        }
        else {
            url = file.getFilePath(records.getEditorsDir(group)) + '/' + type.replace(/.edtr$/, '.json');
        }
        dgroup = group;
        dtype = type;

        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                $.mobile.loading('hide');
                console.debug(data);
                eoGraph = new EOGraph();
                if (data) {
                    if (!eoGraph.init(data)) {
                        utils.informError('Error loading the tree');
                    }
                    else {
                        utils.doCallback(callback);
                    }
                }
                else {
                    utils.informError('No data ');
                }
            }
        });
    };

    /**
     * Implements the records.processEditor interface
     * @param editorName name of the editor
     * @param html html content of the editor
     * @param group from records.EDITOR_GROUP
     * @param online boolean value if the processing is held online
     */
    var processEditor = function(editorName, html, group, online) {
        var $form = $(html);
        var editorsObj = records.loadEditorsMetadata();

        // Add the dom class that will be used in the buttons
        var editorClass = $('#dtree-form-class-name', $form).text();
        if (editorClass !== '') {
            if (editorsObj[group][editorName] === undefined) {
                editorsObj[group][editorName] = {};
            }

            editorsObj[group][editorName]['class'] = editorClass;

            // Save the result
            records.saveEditorsMetadata(editorsObj);
        }
    };

    // Add the plugin editor process to the pipeline
    records.addProcessEditor(processEditor);

    var insertPopupPlaceHolder = function() {
        var $form = $('form');
        var html = '
' +
                       '

' +
                       '
' +
                       '

' +
                       '
' +
                       '
' +
                           '<form id="dtree-form" data-ajax="false" accept-charset="utf-8"></form>' +
                       '
' +
                       '
' +
                       '

' +
                       '
' +
                   '
';

        $form.append(html);
        $('#dtree-container').popup();
    };

    var registerOnFinish = function(func) {
        onFinishDtree = func;
    };

    records.addDisplayEditorFunction(insertPopupPlaceHolder);

    var toggleLongButtons = function(buttons) {
        var triangleLeft = '#dtree-long-prev > .triangle-left';
        var triangleRight = '#dtree-long-next > .triangle-right';

        if (buttons.previous) {
            $(triangleLeft).removeClass('inactive');
        }
        else {
            $(triangleLeft).addClass('inactive');
        }
        if (buttons.next) {
            $(triangleRight).removeClass('inactive');
        }
        else {
            $(triangleRight).addClass('inactive');
        }
    };

    var doNext = function(event) {
        event.stopPropagation();
        event.preventDefault();

        var answers = $('form#dtree-form').serializeArray();
        if (answers.length === 1) {
            eoGraph.next(answers[0].value);
            if (eoGraph.hasNext()) {
                renderPage();
            }
            else {
                utils.doCallback(onFinishDtree);
            }
        }
        else {
            popup('Please answer all the questions');
        }
        return false;
    };

    var doPrev = function(event) {
        event.stopPropagation();
        event.preventDefault();

        eoGraph.previous();
        renderPage();

        return false;
    };

    /*********EVENTS************/
    $(document).on('vclick', '#dtree-prev', doPrev);
    $(document).on('vclick', '#dtree-next', doNext);

    $(document).on('vclick', '#dtree-long-prev', doPrev);
    $(document).on('vclick', '#dtree-long-next', doNext);

    $(document).off('vclick', '#dtree-done');
    $(document).on(
        'vclick',
        '#dtree-done',
        function(event) {
            event.stopPropagation();
            event.preventDefault();

            utils.doCallback(onFinishDtree);

            return false;
        }
    );

    // Dtree from a button inside an editor
    $('body').off('vclick', '.annotate-dtree');
    $('body').on('vclick', '.annotate-dtree', function(event) {
        var fieldcontain = $(event.target).closest('.fieldcontain').get(0);
        var group = localStorage.getItem('annotate-form-group');
        var type = localStorage.getItem('annotate-form-type');
        var $fieldcontain = $(fieldcontain);

        if (fieldcontain && fieldcontain.id) {
            dtreeId = fieldcontain.id;
        }

        loadDtree(group, type, function() {
            $('#dtree-container').popup('open');

            registerOnFinish(function(event) {
                var graph;
                var html;
                var value;
                var dtree;
                var label;

                graph = getReprAndValue(eoGraph);
                value = graph.repr;
                dtree = JSON.stringify(graph.value);
                label = $fieldcontain
                            .find('label[for="' + fieldcontain.id + '"]')
                            .text();

                html = inputValue({
                    label: label,
                    value: value,
                    dtree: dtree
                });

                $(html)
                    .insertBefore('.button-dtree', fieldcontain)
                    .trigger('create');

                $('#dtree-container').popup('close');

                return false;
            });

            renderPage();
        });

    });

    $(document).off('vclick', '.dtree-delete');
    $(document).on('vclick', '.dtree-delete', function(event) {
        event.stopPropagation();
        event.preventDefault();

        var $target = $(event.currentTarget);
        $target.parent().remove();

        return false;
    });

    // Dtree from the the capture page
    $('body').off('click', '.annotate-dtree-form');
    $('body').on('click', '.annotate-dtree-form', function(event) {
        var $editor = $(event.currentTarget);
        var group = $editor.attr('data-editor-group');
        var type = $editor.attr('data-editor-type');

        group = group || records.EDITOR_GROUP.DEFAULT;
        asAForm = true;

        loadDtree(group, type, function() {
            $('body').pagecontainer('change', 'decision-tree.html', {transition: 'fade'});

            registerOnFinish(function() {
                records.annotate(dgroup, dtype);
            });
        });
    });

    // TODO: do this in a more clean and modular way
    // Self register as a widget

    (function() {
        var WIDGET_NAME = 'dtree';

        var initialize = function(index, element) {
            var $el = $(element);

            $.each($('.button-dtree', element), function(index, input) {

                var btn = '' +
                              'Add ' +
                          '';

                $(input)
                    .append(btn)
                    .trigger('create');
            });
        };

        var validate = function(html) {
            return {
                valid: true,
                errors: []
            };
        };

        var serialize = function(element) {
            var $el = $(element);
            var values = [];
            var label;

            $el.find('input[data-dtree-value]').each(function(i, item) {
                values.push(item.value);
            });

            label = $el.find('label[for="' + element.id + '"]').text();

            return {
                serialize: true,
                label: label,
                value: values,
                repr: JSON.stringify(values)
            };
        };

        widgets.registerWidget({
            name: WIDGET_NAME,
            initialize: initialize,
            validate: validate,
            serialize: serialize
        });
    })();

    // listen on any page with class sync-page
    $(document).on('_pageshow', '#decision-tree-page', renderPage);
    $(document).on(records.EVT_EDIT_ANNOTATION, addRecordTreeAnswers);

    $('head').prepend('<link rel="stylesheet" href="plugins/decision-tree/css/style.css" type="text/css" />');
});
<commit_msg>edina/fieldtrip-cobweb-project#59: allow more than one decision trees to be called<commit_after>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

'use strict';

/* global _ */

define(['records', 'utils', 'file', 'widgets', './ext/eo-graph'], function(records, utils, file, widgets, EOGraph) { // jshint ignore:line
    var dgroup, dtype;
    var eoGraph;
    var asAForm = false; // Flag to ignore the records.EVT_EDIT_ANNOTATION event

    var onFinishDtree;

    var pluginRoot = 'plugins/decision-tree/';

    var dtreeId = 'fieldcontain-dtree-1';

    var fieldsetWidget = _.template(
        '<fieldset data-role="controlgroup" data-theme="b">' +
            '<legend><%- question %></legend>' +
            '<%= fields %>' +
        '</fieldset>' +
        '<%= buttons %>'
    );

    var radioWidget = _.template(
        '<label for="radio-<%- id %>"><%- label %>' +
        '<input ' +
            'name="<%= name %>" ' +
            'id="radio-<%= id %>" ' +
            'value="<%= value %>" ' +
            'type="radio" ' +
            '<% if (required === true) { %>required="required"<% } %> ' +
            '<% if (checked === true) { %>checked="checked"<% } %> ' +
        '>'
    );

    var rangeWidget = _.template(
        '<label for="slider-<%- id %>">Input slider:' +
        '<input type="range" name="<%= name %>" id="slider-<%- id %>" value="<%- value %>" min="<%- min %>" max="<%- max %>">'
    );

    var controlButtons = _.template(
        '<% if (previous === true) { %>' +
        '<< Prev' +
        '<% } %>' +
        '<% if (next === true) { %>' +
        'Next >>' +
        '<% } else { %>' +
        'Done.' +
        '<% } %>'
    );

    var inputValue = _.template(
        '
' +
            '
' +
                '<input type="text" ' +
                       'id="dtree-value"' +
                       'value="<%= value %>" ' +
                       'data-dtree-value="<%= dtree %>" ' +
                       'readonly >' +
            '
' +
            '
' +
                '' +
            '
' +
        '
'
    );

    var formatEdge = function(edge) {
        return {
            id: edge.nodeId,
            answer: {
                value: edge.value,
                id: edge.edgeId
            }
        };
    };

    var getReprAndValue = function(graph) {
        var repr;
        var value;

        value = graph.edges().map(formatEdge);
        repr = graph.values().join(', ');

        return {
            repr: repr,
            value: value
        };
    };

    var addRecordTreeAnswers = function(e, annotation) {
        var field;
        var graph;

        field = {
            id: dtreeId,
            label: 'Decision tree'
        };

        if (eoGraph !== undefined && asAForm) {
            graph = getReprAndValue(eoGraph);
            field.repr = graph.repr;
            field.val = [graph.repr];

            annotation.record.properties.fields.push(field);
        }
    };

    var renderFieldsToString = function(name, edges) {
        var elementType;
        var fields = '';
        var edge;
        edges = edges || [];

        for (var i = 0, len = edges.length; i < len; i++) {
            edge = edges[i];
            if (edge.element) {
                elementType = edge.element.type;
            }
            else {
                elementType = 'radio';
            }

            switch (elementType) {
                case 'slider':
                    fields += rangeWidget({
                        id: i,
                        name: name,
                        label: edge.label,
                        min: edge.element.options.min,
                        max: edge.element.options.max,
                        value: edge.element.options.value
                    });
                break;
                default:
                    fields += radioWidget({
                        id: i,
                        name: name,
                        label: edge.label,
                        required: false,
                        checked: false,
                        value: edge.value
                    });
            }
        }

        return fields;
    };

    var renderFieldSetToString = function(node) {
        var buttons = {
            previous: eoGraph.hasPrevious(),
            next: eoGraph.hasNext()
        };

        // Move this to a better place
        toggleLongButtons(buttons);

        return fieldsetWidget({
            question: node.label,
            fields: renderFieldsToString(node.name, node.edges),
            buttons: ''
            // buttons: controlButtons(buttons)
        });
    };

    var renderPage = function() {
        var node;
        var html;
        console.debug('render');

        node = eoGraph.current();

        html = renderFieldSetToString(node);
        $('#dtree-form')
            .html(html)
            .parent()
            .trigger('create');
    };

    /* popup a msg */
    var popup = function(msg) {
        $('#popup-text').html(msg);
        $('#dtree-message')
            .html(msg)
            .slideDown()
            .delay(2000)
            .slideUp();
        $('#dtree-popup').popup('open');
    };

    /**
     * function for initializing DecisionTree
     * download data and start questionnaire
     */
    var loadDtree = function(group, type, callback) {
        var url;

        if (group ===  records.EDITOR_GROUP.DEFAULT) {
            url = 'editors/' + type.replace(/.edtr$/, '.json');
        }
        else {
            url = file.getFilePath(records.getEditorsDir(group)) + '/' + type.replace(/.edtr$/, '.json');
        }
        dgroup = group;
        dtype = type;

        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                $.mobile.loading('hide');
                console.debug(data);
                eoGraph = new EOGraph();
                if (data) {
                    if (!eoGraph.init(data)) {
                        utils.informError('Error loading the tree');
                    }
                    else {
                        utils.doCallback(callback);
                    }
                }
                else {
                    utils.informError('No data ');
                }
            }
        });
    };

    /**
     * Implements the records.processEditor interface
     * @param editorName name of the editor
     * @param html html content of the editor
     * @param group from records.EDITOR_GROUP
     * @param online boolean value if the processing is held online
     */
    var processEditor = function(editorName, html, group, online) {
        var $form = $(html);
        var editorsObj = records.loadEditorsMetadata();

        // Add the dom class that will be used in the buttons
        var editorClass = $('#dtree-form-class-name', $form).text();
        if (editorClass !== '') {
            if (editorsObj[group][editorName] === undefined) {
                editorsObj[group][editorName] = {};
            }

            editorsObj[group][editorName]['class'] = editorClass;

            // Save the result
            records.saveEditorsMetadata(editorsObj);
        }
    };

    // Add the plugin editor process to the pipeline
    records.addProcessEditor(processEditor);

    var insertPopupPlaceHolder = function() {
        var $form = $('form');
        var html = '
' +
                       '

' +
                       '
' +
                       '

' +
                       '
' +
                       '
' +
                           '<form id="dtree-form" data-ajax="false" accept-charset="utf-8"></form>' +
                       '
' +
                       '
' +
                       '

' +
                       '
' +
                   '
';

        $form.append(html);
        $('#dtree-container').popup();
    };

    var registerOnFinish = function(func) {
        onFinishDtree = func;
    };

    records.addDisplayEditorFunction(insertPopupPlaceHolder);

    var toggleLongButtons = function(buttons) {
        var triangleLeft = '#dtree-long-prev > .triangle-left';
        var triangleRight = '#dtree-long-next > .triangle-right';

        if (buttons.previous) {
            $(triangleLeft).removeClass('inactive');
        }
        else {
            $(triangleLeft).addClass('inactive');
        }
        if (buttons.next) {
            $(triangleRight).removeClass('inactive');
        }
        else {
            $(triangleRight).addClass('inactive');
        }
    };

    var doNext = function(event) {
        event.stopPropagation();
        event.preventDefault();

        var answers = $('form#dtree-form').serializeArray();
        if (answers.length === 1) {
            eoGraph.next(answers[0].value);
            if (eoGraph.hasNext()) {
                renderPage();
            }
            else {
                utils.doCallback(onFinishDtree);
            }
        }
        else {
            popup('Please answer all the questions');
        }
        return false;
    };

    var doPrev = function(event) {
        event.stopPropagation();
        event.preventDefault();

        eoGraph.previous();
        renderPage();

        return false;
    };

    /*********EVENTS************/
    $(document).on('vclick', '#dtree-prev', doPrev);
    $(document).on('vclick', '#dtree-next', doNext);

    $(document).on('vclick', '#dtree-long-prev', doPrev);
    $(document).on('vclick', '#dtree-long-next', doNext);

    $(document).off('vclick', '#dtree-done');
    $(document).on(
        'vclick',
        '#dtree-done',
        function(event) {
            event.stopPropagation();
            event.preventDefault();

            utils.doCallback(onFinishDtree);

            return false;
        }
    );

    // Dtree from a button inside an editor
    $('body').off('vclick', '.annotate-dtree');
    $('body').on('vclick', '.annotate-dtree', function(event) {
        var fieldcontain = $(event.target).closest('.fieldcontain').get(0);
        var group = localStorage.getItem('annotate-form-group');
        var type = localStorage.getItem('annotate-form-type');
        var $fieldcontain = $(fieldcontain);
        var dtreeFile = $fieldcontain.find("input:hidden").data("dtree");

        if (fieldcontain && fieldcontain.id) {
            dtreeId = fieldcontain.id;
        }

        loadDtree(group, dtreeFile, function() {
            $('#dtree-container').popup('open');

            registerOnFinish(function(event) {
                var graph;
                var html;
                var value;
                var dtree;
                var label;

                graph = getReprAndValue(eoGraph);
                value = graph.repr;
                dtree = JSON.stringify(graph.value);
                label = $fieldcontain
                            .find('label[for="' + fieldcontain.id + '"]')
                            .text();

                html = inputValue({
                    label: label,
                    value: value,
                    dtree: dtree
                });

                $(html)
                    .insertBefore('#'+fieldcontain.id+' .button-dtree')
                    .trigger('create');

                $('#dtree-container').popup('close');

                return false;
            });

            renderPage();
        });

    });

    $(document).off('vclick', '.dtree-delete');
    $(document).on('vclick', '.dtree-delete', function(event) {
        event.stopPropagation();
        event.preventDefault();

        var $target = $(event.currentTarget);
        $target.parent().remove();

        return false;
    });

    // Dtree from the the capture page
    $('body').off('click', '.annotate-dtree-form');
    $('body').on('click', '.annotate-dtree-form', function(event) {
        var $editor = $(event.currentTarget);
        var group = $editor.attr('data-editor-group');
        var type = $editor.attr('data-editor-type');

        group = group || records.EDITOR_GROUP.DEFAULT;
        asAForm = true;

        loadDtree(group, type, function() {
            $('body').pagecontainer('change', 'decision-tree.html', {transition: 'fade'});

            registerOnFinish(function() {
                records.annotate(dgroup, dtype);
            });
        });
    });

    // TODO: do this in a more clean and modular way
    // Self register as a widget

    (function() {
        var WIDGET_NAME = 'dtree';

        var initialize = function(index, element) {
            var $el = $(element);

            $.each($('.button-dtree', element), function(index, input) {

                var btn = '' +
                              'Add ' +
                          '';

                $(input)
                    .append(btn)
                    .trigger('create');
            });
        };

        var validate = function(html) {
            return {
                valid: true,
                errors: []
            };
        };

        var serialize = function(element) {
            var $el = $(element);
            var values = [];
            var label;

            $el.find('input[data-dtree-value]').each(function(i, item) {
                values.push(item.value);
            });

            label = $el.find('label[for="' + element.id + '"]').text();

            return {
                serialize: true,
                label: label,
                value: values,
                repr: JSON.stringify(values)
            };
        };

        widgets.registerWidget({
            name: WIDGET_NAME,
            initialize: initialize,
            validate: validate,
            serialize: serialize
        });
    })();

    // listen on any page with class sync-page
    $(document).on('_pageshow', '#decision-tree-page', renderPage);
    $(document).on(records.EVT_EDIT_ANNOTATION, addRecordTreeAnswers);

    $('head').prepend('<link rel="stylesheet" href="plugins/decision-tree/css/style.css" type="text/css" />');
});
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars, no-undef */

'use strict'

// app
var app = {
  initialize: function initialize () {
    this.bindEvents()
  },
  bindEvents: function bindEvents () {
    document.addEventListener('deviceready', this.onDeviceReady, false)
    document.addEventListener('resume', this.onDeviceReady, false)
  },
  onDeviceReady: function onDeviceReady () {
    BranchInit(true)
  },
  onDeviceResume: function onDeviceResume () {
    BranchInit(true)
  }
}
app.initialize()

// branch
function BranchInit (isDebug) {
  console.log('Trigger BranchInit()')

  // for development and debugging only
  Branch.setDebug(isDebug)

  // sync with Mixpanel if installed
  Branch.setMixpanelToken('your_mixpanel_token')

  // Branch initialization
  Branch.initSession(function (data) {
    // read deep link data on click
    console.log('Trigger DeepLinkHandler()')
    alert('Deep Link Data: ' + JSON.stringify(data))
  }).then(function (res) {
    console.log(res)
  }).catch(function (err) {
    console.error(err)
  })

  // optional
  Branch.onNonBranchLink(function NonBranchLinkHandler (data) {
    console.log('Trigger NonBranchLinkData()')

    if (data) {
      alert(JSON.stringify(data))
    }
  })
}

function BranchEvent () {
  console.log('Trigger BranchEvent()')

  // event name
  var event = document.getElementById('custom-action').value || 'blank'

  // optional
  var metadata = { 'custom_dictionary': 123, 'anything': 'everything' }
  Branch.userCompletedAction(event, metadata).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchFirstData () {
  console.log('Trigger BranchFirstData()')

  Branch.getFirstReferringParams().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchLatestData () {
  console.log('Trigger BranchLatestData()')

  Branch.getLatestReferringParams().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchUser () {
  console.log('Trigger BranchUser()')

  var userId = document.getElementById('identity').value
  Branch.setIdentity(userId).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchLogout () {
  console.log('Trigger BranchLogout()')

  Branch.logout().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

var branchUniversalObj = null
function BranchUniversalObject () {
  console.log('Trigger BranchUniversalObject()')

  // only canonicalIdentifier is required
  var properties = {
    canonicalIdentifier: '123',
    canonicalUrl: 'http://example.com/123',
    title: 'Content 123',
    contentDescription: 'Content 123 ' + Date.now(),
    contentImageUrl: 'http://lorempixel.com/400/400/',
    price: 12.12,
    currency: 'GBD',
    contentIndexingMode: 'private',
    contentMetadata: {
      custom: 'data',
      testing: 123,
      this_is: true
    }
  }

  // create a branchUniversalObj variable to reference with other Branch methods
  Branch.createBranchUniversalObject(properties).then(function (res) {
    console.log(res)
    branchUniversalObj = res
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.log(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchView () {
  console.log('Trigger BranchView()')

  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }
  branchUniversalObj.registerView().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchDeepLink () {
  console.log('Trigger BranchDeepLink()')

  // optional fields
  var analytics = {
    channel: 'channel',
    feature: 'feature',
    campaign: 'campaign',
    stage: 'stage',
    tags: ['one', 'two', 'three'],
    alias: document.getElementById('alias').value
  }

  // optional fields
  var properties = {
    $fallback_url: 'http://www.example.com/example',
    $desktop_url: 'http://www.example.com/desktop',
    $android_url: 'http://www.example.com/android',
    $ios_url: 'http://www.example.com/ios',
    $ipad_url: 'http://www.example.com/ipad',
    $deeplink_path: 'content/123',
    $match_duration: 2000,
    more_custom: 'data',
    even_more_custom: true,
    this_is_custom: 41231,
    this_is_date: Date.now()
  }

  // needs a universal object
  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }

  branchUniversalObj.generateShortUrl(analytics, properties).then(function (res) {
    console.log(res)
    document.getElementById('generated-url').placeholder = ''
    document.getElementById('generated-url').value = res.url
    alert(JSON.stringify(res.url))
  }).catch(function (err) {
    console.error(err)
    alert(JSON.stringify(err))
  })
}

function BranchShareSheet () {
  console.log('Trigger BranchShareSheet()')

  // optional fields
  var analytics = {
    channel: 'channel',
    feature: 'feature',
    campaign: 'campaign',
    stage: 'stage',
    tags: ['one', 'two', 'three']
  }

  // optional fields
  var properties = {
    $fallback_url: 'http://www.example.com/example',
    $desktop_url: 'http://www.example.com/desktop',
    $android_url: 'http://www.example.com/android',
    $ios_url: 'http://www.example.com/ios',
    $ipad_url: 'http://www.example.com/ipad',
    more_custom: 'data',
    even_more_custom: true,
    this_is_custom: 41231
  }

  var message = 'Check out this link'

  // needs a universal object
  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }

  // optional listeners (must be called before showShareSheet)
  branchUniversalObj.onShareSheetLaunched(function (res) {
    // android only
    console.log(res)
    alert(JSON.stringify(res))
  })
  branchUniversalObj.onShareSheetDismissed(function (res) {
    console.log(res)
    alert(JSON.stringify(res))
  })
  branchUniversalObj.onLinkShareResponse(function (res) {
    console.log(res)
    alert(JSON.stringify(res))
  })
  branchUniversalObj.onChannelSelected(function (res) {
    // android only
    console.log(res)
    alert(JSON.stringify(res))
  })

  // share sheet
  branchUniversalObj.showShareSheet(analytics, properties, message)
}

function BranchSpotlight () {
  console.log('Trigger ListOnSpotlight()')

  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }
  branchUniversalObj.listOnSpotlight().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsLoad () {
  console.log('Trigger BranchReferralsLoad()')

  Branch.loadRewards().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsRedeem () {
  console.log('Trigger BranchReferralsRedeem()')

  var reward = 1000
  Branch.redeemRewards(reward).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsHistory () {
  console.log('Trigger BranchReferralsHistory()')

  Branch.creditHistory().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}
<commit_msg>fix: updated testbed for correct share sheet navigation<commit_after>/* eslint-disable no-unused-vars, no-undef */

'use strict'

// app
var app = {
  initialize: function initialize () {
    this.bindEvents()
  },
  bindEvents: function bindEvents () {
    document.addEventListener('deviceready', this.onDeviceReady, false)
    document.addEventListener('resume', this.onDeviceReady, false)
  },
  onDeviceReady: function onDeviceReady () {
    BranchInit(true)
  },
  onDeviceResume: function onDeviceResume () {
    BranchInit(true)
  }
}
app.initialize()

// branch
function BranchInit (isDebug) {
  console.log('Trigger BranchInit()')

  // for development and debugging only
  Branch.setDebug(isDebug)

  // sync with Mixpanel if installed
  Branch.setMixpanelToken('your_mixpanel_token')

  // Branch initialization
  Branch.initSession(function (data) {
    // read deep link data on click
    console.log('Trigger DeepLinkHandler()')
    alert('Deep Link Data: ' + JSON.stringify(data))
  }).then(function (res) {
    console.log(res)
  }).catch(function (err) {
    console.error(err)
  })

  // optional
  Branch.onNonBranchLink(function NonBranchLinkHandler (data) {
    console.log('Trigger NonBranchLinkData()')

    if (data) {
      alert(JSON.stringify(data))
    }
  })
}

function BranchEvent () {
  console.log('Trigger BranchEvent()')

  // event name
  var event = document.getElementById('custom-action').value || 'blank'

  // optional
  var metadata = { 'custom_dictionary': 123, 'anything': 'everything' }
  Branch.userCompletedAction(event, metadata).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchFirstData () {
  console.log('Trigger BranchFirstData()')

  Branch.getFirstReferringParams().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchLatestData () {
  console.log('Trigger BranchLatestData()')

  Branch.getLatestReferringParams().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchUser () {
  console.log('Trigger BranchUser()')

  var userId = document.getElementById('identity').value
  Branch.setIdentity(userId).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchLogout () {
  console.log('Trigger BranchLogout()')

  Branch.logout().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

var branchUniversalObj = null
function BranchUniversalObject () {
  console.log('Trigger BranchUniversalObject()')

  // only canonicalIdentifier is required
  var properties = {
    canonicalIdentifier: 'content/123',
    canonicalUrl: 'https://example.com/content/123',
    title: 'Content 123 Title',
    contentDescription: 'Content 123 Description ' + Date.now(),
    contentImageUrl: 'http://lorempixel.com/400/400/',
    price: 12.12,
    currency: 'GBD',
    contentIndexingMode: 'private',
    contentMetadata: {
      custom: 'data',
      testing: 123,
      this_is: true
    }
  }

  // create a branchUniversalObj variable to reference with other Branch methods
  Branch.createBranchUniversalObject(properties).then(function (res) {
    console.log(res)
    branchUniversalObj = res
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.log(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchView () {
  console.log('Trigger BranchView()')

  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }
  branchUniversalObj.registerView().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchDeepLink () {
  console.log('Trigger BranchDeepLink()')

  // optional fields
  var analytics = {
    channel: 'facebook',
    feature: 'onboarding',
    campaign: 'content 123 launch',
    stage: 'new user',
    tags: ['one', 'two', 'three'],
    alias: document.getElementById('alias').value
  }

  // optional fields
  var properties = {
    $desktop_url: 'http://www.example.com/desktop',
    $android_url: 'http://www.example.com/android',
    $ios_url: 'http://www.example.com/ios',
    $ipad_url: 'http://www.example.com/ipad',
    $deeplink_path: 'content/123',
    $match_duration: 2000,
    more_custom: 'data',
    even_more_custom: true,
    this_is_custom: 41231,
    this_is_date: Date.now()
  }

  // needs a universal object
  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }

  branchUniversalObj.generateShortUrl(analytics, properties).then(function (res) {
    console.log(res)
    document.getElementById('generated-url').placeholder = ''
    document.getElementById('generated-url').value = res.url
    alert(JSON.stringify('Response: ' + res.url))
  }).catch(function (err) {
    console.error(err)
    alert(JSON.stringify('Error: ' + err))
  })
}

function BranchShareSheet () {
  console.log('Trigger BranchShareSheet()')

  // optional fields
  var analytics = {
    channel: 'facebook',
    feature: 'onboarding',
    campaign: 'content 123 launch',
    stage: 'new user',
    tags: ['one', 'two', 'three']
  }

  // optional fields
  var properties = {
    $desktop_url: 'http://www.example.com/desktop',
    more_custom: 'data',
    even_more_custom: true,
    this_is_custom: 41231
  }

  var message = 'Check out this link'

  // needs a universal object
  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }

  // optional listeners (must be called before showShareSheet)
  branchUniversalObj.onShareSheetLaunched(function (res) {
    // android only
    console.log(res)
  })
  branchUniversalObj.onShareSheetDismissed(function (res) {
    console.log(res)
  })
  branchUniversalObj.onLinkShareResponse(function (res) {
    console.log(res)
  })
  branchUniversalObj.onChannelSelected(function (res) {
    // android only
    console.log(res)
  })

  // share sheet
  branchUniversalObj.showShareSheet(analytics, properties, message)
}

function BranchSpotlight () {
  console.log('Trigger ListOnSpotlight()')

  if (branchUniversalObj === null) {
    return alert('need to Generate Branch Universal Object')
  }
  branchUniversalObj.listOnSpotlight().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsLoad () {
  console.log('Trigger BranchReferralsLoad()')

  Branch.loadRewards().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsRedeem () {
  console.log('Trigger BranchReferralsRedeem()')

  var amount = 100
  Branch.redeemRewards(amount).then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}

function BranchReferralsHistory () {
  console.log('Trigger BranchReferralsHistory()')

  Branch.creditHistory().then(function (res) {
    console.log(res)
    alert('Response: ' + JSON.stringify(res))
  }).catch(function (err) {
    console.error(err)
    alert('Error: ' + JSON.stringify(err))
  })
}
<|endoftext|>


<commit_before>/*
 * This file is part of yoob.js version 0.12
 * Available from https://github.com/catseye/yoob.js/
 * This file is in the public domain.  See http://unlicense.org/ for details.
 */
if (window.yoob === undefined) yoob = {};

/*
 * Functions for creating elements.
 */

yoob.makeCanvas = function(container, width, height) {
    var canvas = document.createElement('canvas');
    if (width) {
        canvas.width = width;
    }
    if (height) {
        canvas.height = height;
    }
    container.appendChild(canvas);
    return canvas;
};

yoob.makeButton = function(container, labelText, fun) {
    var button = document.createElement('button');
    button.innerHTML = labelText;
    container.appendChild(button);
    if (fun) {
        button.onclick = fun;
    }
    return button;
};

yoob.checkBoxNumber = 0;
yoob.makeCheckbox = function(container, checked, labelText, fun) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = 'cfzzzb_' + yoob.checkBoxNumber;
    checkbox.checked = checked;
    var label = document.createElement('label');
    label.htmlFor = 'cfzzzb_' + yoob.checkBoxNumber;
    yoob.checkBoxNumber += 1;
    label.appendChild(document.createTextNode(labelText));

    container.appendChild(checkbox);
    container.appendChild(label);

    if (fun) {
        checkbox.onchange = function(e) {
            fun(checkbox.checked);
        };
    }
    return checkbox;
};

yoob.makeTextInput = function(container, size, value) {
    var input = document.createElement('input');
    input.size = "" + (size || 12);
    input.value = value || "";
    container.appendChild(input);
    return input;
};

yoob.makeSlider = function(container, min, max, value, fun) {
    var slider = document.createElement('input');
    slider.type = "range";
    slider.min = min;
    slider.max = max;
    slider.value = value || 0;
    if (fun) {
        slider.onchange = function(e) {
            fun(parseInt(slider.value, 10));
        };
    }
    container.appendChild(slider);
    return slider;
};

yoob.makeParagraph = function(container, innerHTML) {
    var p = document.createElement('p');
    p.innerHTML = innerHTML || '';
    container.appendChild(p);
    return p;
};

yoob.makeSpan = function(container, innerHTML) {
    var span = document.createElement('span');
    span.innerHTML = innerHTML || '';
    container.appendChild(span);
    return span;
};

yoob.makeDiv = function(container, innerHTML) {
    var div = document.createElement('div');
    div.innerHTML = innerHTML || '';
    container.appendChild(div);
    return div;
};

yoob.makePre = function(container, innerHTML) {
    var elem = document.createElement('pre');
    elem.innerHTML = innerHTML || '';
    container.appendChild(elem);
    return elem;
};

yoob.makePanel = function(container, title, isOpen) {
    isOpen = !!isOpen;
    var panelContainer = document.createElement('div');
    var button = document.createElement('button');
    var innerContainer = document.createElement('div');
    innerContainer.style.display = isOpen ? "block" : "none";

    button.innerHTML = (isOpen ? "∇" : "⊳") + " " + title;
    button.onclick = function(e) {
        isOpen = !isOpen;
        button.innerHTML = (isOpen ? "∇" : "⊳") + " " + title;
        innerContainer.style.display = isOpen ? "block" : "none";
    };

    panelContainer.appendChild(button);
    panelContainer.appendChild(innerContainer);
    container.appendChild(panelContainer);
    return innerContainer;
};

yoob.makeTextArea = function(container, cols, rows, initial) {
    var textarea = document.createElement('textarea');
    textarea.rows = "" + rows;
    textarea.cols = "" + cols;
    if (initial) {
        textarea.value = initial;
    }
    container.appendChild(textarea);
    return textarea;
};

yoob.makeLineBreak = function(container) {
    var br = document.createElement('br');
    container.appendChild(br);
    return br;
};

yoob.makeSelect = function(container, labelText, optionsArray, fun, def) {
    var label = document.createElement('label');
    label.innerHTML = labelText;
    container.appendChild(label);

    var select = document.createElement("select");

    for (var i = 0; i < optionsArray.length; i++) {
        var op = document.createElement("option");
        op.value = optionsArray[i][0];
        op.text = optionsArray[i][1];
        if (optionsArray[i].length > 2) {
            op.selected = optionsArray[i][2];
        } else {
            op.selected = false;
        }
        select.options.add(op);
    }

    if (fun) {
        select.onchange = function(e) {
            fun(optionsArray[select.selectedIndex][0]);
        };
    }

    if (def) {
        var i = 0;
        var opt = select.options[i];
        while (opt) {
            if (opt.value === def) {
                select.selectedIndex = i;
                if (fun) fun(def);
                break;
            }
            i++;
            opt = select.options[i];
        }
    }

    container.appendChild(select);
    return select;
};

var SliderPlusTextInput = function() {
    this.init = function(cfg) {
        this.slider = cfg.slider;
        this.textInput = cfg.textInput;
        this.callback = cfg.callback;
        return this;
    };

    this.set = function(value) {
        this.slider.value = "" + value;
        this.textInput.value = "" + value;
        this.callback(value);
    };
};

yoob.makeSliderPlusTextInput = function(container, label, min_, max_, size, value, fun) {
    yoob.makeSpan(container, label);
    var slider = yoob.makeSlider(container, min_, max_, value);
    var s = "" + value;
    var textInput = yoob.makeTextInput(container, size, s);
    slider.onchange = function(e) {
        textInput.value = slider.value;
        fun(parseInt(slider.value, 10));
    };
    textInput.onchange = function(e) {
        var v = parseInt(textInput.value, 10);
        if (v !== NaN) {
            slider.value = "" + v;
            fun(v);
        }
    };
    return new SliderPlusTextInput().init({
        'slider': slider,
        'textInput': textInput,
        'callback': fun
    });
};

var RangeControl = function() {
    this.init = function(cfg) {
        this.slider = cfg.slider;
        this.textInput = cfg.textInput;
        this.callback = cfg.callback;
        this.incButton = cfg.incButton;
        this.decButton = cfg.decButton;
        return this;
    };

    this.set = function(value) {
        this.slider.value = "" + value;
        this.textInput.value = "" + value;
        this.callback(value);
    };
};

yoob.makeRangeControl = function(container, config) {
    var label = config.label;
    var min_ = config['min'];
    var max_ = config['max'];
    var value = config.value || min_;
    var callback = config.callback || function(v) {};
    var textInputSize = config.textInputSize || 5;
    var withButtons = config.withButtons === false ? false : true;

    yoob.makeSpan(container, label);
    var slider = yoob.makeSlider(container, min_, max_, value);
    var s = "" + value;
    var textInput = yoob.makeTextInput(container, textInputSize, s);
    slider.onchange = function(e) {
        textInput.value = slider.value;
        callback(parseInt(slider.value, 10));
    };
    textInput.onchange = function(e) {
        var v = parseInt(textInput.value, 10);
        if (v !== NaN) {
            slider.value = "" + v;
            callback(v);
        }
    };
    var incButton;
    var decButton;
    if (withButtons) {
        decButton = yoob.makeButton(container, "-", function() {
            var v = parseInt(textInput.value, 10);
            if (v !== NaN && v > min_) {
                v--;
                textInput.value = "" + v;
                slider.value = "" + v;
                callback(v);
            }
        });
        incButton = yoob.makeButton(container, "+", function() {
            var v = parseInt(textInput.value, 10);
            if (v !== NaN && v < max_) {
                v++;
                textInput.value = "" + v;
                slider.value = "" + v;
                callback(v);
            }
        });
    }
    return new RangeControl().init({
        'slider': slider,
        'incButton': incButton,
        'decButton': decButton,
        'textInput': textInput,
        'callback': callback
    });
};

yoob.makeSVG = function(container) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    /* <svg viewBox = "0 0 200 200" version = "1.1"> */
    container.appendChild(svg);
    return svg;
};

yoob.makeSVGElem = function(svg, tag, cfg) {
    var elem = document.createElementNS(svg.namespaceURI, tag);
    for (var key in cfg) {
        if (cfg.hasOwnProperty(key)) {
            elem.setAttribute(key, cfg[key]);
        }
    }
    svg.appendChild(elem);
    return elem;
};
<commit_msg>Make the Javascript more modern and/or actually working.<commit_after>/*
 * This file is part of yoob.js version 0.13-PRE
 * Available from https://github.com/catseye/yoob.js/
 * This file is in the public domain.  See http://unlicense.org/ for details.
 */
if (window.yoob === undefined) yoob = {};

/*
 * Functions for creating elements.
 */

yoob.makeCanvas = function(container, width, height) {
    var canvas = document.createElement('canvas');
    if (width) {
        canvas.width = width;
    }
    if (height) {
        canvas.height = height;
    }
    container.appendChild(canvas);
    return canvas;
};

yoob.makeButton = function(container, labelText, fun) {
    var button = document.createElement('button');
    button.innerHTML = labelText;
    container.appendChild(button);
    if (fun) {
        button.onclick = fun;
    }
    return button;
};

yoob.checkBoxNumber = 0;
yoob.makeCheckbox = function(container, checked, labelText, fun) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = 'cfzzzb_' + yoob.checkBoxNumber;
    checkbox.checked = checked;
    var label = document.createElement('label');
    label.htmlFor = 'cfzzzb_' + yoob.checkBoxNumber;
    yoob.checkBoxNumber += 1;
    label.appendChild(document.createTextNode(labelText));

    container.appendChild(checkbox);
    container.appendChild(label);

    if (fun) {
        checkbox.onchange = function(e) {
            fun(checkbox.checked);
        };
    }
    return checkbox;
};

yoob.makeTextInput = function(container, size, value) {
    var input = document.createElement('input');
    input.size = "" + (size || 12);
    input.value = value || "";
    container.appendChild(input);
    return input;
};

yoob.makeSlider = function(container, min, max, value, fun) {
    var slider = document.createElement('input');
    slider.type = "range";
    slider.min = min;
    slider.max = max;
    slider.value = value || 0;
    if (fun) {
        slider.onchange = function(e) {
            fun(parseInt(slider.value, 10));
        };
    }
    container.appendChild(slider);
    return slider;
};

yoob.makeParagraph = function(container, innerHTML) {
    var p = document.createElement('p');
    p.innerHTML = innerHTML || '';
    container.appendChild(p);
    return p;
};

yoob.makeSpan = function(container, innerHTML) {
    var span = document.createElement('span');
    span.innerHTML = innerHTML || '';
    container.appendChild(span);
    return span;
};

yoob.makeDiv = function(container, innerHTML) {
    var div = document.createElement('div');
    div.innerHTML = innerHTML || '';
    container.appendChild(div);
    return div;
};

yoob.makePre = function(container, innerHTML) {
    var elem = document.createElement('pre');
    elem.innerHTML = innerHTML || '';
    container.appendChild(elem);
    return elem;
};

yoob.makePanel = function(container, title, isOpen) {
    isOpen = !!isOpen;
    var panelContainer = document.createElement('div');
    var button = document.createElement('button');
    var innerContainer = document.createElement('div');
    innerContainer.style.display = isOpen ? "block" : "none";

    button.innerHTML = (isOpen ? "∇" : "⊳") + " " + title;
    button.onclick = function(e) {
        isOpen = !isOpen;
        button.innerHTML = (isOpen ? "∇" : "⊳") + " " + title;
        innerContainer.style.display = isOpen ? "block" : "none";
    };

    panelContainer.appendChild(button);
    panelContainer.appendChild(innerContainer);
    container.appendChild(panelContainer);
    return innerContainer;
};

yoob.makeTextArea = function(container, cols, rows, initial) {
    var textarea = document.createElement('textarea');
    textarea.rows = "" + rows;
    textarea.cols = "" + cols;
    if (initial) {
        textarea.value = initial;
    }
    container.appendChild(textarea);
    return textarea;
};

yoob.makeLineBreak = function(container) {
    var br = document.createElement('br');
    container.appendChild(br);
    return br;
};

yoob.makeSelect = function(container, labelText, optionsArray, fun, def) {
    var label = document.createElement('label');
    label.innerHTML = labelText;
    container.appendChild(label);

    var select = document.createElement("select");

    for (var i = 0; i < optionsArray.length; i++) {
        var op = document.createElement("option");
        op.value = optionsArray[i][0];
        op.text = optionsArray[i][1];
        if (optionsArray[i].length > 2) {
            op.selected = optionsArray[i][2];
        } else {
            op.selected = false;
        }
        select.options.add(op);
    }

    if (fun) {
        select.onchange = function(e) {
            fun(optionsArray[select.selectedIndex][0]);
        };
    }

    if (def) {
        var i = 0;
        var opt = select.options[i];
        while (opt) {
            if (opt.value === def) {
                select.selectedIndex = i;
                if (fun) fun(def);
                break;
            }
            i++;
            opt = select.options[i];
        }
    }

    container.appendChild(select);
    return select;
};

var SliderPlusTextInput = function() {
    this.init = function(cfg) {
        this.slider = cfg.slider;
        this.textInput = cfg.textInput;
        this.callback = cfg.callback;
        return this;
    };

    this.set = function(value) {
        this.slider.value = "" + value;
        this.textInput.value = "" + value;
        this.callback(value);
    };
};

yoob.makeSliderPlusTextInput = function(container, label, min_, max_, size, value, fun) {
    yoob.makeSpan(container, label);
    var slider = yoob.makeSlider(container, min_, max_, value);
    var s = "" + value;
    var textInput = yoob.makeTextInput(container, size, s);
    slider.onchange = function(e) {
        textInput.value = slider.value;
        fun(parseInt(slider.value, 10));
    };
    textInput.onchange = function(e) {
        var v = parseInt(textInput.value, 10);
        if (!isNaN(v)) {
            slider.value = "" + v;
            fun(v);
        }
    };
    return new SliderPlusTextInput().init({
        'slider': slider,
        'textInput': textInput,
        'callback': fun
    });
};

var RangeControl = function() {
    this.init = function(cfg) {
        this.slider = cfg.slider;
        this.textInput = cfg.textInput;
        this.callback = cfg.callback;
        this.incButton = cfg.incButton;
        this.decButton = cfg.decButton;
        return this;
    };

    this.set = function(value) {
        this.slider.value = "" + value;
        this.textInput.value = "" + value;
        this.callback(value);
    };
};

yoob.makeRangeControl = function(container, config) {
    var label = config.label;
    var min_ = config['min'];
    var max_ = config['max'];
    var value = config.value || min_;
    var callback = config.callback || function(v) {};
    var textInputSize = config.textInputSize || 5;
    var withButtons = config.withButtons === false ? false : true;

    yoob.makeSpan(container, label);
    var slider = yoob.makeSlider(container, min_, max_, value);
    var s = "" + value;
    var textInput = yoob.makeTextInput(container, textInputSize, s);
    slider.onchange = function(e) {
        textInput.value = slider.value;
        callback(parseInt(slider.value, 10));
    };
    textInput.onchange = function(e) {
        var v = parseInt(textInput.value, 10);
        if (!isNaN(v)) {
            slider.value = "" + v;
            callback(v);
        }
    };
    var incButton;
    var decButton;
    if (withButtons) {
        decButton = yoob.makeButton(container, "-", function() {
            var v = parseInt(textInput.value, 10);
            if ((!isNaN(v)) && v > min_) {
                v--;
                textInput.value = "" + v;
                slider.value = "" + v;
                callback(v);
            }
        });
        incButton = yoob.makeButton(container, "+", function() {
            var v = parseInt(textInput.value, 10);
            if ((!isNaN(v)) && v < max_) {
                v++;
                textInput.value = "" + v;
                slider.value = "" + v;
                callback(v);
            }
        });
    }
    return new RangeControl().init({
        'slider': slider,
        'incButton': incButton,
        'decButton': decButton,
        'textInput': textInput,
        'callback': callback
    });
};

yoob.makeSVG = function(container) {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    /* <svg viewBox = "0 0 200 200" version = "1.1"> */
    container.appendChild(svg);
    return svg;
};

yoob.makeSVGElem = function(svg, tag, cfg) {
    var elem = document.createElementNS(svg.namespaceURI, tag);
    Object.keys(cfg).forEach(function(key) {
        elem.setAttribute(key, cfg[key]);
    });
    svg.appendChild(elem);
    return elem;
};
<|endoftext|>


<commit_before>/*
 * This file is part of yoob.js version 0.7-PRE
 * Available from https://github.com/catseye/yoob.js/
 * This file is in the public domain.  See http://unlicense.org/ for details.
 */
if (window.yoob === undefined) yoob = {};

/*
 * Functions for creating elements.
 *
 * I dunno -- maybe just setting innerHTML would be better.
 */

yoob.makeCanvas = function(container, width, height) {
    var canvas = document.createElement('canvas');
    if (width) {
        canvas.width = width;
    }
    if (height) {
        canvas.height = height;
    }
    container.appendChild(canvas);
    return canvas;
};

yoob.makeButton = function(container, labelText) {
    var button = document.createElement('button');
    button.innerHTML = labelText;
    container.appendChild(button);
    return button;
};

yoob.checkBoxNumber = 0;
yoob.makeCheckbox = function(container, checked, labelText, fun) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = 'cfzzzb_' + yoob.checkBoxNumber;
    checkbox.checked = checked;
    var label = document.createElement('label');
    label.htmlFor = 'cfzzzb_' + yoob.checkBoxNumber;
    yoob.checkBoxNumber += 1;
    label.appendChild(document.createTextNode(labelText));

    container.appendChild(checkbox);
    container.appendChild(label);

    if (fun) {
        checkbox.onchange = function(e) {
            fun(checkbox.checked);
        }
    }
    return checkbox;
};

yoob.makeSlider = function(container, min, max, value) {
    var slider = document.createElement('input');
    slider.type = "range";
    slider.min = min;
    slider.max = max;
    slider.value = value;
    container.appendChild(slider);
    return slider;
};

yoob.makeParagraph = function(container, innerHTML) {
    var p = document.createElement('p');
    p.innerHTML = innerHTML;
    container.appendChild(p);
    return p;
};

yoob.makeTextArea = function(container, cols, rows, initial) {
    var textarea = document.createElement('textarea');
    textarea.rows = "" + rows;
    textarea.cols = "" + cols;
    if (initial) {
        container.value = initial;
    }
    container.appendChild(textarea);
    return textarea;
};

yoob.makeLineBreak = function(container) {
    var br = document.createElement('br');
    container.appendChild(br);
    return br;
};

yoob.makeSelect = function(container, labelText, optionsArray) {
    var label = document.createElement('label');
    label.innerHTML = labelText;
    container.appendChild(label);

    var select = document.createElement("select");

    for (var i = 0; i < optionsArray.length; i++) {
        var op = document.createElement("option");
        op.value = optionsArray[i][0];
        op.text = optionsArray[i][1];
        if (optionsArray[i].length > 2) {
            op.selected = optionsArray[i][2];
        } else {
            op.selected = false;
        }
        select.options.add(op);
    }

    container.appendChild(select);
    return select;
};
<commit_msg>Updates to element-factory.js.<commit_after>/*
 * This file is part of yoob.js version 0.7-PRE
 * Available from https://github.com/catseye/yoob.js/
 * This file is in the public domain.  See http://unlicense.org/ for details.
 */
if (window.yoob === undefined) yoob = {};

/*
 * Functions for creating elements.
 *
 * I dunno -- maybe just setting innerHTML would be better.
 */

yoob.makeCanvas = function(container, width, height) {
    var canvas = document.createElement('canvas');
    if (width) {
        canvas.width = width;
    }
    if (height) {
        canvas.height = height;
    }
    container.appendChild(canvas);
    return canvas;
};

yoob.makeButton = function(container, labelText, fun) {
    var button = document.createElement('button');
    button.innerHTML = labelText;
    container.appendChild(button);
    if (fun) {
        button.onclick = fun;
    }
    return button;
};

yoob.checkBoxNumber = 0;
yoob.makeCheckbox = function(container, checked, labelText, fun) {
    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = 'cfzzzb_' + yoob.checkBoxNumber;
    checkbox.checked = checked;
    var label = document.createElement('label');
    label.htmlFor = 'cfzzzb_' + yoob.checkBoxNumber;
    yoob.checkBoxNumber += 1;
    label.appendChild(document.createTextNode(labelText));

    container.appendChild(checkbox);
    container.appendChild(label);

    if (fun) {
        checkbox.onchange = function(e) {
            fun(checkbox.checked);
        }
    }
    return checkbox;
};

yoob.makeSlider = function(container, min, max, value) {
    var slider = document.createElement('input');
    slider.type = "range";
    slider.min = min;
    slider.max = max;
    slider.value = value;
    container.appendChild(slider);
    return slider;
};

yoob.makeParagraph = function(container, innerHTML) {
    var p = document.createElement('p');
    p.innerHTML = innerHTML || '';
    container.appendChild(p);
    return p;
};

yoob.makeSpan = function(container, innerHTML) {
    var span = document.createElement('span');
    span.innerHTML = innerHTML || '';
    container.appendChild(span);
    return span;
};

yoob.makeDiv = function(container, innerHTML) {
    var div = document.createElement('div');
    div.innerHTML = innerHTML || '';
    container.appendChild(div);
    return div;
};

yoob.makeTextArea = function(container, cols, rows, initial) {
    var textarea = document.createElement('textarea');
    textarea.rows = "" + rows;
    textarea.cols = "" + cols;
    if (initial) {
        container.value = initial;
    }
    container.appendChild(textarea);
    return textarea;
};

yoob.makeLineBreak = function(container) {
    var br = document.createElement('br');
    container.appendChild(br);
    return br;
};

yoob.makeSelect = function(container, labelText, optionsArray) {
    var label = document.createElement('label');
    label.innerHTML = labelText;
    container.appendChild(label);

    var select = document.createElement("select");

    for (var i = 0; i < optionsArray.length; i++) {
        var op = document.createElement("option");
        op.value = optionsArray[i][0];
        op.text = optionsArray[i][1];
        if (optionsArray[i].length > 2) {
            op.selected = optionsArray[i][2];
        } else {
            op.selected = false;
        }
        select.options.add(op);
    }

    container.appendChild(select);
    return select;
};
<|endoftext|>