<commit_before>const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;

const ContentObjectModel = imports.search.contentObjectModel;
const Engine = imports.search.engine;
const EosKnowledgePrivate = imports.gi.EosKnowledgePrivate;

function transform_v1_description(json) {
    let modules = {};

    switch (json.templateType) {
    case 'A':
        modules['window'] = {
            type: 'Window',
            properties: {
                'title': json['appTitle'],
                'background-image-uri': json['backgroundHomeURI'],
                'blur-background-image-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.4,
                'max-fraction': 0.7,
            },
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-search'] = {
            type: 'SearchBox',
        };
        modules['home-card'] = {
            type: 'CardA',
        };
        modules['results-title-card'] = {
            type: 'SetBannerCard',
        };
        modules['results-search-banner'] = {
            type: 'SearchBanner',
        };
        modules['results-card'] = {
            type: 'CardA',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
        };
        break;
    case 'B':
        modules['window'] = {
            type: 'Window',
            properties: {
                'title': json['appTitle'],
                'background-image-uri': json['backgroundHomeURI'],
                'blur-background-image-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.4,
                'max-fraction': 0.7,
                'visible': true,
                'can-focus': false,
            },
        };
        modules['home-page-item-group'] = {
            type: 'ItemGroup',
            properties: {
                'expand': true,
                'halign': Gtk.Align.FILL,
                'valign': Gtk.Align.FILL,
            },
            slots: {
                arrangement: 'home-page-arrangement',
            },
        };
        modules['home-page-template'] = {
            type: 'HomePageBTemplate',
            slots: {
                top_left: "app-banner",
                top_right: "home-search",
                bottom: "home-page-item-group",
            }
        };
        modules['home-page-arrangement'] = {
            type: 'TiledGridArrangement',
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-search'] = {
            type: 'SearchBox',
            properties: {
                'width_request': 350,
                'visible': true,
                'shadow_type': Gtk.ShadowType.NONE,
                'halign': Gtk.Align.CENTER,
                'valign': Gtk.Align.CENTER,
            }
        };
        modules['home-card'] = {
            type: 'CardB',
        };
        modules['results-title-card'] = {
            type: 'SetBannerCard',
        };
        modules['results-search-banner'] = {
            type: 'SearchBanner',
        };
        modules['results-arrangement'] = {
            type: 'ListArrangement',
        };
        modules['results-card'] = {
            type: 'TextCard',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
        };
        break;
    case 'encyclopedia':
        modules['window'] = {
            type: 'EncyclopediaWindow',
            properties: {
                'title': json['appTitle'],
                'home-background-uri': json['backgroundHomeURI'],
                'results-background-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.5,
                'max-fraction': 0.5,
                'margin-bottom': 42,
            },
        };
        modules['home-search'] = {
            type: 'SearchBox',
            properties: {
                'max-width-chars': 52,
            }
        };
        modules['article-app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.2,
                'max-fraction': 0.2,
                'margin-top': 10,
                'margin-bottom': 10,
            },
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
            properties: {
                'expand': true,
            },
        };
        modules['search-results'] = {
            type: 'SearchModule',
        };
        modules['results-card'] = {
            type: 'TextCard',
            properties: {
                'underline-on-hover': true,
                'decoration': true,
            },
        };
        // FIXME: this should be a submodule of search-results, in the
        // "arrangement" slot, when we get submodules implemented in the factory
        modules['results-arrangement'] = {
            type: 'ListArrangement',
        };
        break;
    case 'reader':
        modules['window'] = {
            type: 'ReaderWindow',
            properties: {
                'title': json['appTitle'],
                'subtitle': json['appSubtitle'],
                'title-image-uri': json['titleImageURI'],
                'home-background-uri': json['backgroundHomeURI'],
                'done-background-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
            },
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-card'] = {
            type: 'ArticleSnippetCard',
        };
        modules['document-card'] = {
            type: 'ReaderDocumentCard',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['results-card'] = {
            type: 'ReaderCard',
            properties: {
                'title-capitalization': EosKnowledgePrivate.TextTransform.UPPERCASE,
            },
        };
        break;
    default:
        throw new Error('Unrecognized v1 preset type: ' + json.templateType);
    }

    return { 'modules': modules };
}

function create_v1_set_models(json, engine) {
    if (!json.hasOwnProperty('sections'))
        return;

    let sections = json['sections'];
    delete json['sections'];
    sections.forEach((section) => {
        if (!section.hasOwnProperty('thumbnailURI'))
            log("WARNING: Missing category thumbnail for " + section['title']);

        let domain = engine.default_domain;
        let sha = GLib.compute_checksum_for_string(GLib.ChecksumType.SHA1,
            'category' + domain + section['title'], -1);
        let id = 'ekn://' + domain + '/' + sha;
        let tags = section['tags'].slice();
        tags.push(Engine.HOME_PAGE_TAG);

        let model = new ContentObjectModel.ContentObjectModel({
            ekn_id: id,
            title: section['title'],
            thumbnail_uri: section['thumbnailURI'],
            featured: !!section['featured'],
            tags: tags,
        });
        engine.add_runtime_object(id, model);
    });
}

// External links used to be prepended with 'browser-', this strips them off.
function normalize_old_browser_urls (url) {
    let scheme = GLib.uri_parse_scheme(uri);
    if (scheme !== null && scheme.startsWith('browser-'))
        uri = uri.slice('browser-'.length);
    return uri;
}
<commit_msg>Use correct variable name<commit_after>const GLib = imports.gi.GLib;
const Gtk = imports.gi.Gtk;

const ContentObjectModel = imports.search.contentObjectModel;
const Engine = imports.search.engine;
const EosKnowledgePrivate = imports.gi.EosKnowledgePrivate;

function transform_v1_description(json) {
    let modules = {};

    switch (json.templateType) {
    case 'A':
        modules['window'] = {
            type: 'Window',
            properties: {
                'title': json['appTitle'],
                'background-image-uri': json['backgroundHomeURI'],
                'blur-background-image-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.4,
                'max-fraction': 0.7,
            },
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-search'] = {
            type: 'SearchBox',
        };
        modules['home-card'] = {
            type: 'CardA',
        };
        modules['results-title-card'] = {
            type: 'SetBannerCard',
        };
        modules['results-search-banner'] = {
            type: 'SearchBanner',
        };
        modules['results-card'] = {
            type: 'CardA',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
        };
        break;
    case 'B':
        modules['window'] = {
            type: 'Window',
            properties: {
                'title': json['appTitle'],
                'background-image-uri': json['backgroundHomeURI'],
                'blur-background-image-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.4,
                'max-fraction': 0.7,
                'visible': true,
                'can-focus': false,
            },
        };
        modules['home-page-item-group'] = {
            type: 'ItemGroup',
            properties: {
                'expand': true,
                'halign': Gtk.Align.FILL,
                'valign': Gtk.Align.FILL,
            },
            slots: {
                arrangement: 'home-page-arrangement',
            },
        };
        modules['home-page-template'] = {
            type: 'HomePageBTemplate',
            slots: {
                top_left: "app-banner",
                top_right: "home-search",
                bottom: "home-page-item-group",
            }
        };
        modules['home-page-arrangement'] = {
            type: 'TiledGridArrangement',
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-search'] = {
            type: 'SearchBox',
            properties: {
                'width_request': 350,
                'visible': true,
                'shadow_type': Gtk.ShadowType.NONE,
                'halign': Gtk.Align.CENTER,
                'valign': Gtk.Align.CENTER,
            }
        };
        modules['home-card'] = {
            type: 'CardB',
        };
        modules['results-title-card'] = {
            type: 'SetBannerCard',
        };
        modules['results-search-banner'] = {
            type: 'SearchBanner',
        };
        modules['results-arrangement'] = {
            type: 'ListArrangement',
        };
        modules['results-card'] = {
            type: 'TextCard',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
        };
        break;
    case 'encyclopedia':
        modules['window'] = {
            type: 'EncyclopediaWindow',
            properties: {
                'title': json['appTitle'],
                'home-background-uri': json['backgroundHomeURI'],
                'results-background-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.5,
                'max-fraction': 0.5,
                'margin-bottom': 42,
            },
        };
        modules['home-search'] = {
            type: 'SearchBox',
            properties: {
                'max-width-chars': 52,
            }
        };
        modules['article-app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
                'min-fraction': 0.2,
                'max-fraction': 0.2,
                'margin-top': 10,
                'margin-bottom': 10,
            },
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['document-card'] = {
            type: 'KnowledgeDocumentCard',
            properties: {
                'expand': true,
            },
        };
        modules['search-results'] = {
            type: 'SearchModule',
        };
        modules['results-card'] = {
            type: 'TextCard',
            properties: {
                'underline-on-hover': true,
                'decoration': true,
            },
        };
        // FIXME: this should be a submodule of search-results, in the
        // "arrangement" slot, when we get submodules implemented in the factory
        modules['results-arrangement'] = {
            type: 'ListArrangement',
        };
        break;
    case 'reader':
        modules['window'] = {
            type: 'ReaderWindow',
            properties: {
                'title': json['appTitle'],
                'subtitle': json['appSubtitle'],
                'title-image-uri': json['titleImageURI'],
                'home-background-uri': json['backgroundHomeURI'],
                'done-background-uri': json['backgroundSectionURI'],
            },
        };
        modules['app-banner'] = {
            type: 'AppBanner',
            properties: {
                'image-uri': json['titleImageURI'],
            },
        };
        modules['top-bar-search'] = {
            type: 'SearchBox',
        };
        modules['home-card'] = {
            type: 'ArticleSnippetCard',
        };
        modules['document-card'] = {
            type: 'ReaderDocumentCard',
        };
        modules['lightbox-card'] = {
            type: 'MediaCard',
        };
        modules['results-card'] = {
            type: 'ReaderCard',
            properties: {
                'title-capitalization': EosKnowledgePrivate.TextTransform.UPPERCASE,
            },
        };
        break;
    default:
        throw new Error('Unrecognized v1 preset type: ' + json.templateType);
    }

    return { 'modules': modules };
}

