<commit_before>var path = require('path'),
	os = require('os');

function baseDir(){
	if (os.platform() == 'win32'){
		var dir = path.join(process.env.SystemRoot || process.env.windir, 'Microsoft.NET');
		var isx64 = os.arch() == 'x64';
		return path.join(dir, isx64 ? 'Framework64' : 'Framework');
	}
	// TODO resolve mono dir
	throw new Error('not supported yet!');
}

function dir(framework){
	// TODO mono support
	var dir = baseDir();
	switch ((framework || '').toLowerCase()){
		case 'net-2.0':
		case '2.0':
		case 'v2.0':
			return path.join(dir, 'v2.0.50727');
		case 'net-3.5':
		case '3.5':
		case 'v3.5':
			return path.join(dir, 'v3.5');
		case 'net-4.0':
		case '4.0':
		case 'v4.0':
			return path.join(dir, 'v4.0.30319');
		default:
			return path.join(dir, 'v3.5');
	}
}

module.exports = {
	baseDir: baseDir,
	dir: dir
};
<commit_msg>using iswin<commit_after>var path = require('path'),
	os = require('os'),
	iswin = require('iswin');

function baseDir(){
	if (iswin()){
		var dir = path.join(process.env.SystemRoot || process.env.windir, 'Microsoft.NET');
		var isx64 = os.arch() == 'x64';
		return path.join(dir, isx64 ? 'Framework64' : 'Framework');
	}
	// TODO resolve mono dir
	throw new Error('not supported yet!');
}

function dir(framework){
	// TODO mono support
	var dir = baseDir();
	switch ((framework || '').toLowerCase()){
		case 'net-2.0':
		case '2.0':
		case 'v2.0':
			return path.join(dir, 'v2.0.50727');
		case 'net-3.5':
		case '3.5':
		case 'v3.5':
			return path.join(dir, 'v3.5');
		case 'net-4.0':
		case '4.0':
		case 'v4.0':
			return path.join(dir, 'v4.0.30319');
		default:
			return path.join(dir, 'v3.5');
	}
}

module.exports = {
	baseDir: baseDir,
	dir: dir
};
<|endoftext|>


<commit_before>var Q=require('q'),
	debug=require('debug')('xuexi:git:clone'),
	async=require('async'),
	merge=require('merge'),
	child_process=require('child_process'),
	run=require('comandante');

(function() {
    var childProcess = require("child_process");
    oldExec = childProcess.exec;
    function myExec() {
        debug('exec called');
        debug(arguments);
        var result = oldExec.apply(this, arguments);
        return result;
    }
    childProcess.exec = myExec;
})();

module.exports=function doClone(_options) {
	var defaultOptions = {
			targetDirectory:"/tmp"
		}, doClonePromise=Q.defer(), options = defaultOptions, repo=this.repo, _this=this;

	if( _options ) {
		debug("merging options");
		merge(options, _options);
		debug("merged options %j", options);
	}

	debug("repo %s %j", repo, options);

	if(!repo) {
		debug("repo not set");
		async.setImmediate(function onError() {
			debug("rejecting promise");
			doClonePromise.reject(new Error("missing required repo url"));
		});
		return doClonePromise.promise;
	}
	//if targetDirectory ends in a /, remove it
	debug("targetDirectory %s", options.targetDirectory);
	if( options.targetDirectory.match(/\/$/) ) {
		options.targetDirectory=options.targetDirectory.slice(0, options.targetDirectory.length-1);
	}
	// run git clone
	var repoMatch=repo.match(/.+\/(.*)/);
	if( !repoMatch ) {
		return doClonePromise.reject(new Error("repo string didn't match required format\n(http[s])|(git):\/\/([^\/]+)\/([^\/]+)\/(.+)(\.git)|()"));
	}
	var repoName=repoMatch[1];
  debug("repoMatch %j", repoMatch);
  _this.gitDir=options.targetDirectory+"/"+repoName;

  // pass env:{"GIT_TERMINAL_PROMPT":"0"} to disable all prompting
	var gc=run('git', ["clone", "https"+repo.match(/(:.*)/)[1]], {cwd:options.targetDirectory, env:{"GIT_TERMINAL_PROMPT":"0"}});
	gc.response="";
  gc.on('error', function onError(msg) {
    debug("child error: %j", msg);
    doClonePromise.reject(new Error(msg));
  });
	gc.on('data', function onData(data) {
		gc.response+=data;
	});
	gc.on('end', function onEnd(err) {
    if (err) {
      debug('exec error: %j\n%j', err, stderr);
      return doClonePromise.reject(new Error(err));
    }
    debug("clone done %j", _this);
    doClonePromise.resolve(_this.gitDir);
	});

	return doClonePromise.promise;
};
<commit_msg>refactored repo matching regex<commit_after>var Q=require('q'),
	debug=require('debug')('xuexi:git:clone'),
	async=require('async'),
	merge=require('merge'),
	child_process=require('child_process'),
	run=require('comandante');

(function() {
    var childProcess = require("child_process");
    oldExec = childProcess.exec;
    function myExec() {
        debug('exec called');
        debug(arguments);
        var result = oldExec.apply(this, arguments);
        return result;
    }
    childProcess.exec = myExec;
})();

module.exports=function doClone(_options) {
	var defaultOptions = {
			targetDirectory:"/tmp"
		}, doClonePromise=Q.defer(), options = defaultOptions, repo=this.repo, _this=this;

	if( _options ) {
		debug("merging options");
		merge(options, _options);
		debug("merged options %j", options);
	}

	debug("repo %s %j", repo, options);

	if(!repo) {
		debug("repo not set");
		async.setImmediate(function onError() {
			debug("rejecting promise");
			doClonePromise.reject(new Error("missing required repo url"));
		});
		return doClonePromise.promise;
	}
	//if targetDirectory ends in a /, remove it
	debug("targetDirectory %s", options.targetDirectory);
	if( options.targetDirectory.match(/\/$/) ) {
		options.targetDirectory=options.targetDirectory.slice(0, options.targetDirectory.length-1);
	}
	// run git clone
	var repoMatch=repo.match(/.+\/([^\.]*)/);
	if( !repoMatch ) {
		return doClonePromise.reject(new Error("repo string didn't match required format\n(http[s])|(git):\/\/([^\/]+)\/([^\/]+)\/(.+)(\.git)|()"));
	}
	var repoName=repoMatch[1];
  debug("repoMatch %j", repoMatch);
  _this.gitDir=options.targetDirectory+"/"+repoName;

  // pass env:{"GIT_TERMINAL_PROMPT":"0"} to disable all prompting
	var gc=run('git', ["clone", "https"+repo.match(/(:.*)/)[1]], {cwd:options.targetDirectory, env:{"GIT_TERMINAL_PROMPT":"0"}});
	gc.response="";
  gc.on('error', function onError(msg) {
    debug("child error: %j", msg);
    doClonePromise.reject(new Error(msg));
  });
	gc.on('data', function onData(data) {
		gc.response+=data;
	});
	gc.on('end', function onEnd(err) {
    if (err) {
      debug('exec error: %j\n%j', err, stderr);
      return doClonePromise.reject(new Error(err));
    }
    debug("clone done %j", _this);
    doClonePromise.resolve(_this.gitDir);
	});

	return doClonePromise.promise;
};
<|endoftext|>


<commit_before>'use strict';

const moment = require('moment');
const Promise = require('bluebird');
const pathFn = require('path');
const _ = require('lodash');
const yaml = require('js-yaml');
const util = require('hexo-util');
const fs = require('hexo-fs');
const yfm = require('hexo-front-matter');

const slugize = util.slugize;
const escapeRegExp = util.escapeRegExp;

