<commit_before>import ClipperLib from 'clipper-lib';

let errorCallback;
export const setErrorCallback = (callback) => {
  errorCallback = callback;
}
ClipperLib.Error = (message) => {
  if (errorCallback) errorCallback(message);
}

const CLIPPER = new ClipperLib.Clipper();
const CLIPPER_OFFSET = new ClipperLib.ClipperOffset();

export default class Shape {
  constructor(paths = [], closed = true, capitalConversion = false, integerConversion = false, removeDuplicates = false) {
    this.paths = paths;
    if (capitalConversion) this.paths = this.paths.map(mapLowerToCapital);
    if (integerConversion) this.paths = this.paths.map(mapToRound);
    if (removeDuplicates) this.paths = this.paths.map(filterPathsDuplicates);
    this.closed = closed;
  }

  _clip(type, ...clipShapes) {
    const solution = new ClipperLib.PolyTree();

    CLIPPER.Clear();
    CLIPPER.AddPaths(this.paths, ClipperLib.PolyType.ptSubject, this.closed);
    for (let i = 0; i < clipShapes.length; i ++) {
      const clipShape = clipShapes[i];
      CLIPPER.AddPaths(clipShape.paths, ClipperLib.PolyType.ptClip, clipShape.closed);
    }
    CLIPPER.Execute(type, solution);

    const newShape = ClipperLib.Clipper.PolyTreeToPaths(solution);
    return new Shape(newShape, this.closed);
  }

  union(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctUnion, ...clipShapes);
  }

  difference(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctDifference, ...clipShapes);
  }

  intersect(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctIntersection, ...clipShapes);
  }

  xor(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctXor, ...clipShapes);
  }

  offset(offset, options = {}) {
    const {
      jointType = 'jtSquare',
      endType = 'etClosedPolygon',
      miterLimit = 2.0,
      roundPrecision = 0.25
    } = options;

    CLIPPER_OFFSET.Clear();
    CLIPPER_OFFSET.ArcTolerance = roundPrecision;
    CLIPPER_OFFSET.MiterLimit = miterLimit;

    const offsetPaths = new ClipperLib.Paths();
    CLIPPER_OFFSET.AddPaths(this.paths, ClipperLib.JoinType[jointType], ClipperLib.EndType[endType]);
    CLIPPER_OFFSET.Execute(offsetPaths, offset);

    return new Shape(offsetPaths, true);
  }

  scaleUp(factor) {
    ClipperLib.JS.ScaleUpPaths(this.paths, factor);

    return this;
  }

  scaleDown(factor) {
    ClipperLib.JS.ScaleDownPaths(this.paths, factor);

    return this;
  }

  firstPoint(toLower = false) {
    if (this.paths.length === 0) {
      return;
    }

    const firstPath = this.paths[0];
    const firstPoint = firstPath[0];
    if (toLower) {
      return vectorToLower(firstPoint);
    } else {
      return firstPoint;
    }
  }

  lastPoint(toLower = false) {
    if (this.paths.length === 0) {
      return;
    }

    const lastPath = this.paths[this.paths.length - 1];
    const lastPoint = this.closed ? lastPath[0] : lastPath[lastPath.length - 1];
    if (toLower) {
      return vectorToLower(lastPoint);
    } else {
      return lastPoint;
    }
  }

  areas() {
    const areas = this.paths.map((path, i) => this.area(i));
    return areas;
  }

  area(index) {
    const path = this.paths[index];
    const area = ClipperLib.Clipper.Area(path);
    return area;
  }

  totalArea() {
    return this.areas().reduce((totalArea, area) => totalArea + area, 0);
  }

  perimeter(index) {
    const path = this.paths[index];
    const perimeter = ClipperLib.JS.PerimeterOfPath(path, this.closed, 1);
    return perimeter;
  }

  perimeters() {
    return this.paths.map(path => ClipperLib.JS.PerimeterOfPath(path, this.closed, 1));
  }

  totalPerimeter() {
    const perimeter = ClipperLib.JS.PerimeterOfPaths(this.paths, this.closed);
    return perimeter;
  }

  reverse() {
    ClipperLib.Clipper.ReversePaths(this.paths);

    return this;
  }

  thresholdArea(minArea) {
    for (const path of [...this.paths]) {
      const area = Math.abs(ClipperLib.Clipper.Area(path));

      if (area < minArea) {
        const index = this.paths.indexOf(path);
        this.paths.splice(index, 1);
      }
    }
    return this;
  }

  join(shape) {
    this.paths.splice(this.paths.length, 0, ...shape.paths);

    return this;
  }

  clone() {
    return new Shape(ClipperLib.JS.Clone(this.paths), this.closed);
  }

  shapeBounds() {
    return ClipperLib.JS.BoundsOfPaths(this.paths);
  }

  pathBounds(index) {
    const path = this.paths[index];

    return ClipperLib.JS.BoundsOfPath(path);
  }

  clean(cleanDelta) {
    return new Shape(ClipperLib.Clipper.CleanPolygons(this.paths, cleanDelta), this.closed);
  }

  orientation(index) {
    const path = this.paths[index];
    return ClipperLib.Clipper.Orientation(path);
  }

  pointInShape(point, capitalConversion = false, integerConversion = false) {
    if (capitalConversion) point = vectorToCapital(point);
    if (integerConversion) point = roundVector(point);
    for (let i = 0; i < this.paths.length; i ++) {
      const pointInPath = this.pointInPath(i, point);
      const orientation = this.orientation(i);

      if ((!pointInPath && orientation) || (pointInPath && !orientation)) {
        return false;
      }
    }

    return true;
  }

  pointInPath(index, point, capitalConversion = false, integerConversion = false) {
    if (capitalConversion) point = vectorToCapital(point);
    if (integerConversion) point = roundVector(point);
    const path = this.paths[index];
    const intPoint = { X: Math.round(point.X), Y: Math.round(point.Y) };

    return ClipperLib.Clipper.PointInPolygon(intPoint, path) > 0;
  }

  fixOrientation() {
    if (!this.closed) {
      return this;
    }

    if (this.totalArea() < 0) {
      this.reverse();
    }

    return this;
  }

  simplify(fillType) {
    if (this.closed) {
      const shape = ClipperLib.Clipper.SimplifyPolygons(this.paths, ClipperLib.PolyFillType[fillType]);
      return new Shape(shape, true);
    } else {
      return this;
    }
  }

  seperateShapes() {
    const shapes = [];

    if (!this.closed) {
      for (const path of this.paths) {
        shapes.push(new Shape([path], false));
      }
    } else {
      const areas = new WeakMap();
      const outlines = [];
      const holes = [];

      for (let i = 0; i < this.paths.length; i ++) {
        const path = this.paths[i];
        const orientation = this.orientation(i);

        if (orientation) {
          const area = this.area(i);
          areas.set(path, area);
          outlines.push(path);
        } else {
          holes.push(path);
        }
      }

      outlines.sort((a, b) => areas.get(a) - areas.get(b));

      for (const outline of outlines) {
        const shape = [outline];

        const index = this.paths.indexOf(outline);

        for (const hole of [...holes]) {
          const pointInHole = this.pointInPath(index, hole[0]);
          if (pointInHole) {
            shape.push(hole);

            const index = holes.indexOf(hole);
            holes.splice(index, 1);
          }
        }

        shapes.push(new Shape(shape, true));
      }
    }

    return shapes;
  }

  round() {
    return new Shape(this.paths.map(mapToRound), this.closed);
  }

  removeDuplicates() {
    return new Shape(this.paths.map(filterPathsDuplicates), this.closed);
  }

  mapToLower() {
    return this.paths.map(mapCapitalToLower);
  }
}

function mapCapitalToLower(path) {
  return path.map(vectorToLower);
}

function vectorToLower({ X, Y }) {
  return { x: X, y: Y };
}

function mapLowerToCapital(path) {
  return path.map(vectorToCapital);
}

function vectorToCapital({ x, y }) {
  return { X: x, Y: y };
}

function mapToRound(path) {
  return path.map(roundVector);
}

function roundVector({ X, Y }) {
  return { X: Math.round(X), Y: Math.round(Y) };
}

function filterPathsDuplicates(path) {
  return path.filter(filterPathDuplicates);
}

function filterPathDuplicates(point, i, array) {
  if (i === 0) return true;

  const prevPoint = array[i - 1];
  return !(point.X === prevPoint.X && point.Y === prevPoint.Y);
}
<commit_msg>Update ClipperLib import to match npm module<commit_after>import ClipperLib from '@doodle3d/clipper-lib/clipper';

let errorCallback;
export const setErrorCallback = (callback) => {
  errorCallback = callback;
}
ClipperLib.Error = (message) => {
  if (errorCallback) errorCallback(message);
}

const CLIPPER = new ClipperLib.Clipper();
const CLIPPER_OFFSET = new ClipperLib.ClipperOffset();

export default class Shape {
  constructor(paths = [], closed = true, capitalConversion = false, integerConversion = false, removeDuplicates = false) {
    this.paths = paths;
    if (capitalConversion) this.paths = this.paths.map(mapLowerToCapital);
    if (integerConversion) this.paths = this.paths.map(mapToRound);
    if (removeDuplicates) this.paths = this.paths.map(filterPathsDuplicates);
    this.closed = closed;
  }

  _clip(type, ...clipShapes) {
    const solution = new ClipperLib.PolyTree();

    CLIPPER.Clear();
    CLIPPER.AddPaths(this.paths, ClipperLib.PolyType.ptSubject, this.closed);
    for (let i = 0; i < clipShapes.length; i ++) {
      const clipShape = clipShapes[i];
      CLIPPER.AddPaths(clipShape.paths, ClipperLib.PolyType.ptClip, clipShape.closed);
    }
    CLIPPER.Execute(type, solution);

    const newShape = ClipperLib.Clipper.PolyTreeToPaths(solution);
    return new Shape(newShape, this.closed);
  }