function create_v1_set_models(json, engine) {
    if (!json.hasOwnProperty('sections'))
        return;

    let sections = json['sections'];
    delete json['sections'];
    sections.forEach((section) => {
        if (!section.hasOwnProperty('thumbnailURI'))
            log("WARNING: Missing category thumbnail for " + section['title']);

        let domain = engine.default_domain;
        let sha = GLib.compute_checksum_for_string(GLib.ChecksumType.SHA1,
            'category' + domain + section['title'], -1);
        let id = 'ekn://' + domain + '/' + sha;
        let tags = section['tags'].slice();
        tags.push(Engine.HOME_PAGE_TAG);

        let model = new ContentObjectModel.ContentObjectModel({
            ekn_id: id,
            title: section['title'],
            thumbnail_uri: section['thumbnailURI'],
            featured: !!section['featured'],
            tags: tags,
        });
        engine.add_runtime_object(id, model);
    });
}

// External links used to be prepended with 'browser-', this strips them off.
function normalize_old_browser_urls (uri) {
    let scheme = GLib.uri_parse_scheme(uri);
    if (scheme !== null && scheme.startsWith('browser-'))
        uri = uri.slice('browser-'.length);
    return uri;
}
<|endoftext|>


<commit_before>
/* Dasca, an idle game by @CylonicRaider (github.com/CylonicRaider/dasca)
 * Game implementation */

'use strict';

/* *** Utilities *** */

function $id(id, elem) {
  return (elem || document).getElementById(id);
}
function $sel(sel, elem) {
  return (elem || document).querySelector(sel);
}
function $selAll(sel, elem) {
  return (elem || document).querySelectorAll(sel);
}

/* Create a DOM element */
function $makeNode(tag, className, attrs, children) {
  /* Allow omitting parameters */
  if (Array.isArray(className)) {
    if (! attrs && ! children) {
      children = className;
      attrs = null;
      className = null;
    }
  } else if (typeof className == "object" && className != null) {
    if (! children) {
      children = attrs;
      attrs = className;
      className = null;
    }
  } else if (Array.isArray(attrs) || typeof attrs == "string") {
    if (! children) {
      children = attrs;
      attrs = null;
    }
  }
  /* Create node */
  var ret = document.createElement(tag);
  /* Set classes */
  if (className) ret.className = className;
  /* Set additional attributes */
  if (attrs) {
    for (var name in attrs) {
      if (! attrs.hasOwnProperty(name)) continue;
      ret.setAttribute(name, attrs[name]);
    }
  }
  /* Add children */
  if (children) {
    if (typeof children == "string") children = [children];
    for (var i = 0; i < children.length; i++) {
      var e = children[i];
      if (! e) {
        /* Allow conditional node omission */
      } else if (typeof e == "string") {
        /* Strings become text nodes */
        ret.appendChild(document.createTextNode(e));
      } else if (typeof e != "object") {
        /* Other primitive types are not allowed */
        throw new Error("Bad child encountered during DOM node creation");
      } else if (Array.isArray(e)) {
        /* Arrays are handled recursively */
        ret.appendChild($makeNode.apply(null, e));
      } else {
        /* Everything else is assumed to be a DOM node */
        ret.appendChild(e);
      }
    }
  }
  return ret;
}

/* Show the given UI element, hiding any siblings and showing all its
 * showable parents */
function showNode(node) {
  if (! node) return;
  /* Resolve ID-s */
  if (typeof node == "string") node = $id(node);
  /* Hide siblings */
  var prev = node.previousElementSibling, next = node.nextElementSibling;
  while (prev) {
    if (prev.classList.contains("selectable"))
      prev.classList.remove("selected");
    prev = prev.previousElementSibling;
  }
  while (next) {
    if (next.classList.contains("selectable"))
      next.classList.remove("selected");
    next = next.nextElementSibling;
  }
  /* Show parent */
  showNode(node.parentNode);
  /* Show node */
  if (node.classList && node.classList.contains("selectable"))
      node.classList.add("selected");
}

/* Hide all selectable children of node
 * Approximate opposite of showNode. */
function hideNodes(node) {
  if (! node) return;
  /* Resolve ID-s */
  if (typeof node == "string") node = $id("node");
  /* Hide children */
  for (var ch = node.firstElementChild; ch; ch = ch.nextElementSibling) {
    if (ch.classList.contains("selectable"))
      ch.classList.remove("selected");
  }
}

/* *** Game mechanics *** */

/* A value changing over time
 * A variable has a value, and a set of handlers which are invoked on every
 * update of it that return increments which are applied to the variable
 * cumulatively.
 * Handlers are objects whose "cb" method is called with three parameters:
 * variable: The Variable object.
 * delta   : The time difference since the last update.
 * now     : The current time.
 * The return values are differences whose sum is added to the value of the
 * variable after each update.
 * If the handler has a rate property, the callback is not invoked, and
 * the change is instead calculated as the product of the time passed and
 * the rate. */
function Variable(value) {
  this.value = value;
  this.handlers = [];
  this.lastUpdate = null;
}

Variable.prototype = {
  /* Aggregate the results of the handlers' return values and increment the
   * value by them. */
  update: function(now) {
    if (this.lastUpdate == null) this.lastUpdate = now;
    var delta = now - this.lastUpdate, incr = 0, hnd = this.handlers;
    for (var i = 0; i < hnd.length; i++) {
      if (hdn[i].rate != null) {
        incr += hnd[i].rate * delta;
      } else {
        incr += hnd[i].cb(this, delta, now);
      }
    }
    this.value += incr;
  },

  /* OOP */
  constructor: Variable
};

/* The main game object */
function Game(state) {
  this._env = Object.create(window);
  this._env.game = this;
  if (state == null) {
    this.state = new GameState(this);
  } else {
    this.state = deserialize(state, this._env);
  }
  this.ui = new GameUI(this);
  this.running = true;
}

Game.prototype = {
  /* Mount the game into the given node */
  mount: function(node) {
    this.ui.mount(node);
  },

  /* Start the game */
  start: function() {
    var intro = [[["i", null, "Darkness."], 1],
                 [["i", null, "Silence."], 3],
                 [["i", null, "Confinement."], 5],
                 [["i", null, "Amnesia."], 8]];
    intro.forEach(function(x) {
      this.addTask(x[1], "game", "showMessage", [x[0]]);
    }, this);
  },

  /* Get the value of a flag */
  getFlag: function(name) {
    return this.state.flags[name];
  },

  /* Set a flag; return whether the value changed */
  setFlag: function(name) {
    var old = this.state.flags[name];
    this.state.flags[name] = true;
    return (! old);
  },

  /* Clear a flag; return whether the value changes */
  clearFlag: function(name) {
    var old = this.state.flags[name];
    this.state.flags[name] = false;
    return (!! old);
  },

  /* Schedule an Action to be run */
  addTask: function(delay, subject, method, args) {
    var task = new Action(subject, method, args, this._env);
    this.state.scheduler.addTaskIn(task, delay);
  },

  /* Show a log message */
  showMessage: function(msg) {
    this.state.messages.push(msg);
    this.ui._showMessage(msg);
  },

  /* Stop running the game */
  exit: function() {
    this.running = false;
  },

  /* OOP */
  constructor: Game
};

/* The (serializable) state of a game
 * The constructor creates a new state; for restoring a saved one, use the
 * deserialization function (in a suitable environment, which is created by
 * the constructor of Game). */
function GameState(game) {
  this.scheduler = Scheduler.makeStrobe(100);
  this.flags = {};
  this.messages = [];
  this._game = game;
}

GameState.prototype = {
  /* OOP */
  constructor: GameState,

  /* Deserialization */
  __restore__: function(obj, env) {
    var ret = Object.create(GameState);
    for (var key in obj) {
      if (! /^_/.test(key) && obj.hasOwnProperty(key)) ret[key] = obj[key];
    }
    ret._game = env.game;
    return ret;
  }
};

/* The DOM-based user interface of the game */
function GameUI(game) {
  this.game = game;
  this.root = null;
  this.parent = null;
}

GameUI.prototype = {
  /* Produce the DOM tree corresponding to this object */
  render: function() {
    if (this.root == null) {
      this.root = $makeNode("div", {id: "game-content"}, [
        ["div", "row row-all", [
          ["div", "col col-quarter inset", [
            ["div", {id: "messagebar"}]
          ]],
          ["div", "col col-all", [
            ["div", "row row-small inset", {id: "tabbar"}],
            ["div", "row row-all inset", {id: "mainpane"}]
          ]]
        ]],
        ["div", "row row-small inset", {id: "bottombar"}, [
          ["button", "btn btn-small dim", {id: "credits-game"}, "Credits"],
          ["div", "col col-all"],
          ["button", "btn btn-small", {id: "exit-game"}, "Exit"]
        ]]
      ]);
      $sel("#exit-game", this.root).addEventListener("click", function() {
        this.game.exit();
        showNode("titlescreen");
      }.bind(this));
      $sel("#credits-game", this.root).addEventListener("click", function() {
        showNode("creditscreen");
      });
      if (this.game.state.messages.length) {
        var m = this.game.state.messages;
        for (var i = 0; i < m.length; i++)
          this._showMessage(m[i]);
      }
    }
    return this.root;
  },

  /* Embed the game's UI into the given DOM node
   * If not already done, the UI is constructed. */
  mount: function(parent) {
    this.parent = parent;
    parent.appendChild(this.render());
  },

  /* Message showing backend */
  _showMessage: function(text) {
    var msgnode = $makeNode("p", "log-message", [text]);
    var msgbar = $sel("#messagebar", this.root);
    msgbar.appendChild(msgnode);
    msgbar.scrollTop = msgbar.scrollHeight;
  },

  /* Consistency */
  constructor: GameUI
};