const rEscapeContent = /<escape(?:[^>]*)>([\s\S]*?)<\/escape>/g;
const rSwigVar = /\{\{[\s\S]*?\}\}/g;
const rSwigComment = /\{#[\s\S]*?#\}/g;
const rSwigBlock = /\{%[\s\S]*?%\}/g;
const rSwigFullBlock = /\{% *(.+?)(?: *| +.*)%\}[\s\S]+?\{% *end\1 *%\}/g;
const placeholder = '\uFFFC';
const rPlaceholder = /(?:<|<)!--\uFFFC(\d+)--(?:>|>)/g;

const preservedKeys = {
  title: true,
  slug: true,
  path: true,
  layout: true,
  date: true,
  content: true
};

function Post(context) {
  this.context = context;
}

Post.prototype.create = function(data, replace, callback) {
  if (!callback && typeof replace === 'function') {
    callback = replace;
    replace = false;
  }

  const ctx = this.context;
  const config = ctx.config;

  data.slug = slugize((data.slug || data.title).toString(), {transform: config.filename_case});
  data.layout = (data.layout || config.default_layout).toLowerCase();
  data.date = data.date ? moment(data.date) : moment();

  return Promise.all([
    // Get the post path
    ctx.execFilter('new_post_path', data, {
      args: [replace],
      context: ctx
    }),
    this._renderScaffold(data)
  ]).spread((path, content) => {
    const result = {
      path,
      content
    };

    return Promise.all([
      // Write content to file
      fs.writeFile(path, content),
      // Create asset folder
      createAssetFolder(path, config.post_asset_folder)
    ]).then(() => {
      ctx.emit('new', result);
    }).thenReturn(result);
  }).asCallback(callback);
};

function prepareFrontMatter(data) {
  const keys = Object.keys(data);
  let key = '';
  let item;

  for (let i = 0, len = keys.length; i < len; i++) {
    key = keys[i];
    item = data[key];

    if (moment.isMoment(item)) {
      data[key] = item.utc().format('YYYY-MM-DD HH:mm:ss');
    } else if (moment.isDate(item)) {
      data[key] = moment.utc(item).format('YYYY-MM-DD HH:mm:ss');
    } else if (typeof item === 'string') {
      data[key] = `"${item}"`;
    }
  }

  return data;
}

Post.prototype._getScaffold = function(layout) {
  const ctx = this.context;

  return ctx.scaffold.get(layout).then(result => {
    if (result != null) return result;
    return ctx.scaffold.get('normal');
  });
};

Post.prototype._renderScaffold = function(data) {
  const tag = this.context.extend.tag;
  let yfmSplit;

  return this._getScaffold(data.layout).then(scaffold => {
    const frontMatter = prepareFrontMatter(_.clone(data));
    yfmSplit = yfm.split(scaffold);

    return tag.render(yfmSplit.data, frontMatter);
  }).then(frontMatter => {
    const separator = yfmSplit.separator;
    const jsonMode = separator[0] === ';';
    let content = '';
    let obj;

    // Parse front-matter
    if (jsonMode) {
      obj = JSON.parse(`{${frontMatter}}`);
    } else {
      obj = yaml.load(frontMatter);
    }

    // Add data which are not in the front-matter
    const keys = Object.keys(data);
    let key = '';

    for (let i = 0, len = keys.length; i < len; i++) {
      key = keys[i];

      if (!preservedKeys[key] && obj[key] == null) {
        obj[key] = data[key];
      }
    }

    // Prepend the separator
    if (yfmSplit.prefixSeparator) content += `${separator}\n`;

    content += yfm.stringify(obj, {
      mode: jsonMode ? 'json' : ''
    });

    // Concat content
    content += yfmSplit.content;

    if (data.content) {
      content += `\n${data.content}`;
    }

    return content;
  });
};

function createAssetFolder(path, assetFolder) {
  if (!assetFolder) return Promise.resolve();

  const target = removeExtname(path);

  return fs.exists(target).then(exist => {
    if (!exist) return fs.mkdirs(target);
  });
}

function removeExtname(str) {
  return str.substring(0, str.length - pathFn.extname(str).length);
}

Post.prototype.publish = function(data, replace, callback) {
  if (!callback && typeof replace === 'function') {
    callback = replace;
    replace = false;
  }

  if (data.layout === 'draft') data.layout = 'post';

  const ctx = this.context;
  const config = ctx.config;
  const draftDir = pathFn.join(ctx.source_dir, '_drafts');
  const slug = data.slug = slugize(data.slug.toString(), {transform: config.filename_case});
  const regex = new RegExp(`^${escapeRegExp(slug)}(?:[^\\/\\\\]+)`);
  const self = this;
  let src = '';
  const result = {};

  data.layout = (data.layout || config.default_layout).toLowerCase();

  // Find the draft
  return fs.listDir(draftDir).then(list => {
    let item = '';

    for (let i = 0, len = list.length; i < len; i++) {
      item = list[i];
      if (regex.test(item)) return item;
    }
  }).then(item => {
    if (!item) throw new Error(`Draft "${slug}" does not exist.`);

    // Read the content
    src = pathFn.join(draftDir, item);
    return fs.readFile(src);
  }).then(content => {
    // Create post
    _.extend(data, yfm(content));
    data.content = data._content;
    delete data._content;

    return self.create(data, replace).then(post => {
      result.path = post.path;
      result.content = post.content;
    });
  }).then(() => // Remove the original draft file
    fs.unlink(src)).then(() => {
    if (!config.post_asset_folder) return;

    // Copy assets
    const assetSrc = removeExtname(src);
    const assetDest = removeExtname(result.path);

    return fs.exists(assetSrc).then(exist => {
      if (!exist) return;

      return fs.copyDir(assetSrc, assetDest).then(() => fs.rmdir(assetSrc));
    });
  }).thenReturn(result).asCallback(callback);
};

Post.prototype.render = function(source, data = {}, callback) {
  const ctx = this.context;
  const config = ctx.config;
  const cache = [];
  const tag = ctx.extend.tag;
  const ext = data.engine || (source ? pathFn.extname(source) : '');

  const isSwig = ext === 'swig';

  let disableNunjucks = false;

  if (ext && ctx.render.renderer.get(ext)) {

    // disable Nunjucks when the renderer spcify that.

    disableNunjucks = disableNunjucks || !!ctx.render.renderer.get(ext).disableNunjucks;

  }

  function escapeContent(str) {
    return `<!--${placeholder}${cache.push(str) - 1}-->`;
  }

  function tagFilter(content) {
    if (disableNunjucks) return content;
    // Replace cache data with real contents
    content = content.replace(rPlaceholder, function(...args) {
      return cache[args[1]];
    });

    // Render with Nunjucks
    data.content = content;
    return tag.render(data.content, data);
  }

  let promise;

  if (data.content != null) {
    promise = Promise.resolve(data.content);
  } else if (source) {
    // Read content from files
    promise = fs.readFile(source);
  } else {
    return Promise.reject(new Error('No input file or string!')).asCallback(callback);
  }

  return promise.then(content => {
    data.content = content;

    // Run "before_post_render" filters
    return ctx.execFilter('before_post_render', data, {context: ctx}).then(() => {
      data.content = data.content.replace(rEscapeContent, (match, content) => escapeContent(content));
    });
  }).then(() => {
    // Skip rendering if this is a swig file
    if (isSwig) return data.content;

    // Escape all Swig tags
    if (!disableNunjucks) {
      data.content = data.content
        .replace(rSwigFullBlock, escapeContent)
        .replace(rSwigBlock, escapeContent)
        .replace(rSwigComment, '')
        .replace(rSwigVar, escapeContent);
    }

    const options = data.markdown || {};
    if (!config.highlight.enable) options.highlight = null;

    // Render with markdown or other renderer
    return ctx.render.render({
      text: data.content,
      path: source,
      engine: data.engine,
      toString: true,
      onRenderEnd: tagFilter
    }, options);
  }).then(content => {
    data.content = content;

    if (!isSwig) {
      return data.content;
    }

    // Render with Nunjucks
    return tag.render(data.content, data);
  }).then(content => {
    data.content = content;

    // Run "after_post_render" filters
    return ctx.execFilter('after_post_render', data, {context: ctx});
  }).asCallback(callback);
};

module.exports = Post;
<commit_msg>refactor: for of loop and use Array Generic method<commit_after>'use strict';

const moment = require('moment');
const Promise = require('bluebird');
const pathFn = require('path');
const _ = require('lodash');
const yaml = require('js-yaml');
const util = require('hexo-util');
const fs = require('hexo-fs');
const yfm = require('hexo-front-matter');

const slugize = util.slugize;
const escapeRegExp = util.escapeRegExp;

const rEscapeContent = /<escape(?:[^>]*)>([\s\S]*?)<\/escape>/g;
const rSwigVar = /\{\{[\s\S]*?\}\}/g;
const rSwigComment = /\{#[\s\S]*?#\}/g;
const rSwigBlock = /\{%[\s\S]*?%\}/g;
const rSwigFullBlock = /\{% *(.+?)(?: *| +.*)%\}[\s\S]+?\{% *end\1 *%\}/g;
const placeholder = '\uFFFC';
const rPlaceholder = /(?:<|<)!--\uFFFC(\d+)--(?:>|>)/g;

const preservedKeys = ['title', 'slug', 'path', 'layout', 'date', 'content'];

function Post(context) {
  this.context = context;
}

Post.prototype.create = function(data, replace, callback) {
  if (!callback && typeof replace === 'function') {
    callback = replace;
    replace = false;
  }

  const ctx = this.context;
  const config = ctx.config;

  data.slug = slugize((data.slug || data.title).toString(), {transform: config.filename_case});
  data.layout = (data.layout || config.default_layout).toLowerCase();
  data.date = data.date ? moment(data.date) : moment();

  return Promise.all([
    // Get the post path
    ctx.execFilter('new_post_path', data, {
      args: [replace],
      context: ctx
    }),
    this._renderScaffold(data)
  ]).spread((path, content) => {
    const result = {
      path,
      content
    };

    return Promise.all([
      // Write content to file
      fs.writeFile(path, content),
      // Create asset folder
      createAssetFolder(path, config.post_asset_folder)
    ]).then(() => {
      ctx.emit('new', result);
    }).thenReturn(result);
  }).asCallback(callback);
};

function prepareFrontMatter(data) {
  for (const key of Object.keys(data)) {
    const item = data[key];

    if (moment.isMoment(item)) {
      data[key] = item.utc().format('YYYY-MM-DD HH:mm:ss');
    } else if (moment.isDate(item)) {
      data[key] = moment.utc(item).format('YYYY-MM-DD HH:mm:ss');
    } else if (typeof item === 'string') {
      data[key] = `"${item}"`;
    }
  }

  return data;
}

Post.prototype._getScaffold = function(layout) {
  const ctx = this.context;

  return ctx.scaffold.get(layout).then(result => {
    if (result != null) return result;
    return ctx.scaffold.get('normal');
  });
};

Post.prototype._renderScaffold = function(data) {
  const tag = this.context.extend.tag;
  let yfmSplit;

  return this._getScaffold(data.layout).then(scaffold => {
    const frontMatter = prepareFrontMatter(_.clone(data));
    yfmSplit = yfm.split(scaffold);

    return tag.render(yfmSplit.data, frontMatter);
  }).then(frontMatter => {
    const separator = yfmSplit.separator;
    const jsonMode = separator[0] === ';';
    let content = '';
    let obj;

    // Parse front-matter
    if (jsonMode) {
      obj = JSON.parse(`{${frontMatter}}`);
    } else {
      obj = yaml.load(frontMatter);
    }

    // Add data which are not in the front-matter
    for (const key of Object.keys(data)) {
      if (!_.includes(preservedKeys, key) && obj[key] == null) {
        obj[key] = data[key];
      }
    }

    // Prepend the separator
    if (yfmSplit.prefixSeparator) content += `${separator}\n`;

    content += yfm.stringify(obj, {
      mode: jsonMode ? 'json' : ''
    });

    // Concat content
    content += yfmSplit.content;

    if (data.content) {
      content += `\n${data.content}`;
    }

    return content;
  });
};

function createAssetFolder(path, assetFolder) {
  if (!assetFolder) return Promise.resolve();

  const target = removeExtname(path);

  return fs.exists(target).then(exist => {
    if (!exist) return fs.mkdirs(target);
  });
}

function removeExtname(str) {
  return str.substring(0, str.length - pathFn.extname(str).length);
}

Post.prototype.publish = function(data, replace, callback) {
  if (!callback && typeof replace === 'function') {
    callback = replace;
    replace = false;
  }

  if (data.layout === 'draft') data.layout = 'post';

  const ctx = this.context;
  const config = ctx.config;
  const draftDir = pathFn.join(ctx.source_dir, '_drafts');
  const slug = data.slug = slugize(data.slug.toString(), {transform: config.filename_case});
  const regex = new RegExp(`^${escapeRegExp(slug)}(?:[^\\/\\\\]+)`);
  const self = this;
  let src = '';
  const result = {};

  data.layout = (data.layout || config.default_layout).toLowerCase();

  // Find the draft
  return fs.listDir(draftDir).then(list => {
    return list.find(item => regex.test(item));
  }).then(item => {
    if (!item) throw new Error(`Draft "${slug}" does not exist.`);

    // Read the content
    src = pathFn.join(draftDir, item);
    return fs.readFile(src);
  }).then(content => {
    // Create post
    _.extend(data, yfm(content));
    data.content = data._content;
    delete data._content;

    return self.create(data, replace).then(post => {
      result.path = post.path;
      result.content = post.content;
    });
  }).then(() => // Remove the original draft file
    fs.unlink(src)).then(() => {
    if (!config.post_asset_folder) return;

    // Copy assets
    const assetSrc = removeExtname(src);
    const assetDest = removeExtname(result.path);

    return fs.exists(assetSrc).then(exist => {
      if (!exist) return;

      return fs.copyDir(assetSrc, assetDest).then(() => fs.rmdir(assetSrc));
    });
  }).thenReturn(result).asCallback(callback);
};

Post.prototype.render = function(source, data = {}, callback) {
  const ctx = this.context;
  const config = ctx.config;
  const cache = [];
  const tag = ctx.extend.tag;
  const ext = data.engine || (source ? pathFn.extname(source) : '');

  const isSwig = ext === 'swig';

  let disableNunjucks = false;

  if (ext && ctx.render.renderer.get(ext)) {

    // disable Nunjucks when the renderer spcify that.

    disableNunjucks = disableNunjucks || !!ctx.render.renderer.get(ext).disableNunjucks;

  }

  function escapeContent(str) {
    return `<!--${placeholder}${cache.push(str) - 1}-->`;
  }

  function tagFilter(content) {
    if (disableNunjucks) return content;
    // Replace cache data with real contents
    content = content.replace(rPlaceholder, function(...args) {
      return cache[args[1]];
    });

    // Render with Nunjucks
    data.content = content;
    return tag.render(data.content, data);
  }

  let promise;

  if (data.content != null) {
    promise = Promise.resolve(data.content);
  } else if (source) {
    // Read content from files
    promise = fs.readFile(source);
  } else {
    return Promise.reject(new Error('No input file or string!')).asCallback(callback);
  }

  return promise.then(content => {
    data.content = content;

    // Run "before_post_render" filters
    return ctx.execFilter('before_post_render', data, {context: ctx}).then(() => {
      data.content = data.content.replace(rEscapeContent, (match, content) => escapeContent(content));
    });
  }).then(() => {
    // Skip rendering if this is a swig file
    if (isSwig) return data.content;

    // Escape all Swig tags
    if (!disableNunjucks) {
      data.content = data.content
        .replace(rSwigFullBlock, escapeContent)
        .replace(rSwigBlock, escapeContent)
        .replace(rSwigComment, '')
        .replace(rSwigVar, escapeContent);
    }

    const options = data.markdown || {};
    if (!config.highlight.enable) options.highlight = null;

    // Render with markdown or other renderer
    return ctx.render.render({
      text: data.content,
      path: source,
      engine: data.engine,
      toString: true,
      onRenderEnd: tagFilter
    }, options);
  }).then(content => {
    data.content = content;

    if (!isSwig) {
      return data.content;
    }

    // Render with Nunjucks
    return tag.render(data.content, data);
  }).then(content => {
    data.content = content;

    // Run "after_post_render" filters
    return ctx.execFilter('after_post_render', data, {context: ctx});
  }).asCallback(callback);
};

module.exports = Post;
<|endoftext|>


<commit_before>const Cookies          = require('js-cookie');
const Client           = require('./client');
const Contents         = require('./contents');
const Header           = require('./header');
const Login            = require('./login');
const Menu             = require('./menu');
const BinarySocket     = require('./socket');
const checkLanguage    = require('../common/country_base').checkLanguage;
const TrafficSource    = require('../common/traffic_source');
const RealityCheck     = require('../pages/user/reality_check/reality_check');
const elementInnerHtml = require('../../_common/common_functions').elementInnerHtml;
const getElementById   = require('../../_common/common_functions').getElementById;
const Crowdin          = require('../../_common/crowdin');
const Language         = require('../../_common/language');
const PushNotification = require('../../_common/lib/push_notification');
const Localize         = require('../../_common/localize');
const localize         = require('../../_common/localize').localize;
const State            = require('../../_common/storage').State;
const scrollToTop      = require('../../_common/scroll').scrollToTop;
const Url              = require('../../_common/url');
const createElement    = require('../../_common/utility').createElement;
const AffiliatePopup   = require('../../static/japan/affiliate_popup');
require('../../_common/lib/polyfills/array.includes');
require('../../_common/lib/polyfills/string.includes');

const Page = (() => {
    const init = () => {
        State.set('is_loaded_by_pjax', false);
        Url.init();
        PushNotification.init();
        onDocumentReady();
        Crowdin.init();
    };

    const onDocumentReady = () => {
        // LocalStorage can be used as a means of communication among
        // different windows. The problem that is solved here is what
        // happens if the user logs out or switches loginid in one
        // window while keeping another window or tab open. This can
        // lead to unintended trades. The solution is to reload the
        // page in all windows after switching loginid or after logout.

        // onLoad.queue does not work on the home page.
        // jQuery's ready function works always.
        $(document).ready(() => {
            // Cookies is not always available.
            // So, fall back to a more basic solution.
            window.addEventListener('storage', (evt) => {
                switch (evt.key) {
                    case 'active_loginid':
                        // not the active tab and logged out or loginid switch
                        if (document.hidden && (evt.newValue === '' || !window.is_logging_in)) {
                            reload();
                        }
                        break;
                    case 'new_release_reload_time':
                        if (evt.newValue !== evt.oldValue) {
                            reload(true);
                        }
                        break;
                    // no default
                }
            });
            scrollToTop();
        });
    };

    const showHiddenElementsBasedOnCompany = (landing_company_name) => {
        console.log('>>>', landing_company_name);
    }

    const onLoad = () => {
        if (State.get('is_loaded_by_pjax')) {
            Url.reset();
        } else {
            init();
            if (!Login.isLoginPages()) {
                Language.setCookie(Language.urlLang());
            }
            Localize.forLang(Language.urlLang());
            Header.onLoad();
            Language.setCookie();
            Menu.makeMobileMenu();
            recordAffiliateExposure();
            endpointNotification();
        }
        Contents.onLoad();

        if (sessionStorage.getItem('showLoginPage')) {
            sessionStorage.removeItem('showLoginPage');
            Login.redirectToLogin();
        }
        if (Client.isLoggedIn()) {
            BinarySocket.wait('authorize').then(() => {
                checkLanguage();
                Menu.init();
                RealityCheck.onLoad();
                const landing_company_name = State.getResponse('authorize.landing_company_name');
                showHiddenElementsBasedOnCompany(landing_company_name);
            });
        } else {
            checkLanguage();
            Menu.init();
            showHiddenElementsBasedOnCompany();
        }
        TrafficSource.setData();
    };

    const onUnload = () => {
        Menu.onUnload();
    };

    const recordAffiliateExposure = () => {
        const token = Url.param('t');
        if (!token || token.length !== 32) {
            return false;
        }

        AffiliatePopup.show();

        const token_length  = token.length;
        const is_subsidiary = /\w{1}/.test(Url.param('s'));

        const cookie_token = Cookies.getJSON('affiliate_tracking');
        if (cookie_token) {
            // Already exposed to some other affiliate.
            if (is_subsidiary && cookie_token && cookie_token.t) {
                return false;
            }
        }

        // Record the affiliate exposure. Overwrite existing cookie, if any.
        const cookie_hash = {};
        if (token_length === 32) {
            cookie_hash.t = token.toString();
        }
        if (is_subsidiary) {
            cookie_hash.s = '1';
        }

        Cookies.set('affiliate_tracking', cookie_hash, {
            expires: 365, // expires in 365 days
            path   : '/',
            domain : `.${location.hostname.split('.').slice(-2).join('.')}`,
        });
        return true;
    };

    const reload = (forced_reload) => { window.location.reload(!!forced_reload); };

    const endpointNotification = () => {
        const server = localStorage.getItem('config.server_url');
        if (server && server.length > 0) {
            const message = `${(/www\.binary\.com/i.test(window.location.hostname) ? '' :
                `${localize('This is a staging server - For testing purposes only')} - `)}
                ${localize('The server endpoint is: [_2]', [Url.urlFor('endpoint'), server])}`;

            const end_note = getElementById('end-note');
            elementInnerHtml(end_note, message);
            end_note.setVisibility(1);

            getElementById('footer').style['padding-bottom'] = end_note.offsetHeight;
        }
    };

    const showNotificationOutdatedBrowser = () => {
        const src = '//browser-update.org/update.min.js';
        if (document.querySelector(`script[src*="${src}"]`)) return;
        window.$buoop = {
            vs     : { i: 11, f: -4, o: -4, s: 9, c: -4 },
            api    : 4,
            l      : Language.get().toLowerCase(),
            url    : 'https://whatbrowser.org/',
            noclose: true, // Do not show the 'ignore' button to close the notification
            text   : localize('Your web browser ([_1]) is out of date and may affect your trading experience. Proceed at your own risk. [_2]Update browser[_3]',
                ['{brow_name}', '', '']),
            reminder: 0, // show all the time
        };
        if (document.body) {
            document.body.appendChild(createElement('script', { src }));
        }
    };

    return {
        onLoad,
        onUnload,
        showNotificationOutdatedBrowser,
    };
})();

module.exports = Page;
<commit_msg>implement parsing function, show elements based on rules<commit_after>const Cookies          = require('js-cookie');
const Client           = require('./client');
const Contents         = require('./contents');
const Header           = require('./header');
const Login            = require('./login');
const Menu             = require('./menu');
const BinarySocket     = require('./socket');
const checkLanguage    = require('../common/country_base').checkLanguage;
const TrafficSource    = require('../common/traffic_source');
const RealityCheck     = require('../pages/user/reality_check/reality_check');
const elementInnerHtml = require('../../_common/common_functions').elementInnerHtml;
const getElementById   = require('../../_common/common_functions').getElementById;
const Crowdin          = require('../../_common/crowdin');
const Language         = require('../../_common/language');
const PushNotification = require('../../_common/lib/push_notification');
const Localize         = require('../../_common/localize');
const localize         = require('../../_common/localize').localize;
const State            = require('../../_common/storage').State;
const scrollToTop      = require('../../_common/scroll').scrollToTop;
const Url              = require('../../_common/url');
const createElement    = require('../../_common/utility').createElement;
const AffiliatePopup   = require('../../static/japan/affiliate_popup');
require('../../_common/lib/polyfills/array.includes');
require('../../_common/lib/polyfills/string.includes');

const Page = (() => {
    const init = () => {
        State.set('is_loaded_by_pjax', false);
        Url.init();
        PushNotification.init();
        onDocumentReady();
        Crowdin.init();
    };

    const onDocumentReady = () => {
        // LocalStorage can be used as a means of communication among
        // different windows. The problem that is solved here is what
        // happens if the user logs out or switches loginid in one
        // window while keeping another window or tab open. This can
        // lead to unintended trades. The solution is to reload the
        // page in all windows after switching loginid or after logout.

        // onLoad.queue does not work on the home page.
        // jQuery's ready function works always.
        $(document).ready(() => {
            // Cookies is not always available.
            // So, fall back to a more basic solution.
            window.addEventListener('storage', (evt) => {
                switch (evt.key) {
                    case 'active_loginid':
                        // not the active tab and logged out or loginid switch
                        if (document.hidden && (evt.newValue === '' || !window.is_logging_in)) {
                            reload();
                        }
                        break;
                    case 'new_release_reload_time':
                        if (evt.newValue !== evt.oldValue) {
                            reload(true);
                        }
                        break;
                    // no default
                }
            });
            scrollToTop();
        });
    };

    const showHiddenElementsBasedOnCompany = (landing_company_name) => {
        if (!landing_company_name) landing_company_name = 'default'; // logged out
        const VISIBLE_CLASSNAME = 'visible';

        function parseAttributeString(attrStr) {
            let names = attrStr.split(',').map(name => name.trim());

            const parsingError = new Error('Invalid data-show attribute value!');

            if (names.some(name => name.length === 0)) {
                throw parsingError;
            }

            const isExclude = names.every(name => name[0] === '-');
            const isInclude = names.every(name => name[0] !== '-');

            if (!isExclude && !isInclude) {
                throw parsingError;
            }

            if (isExclude) {
                names = names.map(name => name.slice(1));
            }

            return {
                isExclude,
                names
            };
        }

        console.log('landing_company_name', landing_company_name);

        document.querySelectorAll('[data-show]').forEach(el => {
            const attrStr = el.dataset.show;
            const { isExclude, names } = parseAttributeString(attrStr);
            console.log(names);
            const nameSet = new Set(names);

            if (isExclude && !nameSet.has(landing_company_name)) {
                el.classList.add(VISIBLE_CLASSNAME);
                console.log('show', el);
            }
            else if (!isExclude && nameSet.has(landing_company_name)) {
                el.classList.add(VISIBLE_CLASSNAME);
                console.log('show', el);
            }
            else {
                console.log('stays hidden', el);
            }
        })
    }

    const onLoad = () => {
        if (State.get('is_loaded_by_pjax')) {
            Url.reset();
        } else {
            init();
            if (!Login.isLoginPages()) {
                Language.setCookie(Language.urlLang());
            }
            Localize.forLang(Language.urlLang());
            Header.onLoad();
            Language.setCookie();
            Menu.makeMobileMenu();
            recordAffiliateExposure();
            endpointNotification();
        }
        Contents.onLoad();

        if (sessionStorage.getItem('showLoginPage')) {
            sessionStorage.removeItem('showLoginPage');
            Login.redirectToLogin();
        }
        if (Client.isLoggedIn()) {
            BinarySocket.wait('authorize').then(() => {
                checkLanguage();
                Menu.init();
                RealityCheck.onLoad();
                const landing_company_name = State.getResponse('authorize.landing_company_name');
                showHiddenElementsBasedOnCompany(landing_company_name);
            });
        } else {
            checkLanguage();
            Menu.init();
            showHiddenElementsBasedOnCompany();
        }
        TrafficSource.setData();
    };

    const onUnload = () => {
        Menu.onUnload();
    };

    const recordAffiliateExposure = () => {
        const token = Url.param('t');
        if (!token || token.length !== 32) {
            return false;
        }

        AffiliatePopup.show();

        const token_length  = token.length;
        const is_subsidiary = /\w{1}/.test(Url.param('s'));

        const cookie_token = Cookies.getJSON('affiliate_tracking');
        if (cookie_token) {
            // Already exposed to some other affiliate.
            if (is_subsidiary && cookie_token && cookie_token.t) {
                return false;
            }
        }

        // Record the affiliate exposure. Overwrite existing cookie, if any.
        const cookie_hash = {};
        if (token_length === 32) {
            cookie_hash.t = token.toString();
        }
        if (is_subsidiary) {
            cookie_hash.s = '1';
        }

        Cookies.set('affiliate_tracking', cookie_hash, {
            expires: 365, // expires in 365 days
            path   : '/',
            domain : `.${location.hostname.split('.').slice(-2).join('.')}`,
        });
        return true;
    };

    const reload = (forced_reload) => { window.location.reload(!!forced_reload); };

    const endpointNotification = () => {
        const server = localStorage.getItem('config.server_url');
        if (server && server.length > 0) {
            const message = `${(/www\.binary\.com/i.test(window.location.hostname) ? '' :
                `${localize('This is a staging server - For testing purposes only')} - `)}
                ${localize('The server endpoint is: [_2]', [Url.urlFor('endpoint'), server])}`;

            const end_note = getElementById('end-note');
            elementInnerHtml(end_note, message);
            end_note.setVisibility(1);

            getElementById('footer').style['padding-bottom'] = end_note.offsetHeight;
        }
    };

    const showNotificationOutdatedBrowser = () => {
        const src = '//browser-update.org/update.min.js';
        if (document.querySelector(`script[src*="${src}"]`)) return;
        window.$buoop = {
            vs     : { i: 11, f: -4, o: -4, s: 9, c: -4 },
            api    : 4,
            l      : Language.get().toLowerCase(),
            url    : 'https://whatbrowser.org/',
            noclose: true, // Do not show the 'ignore' button to close the notification
            text   : localize('Your web browser ([_1]) is out of date and may affect your trading experience. Proceed at your own risk. [_2]Update browser[_3]',
                ['{brow_name}', '', '']),
            reminder: 0, // show all the time
        };
        if (document.body) {
            document.body.appendChild(createElement('script', { src }));
        }
    };

    return {
        onLoad,
        onUnload,
        showNotificationOutdatedBrowser,
    };
})();

module.exports = Page;
<|endoftext|>


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

/**
 * @fileoverview Service for generating feedback based on the evaluation result
 * of the code submitted by the user, preprocessed and augmented with unit
 * tests. This assumes that the base code already passes "compile-time" checks.
 */

tie.factory('FeedbackGeneratorService', [
  'FeedbackObjectFactory', 'CODE_EXECUTION_TIMEOUT_SECONDS', function(
    FeedbackObjectFactory, CODE_EXECUTION_TIMEOUT_SECONDS) {
    // TODO(sll): Update this function to take the programming language into
    // account when generating the human-readable representations. Currently,
    // it assumes that Python is being used.
    var _jsToHumanReadable = function(jsVariable) {
      if (jsVariable === null || jsVariable === undefined) {
        return 'None';
      } else if (typeof jsVariable === 'string') {
        return '"' + jsVariable + '"';
      } else if (typeof jsVariable === 'number') {
        return String(jsVariable);
      } else if (typeof jsVariable === 'boolean') {
        return jsVariable ? 'True' : 'False';
      } else if (Array.isArray(jsVariable)) {
        var humanReadableElements = jsVariable.map(function(arrayElement) {
          return _jsToHumanReadable(arrayElement);
        });
        return '[' + humanReadableElements.join(', ') + ']';
      } else if (typeof jsVariable === 'object') {
        var humanReadableKeyValuePairs = [];
        for (var key in jsVariable) {
          humanReadableKeyValuePairs.push(
            _jsToHumanReadable(key) + ': ' +
            _jsToHumanReadable(jsVariable[key]));
        }
        return '{' + humanReadableKeyValuePairs.join(', ') + '}';
      } else {
        console.error(
          'Could not make the following object human-readable: ', jsVariable);
        return '[UNKNOWN OBJECT]';
      }
    };

    return {
      getFeedback: function(prompt, codeEvalResult) {
        var errorMessage = codeEvalResult.getErrorMessage();
        // We want to catch and handle a timeout error uniquely, rather than
        // integrate it into the existing feedback pipeline.
        if (errorMessage.toString().startsWith('TimeLimitError')) {
          var feedback = FeedbackObjectFactory.create(false);
          feedback.appendTextParagraph(
            ["Your program's exceeded the time limit (",
            CODE_EXECUTION_TIMEOUT_SECONDS,
            " seconds) we've set. Can you try to make it run ",
            "more efficiently?"].join(''));
          return feedback;
        }
        if (errorMessage) {
          var errorInput = codeEvalResult.getErrorInput();
          var inputClause = (
            ' when evaluating the input ' + _jsToHumanReadable(errorInput));
          var feedback = FeedbackObjectFactory.create(false);
          feedback.appendTextParagraph(
            "Looks like your code had a runtime error" + inputClause +
            ". Here's the trace:")
          feedback.appendCodeParagraph(codeEvalResult.getErrorMessage());
          return feedback;
        } else {
          var buggyOutputTests = prompt.getBuggyOutputTests();
          var buggyOutputTestResults =
              codeEvalResult.getBuggyOutputTestResults();
          for (var i = 0; i < buggyOutputTests.length; i++) {
            if (buggyOutputTestResults[i]) {
              // TODO(sll): Use subsequent messages as well if multiple
              // messages are specified.
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph(
                buggyOutputTests[i].getMessages()[0]);
              return feedback;
            }
          }

          var correctnessTests = prompt.getCorrectnessTests();
          var observedOutputs = codeEvalResult.getCorrectnessTestResults();
          for (var i = 0; i < correctnessTests.length; i++) {
            var observedOutput = observedOutputs[i];

            // TODO(eyurko): Add varied statements for when code is incorrect.
            if (!correctnessTests[i].matchesOutput(observedOutput)) {
              var allowedOutputExample = (
                correctnessTests[i].getAnyAllowedOutput());
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph([
                'Your code gave the output ',
                _jsToHumanReadable(observedOutput),
                ' for the input ',
                _jsToHumanReadable(correctnessTests[i].getInput()),
                ' ... but this does not match the expected output ',
                _jsToHumanReadable(allowedOutputExample),
                '.'
              ].join(''));
              return feedback;
            }
          }

          var performanceTests = prompt.getPerformanceTests();
          var performanceTestResults =
              codeEvalResult.getPerformanceTestResults();
          for (var i = 0; i < performanceTests.length; i++) {
            var expectedPerformance = performanceTests[i].getExpectedPerformance();
            var observedPerformance = performanceTestResults[i];

            if (expectedPerformance !== observedPerformance) {
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph([
                'Your code is running more slowly than expected. Can you ',
                'reconfigure it such that it runs in ',
                expectedPerformance,
                ' time?'
              ].join(''));
              return feedback;
            }
          }

          var feedback = FeedbackObjectFactory.create(true);
          feedback.appendTextParagraph([
            'You\'ve completed all the tasks for this question! Click the ',
            '"Next" button to move on to the next question.',
          ].join(''));
          return feedback;
        }
      },
      getSyntaxErrorFeedback: function(errorMessage) {
        var feedback = FeedbackObjectFactory.create(false);
        feedback.appendTextParagraph(
          "Looks like your code did not compile. Here's the error trace: ");
        feedback.appendCodeParagraph(errorMessage);
        return feedback;
      },
      _jsToHumanReadable: _jsToHumanReadable
    };
  }
]);
<commit_msg>Add nullcheck for errorMessage. (#52)<commit_after>// Copyright 2017 The TIE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Service for generating feedback based on the evaluation result
 * of the code submitted by the user, preprocessed and augmented with unit
 * tests. This assumes that the base code already passes "compile-time" checks.
 */

tie.factory('FeedbackGeneratorService', [
  'FeedbackObjectFactory', 'CODE_EXECUTION_TIMEOUT_SECONDS', function(
    FeedbackObjectFactory, CODE_EXECUTION_TIMEOUT_SECONDS) {
    // TODO(sll): Update this function to take the programming language into
    // account when generating the human-readable representations. Currently,
    // it assumes that Python is being used.
    var _jsToHumanReadable = function(jsVariable) {
      if (jsVariable === null || jsVariable === undefined) {
        return 'None';
      } else if (typeof jsVariable === 'string') {
        return '"' + jsVariable + '"';
      } else if (typeof jsVariable === 'number') {
        return String(jsVariable);
      } else if (typeof jsVariable === 'boolean') {
        return jsVariable ? 'True' : 'False';
      } else if (Array.isArray(jsVariable)) {
        var humanReadableElements = jsVariable.map(function(arrayElement) {
          return _jsToHumanReadable(arrayElement);
        });
        return '[' + humanReadableElements.join(', ') + ']';
      } else if (typeof jsVariable === 'object') {
        var humanReadableKeyValuePairs = [];
        for (var key in jsVariable) {
          humanReadableKeyValuePairs.push(
            _jsToHumanReadable(key) + ': ' +
            _jsToHumanReadable(jsVariable[key]));
        }
        return '{' + humanReadableKeyValuePairs.join(', ') + '}';
      } else {
        console.error(
          'Could not make the following object human-readable: ', jsVariable);
        return '[UNKNOWN OBJECT]';
      }
    };

    return {
      getFeedback: function(prompt, codeEvalResult) {
        var errorMessage = codeEvalResult.getErrorMessage();
        // We want to catch and handle a timeout error uniquely, rather than
        // integrate it into the existing feedback pipeline.
        if (errorMessage !== null &&
            errorMessage.toString().startsWith('TimeLimitError')) {
          var feedback = FeedbackObjectFactory.create(false);
          feedback.appendTextParagraph(
            ["Your program's exceeded the time limit (",
            CODE_EXECUTION_TIMEOUT_SECONDS,
            " seconds) we've set. Can you try to make it run ",
            "more efficiently?"].join(''));
          return feedback;
        } else if (errorMessage) {
          var errorInput = codeEvalResult.getErrorInput();
          var inputClause = (
            ' when evaluating the input ' + _jsToHumanReadable(errorInput));
          var feedback = FeedbackObjectFactory.create(false);
          feedback.appendTextParagraph(
            "Looks like your code had a runtime error" + inputClause +
            ". Here's the trace:")
          feedback.appendCodeParagraph(codeEvalResult.getErrorMessage());
          return feedback;
        } else {
          var buggyOutputTests = prompt.getBuggyOutputTests();
          var buggyOutputTestResults =
              codeEvalResult.getBuggyOutputTestResults();
          for (var i = 0; i < buggyOutputTests.length; i++) {
            if (buggyOutputTestResults[i]) {
              // TODO(sll): Use subsequent messages as well if multiple
              // messages are specified.
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph(
                buggyOutputTests[i].getMessages()[0]);
              return feedback;
            }
          }

          var correctnessTests = prompt.getCorrectnessTests();
          var observedOutputs = codeEvalResult.getCorrectnessTestResults();
          for (var i = 0; i < correctnessTests.length; i++) {
            var observedOutput = observedOutputs[i];

            // TODO(eyurko): Add varied statements for when code is incorrect.
            if (!correctnessTests[i].matchesOutput(observedOutput)) {
              var allowedOutputExample = (
                correctnessTests[i].getAnyAllowedOutput());
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph([
                'Your code gave the output ',
                _jsToHumanReadable(observedOutput),
                ' for the input ',
                _jsToHumanReadable(correctnessTests[i].getInput()),
                ' ... but this does not match the expected output ',
                _jsToHumanReadable(allowedOutputExample),
                '.'
              ].join(''));
              return feedback;
            }
          }

          var performanceTests = prompt.getPerformanceTests();
          var performanceTestResults =
              codeEvalResult.getPerformanceTestResults();
          for (var i = 0; i < performanceTests.length; i++) {
            var expectedPerformance = performanceTests[i].getExpectedPerformance();
            var observedPerformance = performanceTestResults[i];

            if (expectedPerformance !== observedPerformance) {
              var feedback = FeedbackObjectFactory.create(false);
              feedback.appendTextParagraph([
                'Your code is running more slowly than expected. Can you ',
                'reconfigure it such that it runs in ',
                expectedPerformance,
                ' time?'
              ].join(''));
              return feedback;
            }
          }

          var feedback = FeedbackObjectFactory.create(true);
          feedback.appendTextParagraph([
            'You\'ve completed all the tasks for this question! Click the ',
            '"Next" button to move on to the next question.',
          ].join(''));
          return feedback;
        }
      },
      getSyntaxErrorFeedback: function(errorMessage) {
        var feedback = FeedbackObjectFactory.create(false);
        feedback.appendTextParagraph(
          "Looks like your code did not compile. Here's the error trace: ");
        feedback.appendCodeParagraph(errorMessage);
        return feedback;
      },
      _jsToHumanReadable: _jsToHumanReadable
    };
  }
]);
<|endoftext|>


<commit_before>angular.module('ngwig-app-templates', ['ng-wig/views/ng-wig.html']);

angular.module("ng-wig/views/ng-wig.html", []).run(["$templateCache", function($templateCache) {
  $templateCache.put("ng-wig/views/ng-wig.html",
    "
\n" +
    "
\n" +
    "
\n" +
    "      <select class=\"form-control\" ng-model=\"style\" ng-change=\"execCommand('formatblock', style.value)\" ng-options=\"style.name for style in styles\">\n" +
    "        <option ng-selected=\"true\" disabled value=\"\">--- Choose a style ---</option>\n" +
    "      </select>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--unordered-list\" title=\"Unordered List\" ng-click=\"execCommand('insertunorderedlist')\"></button>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--ordered-list\" title=\"Ordered List\" ng-click=\"execCommand('insertorderedlist')\"></button>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--bold\" title=\"Bold\" ng-click=\"execCommand('bold')\"></button>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--italic\" title=\"Italic\" ng-click=\"execCommand('italic')\"></button>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--link\" title=\"link\" ng-click=\"execCommand('createlink')\"></button>\n" +
    "

\n" +
    "      <button type=\"button\" class=\"nw-button nw-button--source\" ng-class=\"{ 'nw-button--active': editMode }\" ng-click=\"toggleEditMode()\"></button>\n" +
    "
\n" +
    "
\n" +
    "\n" +
    "
\n" +
    "
\n" +
    "      <textarea class=\"nw-editor__src\" ng-show=\"editMode\" ng-model=\"content\"></textarea>\n" +
    "

\n" +
    "
\n" +
    "
\n" +
    "
\n" +
    "");
}]);
<commit_msg>Delete templates.js<commit_after><|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');

var ZetamGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');
  },

  askFor: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Zetam generator!'));

    this.prompt({
      type    : 'input',
      name    : 'name',
      message : 'Your page name',
      default : 'new-page' // Default to current folder name
    }, function (answers) {
      this.pageName = answers.name;
      this.log(answers.name);
      done();
    }.bind(this));
  },

  app: function () {
    var context = {
      pageName:this.pageName
    }

    this.template('template.html', 'pages/'+ this.pageName +'/template.html',context);

    this.copy('controller.js', 'pages/'+ this.pageName +'/controller.js');
    this.copy('styles.less', 'pages/'+ this.pageName +'/styles.less');
    this.copy('i18n.json', 'pages/'+ this.pageName +'/i18n.json');

    var done = this.async();
    done();
  }
});