  union(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctUnion, ...clipShapes);
  }

  difference(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctDifference, ...clipShapes);
  }

  intersect(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctIntersection, ...clipShapes);
  }

  xor(...clipShapes) {
    return this._clip(ClipperLib.ClipType.ctXor, ...clipShapes);
  }

  offset(offset, options = {}) {
    const {
      jointType = 'jtSquare',
      endType = 'etClosedPolygon',
      miterLimit = 2.0,
      roundPrecision = 0.25
    } = options;

    CLIPPER_OFFSET.Clear();
    CLIPPER_OFFSET.ArcTolerance = roundPrecision;
    CLIPPER_OFFSET.MiterLimit = miterLimit;

    const offsetPaths = new ClipperLib.Paths();
    CLIPPER_OFFSET.AddPaths(this.paths, ClipperLib.JoinType[jointType], ClipperLib.EndType[endType]);
    CLIPPER_OFFSET.Execute(offsetPaths, offset);

    return new Shape(offsetPaths, true);
  }

  scaleUp(factor) {
    ClipperLib.JS.ScaleUpPaths(this.paths, factor);

    return this;
  }

  scaleDown(factor) {
    ClipperLib.JS.ScaleDownPaths(this.paths, factor);

    return this;
  }

  firstPoint(toLower = false) {
    if (this.paths.length === 0) {
      return;
    }

    const firstPath = this.paths[0];
    const firstPoint = firstPath[0];
    if (toLower) {
      return vectorToLower(firstPoint);
    } else {
      return firstPoint;
    }
  }

  lastPoint(toLower = false) {
    if (this.paths.length === 0) {
      return;
    }

    const lastPath = this.paths[this.paths.length - 1];
    const lastPoint = this.closed ? lastPath[0] : lastPath[lastPath.length - 1];
    if (toLower) {
      return vectorToLower(lastPoint);
    } else {
      return lastPoint;
    }
  }

  areas() {
    const areas = this.paths.map((path, i) => this.area(i));
    return areas;
  }

  area(index) {
    const path = this.paths[index];
    const area = ClipperLib.Clipper.Area(path);
    return area;
  }

  totalArea() {
    return this.areas().reduce((totalArea, area) => totalArea + area, 0);
  }

  perimeter(index) {
    const path = this.paths[index];
    const perimeter = ClipperLib.JS.PerimeterOfPath(path, this.closed, 1);
    return perimeter;
  }

  perimeters() {
    return this.paths.map(path => ClipperLib.JS.PerimeterOfPath(path, this.closed, 1));
  }

  totalPerimeter() {
    const perimeter = ClipperLib.JS.PerimeterOfPaths(this.paths, this.closed);
    return perimeter;
  }

  reverse() {
    ClipperLib.Clipper.ReversePaths(this.paths);

    return this;
  }

  thresholdArea(minArea) {
    for (const path of [...this.paths]) {
      const area = Math.abs(ClipperLib.Clipper.Area(path));

      if (area < minArea) {
        const index = this.paths.indexOf(path);
        this.paths.splice(index, 1);
      }
    }
    return this;
  }

  join(shape) {
    this.paths.splice(this.paths.length, 0, ...shape.paths);

    return this;
  }

  clone() {
    return new Shape(ClipperLib.JS.Clone(this.paths), this.closed);
  }

  shapeBounds() {
    return ClipperLib.JS.BoundsOfPaths(this.paths);
  }

  pathBounds(index) {
    const path = this.paths[index];

    return ClipperLib.JS.BoundsOfPath(path);
  }

  clean(cleanDelta) {
    return new Shape(ClipperLib.Clipper.CleanPolygons(this.paths, cleanDelta), this.closed);
  }

  orientation(index) {
    const path = this.paths[index];
    return ClipperLib.Clipper.Orientation(path);
  }

  pointInShape(point, capitalConversion = false, integerConversion = false) {
    if (capitalConversion) point = vectorToCapital(point);
    if (integerConversion) point = roundVector(point);
    for (let i = 0; i < this.paths.length; i ++) {
      const pointInPath = this.pointInPath(i, point);
      const orientation = this.orientation(i);

      if ((!pointInPath && orientation) || (pointInPath && !orientation)) {
        return false;
      }
    }

    return true;
  }

  pointInPath(index, point, capitalConversion = false, integerConversion = false) {
    if (capitalConversion) point = vectorToCapital(point);
    if (integerConversion) point = roundVector(point);
    const path = this.paths[index];
    const intPoint = { X: Math.round(point.X), Y: Math.round(point.Y) };

    return ClipperLib.Clipper.PointInPolygon(intPoint, path) > 0;
  }

  fixOrientation() {
    if (!this.closed) {
      return this;
    }

    if (this.totalArea() < 0) {
      this.reverse();
    }

    return this;
  }

  simplify(fillType) {
    if (this.closed) {
      const shape = ClipperLib.Clipper.SimplifyPolygons(this.paths, ClipperLib.PolyFillType[fillType]);
      return new Shape(shape, true);
    } else {
      return this;
    }
  }

  seperateShapes() {
    const shapes = [];

    if (!this.closed) {
      for (const path of this.paths) {
        shapes.push(new Shape([path], false));
      }
    } else {
      const areas = new WeakMap();
      const outlines = [];
      const holes = [];

      for (let i = 0; i < this.paths.length; i ++) {
        const path = this.paths[i];
        const orientation = this.orientation(i);

        if (orientation) {
          const area = this.area(i);
          areas.set(path, area);
          outlines.push(path);
        } else {
          holes.push(path);
        }
      }

      outlines.sort((a, b) => areas.get(a) - areas.get(b));

      for (const outline of outlines) {
        const shape = [outline];

        const index = this.paths.indexOf(outline);

        for (const hole of [...holes]) {
          const pointInHole = this.pointInPath(index, hole[0]);
          if (pointInHole) {
            shape.push(hole);

            const index = holes.indexOf(hole);
            holes.splice(index, 1);
          }
        }

        shapes.push(new Shape(shape, true));
      }
    }

    return shapes;
  }

  round() {
    return new Shape(this.paths.map(mapToRound), this.closed);
  }

  removeDuplicates() {
    return new Shape(this.paths.map(filterPathsDuplicates), this.closed);
  }

  mapToLower() {
    return this.paths.map(mapCapitalToLower);
  }
}

function mapCapitalToLower(path) {
  return path.map(vectorToLower);
}

function vectorToLower({ X, Y }) {
  return { x: X, y: Y };
}

function mapLowerToCapital(path) {
  return path.map(vectorToCapital);
}

function vectorToCapital({ x, y }) {
  return { X: x, Y: y };
}

function mapToRound(path) {
  return path.map(roundVector);
}

function roundVector({ X, Y }) {
  return { X: Math.round(X), Y: Math.round(Y) };
}

function filterPathsDuplicates(path) {
  return path.filter(filterPathDuplicates);
}

function filterPathDuplicates(point, i, array) {
  if (i === 0) return true;

  const prevPoint = array[i - 1];
  return !(point.X === prevPoint.X && point.Y === prevPoint.Y);
}
<|endoftext|>


<commit_before>import { prefix } from './config';
import { toArray } from './util';
import SocialLikes from './social-likes';

// Symbol to store an instance reference in a DOM node
const symbol = 'socialLikes';

/**
 * Initialize Social Likes on a DOM element.
 *
 * @param {HTMLElement} elem DOM element.
 * @param {Object} [options] Options.
 * @return {SocialLikes}
 */
function init(elem, options = {}) {
	let instance = elem[symbol];
	if (instance) {
		instance.update(options);
	}
	else {
		elem[symbol] = new SocialLikes(elem, options);
	}
	return instance;
}

function autoInit(wait = false) {
	let elements = document.querySelectorAll(`.${prefix}`);
	if (elements) {
		toArray(elements).forEach(init);
	}
	else if (wait) {
		// No elements found. Wait for DOM content loaded to try again in case the script was included in the <head>.
		document.addEventListener('DOMContentLoaded', autoInit);
	}
}

// Auto initialization
autoInit(true);

// Expose
export default init;
<commit_msg>Do not pass index as options to constructor.<commit_after>import { prefix } from './config';
import { toArray } from './util';
import SocialLikes from './social-likes';

// Symbol to store an instance reference in a DOM node
const symbol = 'socialLikes';

/**
 * Initialize Social Likes on a DOM element.
 *
 * @param {HTMLElement} elem DOM element.
 * @param {Object} [options] Options.
 * @return {SocialLikes}
 */
function init(elem, options = {}) {
	let instance = elem[symbol];
	if (instance) {
		instance.update(options);
	}
	else {
		elem[symbol] = new SocialLikes(elem, options);
	}
	return instance;
}

function autoInit(wait = false) {
	let elements = document.querySelectorAll(`.${prefix}`);
	if (elements) {
		toArray(elements).forEach(elem => init(elem));
	}
	else if (wait) {
		// No elements found. Wait for DOM content loaded to try again in case the script was included in the <head>.
		document.addEventListener('DOMContentLoaded', autoInit);
	}
}

// Auto initialization
autoInit(true);

// Expose
export default init;
<|endoftext|>