/* *** Initialization *** */

function init() {
  var game = null;
  $id("startgame").addEventListener("click", function() {
    game = new Game();
    game.mount($id("mainscreen"));
    game.start();
    showNode("mainscreen");
  });
  $id("credits-title").addEventListener("click", function() {
    showNode("creditscreen");
  });
  $id("back-credits").addEventListener("click", function() {
    if (game && game.running) {
      showNode("mainscreen");
    } else {
      showNode("titlescreen");
    }
  });
  showNode("titlescreen");
}

window.addEventListener("load", init);
<commit_msg>Make addTask() more convenient<commit_after>
/* Dasca, an idle game by @CylonicRaider (github.com/CylonicRaider/dasca)
 * Game implementation */

'use strict';

/* *** Utilities *** */

function $id(id, elem) {
  return (elem || document).getElementById(id);
}
function $sel(sel, elem) {
  return (elem || document).querySelector(sel);
}
function $selAll(sel, elem) {
  return (elem || document).querySelectorAll(sel);
}

/* Create a DOM element */
function $makeNode(tag, className, attrs, children) {
  /* Allow omitting parameters */
  if (Array.isArray(className)) {
    if (! attrs && ! children) {
      children = className;
      attrs = null;
      className = null;
    }
  } else if (typeof className == "object" && className != null) {
    if (! children) {
      children = attrs;
      attrs = className;
      className = null;
    }
  } else if (Array.isArray(attrs) || typeof attrs == "string") {
    if (! children) {
      children = attrs;
      attrs = null;
    }
  }
  /* Create node */
  var ret = document.createElement(tag);
  /* Set classes */
  if (className) ret.className = className;
  /* Set additional attributes */
  if (attrs) {
    for (var name in attrs) {
      if (! attrs.hasOwnProperty(name)) continue;
      ret.setAttribute(name, attrs[name]);
    }
  }
  /* Add children */
  if (children) {
    if (typeof children == "string") children = [children];
    for (var i = 0; i < children.length; i++) {
      var e = children[i];
      if (! e) {
        /* Allow conditional node omission */
      } else if (typeof e == "string") {
        /* Strings become text nodes */
        ret.appendChild(document.createTextNode(e));
      } else if (typeof e != "object") {
        /* Other primitive types are not allowed */
        throw new Error("Bad child encountered during DOM node creation");
      } else if (Array.isArray(e)) {
        /* Arrays are handled recursively */
        ret.appendChild($makeNode.apply(null, e));
      } else {
        /* Everything else is assumed to be a DOM node */
        ret.appendChild(e);
      }
    }
  }
  return ret;
}

/* Show the given UI element, hiding any siblings and showing all its
 * showable parents */
function showNode(node) {
  if (! node) return;
  /* Resolve ID-s */
  if (typeof node == "string") node = $id(node);
  /* Hide siblings */
  var prev = node.previousElementSibling, next = node.nextElementSibling;
  while (prev) {
    if (prev.classList.contains("selectable"))
      prev.classList.remove("selected");
    prev = prev.previousElementSibling;
  }
  while (next) {
    if (next.classList.contains("selectable"))
      next.classList.remove("selected");
    next = next.nextElementSibling;
  }
  /* Show parent */
  showNode(node.parentNode);
  /* Show node */
  if (node.classList && node.classList.contains("selectable"))
      node.classList.add("selected");
}

/* Hide all selectable children of node
 * Approximate opposite of showNode. */
function hideNodes(node) {
  if (! node) return;
  /* Resolve ID-s */
  if (typeof node == "string") node = $id("node");
  /* Hide children */
  for (var ch = node.firstElementChild; ch; ch = ch.nextElementSibling) {
    if (ch.classList.contains("selectable"))
      ch.classList.remove("selected");
  }
}

/* *** Game mechanics *** */

/* A value changing over time
 * A variable has a value, and a set of handlers which are invoked on every
 * update of it that return increments which are applied to the variable
 * cumulatively.
 * Handlers are objects whose "cb" method is called with three parameters:
 * variable: The Variable object.
 * delta   : The time difference since the last update.
 * now     : The current time.
 * The return values are differences whose sum is added to the value of the
 * variable after each update.
 * If the handler has a rate property, the callback is not invoked, and
 * the change is instead calculated as the product of the time passed and
 * the rate. */
function Variable(value) {
  this.value = value;
  this.handlers = [];
  this.lastUpdate = null;
}

Variable.prototype = {
  /* Aggregate the results of the handlers' return values and increment the
   * value by them. */
  update: function(now) {
    if (this.lastUpdate == null) this.lastUpdate = now;
    var delta = now - this.lastUpdate, incr = 0, hnd = this.handlers;
    for (var i = 0; i < hnd.length; i++) {
      if (hdn[i].rate != null) {
        incr += hnd[i].rate * delta;
      } else {
        incr += hnd[i].cb(this, delta, now);
      }
    }
    this.value += incr;
  },

  /* OOP */
  constructor: Variable
};

/* The main game object */
function Game(state) {
  this._env = Object.create(window);
  this._env.game = this;
  if (state == null) {
    this.state = new GameState(this);
  } else {
    this.state = deserialize(state, this._env);
  }
  this.ui = new GameUI(this);
  this.running = true;
}

Game.prototype = {
  /* Mount the game into the given node */
  mount: function(node) {
    this.ui.mount(node);
  },

  /* Start the game */
  start: function() {
    var intro = [[["i", null, "Darkness."], 1],
                 [["i", null, "Silence."], 3],
                 [["i", null, "Confinement."], 5],
                 [["i", null, "Amnesia."], 8]];
    intro.forEach(function(x) {
      this.addTask(x[1], "showMessage", x[0]);
    }, this);
  },

  /* Get the value of a flag */
  getFlag: function(name) {
    return this.state.flags[name];
  },

  /* Set a flag; return whether the value changed */
  setFlag: function(name) {
    var old = this.state.flags[name];
    this.state.flags[name] = true;
    return (! old);
  },

  /* Clear a flag; return whether the value changes */
  clearFlag: function(name) {
    var old = this.state.flags[name];
    this.state.flags[name] = false;
    return (!! old);
  },

  /* Schedule an Action to be run */
  addTaskEx: function(delay, subject, method, args) {
    var task = new Action(subject, method, args, this._env);
    return this.state.scheduler.addTaskIn(task, delay);
  },

  /* Convenience wrapper for addTaskEx()
   * Arguments are passed variadically. */
  addTask: function(delay, method) {
    var m = ("game." + method).match(/^(.+)\.([^.]+)$/);
    var args = Array.prototype.slice.call(arguments, 2);
    return this.addTaskEx(delay, m[1], m[2], args);
  },

  /* Show a log message */
  showMessage: function(msg) {
    this.state.messages.push(msg);
    this.ui._showMessage(msg);
  },

  /* Stop running the game */
  exit: function() {
    this.running = false;
  },

  /* OOP */
  constructor: Game
};

/* The (serializable) state of a game
 * The constructor creates a new state; for restoring a saved one, use the
 * deserialization function (in a suitable environment, which is created by
 * the constructor of Game). */
function GameState(game) {
  this.scheduler = Scheduler.makeStrobe(100);
  this.flags = {};
  this.messages = [];
  this._game = game;
}

GameState.prototype = {
  /* OOP */
  constructor: GameState,

  /* Deserialization */
  __restore__: function(obj, env) {
    var ret = Object.create(GameState);
    for (var key in obj) {
      if (! /^_/.test(key) && obj.hasOwnProperty(key)) ret[key] = obj[key];
    }
    ret._game = env.game;
    return ret;
  }
};

/* The DOM-based user interface of the game */
function GameUI(game) {
  this.game = game;
  this.root = null;
  this.parent = null;
}

GameUI.prototype = {
  /* Produce the DOM tree corresponding to this object */
  render: function() {
    if (this.root == null) {
      this.root = $makeNode("div", {id: "game-content"}, [
        ["div", "row row-all", [
          ["div", "col col-quarter inset", [
            ["div", {id: "messagebar"}]
          ]],
          ["div", "col col-all", [
            ["div", "row row-small inset", {id: "tabbar"}],
            ["div", "row row-all inset", {id: "mainpane"}]
          ]]
        ]],
        ["div", "row row-small inset", {id: "bottombar"}, [
          ["button", "btn btn-small dim", {id: "credits-game"}, "Credits"],
          ["div", "col col-all"],
          ["button", "btn btn-small", {id: "exit-game"}, "Exit"]
        ]]
      ]);
      $sel("#exit-game", this.root).addEventListener("click", function() {
        this.game.exit();
        showNode("titlescreen");
      }.bind(this));
      $sel("#credits-game", this.root).addEventListener("click", function() {
        showNode("creditscreen");
      });
      if (this.game.state.messages.length) {
        var m = this.game.state.messages;
        for (var i = 0; i < m.length; i++)
          this._showMessage(m[i]);
      }
    }
    return this.root;
  },

  /* Embed the game's UI into the given DOM node
   * If not already done, the UI is constructed. */
  mount: function(parent) {
    this.parent = parent;
    parent.appendChild(this.render());
  },

  /* Message showing backend */
  _showMessage: function(text) {
    var msgnode = $makeNode("p", "log-message", [text]);
    var msgbar = $sel("#messagebar", this.root);
    msgbar.appendChild(msgnode);
    msgbar.scrollTop = msgbar.scrollHeight;
  },

  /* Consistency */
  constructor: GameUI
};