module.exports = ZetamGenerator;
<commit_msg>Commit message<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');

var ZetamGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');
  },

  askFor: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Zetam generator!'));

    this.prompt({
      type    : 'input',
      name    : 'name',
      message : 'Your page name',
      default : 'new-page' // Default to current folder name
    }, function (answers) {
      this.pageName = answers.name;
      this.log(answers.name);
      done();
    }.bind(this));
  },

  app: function () {
    var context = {
      pageName:this.pageName
    }

    this.template('template.html', 'pages/'+ this.pageName +'/template.html',context);

    this.copy('controller.js', 'pages/'+ this.pageName +'/controller.js');
    this.copy('styles.less', 'pages/'+ this.pageName +'/styles.less');
    this.copy('i18n.json', 'pages/'+ this.pageName +'/i18n.json');
    this.copy('view.js', 'pages/'+ this.pageName +'/view.js');

    var done = this.async();
    done();
  }
});

module.exports = ZetamGenerator;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import { Card, CardTitle, CardText, CardActions } from 'material-ui/Card';
import { Grid, Row, Col } from 'react-flexbox-grid';
import { Link } from 'react-router';
import { List, ListItem } from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import ContentAdd from 'material-ui/svg-icons/content/add';
import FloatingActionButton from 'material-ui/FloatingActionButton';
const OrderAddForm = (
  { promos, products, dishes, onCloseOrder,
    linkPromo, linkProduct, linkDish }) => (
  <Card>
    <CardTitle>
      Pedido
    </CardTitle>
    <CardText>
      <Grid fluid>
        <Row>
          <Col xs>
            <Subheader inset>Promociones</Subheader>
          </Col>
          <Col xs>
            <Link to={linkPromo}>
              <FloatingActionButton mini>
                <ContentAdd />
              </FloatingActionButton>
            </Link>
          </Col>
        </Row>
      </Grid>
      <List>
        {
          promos && promos.map((promo, i) => (
            <ListItem
              key={i}
              primaryText={promo.selected.nombre}
              secondaryText={promo.quantity}
            />
          ))
        }
      </List>
      <Grid fluid>
        <Row>
          <Col xs>
            <Subheader inset>Productos</Subheader>
          </Col>
          <Col xs>
            <Link to={linkProduct}>
              <FloatingActionButton mini>
                <ContentAdd />
              </FloatingActionButton>
            </Link>
          </Col>
        </Row>
      </Grid>
      <List>
        {
          products && products.map((product, i) => (
            <ListItem
              key={i}
              primaryText={product.selected.descripcion}
              secondaryText={product.quantity}
            />
          ))
        }
      </List>
      <Grid fluid>
        <Row>
          <Col xs>
            <Subheader inset>Platos</Subheader>
          </Col>
          <Col xs>
            <Link to={linkDish}>
              <FloatingActionButton mini>
                <ContentAdd />
              </FloatingActionButton>
            </Link>
          </Col>
        </Row>
      </Grid>
      <List>
        {
          dishes && dishes.map((dish, i) => (
            <ListItem
              key={i}
              primaryText={dish.selected.nombre}
              secondaryText={dish.quantity}
            />
          ))
        }
      </List>
    </CardText>
    <CardActions>
      <Grid fluid>
        <Row center="xs">
          <Col xs>
            <RaisedButton label="Enviar Comandas" onTouchTap={() => onCloseOrder()} />
          </Col>
        </Row>
      </Grid>
    </CardActions>
  </Card>
);