<commit_before>/*
 * grunt-html-head-urls-min-toggle
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
	grunt
	    .registerMultiTask('html_head_urls_min_toggle',
	        'Point the html-head href and src urls to minified sources and vice versa.', function() {
		        var global_functions = {};
		        global_functions = require('./html_head_urls_min_toggle__global_functions.js');
		        // global_functions.serialize_object_to_disk(this,
		        // './etc/this_sample_object.json');
		        var fileSystem_Module = global_functions.globalModule_Try('fs');
		        var currentFileHandle;
		        var options_reference_object;
		        try {
			        currentFileHandle = fileSystem_Module.openSync(
			            './node_modules/grunt-html-head-urls-min-toggle/etc/global_options.json', 'r');
			        console.log("LOADED \"OUTDOORS\" VALID REFERENCE OPTIONS...");
		        } catch (current_exception) {
			        console.log("CATCHED...: \"" + current_exception + "\"");
		        }
		        if (currentFileHandle === undefined) {
			        try {
				        currentFileHandle = fileSystem_Module.openSync('./etc/global_options.jsonX', 'r');
				        console.log("LOADED VALID REFERENCE OPTIONS ON DEVELOPMENT ENVIRONMENT...");
			        } catch (current_exception) {
				        console.log("CATCHED: \"" + current_exception + "\"");
			        }
		        }
		        if (currentFileHandle !== undefined) {
			        console.log("VALID FILE HANDLE: \"" + currentFileHandle + "\" FOUND...!");
			        options_reference_object = JSON.parse(fileSystem_Module.readFileSync(currentFileHandle));
			        fileSystem_Module.closeSync(currentFileHandle);
		        } else {
			        console.log("INVALID FILE HANDLE...! LOADING IN HOUSE REFERENCE OPTIONS...!");
			        options_reference_object = {
			          action : [ 'switch', 'clean' ],
			          direction : [ 'min', 'regular' ],
			          file_source : [ 'wildcard', 'list' ]
			        };
		        }
		        var action__current_value = global_functions.casual__options_property_servant(this.data.options,
		            options_reference_object, 'action');
		        if (action__current_value) {
			        switch (action__current_value) {
			        case 'switch':
				        var file_source = global_functions.casual__options_property_servant(this.data.options,
				            options_reference_object, 'file_source');
				        if (file_source === 'list') {
					        for (var il = 0; il < this.data.custom_files.length; il++) {
						        grunt.log.write("\t" + (il + 1) + ": \"" + this.data.custom_files[il] + "\"");
						        if (global_functions.toggle_all_head_links(this.data.options.direction, this.data.custom_files[il])) {
							        grunt.log.write("\t- to \""['green'] + this.data.options.direction['green'] + "\" o.k."['green'] +
							            "\n");
						        } else {
							        grunt.log.write("\t- to \""['red'] + this.data.options.direction['red'] +
							            "\">>> Failed...! <<<"['red'] + "\n");
						        }
					        }
				        }
				        if (file_source === 'wildcard') {
					        for (var ow = 0; ow < this.data.custom_files.length; ow++) {
						        if (this.data.custom_files[ow].hasOwnProperty('cwd') &&
						            this.data.custom_files[ow].hasOwnProperty('src')) {
							        var inner_files_array = global_functions.process_wildcard_input(this.data.custom_files[ow].src,
							            this.data.custom_files[ow].cwd);
							        for (var iw = 0; iw < inner_files_array.length; iw++) {
								        grunt.log.write("\t" + (iw + 1) + ": \"" + inner_files_array[iw] + "\"");
								        if (global_functions.toggle_all_head_links(this.data.options.direction, inner_files_array[iw])) {
									        grunt.log.write("\t- to \""['green'] + this.data.options.direction['green'] + "\" o.k."['green'] +
									            "\n");
								        } else {
									        grunt.log.write("\t- to \""['red'] + this.data.options.direction['red'] +
									            "\">>> Failed...! <<<"['red'] + "\n");
								        }
							        }
						        } else {
							        console.log("MISSING NEEDED \"WILDCARD\" FILE PROPERTIES...!");
							        break;
						        }
					        }
					        break;
				        }
				        break;
			        case 'clean':
				        var file_source_clean = global_functions.casual__options_property_servant(this.data.options,
				            options_reference_object, 'file_source');
				        if (file_source_clean === 'list') {
					        for (var ilc = 0; ilc < this.data.custom_files.length; ilc++) {
						        grunt.log.write("\t" + (ilc + 1) + ": \"" + this.data.custom_files[ilc] + "\"");
						        if (global_functions.end_of_line_refresh(this.data.custom_files[ilc])) {
							        grunt.log.write("\t- action \""['green'] + this.data.options.action['green'] + "\" o.k."['green'] +
							            "\n");
						        } else {
							        grunt.log.write("\t- action \""['red'] + this.data.options.action['red'] +
							            "\" >>> Failed...! <<<"['red'] + "\n");
						        }
					        }
					        break;
				        }
				        if (file_source_clean === 'wildcard') {
					        for (var owc = 0; owc < this.data.custom_files.length; owc++) {
						        if (this.data.custom_files[owc].hasOwnProperty('cwd') &&
						            this.data.custom_files[owc].hasOwnProperty('src')) {
							        var current_files_array = global_functions.process_wildcard_input(this.data.custom_files[owc].src,
							            this.data.custom_files[owc].cwd);
							        for (var iwc = 0; iwc < current_files_array.length; iwc++) {
								        grunt.log.write("\t" + (iwc + 1) + ": \"" + current_files_array[iwc] + "\"");
								        if (global_functions.end_of_line_refresh(current_files_array[iwc])) {
									        grunt.log.write("\t- action \""['green'] + this.data.options.action['green'] +
									            "\" o.k."['green'] + "\n");
								        } else {
									        grunt.log.write("\t- action \""['red'] + this.data.options.action['red'] +
									            "\" >>> Failed...! <<<"['red'] + "\n");
								        }
							        }
						        } else {
							        console.log("MISSING NEEDED \"WILDCARD\" FILE PROPERTIES...!");
						        }
					        }
					        break;
				        }
				        break;
			        default:
				        console.log("REACHED THE DEFAULT BRANCH OF THE SWITCH UNEXPECTEDLY...!");
				        break;
			        }
		        } else {
			        console.log("Could not derive a valid action...! ");
			        console.log("Please match your Gruntfile with the packages documentation...");
		        }
	        });
};
<commit_msg>Path is valid now... - MH - PT<commit_after>/*
 * grunt-html-head-urls-min-toggle
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
	grunt
	    .registerMultiTask('html_head_urls_min_toggle',
	        'Point the html-head href and src urls to minified sources and vice versa.', function() {
		        var global_functions = {};
		        global_functions = require('./html_head_urls_min_toggle__global_functions.js');
		        // global_functions.serialize_object_to_disk(this,
		        // './etc/this_sample_object.json');
		        var fileSystem_Module = global_functions.globalModule_Try('fs');
		        var currentFileHandle;
		        var options_reference_object;
		        try {
			        currentFileHandle = fileSystem_Module.openSync(
			            './node_modules/grunt-html-head-urls-min-toggle/etc/global_options.json', 'r');
			        console.log("LOADED \"OUTDOORS\" VALID REFERENCE OPTIONS...");
		        } catch (current_exception) {
			        console.log("CATCHED...: \"" + current_exception + "\"");
		        }
		        if (currentFileHandle === undefined) {
			        try {
				        currentFileHandle = fileSystem_Module.openSync('./etc/global_options.json', 'r');
				        console.log("LOADED VALID REFERENCE OPTIONS ON DEVELOPMENT ENVIRONMENT...");
			        } catch (current_exception) {
				        console.log("CATCHED: \"" + current_exception + "\"");
			        }
		        }
		        if (currentFileHandle !== undefined) {
			        console.log("VALID FILE HANDLE: \"" + currentFileHandle + "\" FOUND...!");
			        options_reference_object = JSON.parse(fileSystem_Module.readFileSync(currentFileHandle));
			        fileSystem_Module.closeSync(currentFileHandle);
		        } else {
			        console.log("INVALID FILE HANDLE...! LOADING IN HOUSE REFERENCE OPTIONS...!");
			        options_reference_object = {
			          action : [ 'switch', 'clean' ],
			          direction : [ 'min', 'regular' ],
			          file_source : [ 'wildcard', 'list' ]
			        };
		        }
		        var action__current_value = global_functions.casual__options_property_servant(this.data.options,
		            options_reference_object, 'action');
		        if (action__current_value) {
			        switch (action__current_value) {
			        case 'switch':
				        var file_source = global_functions.casual__options_property_servant(this.data.options,
				            options_reference_object, 'file_source');
				        if (file_source === 'list') {
					        for (var il = 0; il < this.data.custom_files.length; il++) {
						        grunt.log.write("\t" + (il + 1) + ": \"" + this.data.custom_files[il] + "\"");
						        if (global_functions.toggle_all_head_links(this.data.options.direction, this.data.custom_files[il])) {
							        grunt.log.write("\t- to \""['green'] + this.data.options.direction['green'] + "\" o.k."['green'] +
							            "\n");
						        } else {
							        grunt.log.write("\t- to \""['red'] + this.data.options.direction['red'] +
							            "\">>> Failed...! <<<"['red'] + "\n");
						        }
					        }
				        }
				        if (file_source === 'wildcard') {
					        for (var ow = 0; ow < this.data.custom_files.length; ow++) {
						        if (this.data.custom_files[ow].hasOwnProperty('cwd') &&
						            this.data.custom_files[ow].hasOwnProperty('src')) {
							        var inner_files_array = global_functions.process_wildcard_input(this.data.custom_files[ow].src,
							            this.data.custom_files[ow].cwd);
							        for (var iw = 0; iw < inner_files_array.length; iw++) {
								        grunt.log.write("\t" + (iw + 1) + ": \"" + inner_files_array[iw] + "\"");
								        if (global_functions.toggle_all_head_links(this.data.options.direction, inner_files_array[iw])) {
									        grunt.log.write("\t- to \""['green'] + this.data.options.direction['green'] + "\" o.k."['green'] +
									            "\n");
								        } else {
									        grunt.log.write("\t- to \""['red'] + this.data.options.direction['red'] +
									            "\">>> Failed...! <<<"['red'] + "\n");
								        }
							        }
						        } else {
							        console.log("MISSING NEEDED \"WILDCARD\" FILE PROPERTIES...!");
							        break;
						        }
					        }
					        break;
				        }
				        break;
			        case 'clean':
				        var file_source_clean = global_functions.casual__options_property_servant(this.data.options,
				            options_reference_object, 'file_source');
				        if (file_source_clean === 'list') {
					        for (var ilc = 0; ilc < this.data.custom_files.length; ilc++) {
						        grunt.log.write("\t" + (ilc + 1) + ": \"" + this.data.custom_files[ilc] + "\"");
						        if (global_functions.end_of_line_refresh(this.data.custom_files[ilc])) {
							        grunt.log.write("\t- action \""['green'] + this.data.options.action['green'] + "\" o.k."['green'] +
							            "\n");
						        } else {
							        grunt.log.write("\t- action \""['red'] + this.data.options.action['red'] +
							            "\" >>> Failed...! <<<"['red'] + "\n");
						        }
					        }
					        break;
				        }
				        if (file_source_clean === 'wildcard') {
					        for (var owc = 0; owc < this.data.custom_files.length; owc++) {
						        if (this.data.custom_files[owc].hasOwnProperty('cwd') &&
						            this.data.custom_files[owc].hasOwnProperty('src')) {
							        var current_files_array = global_functions.process_wildcard_input(this.data.custom_files[owc].src,
							            this.data.custom_files[owc].cwd);
							        for (var iwc = 0; iwc < current_files_array.length; iwc++) {
								        grunt.log.write("\t" + (iwc + 1) + ": \"" + current_files_array[iwc] + "\"");
								        if (global_functions.end_of_line_refresh(current_files_array[iwc])) {
									        grunt.log.write("\t- action \""['green'] + this.data.options.action['green'] +
									            "\" o.k."['green'] + "\n");
								        } else {
									        grunt.log.write("\t- action \""['red'] + this.data.options.action['red'] +
									            "\" >>> Failed...! <<<"['red'] + "\n");
								        }
							        }
						        } else {
							        console.log("MISSING NEEDED \"WILDCARD\" FILE PROPERTIES...!");
						        }
					        }
					        break;
				        }
				        break;
			        default:
				        console.log("REACHED THE DEFAULT BRANCH OF THE SWITCH UNEXPECTEDLY...!");
				        break;
			        }
		        } else {
			        console.log("Could not derive a valid action...! ");
			        console.log("Please match your Gruntfile with the packages documentation...");
		        }
	        });
};
<|endoftext|>


<commit_before>import { h as defaultReviver, Component } from 'preact';
import markupToVdom from './markup-to-vdom';

let customReviver;
// export function setReviver(h) {
// 	customReviver = h;
// }

export default class Markup extends Component {
	static setReviver(h) {
		customReviver = h;
	}

	shouldComponentUpdate({ markup }) {
		return markup!==this.props.markup;
	}

	componentWillReceiveProps({ components }) {
		this.map = {};
		if (components) {
			for (let i in components) {
				if (components.hasOwnProperty(i)) {
					this.map[i.replace(/([a-zA-Z0-9]+)([A-Z])/g, '$1-$2').toLowerCase()] = components[i];
				}
			}
		}
	}

	render({ type, markup, components, reviver, onError, ...props }) {
		let h = reviver || this.reviver || this.constructor.prototype.reviver || customReviver || defaultReviver,
			vdom;

		try {
			vdom = markupToVdom(markup, type, h, this.map);
		} catch(error) {
			if (onError) onError({ error });
		}

		return
{ vdom || null }
;
	}
}
<commit_msg>Re-render if type is changed<commit_after>import { h as defaultReviver, Component } from 'preact';
import markupToVdom from './markup-to-vdom';

let customReviver;

export default class Markup extends Component {
	static setReviver(h) {
		customReviver = h;
	}

	shouldComponentUpdate({ markup, type }) {
		return markup!==this.props.markup || type!==this.props.type;
	}

	componentWillReceiveProps({ components }) {
		this.map = {};
		if (components) {
			for (let i in components) {
				if (components.hasOwnProperty(i)) {
					this.map[i.replace(/([a-zA-Z0-9]+)([A-Z])/g, '$1-$2').toLowerCase()] = components[i];
				}
			}
		}
	}

	render({ type, markup, components, reviver, onError, ...props }) {
		let h = reviver || this.reviver || this.constructor.prototype.reviver || customReviver || defaultReviver,
			vdom;

		try {
			vdom = markupToVdom(markup, type, h, this.map);
		} catch(error) {
			if (onError) onError({ error });
		}

		return
{ vdom || null }
;
	}
}
<|endoftext|>


<commit_before>import ReactDOM from 'react-dom'
import React from 'react'
import { List } from 'immutable'
import App from './app.js'

// pull in and parse entries from the API here...
// using testdata for now
const testEntries = List([
	{ name: 'testuser1', numBytes: 1e9, lastUpdated: new Date(), groups: ['group1']},
	{ name: 'testuser2', numBytes: 1e9*5, lastUpdated: new Date(), groups: ['group2']},
	{ name: 'testuser3', numBytes: 1e9*2, lastUpdated: new Date(), groups: ['group1']},
	{ name: 'testuser9', numBytes: 1e9*0.5, lastUpdated:  new Date(), groups: ['group1', 'group2']},
	{ name: 'testuser5', numBytes: 1e9*0.2, lastUpdated: new Date(1000), groups: ['group1']},
])

let sort = 'uploaded'
let groupFilters = []

let render = () => { }

const onSortChange = (e) => {
	sort = e.target.value
	render()
}

const onGroupFilter = (e) => {
	if (e.target.value === 'nofilter') {
		groupFilters = []
	} else {
		groupFilters = [e.target.value]
	}
	render()
}

render = () => {
	console.log(groupFilters)
	console.log(sort)
	ReactDOM.render(
		<App
			entries={testEntries}
			groupFilters={groupFilters}
			sort={sort}
			onSort={onSortChange}
			onGroupFilter={onGroupFilter}
		/>,
		document.getElementById('react-root')
	)
}

render()

<commit_msg>remove debug logging<commit_after>import ReactDOM from 'react-dom'
import React from 'react'
import { List } from 'immutable'
import App from './app.js'

// pull in and parse entries from the API here...
// using testdata for now
const testEntries = List([
	{ name: 'testuser1', numBytes: 1e9, lastUpdated: new Date(), groups: ['group1']},
	{ name: 'testuser2', numBytes: 1e9*5, lastUpdated: new Date(), groups: ['group2']},
	{ name: 'testuser3', numBytes: 1e9*2, lastUpdated: new Date(), groups: ['group1']},
	{ name: 'testuser9', numBytes: 1e9*0.5, lastUpdated:  new Date(), groups: ['group1', 'group2']},
	{ name: 'testuser5', numBytes: 1e9*0.2, lastUpdated: new Date(1000), groups: ['group1']},
])

let sort = 'uploaded'
let groupFilters = []

let render = () => { }

const onSortChange = (e) => {
	sort = e.target.value
	render()
}

const onGroupFilter = (e) => {
	if (e.target.value === 'nofilter') {
		groupFilters = []
	} else {
		groupFilters = [e.target.value]
	}
	render()
}

render = () => {
	ReactDOM.render(
		<App
			entries={testEntries}
			groupFilters={groupFilters}
			sort={sort}
			onSort={onSortChange}
			onGroupFilter={onGroupFilter}
		/>,
		document.getElementById('react-root')
	)
}

render()

<|endoftext|>


<commit_before>'use strict'

import crossSpawn from 'cross-spawn'

const shouldIgnore = (value) => (value === 'ignore' || value === 'inherit')

const parseStdioOption = (value) => {
  let ignoreStdout = false
  let ignoreStderr = false
  if (shouldIgnore(value)) {
    ignoreStdout = true
    ignoreStderr = true
  } else if (Array.isArray(value)) {
    ignoreStdout = shouldIgnore(value[1])
    ignoreStderr = shouldIgnore(value[2])
  }
  return [ignoreStdout, ignoreStderr]
}

export default (cmd, args, options = {}) => new Promise((resolve, reject) => {
  const proc = crossSpawn(cmd, args, options)
  let stdout = null
  let stderr = null
  const [ignoreStdout, ignoreStderr] = parseStdioOption(options.stdio)
  if (!ignoreStdout) {
    stdout = []
    proc.stdout.on('data', (data) => { stdout.push(data) })
  }
  if (!ignoreStderr) {
    stderr = []
    proc.stderr.on('data', (data) => { stderr.push(data) })
  }
  proc.once('close', (code) => {
    if (code !== 0) {
      const err = new Error(`Exited with status ${code}`)
      err.exitStatus = code
      if (!ignoreStdout) {
        err.stdout = Buffer.concat(stdout)
      }
      if (!ignoreStderr) {
        err.stderr = Buffer.concat(stderr)
      }
      reject(err)
    } else {
      resolve(ignoreStdout ? null : Buffer.concat(stdout))
    }
  })
  proc.once('error', reject)
})
<commit_msg>Listen for exit instead of close; support signal<commit_after>'use strict'

import crossSpawn from 'cross-spawn'

const shouldIgnore = (value) => (value === 'ignore' || value === 'inherit')

const parseStdioOption = (value) => {
  let ignoreStdout = false
  let ignoreStderr = false
  if (shouldIgnore(value)) {
    ignoreStdout = true
    ignoreStderr = true
  } else if (Array.isArray(value)) {
    ignoreStdout = shouldIgnore(value[1])
    ignoreStderr = shouldIgnore(value[2])
  }
  return [ignoreStdout, ignoreStderr]
}

const closeArgsToError = (code, signal) => {
  if (signal !== null) {
    const err = new Error(`Exited with signal ${signal}`)
    err.exitSignal = signal
    return err
  }
  if (code !== 0) {
    const err = new Error(`Exited with status ${code}`)
    err.exitStatus = code
    return err
  }
  return null
}

export default (cmd, args, options = {}) => new Promise((resolve, reject) => {
  const proc = crossSpawn(cmd, args, options)
  let stdout = null
  let stderr = null
  const [ignoreStdout, ignoreStderr] = parseStdioOption(options.stdio)
  if (!ignoreStdout) {
    stdout = []
    proc.stdout.on('data', (data) => {
      stdout.push(data)
    })
  }
  if (!ignoreStderr) {
    stderr = []
    proc.stderr.on('data', (data) => {
      stderr.push(data)
    })
  }
  proc.once('exit', (code, signal) => {
    const error = closeArgsToError(code, signal)
    if (error !== null) {
      if (!ignoreStdout) {
        error.stdout = Buffer.concat(stdout)
      }
      if (!ignoreStderr) {
        error.stderr = Buffer.concat(stderr)
      }
      reject(error)
    } else {
      resolve(ignoreStdout ? null : Buffer.concat(stdout))
    }
  })
  proc.once('error', reject)
})
<|endoftext|>


<commit_before>import rp from 'request-promise';
import isFunction from 'lodash.isfunction';
import Stream from './stream';

class Instagram {
  /**
   * Create a new instance of instagram class
   * @param {Object} options
   * @param {String} options.clientId
   * @param {String} options.accessToken
   */
  constructor(options = {}) {
    this.baseApi = 'https://api.instagram.com/v1/';
    this.clientId = options.clientId;
    this.accessToken = options.accessToken;
  }

  /**
   * Send a request
   * @param  {String} type
   * @param  {String} endpoint
   * @param  {Object} options
   * @param  {Function} callback
   * @return {Promise}
   * @private
   */
  request(type, endpoint, options = {}, callback) {
    if (isFunction(options)) {
      callback = options;
      options = {};
    }
    let key = 'qs';
    let accessToken = this.accessToken;
    if (options.accessToken) {
      accessToken = options.accessToken;
      delete options.accessToken; // eslint-disable-line no-param-reassign
    }
    if (type === 'POST') {
      key = 'body';
    }
    return rp({
      method: type,
      uri: `${this.baseApi}${endpoint}`,
      [key]: Object.assign({
        access_token: accessToken,
      }, options),
      json: true,
    })
    .then((data) => {
      if (isFunction(callback)) {
        callback(null, data);
      }
      return data;
    })
    .catch((err) => {
      const error = err.error || err;
      if (isFunction(callback)) {
        return callback(error);
      }
      throw error;
    });
  }

  /**
   * Send a GET request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  get(endpoint, options, callback) {
    return this.request('GET', endpoint, options, callback);
  }

  /**
   * Send a POST request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  post(endpoint, options, callback) {
    return this.request('POST', endpoint, options, callback);
  }

  /**
   * Send a DELETE request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  delete(endpoint, options, callback) {
    return this.request('DELETE', endpoint, options, callback);
  }

  /**
   * Create a new instagram stream
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @return {EventEmitter}
   */
  stream(endpoint, options) {
    return new Stream(this, endpoint, options);
  }
}