/* *** Initialization *** */

function init() {
  var game = null;
  $id("startgame").addEventListener("click", function() {
    game = new Game();
    game.mount($id("mainscreen"));
    game.start();
    showNode("mainscreen");
  });
  $id("credits-title").addEventListener("click", function() {
    showNode("creditscreen");
  });
  $id("back-credits").addEventListener("click", function() {
    if (game && game.running) {
      showNode("mainscreen");
    } else {
      showNode("titlescreen");
    }
  });
  showNode("titlescreen");
}

window.addEventListener("load", init);
<|endoftext|>


<commit_before>var fontSize = 15;
var width = 1400;
var height = 750;

var tree = d3.layout.tree()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(40,0)");

d3.json("progress.json", function(error, json) {
    var nodes = tree.nodes(json),
    links = tree.links(nodes);

    var link = svg.selectAll("path.link")
	.data(links)
	.enter().append("path")
	.attr("class", "link")
	.attr("d", diagonal);

    var node = svg.selectAll("g.node")
	.data(nodes)
	.enter().append("g")
	.attr("class", "node")
	.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

    //node.append("circle")
    //.attr("r", function(d) { return fontSize / 2.5 * d.name.length; });
    node.append("rect").attr("x", 0).attr("y", -1*fontSize).attr("width", 50).attr("height", 2*fontSize).attr("rx", 10).attr("ry", 10);

    node.append("text")
	.attr("font-size", fontSize + "px")
	.attr("dx", function(d) { return -2 * d.name.length; })
	.attr("dy", 3)  // centered vertically
	.attr("text-anchor", "middle")
	.text(function(d) { return d.name; });
});

d3.select(self.frameElement).style("height", height + "px");
<commit_msg>text is centered<commit_after>var fontSize = 15;
var width = 1400;
var height = 750;

var tree = d3.layout.tree()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(40,0)");  // translate everting to the right in order to not cut off text

d3.json("progress.json", function(error, json) {
    var nodes = tree.nodes(json),
    links = tree.links(nodes);

    var link = svg.selectAll("path.link")
	.data(links)
	.enter().append("path")
	.attr("class", "link")
	.attr("d", diagonal);

    var node = svg.selectAll("g.node")
	.data(nodes)
	.enter().append("g")
	.attr("class", "node")
	.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

    node.append("rect")
	.attr("x", function(d) { return fontSize * -0.5 * d.name.length;})
	.attr("y", -1*fontSize)  // roughly center around text
	.attr("width", function(d) { return fontSize * d.name.length;})
	.attr("height", 2*fontSize)
	.attr("rx", 10)
	.attr("ry", 10);

    node.append("text")
	.attr("font-size", fontSize + "px")
	.attr("dx", function(d) { return -2 * d.name.length; })
	.attr("dy", 3)  // centered vertically
	.attr("text-anchor", "middle")
	.text(function(d) { return d.name; });
});

d3.select(self.frameElement).style("height", height + "px");
<|endoftext|>


<commit_before>window.onload = function() {
  StartBackground();
  CameraInit();
};

var mediaConstraints = { audio: !!navigator.mozGetUserMedia, video: true };
var index = 1;
var mediaRecorder;
var video;
var stream;

function CameraInit() {
  navigator.getUserMedia(mediaConstraints, onMediaInit, onMediaError);
}

function startRecording() {
  var videosContainer = document.getElementById("source");
  videosContainer.appendChild(video);
  videosContainer.appendChild(document.createElement('hr'));
  video.play();
  mediaRecorder = new MediaStreamRecorder(stream);
  mediaRecorder.mimeType = 'video/webm'; // this line is mandatory
  mediaRecorder.videoWidth  = 320;
  mediaRecorder.videoHeight = 240;
  mediaRecorder.ondataavailable = function(blob) {
    var video = document.getElementById("videodata");
    video.src = URL.createObjectURL(blob);
    video.play();
  };
  console.log(mediaRecorder);

  var timeInterval = 10 * 1000;
  timeInterval = parseInt(timeInterval);
  // get blob after specific time interval
  setTimeout(function() {
    video.pause();
    mediaRecorder.stop();
  }, timeInterval);
  mediaRecorder.start(timeInterval);
}

//
function onMediaInit(Stream) {
  video = document.getElementById('videodata');
  video.src = URL.createObjectURL(Stream);
  console.log(video);
  video.height = 240;
  video.width = 320;
  video.autoplay = "true";
  stream = Stream;
}

//
function onMediaError(e) {
  console.error('media error', e);
}

// below function via: http://goo.gl/B3ae8c
function bytesToSize(bytes) {
 var k = 1000;
 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
 if (bytes === 0) return '0 Bytes';
 var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)),10);
 return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

// below function via: http://goo.gl/6QNDcI
function getTimeLength(milliseconds) {
  var data = new Date(milliseconds);
  return data.getUTCHours()+" hours, "+data.getUTCMinutes()+" minutes and "+data.getUTCSeconds()+" second(s)";
}

// Timer global variables.
var count;
var timer;

// Video global variables.
var oggSupported = false;
var webmSupported = false;
var mp4Supported = false;
var isPlaying = false;
var videoExt = "";
var isBackgroundVideo = true;

/**
 * Draws animation frame based on browser.
 */
function draw() {
  if (window.requestAnimationFrame) window.requestAnimationFrame(draw);
  // IE implementation
  else if (window.msRequestAnimationFrame) window.msRequestAnimationFrame(draw);
  // Firefox implementation
  else if (window.mozRequestAnimationFrame) window.mozRequestAnimationFrame(draw);
  // Chrome implementation
  else if (window.webkitRequestAnimationFrame) window.webkitRequestAnimationFrame(draw);
  // Other browsers that do not yet support feature
  else setTimeout(draw, 16.7);
  DrawVideoOnCanvas();
}

/**
 * Start countdown timer.
 */
function handleTimer() {
  if (count === 0) {
    clearInterval(timer);
    document.getElementById("countdown").innerHTML = "Recording";
    play();
  } else {
    var text = "Starting in " + count + "...";
    document.getElementById("countdown").innerHTML = text;
    count--;
  }
}

function inRange(x, lower, upper) {
  return (x > lower) && (x < upper);
}

/**
 * Start the photo booth.
 */
function Start() {
  // Remove start button.
  var boothStartBtn = document.getElementById("boothStart");
  if (boothStart.parentNode) {
    boothStart.parentNode.removeChild(boothStart);
  }

  // Hide background preview.
  document.getElementById("backgroundvideo").style.display = "none";

  // Start timer.
  count = 3;
  timer = setInterval(function() { handleTimer(count); }, 1000);
}

/**
 * Start recording video.
 */
function play() {
  document.getElementById("videodata").play();
  document.getElementById("videoBackgrounddata").play();
  startRecording();
  isPlaying = true;
  draw();
}

/**
 * Apply green screen effects to canvas.
 */