OrderAddForm.propTypes = {
  promos: PropTypes.array,
  products: PropTypes.array,
  dishes: PropTypes.array,
  onCloseOrder: PropTypes.func,
  linkPromo: PropTypes.string,
  linkProduct: PropTypes.string,
  linkDish: PropTypes.string,
};

export default OrderAddForm;
<commit_msg>formato order add<commit_after>import React, { PropTypes } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import { Card, CardTitle, CardText, CardActions } from 'material-ui/Card';
import { Grid, Row, Col } from 'react-flexbox-grid';
import { Link } from 'react-router';
import { List, ListItem } from 'material-ui/List';
import ContentAdd from 'material-ui/svg-icons/content/add';
import Divider from 'material-ui/Divider';

const OrderAddForm = (
  { promos, products, dishes, onCloseOrder,
    linkPromo, linkProduct, linkDish }) => (
  <Card>
    <CardTitle>
      Pedido
    </CardTitle>
    <CardText>
      <List>
        <Card>
          <ListItem
            disabled
            open
            primaryText="Promociones"
            rightIcon={
              <Link to={linkPromo}>
                <ContentAdd />
              </Link>
            }
            nestedItems={
              promos && promos.map((promo, i) => (
                <ListItem
                  key={i}
                  disabled
                  primaryText={promo.selected.nombre}
                  secondaryText={promo.quantity}
                />
              ))
            }
          />
          <Divider />
          <ListItem
            disabled
            open
            primaryText="Productos"
            rightIcon={
              <Link to={linkProduct}>
                <ContentAdd />
              </Link>
            }
            nestedItems={
              products && products.map((product, i) => (
                <ListItem
                  key={i}
                  disabled
                  primaryText={product.selected.descripcion}
                  secondaryText={product.quantity}
                />
              ))
            }
          />
          <Divider />
          <ListItem
            disabled
            open
            primaryText="Platos"
            rightIcon={
              <Link to={linkDish}>
                <ContentAdd />
              </Link>
            }
            nestedItems={
              dishes && dishes.map((dish, i) => (
                <ListItem
                  key={i}
                  disabled
                  primaryText={dish.selected.nombre}
                  secondaryText={dish.quantity}
                />
              ))
            }
          />
        </Card>
      </List>
    </CardText>
    <CardActions>
      <Grid fluid>
        <Row center="xs">
          <Col xs>
            <RaisedButton label="Enviar Comandas" onTouchTap={() => onCloseOrder()} />
          </Col>
        </Row>
      </Grid>
    </CardActions>
  </Card>
);