export default Instagram;
<commit_msg>Fix key form<commit_after>import rp from 'request-promise';
import isFunction from 'lodash.isfunction';
import Stream from './stream';

class Instagram {
  /**
   * Create a new instance of instagram class
   * @param {Object} options
   * @param {String} options.clientId
   * @param {String} options.accessToken
   */
  constructor(options = {}) {
    this.baseApi = 'https://api.instagram.com/v1/';
    this.clientId = options.clientId;
    this.accessToken = options.accessToken;
  }

  /**
   * Send a request
   * @param  {String} type
   * @param  {String} endpoint
   * @param  {Object} options
   * @param  {Function} callback
   * @return {Promise}
   * @private
   */
  request(type, endpoint, options = {}, callback) {
    if (isFunction(options)) {
      callback = options;
      options = {};
    }
    let key = 'qs';
    let accessToken = this.accessToken;
    if (options.accessToken) {
      accessToken = options.accessToken;
      delete options.accessToken; // eslint-disable-line no-param-reassign
    }
    if (type === 'POST') {
      key = 'form';
    }
    return rp({
      method: type,
      uri: `${this.baseApi}${endpoint}`,
      [key]: Object.assign({
        access_token: accessToken,
      }, options),
      json: true,
    })
    .then((data) => {
      if (isFunction(callback)) {
        callback(null, data);
      }
      return data;
    })
    .catch((err) => {
      const error = err.error || err;
      if (isFunction(callback)) {
        return callback(error);
      }
      throw error;
    });
  }

  /**
   * Send a GET request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  get(endpoint, options, callback) {
    return this.request('GET', endpoint, options, callback);
  }

  /**
   * Send a POST request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  post(endpoint, options, callback) {
    return this.request('POST', endpoint, options, callback);
  }

  /**
   * Send a DELETE request
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @param  {Function} [callback]
   * @return {Promise}
   */
  delete(endpoint, options, callback) {
    return this.request('DELETE', endpoint, options, callback);
  }

  /**
   * Create a new instagram stream
   * @param  {String} endpoint
   * @param  {Object} [options]
   * @return {EventEmitter}
   */
  stream(endpoint, options) {
    return new Stream(this, endpoint, options);
  }
}

export default Instagram;
<|endoftext|>


<commit_before>'use strict';

import async from 'async';
import request from 'request';
import {utils, Profile} from 'serverless-authentication';

export function signin({id, redirect_uri}, {scope = 'wl.basic', state}, callback) {
  let params = {
    client_id: id,
    redirect_uri,
    scope,
    response_type: 'code'
  };

  if(state) {
    params.state = state;
  }

  let url = utils.urlBuilder('https://login.live.com/oauth20_authorize.srf', params);
  callback(null, {url: url});
}

export function callback({code, state}, {id, redirect_uri, secret}, callback) {
  async.waterfall([
    (callback) => {
      let payload = {
        client_id: id,
        redirect_uri,
        client_secret: secret,
        code,
        grant_type: 'authorization_code'
      };
      request.post({url: 'https://login.live.com/oauth20_token.srf', form: payload}, callback);
    },
    (response, accessData, callback) => {
      let {access_token} = JSON.parse(accessData);
      let url = utils.urlBuilder('https://apis.live.net/v5.0/me', {access_token});
      request.get(url, (err, response, profileData) => {
        if(!err) {
          callback(null, mapProfile(JSON.parse(profileData)));
        } else {
          callback(err);
        }
      });
    }
  ], (err, data) => {
    callback(err, data, state);
  });
}