function DrawVideoOnCanvas() {
  var object = document.getElementById("videodata");

  var backgroundObject;
  if (isBackgroundVideo) {
    backgroundObject = document.getElementById("videoBackgrounddata");
  } else {
    backgroundObject = document.getElementById("imageBackgrounddata");
  }
  var width = object.width;
  var height = object.height;
  var canvas = document.getElementById("videoscreen");
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  if (canvas.getContext) {
    var context = canvas.getContext('2d');
    context.drawImage(backgroundObject, 0, 0, width, height);
    var imgBackgroundData = context.getImageData(0, 0, width, height);
    context.drawImage(object, 0, 0, width, height);
    imgDataNormal = context.getImageData(0, 0, width, height);
    var imgData = context.createImageData(width, height);

    var r;
    var g;
    var b;
    var a;
    for (i = 0; i < imgData.width * imgData.height * 4; i += 4) {
      r = imgDataNormal.data[i + 0];
      g = imgDataNormal.data[i + 1];
      b = imgDataNormal.data[i + 2];
      a = imgDataNormal.data[i + 3];
      // compare rgb levels for green and set alphachannel to 0;
      if (inRange(r, 0, 50) && inRange(b, 0, 150) &&
          inRange(g, 100, 240)) {
          a = 0;
      }
      if (a !== 0) {
          imgData.data[i + 0] = r;
          imgData.data[i + 1] = g;
          imgData.data[i + 2] = b;
          imgData.data[i + 3] = a;
      }
    }

    for (var y = 0; y < imgData.height; y++) {
      for (var x = 0; x < imgData.width; x++) {
          r = imgData.data[((imgData.width * y) + x) * 4];
          g = imgData.data[((imgData.width * y) + x) * 4 + 1];
          b = imgData.data[((imgData.width * y) + x) * 4 + 2];
          a = imgData.data[((imgData.width * y) + x) * 4 + 3];
          if (imgData.data[((imgData.width * y) + x) * 4 + 3] !== 0) {
              offsetYup = y - 1;
              offsetYdown = y + 1;
              offsetXleft = x - 1;
              offsetxRight = x + 1;
              var change=false;
              if (offsetYup>0) {
                if (imgData.data[((imgData.width * (y-1) ) + (x)) * 4 + 3] === 0) {
                    change=true;
                }
              }
              if (offsetYdown < imgData.height) {
                if (imgData.data[((imgData.width * (y + 1)) + (x)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (offsetXleft > -1) {
                if (imgData.data[((imgData.width * y) + (x -1)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (offsetxRight < imgData.width) {
                if (imgData.data[((imgData.width * y) + (x + 1)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (change) {
                  var gray = (imgData.data[((imgData.width * y) + x) * 4 + 0] * 0.393) + (imgData.data[((imgData.width * y) + x) * 4 + 1] * 0.769) + (imgData.data[((imgData.width * y) + x) * 4 + 2] * 0.189);
                  imgData.data[((imgData.width * y) + x) * 4] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4] *0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 1] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4 + 1]*0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 2] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4 + 2] * 0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 3] = 255;
              }
          }

      }
    }

    for (i = 0; i < imgData.width * imgData.height * 4; i += 4) {
      r = imgData.data[i + 0];
      g = imgData.data[i + 1];
      b = imgData.data[i + 2];
      a = imgData.data[i + 3];
      if (a === 0) {
        imgData.data[i + 0] = imgBackgroundData.data[i + 0];
        imgData.data[i + 1] = imgBackgroundData.data[i + 1];
        imgData.data[i + 2] = imgBackgroundData.data[i + 2];
        imgData.data[i + 3] = imgBackgroundData.data[i + 3];
      }
    }
    context.putImageData(imgData, 0, 0);
  }
}

/**
 * Determine supported video formats.
 */
function SupportedVideoFormat() {
  var video = document.createElement("video");
  if (video.canPlayType('video/ogg; codecs="theora, vorbis"')) {
    oggSupported = true;
  }
  if (video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
    mp4Supported = true;
  }
  if (video.canPlayType('video/webm; codecs="vp8, vorbis"')) {
    webmSupported = true;
  }
}

/**
 * Start background video.
 */
function StartBackground() {
  SupportedVideoFormat();
  if (oggSupported) videoExt = ".ogv";
  if (webmSupported) videoExt = ".webm";
  if (mp4Supported) videoExt = ".mp4";
  loadBackgroundVideo();
}

/**
 * Load background videos into dom.
 */
function loadBackgroundVideo() {
  var value = "";
  var radioObj = document.getElementsByName("background");
  if (!radioObj) return "";
  var radioLength = radioObj.length;
  if (radioLength === undefined) {
    if (radioObj.checked) {
      value = radioObj.value;
    } else {
      value= "";
    }
  }
  for (var i = 0; i < radioLength; i++) {
    if (radioObj[i].checked) {
      value = radioObj[i].value;
    }
  }

  var backgroundType= value.split("/");
  if (backgroundType[0] == "videos") {
    isBackgroundVideo = true;
    var bgVideo = document.getElementById("videoBackgrounddata");
    bgVideo.src = value + videoExt;
    bgVideo.loop = true;
    document.getElementById("videoBackgrounddata").play();
  } else {
    isBackgroundVideo = false;
    document.getElementById("backgroundvideo").style.display = "none";
    document.getElementById("imageBackgrounddata").src = value;
  }
}
/***** SONG STUFF **/
/***** SONG STUFF **/
/***** SONG STUFF **/
var songList = new Array();
songList[0] = [
                "audio/callmemaybe.ogg"
                ];
songList[1] = [
                "audio/lazysong.ogg"
                ];
songList[2] = [
                "audio/single_ladies.ogg"
             ];
songList[3] = [
                "audio/sweet_escape.ogg"
                ];

function selectSong() {
  console.log("x");
/*    var x = document.getElementById("select").selectedIndex;
    console.log(x); */
    var theAudio = document.getElementById("audio1");
    if (document.getElementById('s1').checked) {
      theAudio.src = "audio/callmemaybe.ogg";
       console.log("y");
    }
    else if (document.getElementById('s2').checked) {
      theAudio.src = "audio/lazysong.ogg";
    }
    else if (document.getElementById('s3').checked) {
      theAudio.src = "audio/single_ladies.ogg";
    }
    else if (document.getElementById('s4').checked) {
      theAudio.src = "audio/sweet_escape.ogg";
    }
 /*   if (x == 0) {
        /*theAudio.src = songList[0];
        theAudio.src = "audio/callmemaybe.ogg";
    }
    else if (x == 1) {
      theAudio.src = "audio/lazysong.ogg";
       theAudio.src = songList[1];
   }
    else if (x == 2) {
      theAudio.src = "audio/single_ladies.ogg";
        theAudio.src = songList[2];
    }
    else if (x == 3) {
      theAudio.src = "audio/sweet_escape.ogg";
      /*  theAudio.src = songList[3];
    }
    console.log(theAudio.src); */
    theAudio.play();

}
<commit_msg>Remove audio access<commit_after>window.onload = function() {
  StartBackground();
  CameraInit();
};

var mediaConstraints = { video: true };
var index = 1;
var mediaRecorder;
var video;
var stream;

function CameraInit() {
  navigator.getUserMedia(mediaConstraints, onMediaInit, onMediaError);
}

function startRecording() {
  var videosContainer = document.getElementById("source");
  videosContainer.appendChild(video);
  videosContainer.appendChild(document.createElement('hr'));
  video.play();
  mediaRecorder = new MediaStreamRecorder(stream);
  mediaRecorder.mimeType = 'video/webm'; // this line is mandatory
  mediaRecorder.videoWidth  = 320;
  mediaRecorder.videoHeight = 240;
  mediaRecorder.ondataavailable = function(blob) {
    var video = document.getElementById("videodata");
    video.src = URL.createObjectURL(blob);
    video.play();
  };
  console.log(mediaRecorder);

  var timeInterval = 10 * 1000;
  timeInterval = parseInt(timeInterval);
  // get blob after specific time interval
  setTimeout(function() {
    video.pause();
    mediaRecorder.stop();
  }, timeInterval);
  mediaRecorder.start(timeInterval);
}

//
function onMediaInit(Stream) {
  video = document.getElementById('videodata');
  video.src = URL.createObjectURL(Stream);
  console.log(video);
  video.height = 240;
  video.width = 320;
  video.autoplay = "true";
  stream = Stream;
}

//
function onMediaError(e) {
  console.error('media error', e);
}

// below function via: http://goo.gl/B3ae8c
function bytesToSize(bytes) {
 var k = 1000;
 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
 if (bytes === 0) return '0 Bytes';
 var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)),10);
 return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

// below function via: http://goo.gl/6QNDcI
function getTimeLength(milliseconds) {
  var data = new Date(milliseconds);
  return data.getUTCHours()+" hours, "+data.getUTCMinutes()+" minutes and "+data.getUTCSeconds()+" second(s)";
}

// Timer global variables.
var count;
var timer;

// Video global variables.
var oggSupported = false;
var webmSupported = false;
var mp4Supported = false;
var isPlaying = false;
var videoExt = "";
var isBackgroundVideo = true;

/**
 * Draws animation frame based on browser.
 */
function draw() {
  if (window.requestAnimationFrame) window.requestAnimationFrame(draw);
  // IE implementation
  else if (window.msRequestAnimationFrame) window.msRequestAnimationFrame(draw);
  // Firefox implementation
  else if (window.mozRequestAnimationFrame) window.mozRequestAnimationFrame(draw);
  // Chrome implementation
  else if (window.webkitRequestAnimationFrame) window.webkitRequestAnimationFrame(draw);
  // Other browsers that do not yet support feature
  else setTimeout(draw, 16.7);
  DrawVideoOnCanvas();
}

/**
 * Start countdown timer.
 */
function handleTimer() {
  if (count === 0) {
    clearInterval(timer);
    document.getElementById("countdown").innerHTML = "Recording";
    play();
  } else {
    var text = "Starting in " + count + "...";
    document.getElementById("countdown").innerHTML = text;
    count--;
  }
}

function inRange(x, lower, upper) {
  return (x > lower) && (x < upper);
}

/**
 * Start the photo booth.
 */
function Start() {
  // Remove start button.
  var boothStartBtn = document.getElementById("boothStart");
  if (boothStart.parentNode) {
    boothStart.parentNode.removeChild(boothStart);
  }

  // Hide background preview.
  document.getElementById("backgroundvideo").style.display = "none";

  // Start timer.
  count = 3;
  timer = setInterval(function() { handleTimer(count); }, 1000);
}

/**
 * Start recording video.
 */
function play() {
  document.getElementById("videodata").play();
  document.getElementById("videoBackgrounddata").play();
  startRecording();
  isPlaying = true;
  draw();
}

/**
 * Apply green screen effects to canvas.
 */
function DrawVideoOnCanvas() {
  var object = document.getElementById("videodata");

  var backgroundObject;
  if (isBackgroundVideo) {
    backgroundObject = document.getElementById("videoBackgrounddata");
  } else {
    backgroundObject = document.getElementById("imageBackgrounddata");
  }
  var width = object.width;
  var height = object.height;
  var canvas = document.getElementById("videoscreen");
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  if (canvas.getContext) {
    var context = canvas.getContext('2d');
    context.drawImage(backgroundObject, 0, 0, width, height);
    var imgBackgroundData = context.getImageData(0, 0, width, height);
    context.drawImage(object, 0, 0, width, height);
    imgDataNormal = context.getImageData(0, 0, width, height);
    var imgData = context.createImageData(width, height);

    var r;
    var g;
    var b;
    var a;
    for (i = 0; i < imgData.width * imgData.height * 4; i += 4) {
      r = imgDataNormal.data[i + 0];
      g = imgDataNormal.data[i + 1];
      b = imgDataNormal.data[i + 2];
      a = imgDataNormal.data[i + 3];
      // compare rgb levels for green and set alphachannel to 0;
      if (inRange(r, 0, 50) && inRange(b, 0, 150) &&
          inRange(g, 100, 240)) {
          a = 0;
      }
      if (a !== 0) {
          imgData.data[i + 0] = r;
          imgData.data[i + 1] = g;
          imgData.data[i + 2] = b;
          imgData.data[i + 3] = a;
      }
    }

    for (var y = 0; y < imgData.height; y++) {
      for (var x = 0; x < imgData.width; x++) {
          r = imgData.data[((imgData.width * y) + x) * 4];
          g = imgData.data[((imgData.width * y) + x) * 4 + 1];
          b = imgData.data[((imgData.width * y) + x) * 4 + 2];
          a = imgData.data[((imgData.width * y) + x) * 4 + 3];
          if (imgData.data[((imgData.width * y) + x) * 4 + 3] !== 0) {
              offsetYup = y - 1;
              offsetYdown = y + 1;
              offsetXleft = x - 1;
              offsetxRight = x + 1;
              var change=false;
              if (offsetYup>0) {
                if (imgData.data[((imgData.width * (y-1) ) + (x)) * 4 + 3] === 0) {
                    change=true;
                }
              }
              if (offsetYdown < imgData.height) {
                if (imgData.data[((imgData.width * (y + 1)) + (x)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (offsetXleft > -1) {
                if (imgData.data[((imgData.width * y) + (x -1)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (offsetxRight < imgData.width) {
                if (imgData.data[((imgData.width * y) + (x + 1)) * 4 + 3] === 0) {
                  change = true;
                }
              }
              if (change) {
                  var gray = (imgData.data[((imgData.width * y) + x) * 4 + 0] * 0.393) + (imgData.data[((imgData.width * y) + x) * 4 + 1] * 0.769) + (imgData.data[((imgData.width * y) + x) * 4 + 2] * 0.189);
                  imgData.data[((imgData.width * y) + x) * 4] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4] *0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 1] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4 + 1]*0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 2] = (gray * 0.2) + (imgBackgroundData.data[((imgData.width * y) + x) * 4 + 2] * 0.9);
                  imgData.data[((imgData.width * y) + x) * 4 + 3] = 255;
              }
          }

      }
    }

    for (i = 0; i < imgData.width * imgData.height * 4; i += 4) {
      r = imgData.data[i + 0];
      g = imgData.data[i + 1];
      b = imgData.data[i + 2];
      a = imgData.data[i + 3];
      if (a === 0) {
        imgData.data[i + 0] = imgBackgroundData.data[i + 0];
        imgData.data[i + 1] = imgBackgroundData.data[i + 1];
        imgData.data[i + 2] = imgBackgroundData.data[i + 2];
        imgData.data[i + 3] = imgBackgroundData.data[i + 3];
      }
    }
    context.putImageData(imgData, 0, 0);
  }
}

/**
 * Determine supported video formats.
 */
function SupportedVideoFormat() {
  var video = document.createElement("video");
  if (video.canPlayType('video/ogg; codecs="theora, vorbis"')) {
    oggSupported = true;
  }
  if (video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
    mp4Supported = true;
  }
  if (video.canPlayType('video/webm; codecs="vp8, vorbis"')) {
    webmSupported = true;
  }
}

/**
 * Start background video.
 */
function StartBackground() {
  SupportedVideoFormat();
  if (oggSupported) videoExt = ".ogv";
  if (webmSupported) videoExt = ".webm";
  if (mp4Supported) videoExt = ".mp4";
  loadBackgroundVideo();
}

/**
 * Load background videos into dom.
 */
function loadBackgroundVideo() {
  var value = "";
  var radioObj = document.getElementsByName("background");
  if (!radioObj) return "";
  var radioLength = radioObj.length;
  if (radioLength === undefined) {
    if (radioObj.checked) {
      value = radioObj.value;
    } else {
      value= "";
    }
  }
  for (var i = 0; i < radioLength; i++) {
    if (radioObj[i].checked) {
      value = radioObj[i].value;
    }
  }

  var backgroundType= value.split("/");
  if (backgroundType[0] == "videos") {
    isBackgroundVideo = true;
    var bgVideo = document.getElementById("videoBackgrounddata");
    bgVideo.src = value + videoExt;
    bgVideo.loop = true;
    document.getElementById("videoBackgrounddata").play();
  } else {
    isBackgroundVideo = false;
    document.getElementById("backgroundvideo").style.display = "none";
    document.getElementById("imageBackgrounddata").src = value;
  }
}
/***** SONG STUFF **/
/***** SONG STUFF **/
/***** SONG STUFF **/
var songList = new Array();
songList[0] = [
                "audio/callmemaybe.ogg"
                ];
songList[1] = [
                "audio/lazysong.ogg"
                ];
songList[2] = [
                "audio/single_ladies.ogg"
             ];
songList[3] = [
                "audio/sweet_escape.ogg"
                ];

function selectSong() {
  console.log("x");
/*    var x = document.getElementById("select").selectedIndex;
    console.log(x); */
    var theAudio = document.getElementById("audio1");
    if (document.getElementById('s1').checked) {
      theAudio.src = "audio/callmemaybe.ogg";
       console.log("y");
    }
    else if (document.getElementById('s2').checked) {
      theAudio.src = "audio/lazysong.ogg";
    }
    else if (document.getElementById('s3').checked) {
      theAudio.src = "audio/single_ladies.ogg";
    }
    else if (document.getElementById('s4').checked) {
      theAudio.src = "audio/sweet_escape.ogg";
    }
 /*   if (x == 0) {
        /*theAudio.src = songList[0];
        theAudio.src = "audio/callmemaybe.ogg";
    }
    else if (x == 1) {
      theAudio.src = "audio/lazysong.ogg";
       theAudio.src = songList[1];
   }
    else if (x == 2) {
      theAudio.src = "audio/single_ladies.ogg";
        theAudio.src = songList[2];
    }
    else if (x == 3) {
      theAudio.src = "audio/sweet_escape.ogg";
      /*  theAudio.src = songList[3];
    }
    console.log(theAudio.src); */
    theAudio.play();

}
<|endoftext|>


<commit_before>var titleInput = $('.title-input-js');
var descriptionInput = $('.description-input-js');
var saveButton = $('.save-button');
var qualityValue = ['Swill', 'Plausible', 'Genius'];
var qualityKey = {
  0: ' Swill',
  1: ' Plausible',
  2: ' Genius'
}

$(document).ready(function(){
  renderIdeas();
});

function createNewIdea() {
  var title = titleInput.val();
  var description = descriptionInput.val();
  var id = Date.now();
  var quality = this.quality;
  var details = JSON.stringify({
    'id': id, 'title': title,
    'description': description,
    'quality': qualityValue[0],
    'counter': 0
  });
  localStorage.setItem(id, details);
};

function clearInputs() {
  titleInput.val('');
  descriptionInput.val('');
}

function clearIdeas() {
  $('ul').empty();
}

function renderIdeas(qualityStuff) {
  for (var i in window.localStorage){
    var idea = JSON.parse(localStorage.getItem(i));
    var title = idea['title'];
    var description = idea['description'];
    var quality = qualityKey[idea['counter']];
    var id = idea['id'];
    var counter = idea['counter'];
    renderTheIdea(id, title, description, quality, counter);
  }
}

function renderTheIdea(id, title, description, quality, counter) {
  $('ul').prepend(
    '
' +
      '
' +
      '
' + title + '
' +
      '<button class="delete-button" type=button></button>' +
      '
' +
      '
' + description + '
' +
      '
' +
      '<button class="upvote-button" type=button data-id=' + counter + '></button>' +
      '<button class="downvote-button" type=button data-id=' + counter + '></button>' +
      '
' + 'Ranking:' + '' + quality + '' + '
' +
      '
' +
    '
');
};

saveButton.on('click', function () {
  createNewIdea();
  clearIdeas();
  renderIdeas();
  clearInputs();
});

$('ul').on('click', '.delete-button', function () {
    var id = parseInt(this.closest('li').id);
    localStorage.removeItem(id);
    $(this).parent().parent().remove('li');
  });

$('ul').on('click', '.upvote-button', function () {
  var qualityOutput = $(this).parent().parent('li').find('.quality-value');
  var newCounter = $(this).data("id");
  if ( newCounter < 2) {
    newCounter = (newCounter+1);
    $(this).attr('id', newCounter)
    debugger
    qualityOutput.replaceWith(
      '' + qualityKey[`${newCounter}`] + ''
    );
  }

  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({
    'id': id,
    'title': title,
    'description': description,
    'quality': quality,
    'counter': newCounter
  });
  localStorage.setItem(id, details);
  clearIdeas();
  renderIdeas();
});

$('ul').on('click', '.downvote-button', function() {
  var qualityOutput = $(this).parent().parent('li').find('.quality-value');
  var newCounter = $(this).data("id");
  if ( newCounter > 0) {
    newCounter = (newCounter-1);
    $(this).attr('id', newCounter)
    qualityOutput.replaceWith(
      '' + qualityKey[`${newCounter}`] + ''
    );
  }

  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({
    'id': id,
    'title': title,
    'description': description,
    'quality': quality,
    'counter': newCounter
  });
  localStorage.setItem(id, details);
  clearIdeas();
  renderIdeas();
});

$('#search-bar').keyup(function () {
    var filter = $(this).val();
    $('li').each(function () {
        if ($(this).text().search(new RegExp(filter, 'i')) < 0) {
            $(this).hide();
        } else {
            $(this).show()
        }
    });
});

function updateTitle() {
  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({'id': id, 'title': title, 'description': description, 'quality': quality});
  localStorage.setItem(id, details);
};

$('ul').on('focusout', '.idea-title', function () {
  debugger;
  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({
    'id': id,
    'title': title,
    'description': description,
    'quality': quality,
    'counter': newCounter
  });
  localStorage.setItem(id, details);
  reRenderDOM();
});

function getIdea(id) {
  return JSON.parse(localStorage.getItem(id));
}

function storeIdea(id, idea) {
  localStorage.setItem(id, JSON.stringify(idea));
}

$('ul').on('focusout', '.idea-description', function () {
  var id = parseInt(this.closest('li').id);
  var description = $(this).parent('li').find('.idea-description').text();
  var currentIdea = getIdea(id);
  currentIdea.description = description
  storeIdea(id, currentIdea);
  reRenderDOM();
});

function reRenderDOM() {
  clearIdeas();
  renderIdeas();
}
<commit_msg>basically done<commit_after>var titleInput = $('.title-input-js');
var descriptionInput = $('.description-input-js');
var saveButton = $('.save-button');
var qualityValue = ['Swill', 'Plausible', 'Genius'];
var qualityKey = {
  0: ' Swill',
  1: ' Plausible',
  2: ' Genius'
}

$(document).ready(function(){
  renderIdeas();
});

function createNewIdea() {
  var title = titleInput.val();
  var description = descriptionInput.val();
  var id = Date.now();
  var quality = this.quality;
  var details = JSON.stringify({
    'id': id, 'title': title,
    'description': description,
    'quality': qualityValue[0],
    'counter': 0
  });
  localStorage.setItem(id, details);
};

function clearInputs() {
  titleInput.val('');
  descriptionInput.val('');
}

function clearIdeas() {
  $('ul').empty();
}

function renderIdeas(qualityStuff) {
  for (var i in window.localStorage){
    var idea = JSON.parse(localStorage.getItem(i));
    var title = idea['title'];
    var description = idea['description'];
    var quality = qualityKey[idea['counter']];
    var id = idea['id'];
    var counter = idea['counter'];
    renderTheIdea(id, title, description, quality, counter);
  }
}

function renderTheIdea(id, title, description, quality, counter) {
  $('ul').prepend(
    '
' +
      '
' +
      '
' + title + '
' +
      '<button class="delete-button" type=button></button>' +
      '
' +
      '
' + description + '
' +
      '
' +
      '<button class="upvote-button" type=button data-id=' + counter + '></button>' +
      '<button class="downvote-button" type=button data-id=' + counter + '></button>' +
      '
' + 'Ranking:' + '' + quality + '' + '
' +
      '
' +
    '
');
};

saveButton.on('click', function () {
  createNewIdea();
  clearIdeas();
  renderIdeas();
  clearInputs();
});

$('ul').on('click', '.delete-button', function () {
    var id = parseInt(this.closest('li').id);
    localStorage.removeItem(id);
    $(this).parent().parent().remove('li');
  });

$('ul').on('click', '.upvote-button', function () {
  var qualityOutput = $(this).parent().parent('li').find('.quality-value');
  var newCounter = $(this).data("id");
  if ( newCounter < 2) {
    newCounter = (newCounter+1);
    $(this).attr('id', newCounter)
    debugger
    qualityOutput.replaceWith(
      '' + qualityKey[`${newCounter}`] + ''
    );
  }

  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({
    'id': id,
    'title': title,
    'description': description,
    'quality': quality,
    'counter': newCounter
  });
  localStorage.setItem(id, details);
  clearIdeas();
  renderIdeas();
});

$('ul').on('click', '.downvote-button', function() {
  var qualityOutput = $(this).parent().parent('li').find('.quality-value');
  var newCounter = $(this).data("id");
  if ( newCounter > 0) {
    newCounter = (newCounter-1);
    $(this).attr('id', newCounter)
    qualityOutput.replaceWith(
      '' + qualityKey[`${newCounter}`] + ''
    );
  }

  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({
    'id': id,
    'title': title,
    'description': description,
    'quality': quality,
    'counter': newCounter
  });
  localStorage.setItem(id, details);
  clearIdeas();
  renderIdeas();
});

$('#search-bar').keyup(function () {
    var filter = $(this).val();
    $('li').each(function () {
        if ($(this).text().search(new RegExp(filter, 'i')) < 0) {
            $(this).hide();
        } else {
            $(this).show()
        }
    });
});

function updateTitle() {
  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var description = $(this).parent().parent('li').find('.idea-description').text();
  var quality = $(this).parent().parent('li').find('.quality-value').text();
  var details = JSON.stringify({'id': id, 'title': title, 'description': description, 'quality': quality});
  localStorage.setItem(id, details);
};

function getIdea(id) {
  return JSON.parse(localStorage.getItem(id));
}

function storeIdea(id, idea) {
  localStorage.setItem(id, JSON.stringify(idea));
}

$('ul').on('focusout', '.idea-title', function () {
  var id = parseInt(this.closest('li').id);
  var title = $(this).parent().parent('li').find('.idea-title').text();
  var currentIdea = getIdea(id);
  currentIdea.title = title
  storeIdea(id, currentIdea);
  reRenderDOM();
});

$('ul').on('focusout', '.idea-description', function () {
  var id = parseInt(this.closest('li').id);
  var description = $(this).parent('li').find('.idea-description').text();
  var currentIdea = getIdea(id);
  currentIdea.description = description
  storeIdea(id, currentIdea);
  reRenderDOM();
});

function reRenderDOM() {
  clearIdeas();
  renderIdeas();
}
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import images from '../utils/images';
import messages from '../utils/messages';

import CordovaPreview from './basic_components/cordova-preview-component';
import DefaultPreview from './basic_components/default-preview-component';

const defaultFileTypes = ['image/jpeg', 'image/png', 'image/gif'];

class ImagePreview extends Component {
  static propTypes ={
    imageUrl: PropTypes.string,
    DefaultImage: PropTypes.oneOfType([
      PropTypes.func, PropTypes.object,
    ]),
    clearImageData: PropTypes.func,
    setImageUrl: PropTypes.func,
    onError: PropTypes.func,
    options: PropTypes.object,
    isCordova: PropTypes.bool,
    maxWidth: PropTypes.number,
    maxHeight: PropTypes.number,
    resize: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    if (props.options) {
      this.allowedFileTypes = props.options.allowedFileTypes
        || ['image/jpeg', 'image/png', 'image/gif'];
      this.acceptFileTypes = this.allowedFileTypes.join(',');
      this.multipleUpload = props.options.multipleUpload
        && !this.props.options.crop
        || false;
    } else {
      this.allowedFileTypes = defaultFileTypes;
    }
  }

  onFileChange = (e) => {
    const { files } = e.target;
    if (!files.length) {
      this.props.clearImageData();
    } else if (this.multipleUpload && files[0] instanceof File) {
      this.handleMultipleFiles(files);
    } else if (files.length === 1) {
      if (!(files[0] instanceof File)) {
        this.props.setImageUrl({ imageData: files[0], imageType: 'image/jpeg' });
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onloadend = () => {
          const { imageType } = this.checkFile(reader.result);
          if (!imageType) return;
          this.props.setImageUrl({ imageData: reader.result, imageType });
        };
      }
    }
    if (this.imageInput) this.imageInput.value = null;
  };

  handleCordovaImage = () => {
    const { resize } = this.props;
    let maxWidth;
    let maxHeight;
    if (resize) {
      maxWidth = this.props.maxWidth;
      maxHeight = this.props.maxHeight;
    }
    const onDeviceReady = () => {
      if (!navigator || !navigator.camera) {
        throw new Error('Camera plugin is not available');
      }
      navigator.camera.getPicture(
        (url) => this.onFileChange({ target: { files: [`data:image/jpeg;base64,${url}`] } }),
        (e) => console.error(e),
        {
          quality: 50,
          targetHeight: maxHeight || 1024,
          targetWidth: maxWidth || 1024,
          sourceType: window.Camera.PictureSourceType.SAVEDPHOTOALBUM,
          destinationType: window.Camera.DestinationType.DATA_URL,
          mediaType: window.Camera.MediaType.PICTURE,
          correctOrientation: true,
        }
      );
    };
    document.addEventListener('deviceready', onDeviceReady, false);
  };

  checkFile = (imageUrl) => {
    const { onError } = this.props;
    const imageType = images.getImageType(imageUrl);
    if (!~this.allowedFileTypes.indexOf(imageType)) {
      onError(
        `${messages['wrong_file_type']}${this.allowedFileTypes.join(', ')}`
      );
      return {};
    }
    return { imageType };
  };

  handleMultipleFiles = (files) => {
    const promisifiedImagesUrls = [];
    Array.prototype.forEach.call(files, (file) => {
      const promisifiedReader = new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = () => {
          const { imageType } = this.checkFile(reader.result);
          if (!imageType) reject('File type is not supported');
          resolve({ imageData: reader.result, imageType });
        };
      });
      promisifiedImagesUrls.push(promisifiedReader);
    });
    this.props.setImageUrl({ promisifiedImagesUrls });
  };

  render() {
    const { isCordova, imageUrl, DefaultImage, options, clearImageData } = this.props;
    const fullWidth = options && options.fullWidth;
    return (
      isCordova
        ? <CordovaPreview
          DefaultImage={DefaultImage}
          fullWidth={fullWidth}
          clearImageData={clearImageData}
          imageUrl={imageUrl}
          onImageSelect={this.handleCordovaImage}
        />
        : <DefaultPreview
          imageUrl={imageUrl}
          DefaultImage={DefaultImage}
          fullWidth={fullWidth}
          clearImageData={clearImageData}
          allowedFileTypes={this.allowedFileTypes}
          multipleUpload={this.multipleUpload}
          onFileChange={this.onFileChange}
          ref={(preview) => { if (preview) this.imageInput = preview.imageInput; }}
        />
    );
  }
}

export default ImagePreview;
<commit_msg>add callback for original image size checking<commit_after>import React, { PropTypes, Component } from 'react';
import images from '../utils/images';
import messages from '../utils/messages';

import CordovaPreview from './basic_components/cordova-preview-component';
import DefaultPreview from './basic_components/default-preview-component';

const defaultFileTypes = ['image/jpeg', 'image/png', 'image/gif'];

class ImagePreview extends Component {
  static propTypes ={
    imageUrl: PropTypes.string,
    DefaultImage: PropTypes.oneOfType([
      PropTypes.func, PropTypes.object,
    ]),
    onImageSizeGet: PropTypes.func,
    clearImageData: PropTypes.func,
    setImageUrl: PropTypes.func,
    onError: PropTypes.func,
    options: PropTypes.object,
    isCordova: PropTypes.bool,
    maxWidth: PropTypes.number,
    maxHeight: PropTypes.number,
    resize: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    if (props.options) {
      this.allowedFileTypes = props.options.allowedFileTypes
        || ['image/jpeg', 'image/png', 'image/gif'];
      this.acceptFileTypes = this.allowedFileTypes.join(',');
      this.multipleUpload = props.options.multipleUpload
        && !this.props.options.crop
        || false;
    } else {
      this.allowedFileTypes = defaultFileTypes;
    }
  }

  onFileChange = (e) => {
    const { onImageSizeGet, setImageUrl } = this.props;
    console.log(onImageSizeGet);
    const { files } = e.target;
    if (!files.length) {
      this.props.clearImageData();
    } else if (this.multipleUpload && files[0] instanceof File) {
      this.handleMultipleFiles(files);
    } else if (files.length === 1) {
      if (!(files[0] instanceof File)) {
        if (onImageSizeGet) {
          const image = new Image();
          image.src = files[0];
          image.onload = () => {
            onImageSizeGet({ width: image.width, height: image.height });
          };
        }
        setImageUrl({ imageData: files[0], imageType: 'image/jpeg' });
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onloadend = () => {
          const { imageType } = this.checkFile(reader.result);
          if (!imageType) return;
          if (onImageSizeGet) {
            const image = new Image();
            image.src = reader.result;
            image.onload = () => {
              onImageSizeGet({ width: image.width, height: image.height });
            };
          }
          setImageUrl({ imageData: reader.result, imageType });
        };
      }
    }
    if (this.imageInput) this.imageInput.value = null;
  };

  handleCordovaImage = () => {
    const { resize } = this.props;
    let maxWidth;
    let maxHeight;
    if (resize) {
      maxWidth = this.props.maxWidth;
      maxHeight = this.props.maxHeight;
    }
    const onDeviceReady = () => {
      if (!navigator || !navigator.camera) {
        throw new Error('Camera plugin is not available');
      }
      navigator.camera.getPicture(
        (url) => this.onFileChange({ target: { files: [`data:image/jpeg;base64,${url}`] } }),
        (e) => console.error(e),
        {
          quality: 50,
          targetHeight: maxHeight || 1024,
          targetWidth: maxWidth || 1024,
          sourceType: window.Camera.PictureSourceType.SAVEDPHOTOALBUM,
          destinationType: window.Camera.DestinationType.DATA_URL,
          mediaType: window.Camera.MediaType.PICTURE,
          correctOrientation: true,
        }
      );
    };
    document.addEventListener('deviceready', onDeviceReady, false);
  };

  checkFile = (imageUrl) => {
    const { onError } = this.props;
    const imageType = images.getImageType(imageUrl);
    if (!~this.allowedFileTypes.indexOf(imageType)) {
      onError(
        `${messages['wrong_file_type']}${this.allowedFileTypes.join(', ')}`
      );
      return {};
    }
    return { imageType };
  };

  handleMultipleFiles = (files) => {
    const { onImageSizeGet, setImageUrl } = this.props;
    const promisifiedImagesUrls = [];
    Array.prototype.forEach.call(files, (file) => {
      const promisifiedReader = new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = () => {
          const { imageType } = this.checkFile(reader.result);
          if (onImageSizeGet) {
            const image = new Image();
            image.src = reader.result;
            image.onload = () => {
              onImageSizeGet({ width: image.width, height: image.height });
            };
          }
          if (!imageType) reject('File type is not supported');
          resolve({ imageData: reader.result, imageType });
        };
      });
      promisifiedImagesUrls.push(promisifiedReader);
    });
    setImageUrl({ promisifiedImagesUrls });
  };

  render() {
    const { isCordova, imageUrl, DefaultImage, options, clearImageData } = this.props;
    const fullWidth = options && options.fullWidth;
    return (
      isCordova
        ? <CordovaPreview
          DefaultImage={DefaultImage}
          fullWidth={fullWidth}
          clearImageData={clearImageData}
          imageUrl={imageUrl}
          onImageSelect={this.handleCordovaImage}
        />
        : <DefaultPreview
          imageUrl={imageUrl}
          DefaultImage={DefaultImage}
          fullWidth={fullWidth}
          clearImageData={clearImageData}
          allowedFileTypes={this.allowedFileTypes}
          multipleUpload={this.multipleUpload}
          onFileChange={this.onFileChange}
          ref={(preview) => { if (preview) this.imageInput = preview.imageInput; }}
        />
    );
  }
}

export default ImagePreview;
<|endoftext|>


<commit_before>import Inquiry from '../db/models/inquiry'
import User from '../db/models/user'

export default {
  inquiryGet: (req, res, next) => {
    let userId = req.params.userId
    if (userId) {
      User.getUserById(userId)
        .then((user) => {
          if (user) {
            Inquiry.getAllInquiriesForTrippian(userId)
              .then((inquiries) => {
                console.log(inquiries)
                if(inquiries.length) {
                  res.json(inquiries)
                }
              })
          }
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryPost: (req, res, next) => {
    let postDetails = req.body
    let trippianId = parseInt(req.params.trippianId)
    let userId = req.body.userId
    if (postDetails) {
      Inquiry.createInquiry(userId, trippianId, postDetails)
        .then((createdInquiry) => {
          console.log(createdInquiry)
          res.json(createdInquiry)
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryPut: (req,res, next) => {
    let putDetails = req.body
    let inquiryId = req.params.inquiryId
    let accept = req.query.cat
    if (putDetails && inquiryId) { //update inquiry
      Inquiry.updateInquiry(putDetails, inquiryId)
        .then((updatedInquiry) => {
          console.log(updatedInquiry)
          res.json(updatedInquiry)
        })
        .catch((error) => {
          next (error)
        })
    }
    if (inquiryId && accept) { //trippian accepts
      Inquiry.acceptInquiry(inquiryId)
        .then((accepted) => {
          if (accepted) {
            Inquiry.deleteInquiry(inquiryId)
              .then((deleted) => {
                console.log(accepted)
                res.json(accepted)
              })
          }
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryDelete: (req, res, next ) => {
    let inquiryId = req.params.inquiryId
    if (inquiryId) {
      Inquiry.deleteInquiry(inquiryId)
        .then((deleted) => {
          console.log(deleted)
          res.json(deleted)
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  allInquiryGet: (req, res, next) => {
    Inquiry.getAllInquiries()
      .then(allInquiries => {
        console.log(allInquiries)
        res.json(allInquiries)
      })
      .catch(error => {
        next(error)
      })
  }
}<commit_msg>feat(server): update inquiry property<commit_after>import Inquiry from '../db/models/inquiry'
import User from '../db/models/user'

export default {
  inquiryGet: (req, res, next) => {
    let userId = req.params.userId
    if (userId) {
      User.getUserById(userId)
        .then((user) => {
          if (user) {
            Inquiry.getAllInquiriesForTrippian(userId)
              .then((inquiries) => {
                console.log(inquiries)
                if(inquiries.length) {
                  res.json(inquiries)
                }
              })
          }
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryPost: (req, res, next) => {
    let postDetails = req.body
    let trippianId = parseInt(req.params.trippianId)
    let sender = req.body.senderId
    if (postDetails) {
      Inquiry.createInquiry(sender, trippianId, postDetails)
        .then((createdInquiry) => {
          console.log(createdInquiry)
          res.json(createdInquiry)
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryPut: (req,res, next) => {
    let putDetails = req.body
    let inquiryId = req.params.inquiryId
    let accept = req.query.cat
    if (putDetails && inquiryId) { //update inquiry
      Inquiry.updateInquiry(putDetails, inquiryId)
        .then((updatedInquiry) => {
          console.log(updatedInquiry)
          res.json(updatedInquiry)
        })
        .catch((error) => {
          next (error)
        })
    }
    if (inquiryId && accept) { //trippian accepts
      Inquiry.acceptInquiry(inquiryId)
        .then((accepted) => {
          if (accepted) {
            Inquiry.deleteInquiry(inquiryId)
              .then((deleted) => {
                console.log(accepted)
                res.json(accepted)
              })
          }
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  inquiryDelete: (req, res, next ) => {
    let inquiryId = req.params.inquiryId
    if (inquiryId) {
      Inquiry.deleteInquiry(inquiryId)
        .then((deleted) => {
          console.log(deleted)
          res.json(deleted)
        })
        .catch((error) => {
          next(error)
        })
    }
  },
  allInquiryGet: (req, res, next) => {
    Inquiry.getAllInquiries()
      .then(allInquiries => {
        console.log(allInquiries)
        res.json(allInquiries)
      })
      .catch(error => {
        next(error)
      })
  }
}<|endoftext|>