OrderAddForm.propTypes = {
  promos: PropTypes.array,
  products: PropTypes.array,
  dishes: PropTypes.array,
  onCloseOrder: PropTypes.func,
  linkPromo: PropTypes.string,
  linkProduct: PropTypes.string,
  linkDish: PropTypes.string,
};

export default OrderAddForm;
<|endoftext|>


<commit_before>/*
*/

var	$signDiv;
var	$searchDiv;
var	$alert;
var $results;
var $navSignBt;

function computeContextFromForm(form) {
	$.each($(form).serializeArray(), function(i, field) {
		sessionStorage[field.name] = field.value;
	});
	console.log(sessionStorage);
}

function showSearchDiv() {
	sessionStorage.signInOk = 'true';
	resetNavSignButton();

	$('#user-info').html('=> Username: [' + sessionStorage.username
		+ '], application identifier: [' + sessionStorage.id + ']');
	$signDiv.css('visibility', 'hidden');
	$signDiv.css('display', 'none');
	$searchDiv.css('visibility', 'visible');
	$searchDiv.css('display', 'block');
	$searchDiv.find('[name="q"]').focus();
	$alert = $('#search-alert');
}

function showSignDiv() {
	resetNavSignButton();

	$signDiv.css('visibility', 'visible');
	$signDiv.css('display', 'block');
	$searchDiv.css('visibility', 'hidden');
	$searchDiv.css('display', 'none');

	$('#sign-form').find('[name="username"]').focus();
	$searchDiv.css('visibility', 'hidden');
	$alert = $('#sign-alert');
}