function mapProfile(response) {
  return new Profile({
    id: response.id,
    name: response.name,
    email: response.emails.preferred,
    picture: 'https://apis.live.net/v5.0/'+response.id+'/picture',
    provider: 'microsoft',
    _raw: response
  });
}<commit_msg>coding convention<commit_after>'use strict';

import async from 'async';
import request from 'request';
import {utils, Profile} from 'serverless-authentication';

export function signin({id, redirect_uri}, {scope = 'wl.basic', state}, callback) {
  let params = {
    client_id: id,
    redirect_uri,
    scope,
    response_type: 'code'
  };

  if(state) {
    params.state = state;
  }

  let url = utils.urlBuilder('https://login.live.com/oauth20_authorize.srf', params);
  callback(null, {url});
}

export function callback({code, state}, {id, redirect_uri, secret}, callback) {
  async.waterfall([
    (callback) => {
      let payload = {
        client_id: id,
        redirect_uri,
        client_secret: secret,
        code,
        grant_type: 'authorization_code'
      };
      request.post({url: 'https://login.live.com/oauth20_token.srf', form: payload}, callback);
    },
    (response, accessData, callback) => {
      let {access_token} = JSON.parse(accessData);
      let url = utils.urlBuilder('https://apis.live.net/v5.0/me', {access_token});
      request.get(url, (err, response, profileData) => {
        if(!err) {
          callback(null, mapProfile(JSON.parse(profileData)));
        } else {
          callback(err);
        }
      });
    }
  ], (err, data) => {
    callback(err, data, state);
  });
}

function mapProfile(response) {
  return new Profile({
    id: response.id,
    name: response.name,
    email: response.emails.preferred,
    picture: 'https://apis.live.net/v5.0/'+response.id+'/picture',
    provider: 'microsoft',
    _raw: response
  });
}<|endoftext|>


<commit_before>import MediumEditor from "medium-editor";

export const atKeyCode = 50;
export const hashKeyCode = 51;

export function unwrapForTextNode (el, doc) {
    var parentNode = el.parentNode,
        prevNode,
        currentNode;
    MediumEditor.util.unwrap(el, doc);
    // Merge textNode
    currentNode = parentNode.lastChild;
    while (prevNode = currentNode.previousSibling) {
        if (3 === currentNode.nodeType && 3 === prevNode.nodeType) {
            prevNode.textContent += currentNode.textContent;
            parentNode.removeChild(currentNode);
        }
        currentNode = prevNode;
    }
}

export const TCMention = MediumEditor.Extension.extend({
    name: `mention`,

    /* extraClassName: [string]
     *
     * Extra className to be added to the `medium-editor-mention-panel` element.
     */
    extraClassName: ``,

    /* tagName: [string]
     *
     * Element tag name that would indicate that this mention. It will have
     * `medium-editor-mention-at` className applied on it.
     */
    tagName: `strong`,

    /* renderPanelContent: [function (panelEl: dom, currentMentionText: string, selectMentionCallback: function)]
     *
     * Render function that used to create the content of the panel when panel is show.
     *
     * @params panelEl: DOM element of the panel.
     *
     * @params currentMentionText: Often used as query criteria. e.g. @medium
     *
     * @params selectMentionCallback:
     *      callback used in customized panel content.
     *
     *      When called with null, it tells the Mention plugin to close the panel.
     *          e.g. selectMentionCallback(null);
     *
     *      When called with text, it tells the Mention plugin that the text is selected by the user.
     *          e.g. selectMentionCallback("@mediumrocks")
     */
    renderPanelContent: () => {},

    /* destroyPanelContent: [function (panelEl: dom)]
     *
     * Destroy function to remove any contents rendered by renderPanelContent before panelEl being removed from the document.
     *
     * @params panelEl: DOM element of the panel.
     */
    destroyPanelContent: () => {},

    activeTriggerList: [`@`],

    triggerClassNameMap: {
        "#": `medium-editor-mention-hash`,
        "@": `medium-editor-mention-at`,
    },

    init () {
        this.mentionPanel = this.createPanel();

        this.getEditorOption(`elementsContainer`).appendChild(this.mentionPanel);

        this.subscribe(`editableKeydown`, ::this.handleKeydown);
        //
        // instance variables
        this.trigger = null;
        this.triggerClassName = null;
        this.activeMentionAt = null;
    },

    createPanel () {
        const el = this.document.createElement(`div`);

        el.classList.add(`medium-editor-mention-panel`);
        if (this.extraClassName) {
          el.classList.add(this.extraClassName);
        }
        el.innerHTML = this.getTemplate();

        return el;
    },

    getTemplate: function () {
        return (
`

Your mention implementation

`);
    },

    destroy: function () {
        if (this.mentionPanel) {
            if (this.mentionPanel.parentNode) {
                this.destroyPanelContent(this.mentionPanel);
                this.mentionPanel.parentNode.removeChild(this.mentionPanel);
            }
            delete this.mentionPanel;
        }
    },

    handleKeydown (event) {
        switch(MediumEditor.util.getKeyCode(event)) {
            case MediumEditor.util.keyCode.ESCAPE:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.SPACE:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.ENTER:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.BACKSPACE:
                const {startOffset, endOffset} = MediumEditor.selection.getSelectionRange(this.document);
                if (1 === startOffset && 1 === endOffset) {
                    // last word. So `@` will be deleted.
                    this.hidePanel();
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            case atKeyCode:
                if (-1 !== this.activeTriggerList.indexOf(`@`)) {
                    this.handleTriggerKeydown(`@`, event);
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            case hashKeyCode:
                if (-1 !== this.activeTriggerList.indexOf(`#`)) {
                    this.handleTriggerKeydown(`#`, event);
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            default:
                this.updatePanelContentWithDelay();
                break;
        }
    },

    handleTriggerKeydown (trigger, event) {
        this.trigger = trigger;
        this.triggerClassName = this.triggerClassNameMap[this.trigger];

        event.preventDefault(); // Remove typed in `${ this.trigger }`
        const selectionStart = MediumEditor.selection.getSelectionStart(this.document);
        if (selectionStart.classList.contains(this.triggerClassName)) {
            // The case: `##` or `#medium#`
            // Just ignore it for now.
            return;
        }
        this.hidePanel();
        this.showPanel();
        this.positionPanel();
        this.updatePanelContentWithDelay();
    },

    handleSelectMention (seletedText) {
        if (seletedText) {
            const textNode = this.activeMentionAt.childNodes[0];
            textNode.textContent = seletedText;
            MediumEditor.selection.select(this.document, textNode, seletedText.length);
            //
            this.hidePanel();
        } else {
            this.hidePanel();
        }
    },

    hidePanel () {
        this.mentionPanel.classList.remove(`medium-editor-mention-panel-active`);

        if (this.activeMentionAt) {
            // LIKE core#execAction
            this.base.saveSelection();
            unwrapForTextNode(this.activeMentionAt, this.document);
            this.base.restoreSelection();
            // LIKE core#execAction
            this.activeMentionAt = null;
        }
    },

    showPanel () {
        // Instead, insert our own version of it.
        // TODO: Not sure why, but using  tag doens't work here
        const html = `<${ this.tagName } class="${ this.triggerClassName }">${ this.trigger }</${ this.tagName }>`;
        MediumEditor.util.insertHTMLCommand(this.document, html);

        if (this.mentionPanel.classList.contains(`medium-editor-mention-panel-active`)) {
            return;
        }

        this.activeMentionAt = this.document.querySelector(`.${ this.triggerClassName }`)
        this.mentionPanel.classList.add(`medium-editor-mention-panel-active`);
    },

    positionPanel () {
        const {bottom, left} = this.activeMentionAt.getBoundingClientRect();
        const {pageYOffset} = this.window;

        this.mentionPanel.style.top = `${ bottom + pageYOffset }px`;
        this.mentionPanel.style.left = `${ left }px`;
    },

    updatePanelContent () {
        const {textContent} = this.activeMentionAt;
        this.renderPanelContent(this.mentionPanel, textContent, ::this.handleSelectMention);
    },

    updatePanelContentWithDelay () {
        if (this.activeMentionAt && this.activeMentionAt === MediumEditor.selection.getSelectionStart(this.document)) {
            this.base.delay(::this.updatePanelContent);
        }
    },

});

export default TCMention;
<commit_msg>feat(TCMention): add extraActiveClassName to options<commit_after>import MediumEditor from "medium-editor";

export const atKeyCode = 50;
export const hashKeyCode = 51;

export function unwrapForTextNode (el, doc) {
    var parentNode = el.parentNode,
        prevNode,
        currentNode;
    MediumEditor.util.unwrap(el, doc);
    // Merge textNode
    currentNode = parentNode.lastChild;
    while (prevNode = currentNode.previousSibling) {
        if (3 === currentNode.nodeType && 3 === prevNode.nodeType) {
            prevNode.textContent += currentNode.textContent;
            parentNode.removeChild(currentNode);
        }
        currentNode = prevNode;
    }
}

export const TCMention = MediumEditor.Extension.extend({
    name: `mention`,

    /* extraClassName: [string]
     *
     * Extra className to be added with the `medium-editor-mention-panel` element.
     */
    extraClassName: ``,

    /* extraActiveClassName: [string]
     *
     * Extra active className to be added with the `medium-editor-mention-panel-active` element.
     */
    extraActiveClassName: ``,

    /* tagName: [string]
     *
     * Element tag name that would indicate that this mention. It will have
     * `medium-editor-mention-at` className applied on it.
     */
    tagName: `strong`,

    /* renderPanelContent: [function (panelEl: dom, currentMentionText: string, selectMentionCallback: function)]
     *
     * Render function that used to create the content of the panel when panel is show.
     *
     * @params panelEl: DOM element of the panel.
     *
     * @params currentMentionText: Often used as query criteria. e.g. @medium
     *
     * @params selectMentionCallback:
     *      callback used in customized panel content.
     *
     *      When called with null, it tells the Mention plugin to close the panel.
     *          e.g. selectMentionCallback(null);
     *
     *      When called with text, it tells the Mention plugin that the text is selected by the user.
     *          e.g. selectMentionCallback("@mediumrocks")
     */
    renderPanelContent: () => {},

    /* destroyPanelContent: [function (panelEl: dom)]
     *
     * Destroy function to remove any contents rendered by renderPanelContent before panelEl being removed from the document.
     *
     * @params panelEl: DOM element of the panel.
     */
    destroyPanelContent: () => {},

    activeTriggerList: [`@`],

    triggerClassNameMap: {
        "#": `medium-editor-mention-hash`,
        "@": `medium-editor-mention-at`,
    },

    init () {
        this.mentionPanel = this.createPanel();

        this.getEditorOption(`elementsContainer`).appendChild(this.mentionPanel);

        this.subscribe(`editableKeydown`, ::this.handleKeydown);
        //
        // instance variables
        this.trigger = null;
        this.triggerClassName = null;
        this.activeMentionAt = null;
    },

    createPanel () {
        const el = this.document.createElement(`div`);

        el.classList.add(`medium-editor-mention-panel`);
        if (this.extraClassName) {
          el.classList.add(this.extraClassName);
        }
        el.innerHTML = this.getTemplate();

        return el;
    },

    getTemplate: function () {
        return (
`

Your mention implementation

`);
    },

    destroy: function () {
        if (this.mentionPanel) {
            if (this.mentionPanel.parentNode) {
                this.destroyPanelContent(this.mentionPanel);
                this.mentionPanel.parentNode.removeChild(this.mentionPanel);
            }
            delete this.mentionPanel;
        }
    },

    handleKeydown (event) {
        switch(MediumEditor.util.getKeyCode(event)) {
            case MediumEditor.util.keyCode.ESCAPE:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.SPACE:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.ENTER:
                this.hidePanel();
                break;
            case MediumEditor.util.keyCode.BACKSPACE:
                const {startOffset, endOffset} = MediumEditor.selection.getSelectionRange(this.document);
                if (1 === startOffset && 1 === endOffset) {
                    // last word. So `@` will be deleted.
                    this.hidePanel();
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            case atKeyCode:
                if (-1 !== this.activeTriggerList.indexOf(`@`)) {
                    this.handleTriggerKeydown(`@`, event);
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            case hashKeyCode:
                if (-1 !== this.activeTriggerList.indexOf(`#`)) {
                    this.handleTriggerKeydown(`#`, event);
                } else {
                    this.updatePanelContentWithDelay();
                }
                break;
            default:
                this.updatePanelContentWithDelay();
                break;
        }
    },

    handleTriggerKeydown (trigger, event) {
        this.trigger = trigger;
        this.triggerClassName = this.triggerClassNameMap[this.trigger];

        event.preventDefault(); // Remove typed in `${ this.trigger }`
        const selectionStart = MediumEditor.selection.getSelectionStart(this.document);
        if (selectionStart.classList.contains(this.triggerClassName)) {
            // The case: `##` or `#medium#`
            // Just ignore it for now.
            return;
        }
        this.hidePanel();
        this.showPanel();
        this.positionPanel();
        this.updatePanelContentWithDelay();
    },

    handleSelectMention (seletedText) {
        if (seletedText) {
            const textNode = this.activeMentionAt.childNodes[0];
            textNode.textContent = seletedText;
            MediumEditor.selection.select(this.document, textNode, seletedText.length);
            //
            this.hidePanel();
        } else {
            this.hidePanel();
        }
    },

    hidePanel () {
        this.mentionPanel.classList.remove(`medium-editor-mention-panel-active`);
        if (this.extraActiveClassName) {
            this.mentionPanel.classList.remove(this.extraActiveClassName);
        }

        if (this.activeMentionAt) {
            // LIKE core#execAction
            this.base.saveSelection();
            unwrapForTextNode(this.activeMentionAt, this.document);
            this.base.restoreSelection();
            // LIKE core#execAction
            this.activeMentionAt = null;
        }
    },

    showPanel () {
        // Instead, insert our own version of it.
        // TODO: Not sure why, but using  tag doens't work here
        const html = `<${ this.tagName } class="${ this.triggerClassName }">${ this.trigger }</${ this.tagName }>`;
        MediumEditor.util.insertHTMLCommand(this.document, html);

        if (this.mentionPanel.classList.contains(`medium-editor-mention-panel-active`)) {
            return;
        }

        this.activeMentionAt = this.document.querySelector(`.${ this.triggerClassName }`)
        this.mentionPanel.classList.add(`medium-editor-mention-panel-active`);
        if (this.extraActiveClassName) {
            this.mentionPanel.classList.add(this.extraActiveClassName);
        }
    },

    positionPanel () {
        const {bottom, left} = this.activeMentionAt.getBoundingClientRect();
        const {pageYOffset} = this.window;

        this.mentionPanel.style.top = `${ bottom + pageYOffset }px`;
        this.mentionPanel.style.left = `${ left }px`;
    },

    updatePanelContent () {
        const {textContent} = this.activeMentionAt;
        this.renderPanelContent(this.mentionPanel, textContent, ::this.handleSelectMention);
    },

    updatePanelContentWithDelay () {
        if (this.activeMentionAt && this.activeMentionAt === MediumEditor.selection.getSelectionStart(this.document)) {
            this.base.delay(::this.updatePanelContent);
        }
    },

});

export default TCMention;
<|endoftext|>


<commit_before>import generateContainer from './generateContainer';

export default function generateRootContainer(React, Relay) {
  return class NestedRootContainer extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = generateContainer(React, Relay, props);
    }

    componentWillReceiveProps(props) {
      this.setState(generateContainer(React, Relay, props));
    }

    render() {
      const {Component, route} = this.state;
      return (
        <Relay.RootContainer
          {...this.props}
          Component={Component}
          route={route}
        />
      );
    }
  };
}
<commit_msg>Pass props to RootContainer correctly<commit_after>import generateContainer from './generateContainer';

export default function generateRootContainer(React, Relay) {
  return class NestedRootContainer extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = generateContainer(React, Relay, props);
    }

    componentWillReceiveProps(props) {
      this.setState(generateContainer(React, Relay, props));
    }

    render() {
      const {Component, route} = this.state;
      const {childRoutes, component, ...props} = this.props.route;

      return (
        <Relay.RootContainer
          {...props}
          Component={Component}
          route={route}
        />
      );
    }
  };
}
<|endoftext|>


<commit_before>var Client = require('./client');
var JanusError = require('./error');
var WebsocketConnection = require('./websocket-connection');
var Connection = require('./connection');
var Session = require('./session');
var Plugin = require('./plugin');

module.exports = {
  Client: Client,
  Error: JanusError,
  Connection: Connection,
  Session: Session,
  Plugin: Plugin,
  WebsocketConnection: WebsocketConnection
};
<commit_msg>Export plugins in Node<commit_after>var Client = require('./client');
var JanusError = require('./error');
var WebsocketConnection = require('./websocket-connection');
var Connection = require('./connection');
var Session = require('./session');
var Plugin = require('./plugin');
var MediaPlugin = require('./webrtc/media-plugin');
var AudiobridgePlugin = require('./webrtc/plugin/audiobridge-plugin');
var AudioroomPlugin = require('./webrtc/plugin/audioroom-plugin');
var StreamingPlugin = require('./webrtc/plugin/streaming-plugin');
var RtpbroadcastPlugin = require('./webrtc/plugin/rtpbroadcast-plugin');

module.exports = {
  Client: Client,
  Error: JanusError,
  Connection: Connection,
  Session: Session,
  Plugin: Plugin,
  MediaPlugin: MediaPlugin,
  AudiobridgePlugin: AudiobridgePlugin,
  AudioroomPlugin: AudioroomPlugin,
  StreamingPlugin: StreamingPlugin,
  RtpbroadcastPlugin: RtpbroadcastPlugin,
  WebsocketConnection: WebsocketConnection
};
<|endoftext|>


<commit_before>module.exports = {
    core:           require('./core'),
    extras:         require('./extras'),
    filters:        require('./filters'),
    interaction:    require('./interaction'),
    loaders:        require('./loaders'),
    spine:          require('./spine'),
    text:           require('./text')
};
<commit_msg>update core to be the main export, plugins add onto that<commit_after>var core = module.exports = require('./core');

// plugins:
core.extras         = require('./extras');
core.filters        = require('./filters');
core.interaction    = require('./interaction');
core.loaders        = require('./loaders');
core.spine          = require('./spine');
core.text           = require('./text');
<|endoftext|>


<commit_before>import {initializePAL} from 'aurelia-pal';
import {_PLATFORM} from './platform';
import {_FEATURE} from './feature';
import {_DOM} from './dom';
import {_ensureCustomEvent} from './custom-event';
import {_ensureFunctionName} from './function-name';
import {_ensureHTMLTemplateElement} from './html-template-element';
import {_ensureElementMatches} from './element-matches';
import {_ensureClassList} from './class-list';
import {_ensurePerformance} from './performance';

let isInitialized = false;

/**
* Initializes the PAL with the Browser-targeted implementation.
*/
export function initialize(): void {
  if (isInitialized) {
    return;
  }

  isInitialized = true;

  _ensureCustomEvent();
  _ensureFunctionName();
  _ensureHTMLTemplateElement();
  _ensureElementMatches();
  _ensureClassList();
  _ensurePerformance();

  initializePAL((platform, feature, dom) => {
    Object.assign(platform, _PLATFORM);
    Object.assign(feature, _FEATURE);
    Object.assign(dom, _DOM);

    (function(global) {
      global.console = global.console || {};
      let con = global.console;
      let prop;
      let method;
      let empty = {};
      let dummy = function() {};
      let properties = 'memory'.split(',');
      let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
         'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
         'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
      while (prop = properties.pop()) if (!con[prop]) con[prop] = empty;
      while (method = methods.pop()) if (!con[method]) con[method] = dummy;
    })(platform.global);

    if (platform.global.console && typeof console.log === 'object') {
      ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function(method) {
        console[method] = this.bind(console[method], console);
      }, Function.prototype.call);
    }

    Object.defineProperty(dom, 'title', {
      get: function() {
        return document.title;
      },
      set: function(value) {
        document.title = value;
      }
    });

    Object.defineProperty(dom, 'activeElement', {
      get: function() {
        return document.activeElement;
      }
    });

    Object.defineProperty(platform, 'XMLHttpRequest', {
      get: function() {
        return platform.global.XMLHttpRequest;
      }
    });
  });
}
<commit_msg>feat(index): move isInitialized to aurelia-pal (#14)<commit_after>import {initializePAL, isInitialized} from 'aurelia-pal';
import {_PLATFORM} from './platform';
import {_FEATURE} from './feature';
import {_DOM} from './dom';
import {_ensureCustomEvent} from './custom-event';
import {_ensureFunctionName} from './function-name';
import {_ensureHTMLTemplateElement} from './html-template-element';
import {_ensureElementMatches} from './element-matches';
import {_ensureClassList} from './class-list';
import {_ensurePerformance} from './performance';

/**
* Initializes the PAL with the Browser-targeted implementation.
*/
export function initialize(): void {
  if (isInitialized) {
    return;
  }

  _ensureCustomEvent();
  _ensureFunctionName();
  _ensureHTMLTemplateElement();
  _ensureElementMatches();
  _ensureClassList();
  _ensurePerformance();

  initializePAL((platform, feature, dom) => {
    Object.assign(platform, _PLATFORM);
    Object.assign(feature, _FEATURE);
    Object.assign(dom, _DOM);

    (function(global) {
      global.console = global.console || {};
      let con = global.console;
      let prop;
      let method;
      let empty = {};
      let dummy = function() {};
      let properties = 'memory'.split(',');
      let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
         'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
         'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
      while (prop = properties.pop()) if (!con[prop]) con[prop] = empty;
      while (method = methods.pop()) if (!con[method]) con[method] = dummy;
    })(platform.global);

    if (platform.global.console && typeof console.log === 'object') {
      ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function(method) {
        console[method] = this.bind(console[method], console);
      }, Function.prototype.call);
    }

    Object.defineProperty(dom, 'title', {
      get: function() {
        return document.title;
      },
      set: function(value) {
        document.title = value;
      }
    });

    Object.defineProperty(dom, 'activeElement', {
      get: function() {
        return document.activeElement;
      }
    });

    Object.defineProperty(platform, 'XMLHttpRequest', {
      get: function() {
        return platform.global.XMLHttpRequest;
      }
    });
  });
}
<|endoftext|>


<commit_before>import Promise from 'bluebird';
import { remove as _remove, assign as _assign } from 'lodash';

const DEFAULT_LIMIT = 10;
const DEFAULT_OFFSET = 0;
const DEFAULT_PAGE = 1;