function searchOk(data, textStatus, jqXHR) {
	$alert.html('=> [' + data.total + '] result(s), search took [' + data.took + '] millisecond(s)');
	console.log(data);

	$results.empty();
	for (i=0; i < data.total; i++)
		$results.append('
'
			 + JSON.stringify(data.results[i], null, 4)
			 + '

')

	prettyPrint();
}

function showError(jqxhr, textStatus, errorThrown) {
	console.log(textStatus + ': ' + errorThrown);
	console.log(jqxhr);

	if (errorThrown) $alert.html('=> ' +  errorThrown);
	else $alert.html('=> ' + textStatus);
	if (jqxhr.responseJSON) $alert.append(': ' + jqxhr.responseJSON.error.message);
}

function signIn(event) {
	console.log('Signing in...');
	computeContextFromForm('#sign-form');

	$.ajax({
		method: "GET",
		url: "http://localhost:8080/v1/login",
		cache: false,
		headers : {
			'x-magic-app-id':  sessionStorage.id,
			Authorization: 'Basic ' + btoa(sessionStorage.username + ':' + sessionStorage.password)
		},
		success: showSearchDiv,
		error: showError
	});

	$('#sign-in').blur();
	return false;
}

function createAccount(event) {
	console.log('Creating account...');
	computeContextFromForm('#create-form');

	$.ajax({
		method: 'POST',
		url: 'http://localhost:8080/v1/account',
		cache: false,
		contentType: 'application/json; charset=UTF-8',
		data: JSON.stringify(sessionStorage),
		processData: false,
		success: showSearchDiv,
		error: showError
	});

	$('#create-account').blur();
	return false;
}

function searchObjects(event) {
	console.log('Searching objects ...');

	$.ajax({
		method: "GET",
		url: "http://localhost:8080/v1/data",
		cache: false,
		headers : {
			'x-magic-app-id':  sessionStorage.id,
			Authorization: 'Basic ' + btoa(sessionStorage.username + ':' + sessionStorage.password)
		},
		data: $('#search-form').serialize(),
		success: searchOk,
		error: showError
	});

	$searchDiv.find('[name="q"]').focus();
	return false;
}

function resetNavSignButton() {
	if (sessionStorage.signInOk) {
		$navSignBt.html('Sign out');
		$navSignBt.one('click', function () {
			sessionStorage.removeItem('signInOk');
			resetNavSignButton();
			if (window.location.pathname == '/console.html') showSignDiv();
			return false;
		});
	} else {
		$navSignBt.html('Sign in');
		$navSignBt.click(function () {
			window.location.assign('/console.html');
		});
	}
}

function init() {

	$navSignBt = $('#nav-sign-bt');
	resetNavSignButton();

	if (window.location.pathname == '/console.html') {

		$signDiv = $('#sign-div');
		$searchDiv = $('#search-div');
		$alert = $('#sign-alert');
		$results = $('#search-results');

		$('#sign-form').submit(signIn);
		$('#create-form').submit(createAccount);
		$('#search-form').submit(searchObjects);

		if (sessionStorage.signInOk) showSearchDiv();
		else showSignDiv();
	}
}

$(document).ready(init);<commit_msg>Sets the search page size to 25. Fixes the number of results displayed. Changes the welcome message.<commit_after>/*
*/

var	$signDiv;
var	$searchDiv;
var	$alert;
var $results;
var $navSignBt;

function computeContextFromForm(form) {
	$.each($(form).serializeArray(), function(i, field) {
		sessionStorage[field.name] = field.value;
	});
	console.log(sessionStorage);
}

function showSearchDiv() {
	sessionStorage.signInOk = 'true';
	resetNavSignButton();

	$('#user-info').html('=> Hello [' + sessionStorage.username
		+ '], your x-magic-app-id is [' + sessionStorage.id + ']');
	$signDiv.css('visibility', 'hidden');
	$signDiv.css('display', 'none');
	$searchDiv.css('visibility', 'visible');
	$searchDiv.css('display', 'block');
	$searchDiv.find('[name="q"]').focus();
	$alert = $('#search-alert');
}

function showSignDiv() {
	resetNavSignButton();

	$signDiv.css('visibility', 'visible');
	$signDiv.css('display', 'block');
	$searchDiv.css('visibility', 'hidden');
	$searchDiv.css('display', 'none');

	$('#sign-form').find('[name="username"]').focus();
	$searchDiv.css('visibility', 'hidden');
	$alert = $('#sign-alert');
}

function searchOk(data, textStatus, jqXHR) {
	$alert.html('=> [' + data.total + '] result(s), [' + data.results.length + '] displayed, search took [' + data.took + '] millisecond(s)');
	console.log(data);

	$results.empty();
	for (i=0; i < data.results.length; i++)
		$results.append('
'
			 + JSON.stringify(data.results[i], null, 4)
			 + '

')

	prettyPrint();
}

function showError(jqxhr, textStatus, errorThrown) {
	console.log(textStatus + ': ' + errorThrown);
	console.log(jqxhr);

	if (errorThrown) $alert.html('=> ' +  errorThrown);
	else $alert.html('=> ' + textStatus);
	if (jqxhr.responseJSON) $alert.append(': ' + jqxhr.responseJSON.error.message);
}

function signIn(event) {
	console.log('Signing in...');
	computeContextFromForm('#sign-form');

	$.ajax({
		method: "GET",
		url: "http://localhost:8080/v1/login",
		cache: false,
		headers : {
			'x-magic-app-id':  sessionStorage.id,
			Authorization: 'Basic ' + btoa(sessionStorage.username + ':' + sessionStorage.password)
		},
		success: showSearchDiv,
		error: showError
	});

	$('#sign-in').blur();
	return false;
}

function createAccount(event) {
	console.log('Creating account...');
	computeContextFromForm('#create-form');

	$.ajax({
		method: 'POST',
		url: 'http://localhost:8080/v1/account',
		cache: false,
		contentType: 'application/json; charset=UTF-8',
		data: JSON.stringify(sessionStorage),
		processData: false,
		success: showSearchDiv,
		error: showError
	});

	$('#create-account').blur();
	return false;
}

function searchObjects(event) {
	console.log('Searching objects ...');

	$.ajax({
		method: "GET",
		url: "http://localhost:8080/v1/data",
		cache: false,
		headers : {
			'x-magic-app-id':  sessionStorage.id,
			Authorization: 'Basic ' + btoa(sessionStorage.username + ':' + sessionStorage.password)
		},
		data: {
			q: $('input[name="q"]').val(),
			from: 0,
			size: 25
		},
		success: searchOk,
		error: showError
	});

	$searchDiv.find('input[name="q"]').focus();
	return false;
}

function resetNavSignButton() {
	if (sessionStorage.signInOk) {
		$navSignBt.html('Sign out');
		$navSignBt.one('click', function () {
			sessionStorage.removeItem('signInOk');
			resetNavSignButton();
			if (window.location.pathname == '/console.html') showSignDiv();
			return false;
		});
	} else {
		$navSignBt.html('Sign in');
		$navSignBt.click(function () {
			window.location.assign('/console.html');
		});
	}
}

function init() {

	$navSignBt = $('#nav-sign-bt');
	resetNavSignButton();

	if (window.location.pathname == '/console.html') {

		$signDiv = $('#sign-div');
		$searchDiv = $('#search-div');
		$alert = $('#sign-alert');
		$results = $('#search-results');

		$('#sign-form').submit(signIn);
		$('#create-form').submit(createAccount);
		$('#search-form').submit(searchObjects);

		if (sessionStorage.signInOk) showSearchDiv();
		else showSignDiv();
	}
}

$(document).ready(init);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { fullscreen } from '../utils';
import Video from './Video';

import './CollageCanvas.css';
// import DogGridSvg from '../svgs/dot-grid.svg';
// import PlaySvg from '../svgs/play.svg';
import FullscreenSvg from '../svgs/fullscreen.svg';
import FullscreenOffSvg from '../svgs/fullscreen-off.svg';

export default class CollageCanvas extends Component {
  static propTypes = {
    collage: PropTypes.object.isRequired
  }

  state = {
    background: null
  }

  constructor() {
    super();
    this.resized = this.resized.bind(this);
    this.play = this.play.bind(this);
    this.fullscreen = this.fullscreen.bind(this);
    this.registerChildPlayer = this.registerChildPlayer.bind(this);
    this.muteAllPlayers = this.muteAllPlayers.bind(this);

    this.players = [];
  }

  componentDidMount() {
    this.loadResources();
    window.addEventListener('resize', this.resized);
    this.resized();
  }

  componentDidUpdate(prevProps, prevState) {
    if(prevProps.collage.id !== this.props.collage.id) {
      this.loadResources();
    }
    this.drawCanvas();
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resized);
  }

  registerChildPlayer(player) {
    this.players.push(player);
  }

  play() {
    // Loop though all the video elements and start playback
    this.resources.videos.forEach(video => {
      if(!video.player.paused()) {
        video.player.pause();
      }
      video.player.play();
    });
  }

  muteAllPlayers(exceptPlayer) {
    this.players.forEach(player => {
      if(player !== exceptPlayer) {
        player.muted(true);
      }
    });
  }

  /* Loads the background image and all the videos that makes up the collage */
  loadResources() {
    const collage = this.props.collage;
    // The background image
    const background = document.createElement('img');
    background.addEventListener('load', () => {
      this.setState({ background });
    });
    background.src = collage.image;
  }

  drawCanvas() {
    // Initiate the canvas
    const ctx = this.canvas.getContext('2d');

    if(this.state.background) {
      const backgroundPosition = this.backgroundPosition();

      ctx.drawImage(
        this.state.background,
        backgroundPosition.x,
        backgroundPosition.y,
        backgroundPosition.width,
        backgroundPosition.height
      );
    }
  }

  resized() {
    const devicePixelRatio = window.devicePixelRatio || 1;
    this.canvas.height = this.canvas.offsetHeight * devicePixelRatio;
    this.canvas.width = this.canvas.offsetWidth * devicePixelRatio;
    this.setState(this.state);
  }

  fullscreen() {
    if (!fullscreen.is()) {
      fullscreen.request(this.everything);
    } else {
      fullscreen.exit();
    }
    // Update the state
    this.setState({
      fullscreen: fullscreen.is()
    });
  }

  backgroundPosition() {
    const background = this.state.background;
    const canvas = this.canvas;

    const canvasRatio = canvas.width / canvas.height;
    const backgroundRatio = background.width / background.height;

    if(canvasRatio > backgroundRatio) {
      const height = canvas.height;
      const width = canvas.height * backgroundRatio;
      return {
        height,
        width,
        x: (canvas.width - width) / 2,
        y: 0
      }
    } else {
      const height = canvas.width / backgroundRatio;
      const width = canvas.width;
      return {
        height,
        width,
        x: 0,
        y: (canvas.height - height) / 2
      }
    }
  }

  render() {
    return (

 { this.everything = e; }}>
        <canvas className="CollageCanvas__canvas"
          ref={(e) => { this.canvas = e; }} />

        { this.state.background &&
          this.props.collage.videos.map(video => {
            return (
              <Video
                key={video.videoData.title}
                video={video}
                background={this.backgroundPosition()}
                registerChildPlayer={this.registerChildPlayer}
                muteAllPlayers={this.muteAllPlayers}/> )})
        }

            Del på Facebook

            DKA

          {this.state.fullscreen ? (

          ) : (

          )}

    );
  }
}
<commit_msg>Remove play method<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { fullscreen } from '../utils';
import Video from './Video';