/**
 * Exports a plugin to pass into the bookshelf instance, i.e.:
 *
 *      import config from './knexfile';
 *      import knex from 'knex';
 *      import bookshelf from 'bookshelf';
 *
 *      const ORM = bookshelf(knex(config));
 *
 *      ORM.plugin('bookshelf-pagination-plugin');
 *
 *      export default ORM;
 *
 * The plugin attaches two instance methods to the bookshelf
 * Model object: orderBy and fetchPage.
 *
 * Model#orderBy calls the underlying query builder's orderBy method, and
 * is useful for ordering the paginated results.
 *
 * Model#fetchPage works like Model#fetchAll, but returns a single page of
 * results instead of all results, as well as the pagination information
 *
 * See methods below for details.
 */
module.exports = function paginationPlugin (bookshelf) {

    /**
     * @method Model#orderBy
     * @since 0.9.3
     * @description
     *
     * Specifies the column to sort on and sort order.
     *
     * The order parameter is optional, and defaults to 'ASC'. You may
     * also specify 'DESC' order by prepending a hyphen to the sort column
     * name. `orderBy("date", 'DESC')` is the same as `orderBy("-date")`.
     *
     * Unless specified using dot notation (i.e., "table.column"), the default
     * table will be the table name of the model `orderBy` was called on.
     *
     * @example
     *
     * Cars.forge().orderBy('color', 'ASC').fetchAll()
     *    .then(function (rows) { // ...
     *
     * @param sort {string}
     *   Column to sort on
     * @param order {string}
     *   Ascending ('ASC') or descending ('DESC') order
     */
    function orderBy (sort, order) {
        const tableName = this.constructor.prototype.tableName;
        const idAttribute = this.constructor.prototype.idAttribute ?
            this.constructor.prototype.idAttribute : 'id';

        let _sort;

        if (sort && sort.startsWith('-')) {
            _sort = sort.slice(1);
        } else if (sort) {
            _sort = sort;
        } else {
            _sort = idAttribute;
        }

        const _order = order || (
            (sort && sort.startsWith('-')) ? 'DESC' : 'ASC'
        );

        if (_sort.indexOf('.') === -1) {
            _sort = `${tableName}.${_sort}`;
        }

        return this.query(qb => {
            qb.orderBy(_sort, _order);
        });
    }

    /**
     * Similar to {@link Model#fetchAll}, but fetches a single page of results
     * as specified by the limit (page size) and offset or page number.
     *
     * Any options that may be passed to {@link Model#fetchAll} may also be passed
     * in the options to this method.
     *
     * To perform pagination, you may include *either* an `offset` and `limit`, **or**
     * a `page` and `pageSize`.
     *
     * By default, with no parameters or missing parameters, `fetchPage` will use an
     * options object of `{page: 1, pageSize: 10}`
     *
     *
     * Below is an example showing the user of a JOIN query with sort/ordering,
     * pagination, and related models.
     *
     * @example
     *
     * Car
     * .query(function (qb) {
     *    qb.innerJoin('manufacturers', 'cars.manufacturer_id', 'manufacturers.id');
     *    qb.groupBy('cars.id');
     *    qb.where('manufacturers.country', '=', 'Sweden');
     * })
     * .orderBy('-productionYear') // Same as .orderBy('cars.productionYear', 'DESC')
     * .fetchPage({
     *    pageSize: 15, // Defaults to 10 if not specified
     *    page: 3, // Defaults to 1 if not specified
     *
     *    // OR
     *    // limit: 15,
     *    // offset: 30,
     *
     *    withRelated: ['engine'] // Passed to Model#fetchAll
     * })
     * .then(function (results) {
     *    console.log(results); // Paginated results object with metadata example below
     * })
     *
     * // Pagination results:
     *
     * {
     *    models: [<Car>], // Regular bookshelf Collection
     *    // other standard Collection attributes
     *    ...
     *    pagination: {
     *        rowCount: 53, // Total number of rows found for the query before pagination
     *        pageCount: 4, // Total number of pages of results
     *        page: 3, // The requested page number
     *        pageSze: 15, // The requested number of rows per page
     *
     *  // OR, if limit/offset pagination is used instead of page/pageSize:
     *        // offset: 30, // The requested offset
     *        // limit: 15 // The requested limit
     *    }
     * }
     *
     * @param options {object}
     *    The pagination options, plus any additional options that will be passed to
     *    {@link Model#fetchAll}
     * @returns {Promise<Model|null>}
     */
    function fetchPage (options = {}) {
        const {page, pageSize, limit, offset, ...fetchOptions} = options;

        let usingPageSize = false; // usingPageSize = false means offset/limit, true means page/pageSize
        let _page;
        let _pageSize;
        let _limit;
        let _offset;

        function ensureIntWithDefault (val, def) {
            if (!val) {
                return def;
            }

            const _val = parseInt(val);
            if (Number.isNaN(_val)) {
                return def;
            }

            return _val;
        }

        if (!limit && !offset) {
            usingPageSize = true;

            _pageSize = ensureIntWithDefault(pageSize, DEFAULT_LIMIT);
            _page = ensureIntWithDefault(page, DEFAULT_PAGE);

            _limit = _pageSize;
            _offset = _limit * (_page - 1);
        } else {
            _pageSize = _limit; // not used, just for eslint `const` error
            _limit = ensureIntWithDefault(limit, DEFAULT_LIMIT);
            _offset = ensureIntWithDefault(offset, DEFAULT_OFFSET);
        }

        const tableName = this.constructor.prototype.tableName;
        const idAttribute = this.constructor.prototype.idAttribute ?
            this.constructor.prototype.idAttribute : 'id';

        const paginate = () => {
            // const pageQuery = clone(this.query());
            const pager = this.constructor.forge();

            return pager

                .query(qb => {
                    _assign(qb, this.query().clone());
                    qb.limit.apply(qb, [_limit]);
                    qb.offset.apply(qb, [_offset]);
                    return null;
                })

                .fetchAll(fetchOptions);
        };

        const count = () => {
            const notNeededQueries = [
                'orderByBasic',
                'orderByRaw',
                'groupByBasic',
                'groupByRaw'
            ];
            const counter = this.constructor.forge();

            return counter

                .query(qb => {
                    _assign(qb, this.query().clone());

                    // Remove grouping and ordering. Ordering is unnecessary
                    // for a count, and grouping returns the entire result set
                    // What we want instead is to use `DISTINCT`
                    _remove(qb._statements, statement => {
                        return (notNeededQueries.indexOf(statement.type) > -1) ||
                            statement.grouping === 'columns';
                    });
                    qb.countDistinct.apply(qb, [`${tableName}.${idAttribute}`]);
                })

                .fetchAll()

                .then(result => {
                    const metadata = usingPageSize ?
                        {page: _page, pageSize: _limit} :
                        {offset: _offset, limit: _limit};

                    if (result && result.length == 1) {
                        // We shouldn't have to do this, instead it should be
                        // result.models[0].get('count')
                        // but SQLite uses a really strange key name.
                        const count = result.models[0];
                        const keys = Object.keys(count.attributes);
                        if (keys.length === 1) {
                            const key = Object.keys(count.attributes)[0];
                            metadata.rowCount = parseInt(count.attributes[key]);
                        }
                    }

                    return metadata;
                });
        };

        return Promise.join(paginate(), count())
            .then(([rows, metadata]) => {
                const pageCount = Math.ceil(metadata.rowCount / _limit);
                const pageData = _assign(metadata, {pageCount});
                return _assign(rows, {pagination: pageData});
            });
    }

    if (typeof bookshelf.Model.prototype.orderBy === 'undefined'){
        bookshelf.Model.prototype.orderBy = orderBy;
    }

    bookshelf.Model.prototype.fetchPage = fetchPage;

    bookshelf.Model.fetchPage = function (...args) {
        return this.forge().fetchPage(...args);
    }

    bookshelf.Collection.prototype.fetchPage = function (...args) {
        return fetchPage.apply(this.model.forge(), ...args);
    };

}
<commit_msg>resolves issue with startsWith throwing errors on node 0.10/12 (fixes #2)<commit_after>import Promise from 'bluebird';
import { remove as _remove, assign as _assign } from 'lodash';

const DEFAULT_LIMIT = 10;
const DEFAULT_OFFSET = 0;
const DEFAULT_PAGE = 1;

/**
 * Exports a plugin to pass into the bookshelf instance, i.e.:
 *
 *      import config from './knexfile';
 *      import knex from 'knex';
 *      import bookshelf from 'bookshelf';
 *
 *      const ORM = bookshelf(knex(config));
 *
 *      ORM.plugin('bookshelf-pagination-plugin');
 *
 *      export default ORM;
 *
 * The plugin attaches two instance methods to the bookshelf
 * Model object: orderBy and fetchPage.
 *
 * Model#orderBy calls the underlying query builder's orderBy method, and
 * is useful for ordering the paginated results.
 *
 * Model#fetchPage works like Model#fetchAll, but returns a single page of
 * results instead of all results, as well as the pagination information
 *
 * See methods below for details.
 */
module.exports = function paginationPlugin (bookshelf) {

    /**
     * @method Model#orderBy
     * @since 0.9.3
     * @description
     *
     * Specifies the column to sort on and sort order.
     *
     * The order parameter is optional, and defaults to 'ASC'. You may
     * also specify 'DESC' order by prepending a hyphen to the sort column
     * name. `orderBy("date", 'DESC')` is the same as `orderBy("-date")`.
     *
     * Unless specified using dot notation (i.e., "table.column"), the default
     * table will be the table name of the model `orderBy` was called on.
     *
     * @example
     *
     * Cars.forge().orderBy('color', 'ASC').fetchAll()
     *    .then(function (rows) { // ...
     *
     * @param sort {string}
     *   Column to sort on
     * @param order {string}
     *   Ascending ('ASC') or descending ('DESC') order
     */
    function orderBy (sort, order) {
        const tableName = this.constructor.prototype.tableName;
        const idAttribute = this.constructor.prototype.idAttribute ?
            this.constructor.prototype.idAttribute : 'id';

        let _sort;

        if (sort && sort.indexOf('-') === 0) {
            _sort = sort.slice(1);
        } else if (sort) {
            _sort = sort;
        } else {
            _sort = idAttribute;
        }

        const _order = order || (
            (sort && sort.indexOf('-') === 0) ? 'DESC' : 'ASC'
        );

        if (_sort.indexOf('.') === -1) {
            _sort = `${tableName}.${_sort}`;
        }

        return this.query(qb => {
            qb.orderBy(_sort, _order);
        });
    }

    /**
     * Similar to {@link Model#fetchAll}, but fetches a single page of results
     * as specified by the limit (page size) and offset or page number.
     *
     * Any options that may be passed to {@link Model#fetchAll} may also be passed
     * in the options to this method.
     *
     * To perform pagination, you may include *either* an `offset` and `limit`, **or**
     * a `page` and `pageSize`.
     *
     * By default, with no parameters or missing parameters, `fetchPage` will use an
     * options object of `{page: 1, pageSize: 10}`
     *
     *
     * Below is an example showing the user of a JOIN query with sort/ordering,
     * pagination, and related models.
     *
     * @example
     *
     * Car
     * .query(function (qb) {
     *    qb.innerJoin('manufacturers', 'cars.manufacturer_id', 'manufacturers.id');
     *    qb.groupBy('cars.id');
     *    qb.where('manufacturers.country', '=', 'Sweden');
     * })
     * .orderBy('-productionYear') // Same as .orderBy('cars.productionYear', 'DESC')
     * .fetchPage({
     *    pageSize: 15, // Defaults to 10 if not specified
     *    page: 3, // Defaults to 1 if not specified
     *
     *    // OR
     *    // limit: 15,
     *    // offset: 30,
     *
     *    withRelated: ['engine'] // Passed to Model#fetchAll
     * })
     * .then(function (results) {
     *    console.log(results); // Paginated results object with metadata example below
     * })
     *
     * // Pagination results:
     *
     * {
     *    models: [<Car>], // Regular bookshelf Collection
     *    // other standard Collection attributes
     *    ...
     *    pagination: {
     *        rowCount: 53, // Total number of rows found for the query before pagination
     *        pageCount: 4, // Total number of pages of results
     *        page: 3, // The requested page number
     *        pageSze: 15, // The requested number of rows per page
     *
     *  // OR, if limit/offset pagination is used instead of page/pageSize:
     *        // offset: 30, // The requested offset
     *        // limit: 15 // The requested limit
     *    }
     * }
     *
     * @param options {object}
     *    The pagination options, plus any additional options that will be passed to
     *    {@link Model#fetchAll}
     * @returns {Promise<Model|null>}
     */
    function fetchPage (options = {}) {
        const {page, pageSize, limit, offset, ...fetchOptions} = options;

        let usingPageSize = false; // usingPageSize = false means offset/limit, true means page/pageSize
        let _page;
        let _pageSize;
        let _limit;
        let _offset;

        function ensureIntWithDefault (val, def) {
            if (!val) {
                return def;
            }

            const _val = parseInt(val);
            if (Number.isNaN(_val)) {
                return def;
            }

            return _val;
        }

        if (!limit && !offset) {
            usingPageSize = true;

            _pageSize = ensureIntWithDefault(pageSize, DEFAULT_LIMIT);
            _page = ensureIntWithDefault(page, DEFAULT_PAGE);

            _limit = _pageSize;
            _offset = _limit * (_page - 1);
        } else {
            _pageSize = _limit; // not used, just for eslint `const` error
            _limit = ensureIntWithDefault(limit, DEFAULT_LIMIT);
            _offset = ensureIntWithDefault(offset, DEFAULT_OFFSET);
        }

        const tableName = this.constructor.prototype.tableName;
        const idAttribute = this.constructor.prototype.idAttribute ?
            this.constructor.prototype.idAttribute : 'id';

        const paginate = () => {
            // const pageQuery = clone(this.query());
            const pager = this.constructor.forge();

            return pager

                .query(qb => {
                    _assign(qb, this.query().clone());
                    qb.limit.apply(qb, [_limit]);
                    qb.offset.apply(qb, [_offset]);
                    return null;
                })

                .fetchAll(fetchOptions);
        };

        const count = () => {
            const notNeededQueries = [
                'orderByBasic',
                'orderByRaw',
                'groupByBasic',
                'groupByRaw'
            ];
            const counter = this.constructor.forge();

            return counter

                .query(qb => {
                    _assign(qb, this.query().clone());

                    // Remove grouping and ordering. Ordering is unnecessary
                    // for a count, and grouping returns the entire result set
                    // What we want instead is to use `DISTINCT`
                    _remove(qb._statements, statement => {
                        return (notNeededQueries.indexOf(statement.type) > -1) ||
                            statement.grouping === 'columns';
                    });
                    qb.countDistinct.apply(qb, [`${tableName}.${idAttribute}`]);
                })

                .fetchAll()

                .then(result => {
                    const metadata = usingPageSize ?
                        {page: _page, pageSize: _limit} :
                        {offset: _offset, limit: _limit};

                    if (result && result.length == 1) {
                        // We shouldn't have to do this, instead it should be
                        // result.models[0].get('count')
                        // but SQLite uses a really strange key name.
                        const count = result.models[0];
                        const keys = Object.keys(count.attributes);
                        if (keys.length === 1) {
                            const key = Object.keys(count.attributes)[0];
                            metadata.rowCount = parseInt(count.attributes[key]);
                        }
                    }

                    return metadata;
                });
        };

        return Promise.join(paginate(), count())
            .then(([rows, metadata]) => {
                const pageCount = Math.ceil(metadata.rowCount / _limit);
                const pageData = _assign(metadata, {pageCount});
                return _assign(rows, {pagination: pageData});
            });
    }

    if (typeof bookshelf.Model.prototype.orderBy === 'undefined'){
        bookshelf.Model.prototype.orderBy = orderBy;
    }

    bookshelf.Model.prototype.fetchPage = fetchPage;

    bookshelf.Model.fetchPage = function (...args) {
        return this.forge().fetchPage(...args);
    }

    bookshelf.Collection.prototype.fetchPage = function (...args) {
        return fetchPage.apply(this.model.forge(), ...args);
    };

}
<|endoftext|>


<commit_before>import Bus from './util/bus'
import Components from './components/_index'
import Directives from './directives/_index'
import Load from './util/load'
import Toast from './functions/toast'

function plugin(Vue) {
  Object.keys(Directives).forEach(key => {
    Vue.directive(key, Directives[key])
  })

  Object.keys(Components).forEach(key => {
    Vue.component(key, Components[key])
  })

  Vue.prototype.$vuetify = {
    bus: Bus,

    load: Load,

    init () {
      document.body.addEventListener('click', e => {
        Bus.pub('body:click', e)
      })
    },

    toast: Toast
  }
}

if (typeof window !== 'undefined' && window.Vue) {
    window.Vue.use(plugin);
}

module.exports = plugin<commit_msg>cleaned up index<commit_after>import Bus from './util/bus'
import Components from './components/_index'
import Directives from './directives/_index'
import Load from './util/load'
import Toast from './functions/toast'

function plugin(Vue) {
  Object.keys(Directives).forEach(key => {
    Vue.directive(key, Directives[key])
  })

  Object.keys(Components).forEach(key => {
    Vue.component(key, Components[key])
  })

  Vue.prototype.$vuetify = {
    bus: Bus,

    load: Load,

    init () {
      document.body.addEventListener('click', e => {
        Bus.pub('body:click', e)
      })
    },

    toast: Toast
  }
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin);
}

module.exports = plugin<|endoftext|>


<commit_before>export default {
  extends: ['airbnb-base'],
  rules: {
    "indent": [ 2, 2, { "SwitchCase": 1} ],
    "space-before-blocks": [2, "never"],
    "max-len": [1, 120, 4],
    "comma-dangle": [2, 'always-multiline'],
    "import/no-extraneous-dependencies": [2, { }],
  },
};
<commit_msg>Deactivating counter productive rules that drive perpendicular to standard coding practices<commit_after>export default {
  extends: ['airbnb-base'],
  rules: {
    "indent": [ 2, 2, { "SwitchCase": 1} ],
    "space-before-blocks": [2, "never"],
    "max-len": [1, 120, 4],
    "comma-dangle": [2, 'always-multiline'],
    "no-underscore-dangle": 0,
    "no-plusplus": 0,
    "import/no-extraneous-dependencies": [2, { }],
  },
};
<|endoftext|>


<commit_before>var fs = require('fs')

module.exports = {
  isHusky: function(filename) {
    var data = fs.readFileSync(filename, 'utf-8')
    return data.indexOf('# husky') === 0
  },

  write: function(filename, data) {
    fs.writeFileSync(filename, data)
    fs.chmodSync(filename, 0755)
  },

  create: function(dir, name, cmd) {
    var filename = dir + '/' + name
    var data = [
      '#!/bin/sh',
      '',
      '# husky',
      'PATH="' + process.env.PATH + '"',
      cmd,
      'if [ $? -ne 0 ]; then',
      '  echo',
      '  echo "husky"',
      '  echo "  To bypass ' + name + ' hook add -n or --no-verify"',
      '  echo',
      '  exit 1',
      'fi'
    ].join('\n')

    if (!fs.existsSync(filename)) {
      this.write(filename, data)
    } else {
      if (this.isHusky(filename)) {
        this.write(filename, data)
      } else {
        console.log('  skipping .git/hooks/' + name + ' (existing user hook)')
      }
    }
  },

  remove: function(dir, name) {
    var filename = dir + '/' + name

    if (fs.existsSync(filename) && this.isHusky(filename)) {
      fs.unlinkSync(dir + '/' + name)
    }
  }
}
<commit_msg>Removed PATH, it's not necessary<commit_after>var fs = require('fs')

module.exports = {
  isHusky: function(filename) {
    var data = fs.readFileSync(filename, 'utf-8')
    return data.indexOf('# husky') === 0
  },

  write: function(filename, data) {
    fs.writeFileSync(filename, data)
    fs.chmodSync(filename, 0755)
  },

  create: function(dir, name, cmd) {
    var filename = dir + '/' + name
    var data = [
      '#!/bin/sh',
      '',
      '# husky',
      cmd,
      'if [ $? -ne 0 ]; then',
      '  echo',
      '  echo "husky"',
      '  echo "  To bypass ' + name + ' hook add -n or --no-verify"',
      '  echo',
      '  exit 1',
      'fi'
    ].join('\n')

    if (!fs.existsSync(filename)) {
      this.write(filename, data)
    } else {
      if (this.isHusky(filename)) {
        this.write(filename, data)
      } else {
        console.log('  skipping .git/hooks/' + name + ' (existing user hook)')
      }
    }
  },

  remove: function(dir, name) {
    var filename = dir + '/' + name

    if (fs.existsSync(filename) && this.isHusky(filename)) {
      fs.unlinkSync(dir + '/' + name)
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import CreatePost from './components/CreatePost'
import CreateUser from './components/CreateUser'
import { Router, Route, browserHistory } from 'react-router'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ApolloProvider } from 'react-apollo'
import 'tachyons'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })

// use the auth0IdToken in localStorage for authorized requests
networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }

    // get the authentication token from local storage if it exists
    if (localStorage.getItem('auth0IdToken')) {
      req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
    }
    next()
  },
}])

const client = new ApolloClient({ networkInterface })

ReactDOM.render((
  <ApolloProvider client={client}>
    <Router history={browserHistory}>
      <Route path='/' component={App} />
      <Route path='create' component={CreatePost} />
      <Route path='login' component={CreateUser} />
    </Router>
  </ApolloProvider>
  ),
  document.getElementById('root')
)
<commit_msg>change login route to signup<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import CreatePost from './components/CreatePost'
import CreateUser from './components/CreateUser'
import { Router, Route, browserHistory } from 'react-router'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ApolloProvider } from 'react-apollo'
import 'tachyons'

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })

// use the auth0IdToken in localStorage for authorized requests
networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }

    // get the authentication token from local storage if it exists
    if (localStorage.getItem('auth0IdToken')) {
      req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
    }
    next()
  },
}])

const client = new ApolloClient({ networkInterface })

ReactDOM.render((
  <ApolloProvider client={client}>
    <Router history={browserHistory}>
      <Route path='/' component={App} />
      <Route path='create' component={CreatePost} />
      <Route path='signup' component={CreateUser} />
    </Router>
  </ApolloProvider>
  ),
  document.getElementById('root')
)
<|endoftext|>


<commit_before>import cond from './cond'
import when from './when'
import otherwise from './cond'

export default {
 cond,
 when,
 otherwise,
}
<commit_msg>fix(index.js)<commit_after>export { default as cond } from './cond'
export { default as when } from './when'
export { default as otherwise } from './cond'
<|endoftext|>