import './CollageCanvas.css';
// import DogGridSvg from '../svgs/dot-grid.svg';
// import PlaySvg from '../svgs/play.svg';
import FullscreenSvg from '../svgs/fullscreen.svg';
import FullscreenOffSvg from '../svgs/fullscreen-off.svg';

export default class CollageCanvas extends Component {
  static propTypes = {
    collage: PropTypes.object.isRequired
  }

  state = {
    background: null
  }

  constructor() {
    super();
    this.resized = this.resized.bind(this);
    this.fullscreen = this.fullscreen.bind(this);
    this.registerChildPlayer = this.registerChildPlayer.bind(this);
    this.muteAllPlayers = this.muteAllPlayers.bind(this);

    this.players = [];
  }

  componentDidMount() {
    this.loadResources();
    window.addEventListener('resize', this.resized);
    this.resized();
  }

  componentDidUpdate(prevProps, prevState) {
    if(prevProps.collage.id !== this.props.collage.id) {
      this.loadResources();
    }
    this.drawCanvas();
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resized);
  }

  registerChildPlayer(player) {
    this.players.push(player);
  }

  muteAllPlayers(exceptPlayer) {
    this.players.forEach(player => {
      if(player !== exceptPlayer) {
        player.muted(true);
      }
    });
  }

  /* Loads the background image*/
  loadResources() {
    const collage = this.props.collage;
    // The background image
    const background = document.createElement('img');
    background.addEventListener('load', () => this.setState({ background }) );
    // Start loading the image so we can trigger the above listener.
    background.src = collage.image;
  }

  drawCanvas() {
    // Initiate the canvas
    const ctx = this.canvas.getContext('2d');

    if(this.state.background) {
      const backgroundPosition = this.backgroundPosition();

      ctx.drawImage(
        this.state.background,
        backgroundPosition.x,
        backgroundPosition.y,
        backgroundPosition.width,
        backgroundPosition.height
      );
    }
  }

  resized() {
    const devicePixelRatio = window.devicePixelRatio || 1;
    this.canvas.height = this.canvas.offsetHeight * devicePixelRatio;
    this.canvas.width = this.canvas.offsetWidth * devicePixelRatio;
    this.setState(this.state);
  }

  fullscreen() {
    if (!fullscreen.is()) {
      fullscreen.request(this.everything);
    } else {
      fullscreen.exit();
    }
    // Update the state
    this.setState({
      fullscreen: fullscreen.is()
    });
  }

  backgroundPosition() {
    const background = this.state.background;
    const canvas = this.canvas;

    const canvasRatio = canvas.width / canvas.height;
    const backgroundRatio = background.width / background.height;

    if(canvasRatio > backgroundRatio) {
      const height = canvas.height;
      const width = canvas.height * backgroundRatio;
      return {
        height,
        width,
        x: (canvas.width - width) / 2,
        y: 0
      }
    } else {
      const height = canvas.width / backgroundRatio;
      const width = canvas.width;
      return {
        height,
        width,
        x: 0,
        y: (canvas.height - height) / 2
      }
    }
  }

  render() {
    return (

 { this.everything = e; }}>
        <canvas className="CollageCanvas__canvas"
          ref={(e) => { this.canvas = e; }} />

        { this.state.background &&
          this.props.collage.videos.map(video => {
            return (
              <Video
                key={video.videoData.title}
                video={video}
                background={this.backgroundPosition()}
                registerChildPlayer={this.registerChildPlayer}
                muteAllPlayers={this.muteAllPlayers}/> )})
        }

            Del på Facebook

            DKA

          {this.state.fullscreen ? (

          ) : (

          )}

    );
  }
}
<|endoftext|>