<commit_before>import Ember from 'ember';
import config from './config/environment';
import route from 'ember-enhanced-router/route';

// if any controller.documentTitleToken exists, then it'll be used as the titleToken if no
// title has been defined in the router

// application route with title `Ember Enhanced Router`
export default route(null, 'Ember Enhanced Router').routes(
  // `home` route with no title token and `/` as path
  route('home@/', false),

  // `dashboard` route with title token `Dashboard` and `dashboard` as path
  route('dashboard'),

  // `members` route with title token `All Members` and `users` as path
  route('members@users', 'All Members').routes(
    // `index` route with no title token and `/` as path (because `index`)
    route('index'),

    // `show` route with `User <controller.name>` title token and `:user_id` as path
    route('show@:user_id', 'User {{name}}'),

    // `new` route with `New User` title and `new` as path (true stop bubbling for tokens)
    route('new', 'New User', {resetTitle: true}),

    // `edit` route with either `Edit Profile` or `"<controller.model.name>"` title token and `:user_id/edit` as path
    // the computed property has the controller as context
    route('edit@:user_id/edit', function () {
      if (this.get('isSessionUser')) {
        return 'Edit Profile';
      }
      else {
        return '"' + this.get('name') + '"';
      }
    }.property('isSessionUser', 'model.name'))
  ),

  // the catchall route
  route('catchall@*')
).toRouter({location: config.locationType});
<commit_msg>Fixed the demo app to reflect the template<commit_after>import Ember from 'ember';
import config from './config/environment';
import route from 'ember-enhanced-router/route';

// if any controller.documentTitleToken exists, then it'll be used as the titleToken if no
// title has been defined in the router

// application route with title `Ember Enhanced Router`
export default route(null, 'Ember Enhanced Router').routes(
  // `home` route with no title token and `/` as path
  route('home@/', false),

  // `dashboard` route with title token `Dashboard` and `dashboard` as path
  route('dashboard'),

  // `members` route with title token `All Members` and `users` as path
  route('members@users', 'All Members').routes(
    // `index` route with no title token and `/` as path (because `index`)
    route('index'),

    // `show` route with `User <controller.name>` title token and `:user_id` as path
    route('show@:user_id', 'User {{name}}'),

    // `new` route with `New User` title and `new` as path (true stop bubbling for tokens)
    route('new', 'New User', {resetTitle: true}),

    // `edit` route with either `Edit Profile` or `"<controller.model.name>"` title token and `:user_id/edit` as path
    // the computed property has the controller as context
    route('edit@:user_id/edit', function () {
      if (this.get('isSessionUser')) {
        return 'Edit Profile';
      }
      else {
        return '"' + this.get('name') + '"';
      }
    }.property('isSessionUser', 'model.name'))
  ),

  // the catchall route
  route('catchall@*', 'Nothing Here!')
).toRouter({location: config.locationType});
<|endoftext|>


<commit_before>import AddonDocsRouter, { docsRoute } from 'ember-cli-addon-docs/router';
import config from './config/environment';

const Router = AddonDocsRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL,
});

Router.map(function() {
  docsRoute(this, function() {
    this.route('getting-started', function() {
      this.route('installation');
      this.route('configuration');
    });

    this.route('ts', function() {
      this.route('overview');
      this.route('decorators');
      this.route('with-addons');
      this.route('using-ts-effectively');
      this.route('current-limitations');
    });

    this.route('ember', function() {
      this.route('overview');
      this.route('components');
      this.route('services');
      this.route('testing');
      this.route('routes');
      this.route('controllers');
      this.route('helpers');
      this.route('apps-and-addons');
    });

    this.route('ember-data', function() {
      this.route('overview');
      this.route('models');
      // this.route('adapters');
      // this.route('serializers');
      // this.route('transforms');
    });

    this.route('legacy', function() {
      this.route('overview');
      this.route('ember-object');
      this.route('computed-properties');
      this.route('mixins');
      // this.route('ember-component');
    });

    this.route('cookbook', function() {
      this.route('overview');
      this.route('working-with-route-models');
    });

    this.route('upgrade-notes');

    this.route('troubleshooting', function() {
      this.route('conflicting-types');
    });
    this.route('type-defs', function () {
      this.route('package-names');
    });
  });
});

export default Router;
<commit_msg>docs: remove addon-docs from dummy app router<commit_after>import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL,
});

Router.map(function() {});

export default Router;
<|endoftext|>


<commit_before>var SbInterval = 6;
var progwidth = 950;
var progheight = 14;
var progtop    = 2;
var summary_success = 0;
var run_active;
var kfiles = 0;
var last_kfile = 1;
var history = [[]];

/* Disabling jQuery caching */
$.ajaxSetup({
	cache: false
});

function catwidth (variable, queued) {
	if (variable == 0)
		return 0;
	var width = variable * progwidth / queued;
	return (width < 1) ? 1 : Math.round (width);
}

function maxcatwidth(A, B, C, D, queued) {
	var cat = new Array();
	cat[0] = catwidth (A, queued);
	cat[1] = catwidth (B, queued);
	cat[2] = catwidth (C, queued);
	cat[3] = catwidth (D, queued);
	cat.sort(function(a,b){return a-b});
	return (progwidth - cat[0] - cat[1] - cat[2]);
}

function minidraw(x, context, color, queued, variable, mcw) {
	var width = catwidth (variable, queued);
	if (width == 0)
		return (0);
	if (width > mcw)
		width = mcw;
	context.fillStyle = color;
	context.fillRect(x, progtop + 1, width, progheight + 2);
	return (width);
}

function update_canvas(stats) {
	var queued = stats.queued;
	var built = stats.built;
	var failed = stats.failed;
	var skipped = stats.skipped;
	var ignored = stats.ignored;

	var canvas = document.getElementById('progressbar');
	if (canvas.getContext === undefined) {
		/* Not supported */
		return;
	}

	var context = canvas.getContext('2d');

	context.rect(0, progtop, progwidth, progheight + 2);
	context.fillStyle = '#D8D8D8';
	context.fillRect(0, progtop + 1, progwidth, progheight);
	var x = 0;
	var mcw = maxcatwidth (built, failed, ignored, skipped, queued);
	x += minidraw(x, context, "#339966", queued, built, mcw);
	x += minidraw(x, context, "#CC0033", queued, failed, mcw);
	x += minidraw(x, context, "#FFCC33", queued, ignored, mcw);
	x += minidraw(x, context, "#CC6633", queued, skipped, mcw);
}

function filter (txt) {
	$('#report input').val (txt).trigger('search');
}

function process_summary(data) {
	var html;
	var RB = '
';
	var RE = '
';
	var B = '';
	var E = '	';

	kfiles = data.kfiles;
	run_active = data.active;
	$('#profile').html(data.profile);
	$('#kickoff').html(data.kickoff);
	if (data.stats) {
		$.each(data.stats, function(status, count) {
			html = count;
			$('#stats_' + status).html(html);
		});
		update_canvas (data.stats);
	}

	$('#builders_body tbody').empty();
	for (n = 0; n < data.builders.length; n++) {
		var trow = RB + ''
			  + data.builders[n].ID + E +
			B + data.builders[n].elapsed + E +
			B + data.builders[n].phase + E +
			B + data.builders[n].origin + E +
			B + data.builders[n].lines + E +
			RE;
		$('#builders_body tbody').append (trow);
	}
}

function digit2(n){
	return n > 9 ? "" + n: "0" + n;
}

function logfile (origin) {
	var parts = origin.split('/');
	return parts[0] + '___' + parts[1] + '.log';
}

function format_skips (s) {
	if (s == 0) {
		return 'no ports were skipped';
	} else if (s == 1) {
		return 'caused 1 skip';
	} else {
		return 'caused ' + s + ' skips';
	}
}

function format_result (result) {
	return '
' + result + '
';
}

function format_entry (entry, origin) {
	return '' +
		entry + '';
}

function information (result, origin, info) {
	var parts;
	if (result == "built") {
		return 'logfile';
	} else if (result == "failed") {
		parts = info.split(':');
		return parts[0] + ' phase failed (logfile), ' + format_skips (parts[1]);
	} else if (result == "skipped") {
		return 'Issue with ' + info;
	} else if (result == "ignored") {
		parts = info.split(':|:');
		return parts[0] + ' (' + format_skips (parts[1]) + ')';
	} else {
		return "??";
	}

}

function portsmon (origin) {
	var parts = origin.split('/');
	return '' + origin + '';
}

function process_history_file(data, k) {
	history [k] = [];
	for (n = 0; n < data.length; n++) {
		var trow = [];
		trow.push(format_entry (data[n].entry, data[n].origin));
		trow.push(data[n].elapsed);
		trow.push('[' + data[n].ID + ']');
		trow.push(format_result (data[n].result));
		trow.push(portsmon (data[n].origin));
		trow.push(information (data[n].result, data[n].origin, data[n].info));
		trow.push(data[n].duration);
		history [k].push (trow);
	}
}

function update_history_success(kfile) {
	if (kfile == kfiles) {
		var full_history = [];
		for (var k = 1; k <= kfiles; k++) {
			full_history = full_history.concat (history[k]);
		}
		$('#report_table').dataTable().fnClearTable();
		$('#report_table').dataTable().fnAddData(full_history);
		if (run_active) {
			setTimeout(update_summary_and_builders, SbInterval * 1000);
		}
	} else {
		last_kfile = kfile + 1;
		update_history();
	}
}

function update_history() {
	clearInterval(update_history);
	$.ajax({
		url: digit2(last_kfile) + '_history.json',
		dataType: 'json',
		success: function(data) {
			process_history_file(data, last_kfile);
			update_history_success (last_kfile);
		},
		error: function(data) {
			/* May not be there yet, try again shortly */
			setTimeout(update_history, SbInterval * 500);
		}
	})
}

function update_summary_and_builders() {
	$.ajax({
		url: 'summary.json',
		dataType: 'json',
		success: function(data) {
			process_summary(data);
			clearInterval(update_summary_and_builders);
			update_history();
		},
		error: function(data) {
			/* May not be there yet, try again shortly */
			setTimeout(update_summary_and_builders, SbInterval * 500);
		}
	});
}

$(document).ready(function() {

	$('#report_table').dataTable({
		"aaSorting": [[ 0, 'desc' ]],
		"bProcessing": true, // Show processing icon
		"bDeferRender": true, // Defer creating TR/TD until needed
		"aoColumnDefs": [
			{"bSortable": false, "aTargets": [1,2,3,5]},
			{"bSearchable": false, "aTargets": [0,1,6]},
		],
		"bStateSave": true, // Enable cookie for keeping state
		"aLengthMenu":[10,20,50, 100, 200],
		"iDisplayLength": 20,
		});

	update_summary_and_builders();
})

$(document).bind("keydown", function(e) {
  /* Disable F5 refreshing since this is AJAX driven. */
  if (e.which == 116) {
    e.preventDefault();
  }
});
<commit_msg>Handle zero kfiles case in javascript<commit_after>var SbInterval = 6;
var progwidth = 950;
var progheight = 14;
var progtop    = 2;
var summary_success = 0;
var run_active;
var kfiles = 0;
var last_kfile = 1;
var history = [[]];

/* Disabling jQuery caching */
$.ajaxSetup({
	cache: false
});

function catwidth (variable, queued) {
	if (variable == 0)
		return 0;
	var width = variable * progwidth / queued;
	return (width < 1) ? 1 : Math.round (width);
}

function maxcatwidth(A, B, C, D, queued) {
	var cat = new Array();
	cat[0] = catwidth (A, queued);
	cat[1] = catwidth (B, queued);
	cat[2] = catwidth (C, queued);
	cat[3] = catwidth (D, queued);
	cat.sort(function(a,b){return a-b});
	return (progwidth - cat[0] - cat[1] - cat[2]);
}

function minidraw(x, context, color, queued, variable, mcw) {
	var width = catwidth (variable, queued);
	if (width == 0)
		return (0);
	if (width > mcw)
		width = mcw;
	context.fillStyle = color;
	context.fillRect(x, progtop + 1, width, progheight + 2);
	return (width);
}

function update_canvas(stats) {
	var queued = stats.queued;
	var built = stats.built;
	var failed = stats.failed;
	var skipped = stats.skipped;
	var ignored = stats.ignored;

	var canvas = document.getElementById('progressbar');
	if (canvas.getContext === undefined) {
		/* Not supported */
		return;
	}

	var context = canvas.getContext('2d');

	context.rect(0, progtop, progwidth, progheight + 2);
	context.fillStyle = '#D8D8D8';
	context.fillRect(0, progtop + 1, progwidth, progheight);
	var x = 0;
	var mcw = maxcatwidth (built, failed, ignored, skipped, queued);
	x += minidraw(x, context, "#339966", queued, built, mcw);
	x += minidraw(x, context, "#CC0033", queued, failed, mcw);
	x += minidraw(x, context, "#FFCC33", queued, ignored, mcw);
	x += minidraw(x, context, "#CC6633", queued, skipped, mcw);
}

function filter (txt) {
	$('#report input').val (txt).trigger('search');
}

function process_summary(data) {
	var html;
	var RB = '
';
	var RE = '
';
	var B = '';
	var E = '	';

	kfiles = data.kfiles;
	run_active = data.active;
	$('#profile').html(data.profile);
	$('#kickoff').html(data.kickoff);
	if (data.stats) {
		$.each(data.stats, function(status, count) {
			html = count;
			$('#stats_' + status).html(html);
		});
		update_canvas (data.stats);
	}

	$('#builders_body tbody').empty();
	for (n = 0; n < data.builders.length; n++) {
		var trow = RB + ''
			  + data.builders[n].ID + E +
			B + data.builders[n].elapsed + E +
			B + data.builders[n].phase + E +
			B + data.builders[n].origin + E +
			B + data.builders[n].lines + E +
			RE;
		$('#builders_body tbody').append (trow);
	}
}

function digit2(n){
	return n > 9 ? "" + n: "0" + n;
}

function logfile (origin) {
	var parts = origin.split('/');
	return parts[0] + '___' + parts[1] + '.log';
}

function format_skips (s) {
	if (s == 0) {
		return 'no ports were skipped';
	} else if (s == 1) {
		return 'caused 1 skip';
	} else {
		return 'caused ' + s + ' skips';
	}
}

function format_result (result) {
	return '
' + result + '
';
}

function format_entry (entry, origin) {
	return '' +
		entry + '';
}

function information (result, origin, info) {
	var parts;
	if (result == "built") {
		return 'logfile';
	} else if (result == "failed") {
		parts = info.split(':');
		return parts[0] + ' phase failed (logfile), ' + format_skips (parts[1]);
	} else if (result == "skipped") {
		return 'Issue with ' + info;
	} else if (result == "ignored") {
		parts = info.split(':|:');
		return parts[0] + ' (' + format_skips (parts[1]) + ')';
	} else {
		return "??";
	}

}

function portsmon (origin) {
	var parts = origin.split('/');
	return '' + origin + '';
}

function process_history_file(data, k) {
	history [k] = [];
	for (n = 0; n < data.length; n++) {
		var trow = [];
		trow.push(format_entry (data[n].entry, data[n].origin));
		trow.push(data[n].elapsed);
		trow.push('[' + data[n].ID + ']');
		trow.push(format_result (data[n].result));
		trow.push(portsmon (data[n].origin));
		trow.push(information (data[n].result, data[n].origin, data[n].info));
		trow.push(data[n].duration);
		history [k].push (trow);
	}
}

function cycle () {
	if (run_active) {
		setTimeout(update_summary_and_builders, SbInterval * 1000);
	}
}

function update_history_success(kfile) {
	if (kfile == kfiles) {
		var full_history = [];
		for (var k = 1; k <= kfiles; k++) {
			full_history = full_history.concat (history[k]);
		}
		$('#report_table').dataTable().fnClearTable();
		$('#report_table').dataTable().fnAddData(full_history);
		cycle();
	} else {
		last_kfile = kfile + 1;
		update_history();
	}
}

function update_history() {
	if (kfiles == 0) {
		cycle();
		return;
	}
	clearInterval(update_history);
	$.ajax({
		url: digit2(last_kfile) + '_history.json',
		dataType: 'json',
		success: function(data) {
			process_history_file(data, last_kfile);
			update_history_success (last_kfile);
		},
		error: function(data) {
			/* May not be there yet, try again shortly */
			setTimeout(update_history, SbInterval * 500);
		}
	})
}

function update_summary_and_builders() {
	$.ajax({
		url: 'summary.json',
		dataType: 'json',
		success: function(data) {
			process_summary(data);
			clearInterval(update_summary_and_builders);
			update_history();
		},
		error: function(data) {
			/* May not be there yet, try again shortly */
			setTimeout(update_summary_and_builders, SbInterval * 500);
		}
	});
}

$(document).ready(function() {

	$('#report_table').dataTable({
		"aaSorting": [[ 0, 'desc' ]],
		"bProcessing": true, // Show processing icon
		"bDeferRender": true, // Defer creating TR/TD until needed
		"aoColumnDefs": [
			{"bSortable": false, "aTargets": [1,2,3,5]},
			{"bSearchable": false, "aTargets": [0,1,6]},
		],
		"bStateSave": true, // Enable cookie for keeping state
		"aLengthMenu":[10,20,50, 100, 200],
		"iDisplayLength": 20,
		});

	update_summary_and_builders();
})

$(document).bind("keydown", function(e) {
  /* Disable F5 refreshing since this is AJAX driven. */
  if (e.which == 116) {
    e.preventDefault();
  }
});
<|endoftext|>


<commit_before>/**
 * @file ScrollableTable component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';

// Statics
import TableFragment from '../_statics/TableFragment';

// Vendors
import isEmpty from 'lodash/isEmpty';
import Util from '../_vendors/Util';

class ScrollableTable extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.wrapper = createRef();

        this.state = {
            wrapperEl: null
        };

    }

    componentDidMount() {
        this.setState({
            wrapperEl: this.wrapper && this.wrapper.current
        });
    }

    getChildren = () => {

        const {children} = this.props,
            {wrapperEl} = this.state;

        return (typeof children === 'function' ? children(wrapperEl) : children) || null;

    };

    render() {

        const {

                className, style, scroll,

                // not passing down these props
                children: c, fragment, useDynamicRender, scrollHeight, rowHeight, scrollBuffer,

                ...restProps

            } = this.props,
            children = this.getChildren();

        return !isEmpty(scroll) ? (
                <div {...restProps}
                     ref={this.wrapper}
                     className={className}
                     style={style}>
                    {children}
                </div>
            )
            :
            children;

    }
}

ScrollableTable.propTypes = {

    children: PropTypes.any,

    className: PropTypes.string,
    style: PropTypes.object,

    /**
     * scroll
     */
    scroll: PropTypes.shape({
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
        height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
        maxHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
    }),

    fragment: PropTypes.oneOf(Util.enumerateValue(TableFragment)),

    /**
     * Dynamic Render
     */
    useDynamicRender: PropTypes.bool,
    scrollHeight: PropTypes.number,
    rowHeight: PropTypes.number,
    scrollBuffer: PropTypes.number

};

ScrollableTable.defaultProps = {

    /**
     * Dynamic Render
     */
    useDynamicRender: false,
    scrollHeight: 500,
    rowHeight: 50,
    scrollBuffer: 8

};

export default ScrollableTable;
<commit_msg>update ScrollableTable<commit_after>/**
 * @file ScrollableTable component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';

// Statics
import TableFragment from '../_statics/TableFragment';

// Vendors
import isEmpty from 'lodash/isEmpty';
import Util from '../_vendors/Util';

class ScrollableTable extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.wrapper = createRef();

        this.state = {
            wrapperEl: null
        };

    }

    componentDidMount() {
        this.setState({
            wrapperEl: this.wrapper && this.wrapper.current
        });
    }

    getChildren = () => {

        const {children} = this.props,
            {wrapperEl} = this.state;

        return (typeof children === 'function' ? children(wrapperEl) : children) || null;

    };

    render() {

        const {

                className, style, scroll, useDynamicRender,

                // not passing down these props
                children: c, fragment, scrollHeight, rowHeight, scrollBuffer,

                ...restProps

            } = this.props,
            children = this.getChildren();

        return useDynamicRender || !isEmpty(scroll) ?
            <div {...restProps}
                 ref={this.wrapper}
                 className={className}
                 style={style}>
                {children}
            </div>
            :
            children;

    }
}

ScrollableTable.propTypes = {

    children: PropTypes.any,

    className: PropTypes.string,
    style: PropTypes.object,

    /**
     * scroll
     */
    scroll: PropTypes.shape({
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
        height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
        maxHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
    }),

    fragment: PropTypes.oneOf(Util.enumerateValue(TableFragment)),

    /**
     * Dynamic Render
     */
    useDynamicRender: PropTypes.bool,
    scrollHeight: PropTypes.number,
    rowHeight: PropTypes.number,
    scrollBuffer: PropTypes.number

};

ScrollableTable.defaultProps = {

    /**
     * Dynamic Render
     */
    useDynamicRender: false,
    scrollHeight: 500,
    rowHeight: 50,
    scrollBuffer: 8

};

export default ScrollableTable;
<|endoftext|>


<commit_before>/**
 * boot
 */

const riot = require('riot');
require('velocity-animate');
const api = require('./common/scripts/api');
const signout = require('./common/scripts/signout');
const generateDefaultUserdata = require('./common/scripts/generate-default-userdata');
const mixins = require('./common/mixins');
const checkForUpdate = require('./common/scripts/check-for-update');
require('./common/tags');

/**
 * MISSKEY ENTORY POINT!
 */

document.domain = CONFIG.host;

// Set global configration
riot.mixin({
	CONFIG: CONFIG
});

// ↓ iOS待ちPolyfill (SEE: http://caniuse.com/#feat=fetch)
require('whatwg-fetch');

// ↓ NodeList、HTMLCollectionで forEach を使えるようにする
if (NodeList.prototype.forEach === undefined) {
	NodeList.prototype.forEach = Array.prototype.forEach;
}
if (HTMLCollection.prototype.forEach === undefined) {
	HTMLCollection.prototype.forEach = Array.prototype.forEach;
}

// ↓ iOSでプライベートモードだとlocalStorageが使えないので既存のメソッドを上書きする
try {
	localStorage.setItem('kyoppie', 'yuppie');
} catch (e) {
	Storage.prototype.setItem = () => { }; // noop
}

// Check for Update
checkForUpdate();

// ユーザーをフェッチしてコールバックする
module.exports = callback => {
	// Get cached account data
	let cachedMe = JSON.parse(localStorage.getItem('me'));

	if (cachedMe && cachedMe.data && cachedMe.data.cache) {
		fetched(cachedMe);

		// 後から新鮮なデータをフェッチ
		fetchme(cachedMe.token, freshData => {
			Object.assign(cachedMe, freshData);
			cachedMe.trigger('updated');
		});
	} else {
		// キャッシュ無効なのにキャッシュが残ってたら掃除
		if (cachedMe) {
			localStorage.removeItem('me');
		}

		// Get token from cookie
		const i = (document.cookie.match(/i=(!\w+)/) || [null, null])[1];

		fetchme(i, fetched);
	}

	function fetched(me) {
		if (me) {
			riot.observable(me);

			me.update = data => {
				if (data) Object.assign(me, data);
				me.trigger('updated');
			};

			if (me.data.cache) {
				localStorage.setItem('me', JSON.stringify(me));

				me.on('updated', () => {
					// キャッシュ更新
					localStorage.setItem('me', JSON.stringify(me));
				});
			}
		}

		mixins(me);

		const init = document.getElementById('init');
		init.parentNode.removeChild(init);

		const app = document.createElement('div');
		app.setAttribute('id', 'app');
		document.body.appendChild(app);

		try {
			callback(me);
		} catch (e) {
			panic(e);
		}
	}
};

// ユーザーをフェッチしてコールバックする
function fetchme(token, cb) {
	let me = null;

	// Return when not signed in
	if (token == null) {
		return done();
	}

	// Fetch user
	fetch(CONFIG.apiUrl + '/i', {
		method: 'POST',
		body: JSON.stringify({
			i: token
		})
	}).then(res => {
		// When failed to authenticate user
		if (res.status !== 200) {
			return signout();
		}

		res.json().then(i => {
			me = i;
			me.token = token;

			// initialize it if user data is empty
			me.data ? done() : init();
		});
	}, () => {
		riot.mount(document.body.appendChild(document.createElement('mk-core-error')), {
			retry: () => {
				fetchme(token, cb);
			}
		});
	});

	function done() {
		if (cb) cb(me);
	}

	function init() {
		const data = generateDefaultUserdata();
		api(token, 'i/appdata/set', {
			data: JSON.stringify(data)
		}).then(() => {
			me.data = data;
			done();
		});
	}
}

function panic(e) {
	console.error(e);
	document.body.innerHTML = '

致命的な問題が発生しました。

';
	// TODO: Report the bug
}
<commit_msg>[Client] Use strict<commit_after>/**
 * boot
 */

const riot = require('riot');
require('velocity-animate');
const api = require('./common/scripts/api');
const signout = require('./common/scripts/signout');
const generateDefaultUserdata = require('./common/scripts/generate-default-userdata');
const mixins = require('./common/mixins');
const checkForUpdate = require('./common/scripts/check-for-update');
require('./common/tags');

/**
 * MISSKEY ENTORY POINT!
 */

"use strict";

document.domain = CONFIG.host;

// Set global configration
riot.mixin({
	CONFIG: CONFIG
});

// ↓ iOS待ちPolyfill (SEE: http://caniuse.com/#feat=fetch)
require('whatwg-fetch');

// ↓ NodeList、HTMLCollectionで forEach を使えるようにする
if (NodeList.prototype.forEach === undefined) {
	NodeList.prototype.forEach = Array.prototype.forEach;
}
if (HTMLCollection.prototype.forEach === undefined) {
	HTMLCollection.prototype.forEach = Array.prototype.forEach;
}

// ↓ iOSでプライベートモードだとlocalStorageが使えないので既存のメソッドを上書きする
try {
	localStorage.setItem('kyoppie', 'yuppie');
} catch (e) {
	Storage.prototype.setItem = () => { }; // noop
}

// Check for Update
checkForUpdate();

// ユーザーをフェッチしてコールバックする
module.exports = callback => {
	// Get cached account data
	let cachedMe = JSON.parse(localStorage.getItem('me'));

	if (cachedMe && cachedMe.data && cachedMe.data.cache) {
		fetched(cachedMe);

		// 後から新鮮なデータをフェッチ
		fetchme(cachedMe.token, freshData => {
			Object.assign(cachedMe, freshData);
			cachedMe.trigger('updated');
		});
	} else {
		// キャッシュ無効なのにキャッシュが残ってたら掃除
		if (cachedMe) {
			localStorage.removeItem('me');
		}

		// Get token from cookie
		const i = (document.cookie.match(/i=(!\w+)/) || [null, null])[1];

		fetchme(i, fetched);
	}

	function fetched(me) {
		if (me) {
			riot.observable(me);

			me.update = data => {
				if (data) Object.assign(me, data);
				me.trigger('updated');
			};

			if (me.data.cache) {
				localStorage.setItem('me', JSON.stringify(me));

				me.on('updated', () => {
					// キャッシュ更新
					localStorage.setItem('me', JSON.stringify(me));
				});
			}
		}

		mixins(me);

		const init = document.getElementById('init');
		init.parentNode.removeChild(init);

		const app = document.createElement('div');
		app.setAttribute('id', 'app');
		document.body.appendChild(app);

		try {
			callback(me);
		} catch (e) {
			panic(e);
		}
	}
};

// ユーザーをフェッチしてコールバックする
function fetchme(token, cb) {
	let me = null;

	// Return when not signed in
	if (token == null) {
		return done();
	}

	// Fetch user
	fetch(CONFIG.apiUrl + '/i', {
		method: 'POST',
		body: JSON.stringify({
			i: token
		})
	}).then(res => {
		// When failed to authenticate user
		if (res.status !== 200) {
			return signout();
		}

		res.json().then(i => {
			me = i;
			me.token = token;

			// initialize it if user data is empty
			me.data ? done() : init();
		});
	}, () => {
		riot.mount(document.body.appendChild(document.createElement('mk-core-error')), {
			retry: () => {
				fetchme(token, cb);
			}
		});
	});

	function done() {
		if (cb) cb(me);
	}

	function init() {
		const data = generateDefaultUserdata();
		api(token, 'i/appdata/set', {
			data: JSON.stringify(data)
		}).then(() => {
			me.data = data;
			done();
		});
	}
}

function panic(e) {
	console.error(e);
	document.body.innerHTML = '

致命的な問題が発生しました。

';
	// TODO: Report the bug
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TimeAgo from 'react-timeago';
import DeleteAnnotationMutation from '../../relay/DeleteAnnotationMutation';

class Annotation extends Component {
  handleDelete(id) {
    var onFailure = (transaction) => {
      transaction.getError().json().then(function(json) {
        var message = 'Could not delete annotation';
        if (json.error) {
          message = json.error;
        }
        window.alert(message);
      });
    };

    var onSuccess = (response) => {
    };

    Relay.Store.commitUpdate(
      new DeleteAnnotationMutation({
        parent_type: this.props.annotatedType.toLowerCase(),
        annotated: this.props.annotated,
        id: id
      }),
      { onSuccess, onFailure }
    );
  }

  render() {
    const annotation = this.props.annotation;

    let content = JSON.parse(annotation.content);
    let template;
    switch (annotation.annotation_type) {
      case 'comment':
        content = content.text;
        template = (

            <div className='annotation__avatar' style={{backgroundImage: `url(${annotation.annotator.profile_image})`}}>

{annotation.annotator.name}

                <TimeAgo date={annotation.created_at} live={false} />

                  <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

{content}

        );
        break;
      case 'status':
        const statusCode = content.status.toLowerCase().replace(' ', '-');
        template = (

                Status set to
                <span className={`annotation__status annotation__status--${statusCode}`}>{content.status}
                 by
                {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />

                  <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

        );
        break;
      case 'tag':
        const message = `Tagged #${content.tag} by `;
        template = (

                {message}
                {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />

                  <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

        );
        break;
      case 'flag':
        template = (

                Flagged as {content.flag} by
                {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />

                  <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

        );
        break;
      default:
        content = annotation.content;
        template = (

                {content}

                  <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

        );
    }

    return template;
  }
}

export default Annotation;
<commit_msg>Reduce duplication in new annotations templates<commit_after>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TimeAgo from 'react-timeago';
import DeleteAnnotationMutation from '../../relay/DeleteAnnotationMutation';

class Annotation extends Component {
  handleDelete(id) {
    var onFailure = (transaction) => {
      transaction.getError().json().then(function(json) {
        var message = 'Could not delete annotation';
        if (json.error) {
          message = json.error;
        }
        window.alert(message);
      });
    };

    var onSuccess = (response) => {
    };

    Relay.Store.commitUpdate(
      new DeleteAnnotationMutation({
        parent_type: this.props.annotatedType.toLowerCase(),
        annotated: this.props.annotated,
        id: id
      }),
      { onSuccess, onFailure }
    );
  }

  render() {
    const annotation = this.props.annotation;
    const annotationActions = (

        <button className='annotation__delete' onClick={this.handleDelete.bind(this, annotation.id)} title='Delete'>×</button>

    );
    let content = JSON.parse(annotation.content);
    let contentTemplate;

    switch (annotation.annotation_type) {
      case 'comment':
        const commentText = content.text;
        contentTemplate = (

{annotation.annotator.name}

              <TimeAgo date={annotation.created_at} live={false} />
              {annotationActions}

{commentText}

        );
        break;
      case 'status':
        const statusCode = content.status.toLowerCase().replace(' ', '-');
        contentTemplate = (

              Status set to
              <span className={`annotation__status annotation__status--${statusCode}`}>{content.status}
               by
              {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />
              {annotationActions}

        );
        break;
      case 'tag':
        const message = `Tagged #${content.tag} by `;
        contentTemplate = (

              {message}
              {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />
              {annotationActions}

        );
        break;
      case 'flag':
        contentTemplate = (

              Flagged as {content.flag} by
              {annotation.annotator.name} <TimeAgo date={annotation.created_at} live={false} />
              {annotationActions}

        );
        break;
      default:
        content = annotation.content;
        contentTemplate = (

              {content}
              {annotationActions}

        );
    }

    return (
      <div className={`annotation annotation--${annotation.annotation_type}`} id={'annotation-' + annotation.dbid}>
        {annotation.annotation_type === 'comment' ? (
          <div className='annotation__avatar' style={{backgroundImage: `url(${annotation.annotator.profile_image})`}}>

        ) : null}
        {contentTemplate}

    )
  }
}

export default Annotation;
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router';
import App from './app/App';
import Donators from './app/components/Donators'

//Render routes
ReactDOM.render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="donators" component={Donators}/>
        </Route>
    </Router>

), document.getElementById("app"));

<commit_msg>changed routing to hashHistory<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, hashHistory } from 'react-router';
import App from './app/App';
import Donators from './app/components/Donators'

//Render routes
ReactDOM.render((
    <Router history={hashHistory}>
        <Route path="/" component={App}>
            <Route path="donators" component={Donators}/>
        </Route>
    </Router>

), document.getElementById("app"));

<|endoftext|>


<commit_before>define(['js/data/DataSource'], function (DataSource) {

    return DataSource.Processor.inherit("sprd.model.processor.DefaultProcessor", {
        _composeSubModel: function (model, action, options) {
            // we do not want to compose sub models, but rather return a reference to the model
            return {
                id: model.$.id,
                // TODO: determinate href
                href: model.$.href
            }
        },

        _getIdForValue: function (value) {

            if (value.id && value.href) {
                var id = value.href.split("/").pop();
                if (id) {
                    value.id = id;
                    return id;
                }
            }

            return value.id;
        }

    });
});<commit_msg>removed href stuff<commit_after>define(['js/data/DataSource'], function (DataSource) {

    return DataSource.Processor.inherit("sprd.model.processor.DefaultProcessor", {
        _composeSubModel: function (model, action, options) {
            // we do not want to compose sub models, but rather return a reference to the model
            return {
                id: model.$.id
            }
        }

    });
});<|endoftext|>


<commit_before>import { Command } from 'substance'

/*
  This command intended to switch view and scroll to the selected node.
  Command state becoming active only for certain type of custom selection,
  e.g. if you want to use it, provide config with selectionType property.
*/
export default class EditEntityCommand extends Command {
  getCommandState (params, context) {
    let sel = params.selection
    let newState = {
      disabled: true
    }

    if (sel.isCustomSelection()) {
      if (sel.customType === this.config.selectionType) {
        newState.disabled = false
        newState.nodeId = sel.nodeId
      }
    }

    return newState
  }

  execute (params, context) {
    const appState = context.appState
    const viewName = appState.get('viewName')
    if (viewName !== 'metadata') {
      const sel = params.selection
      context.editor.send('updateViewName', 'metadata')
      context.articlePanel.refs.content.send('scrollTo', { nodeId: sel.nodeId })
    }
  }
}
<commit_msg>Set selection when editing an entity from manuscript view.<commit_after>import { Command } from 'substance'

/*
  This command intended to switch view and scroll to the selected node.
  Command state becoming active only for certain type of custom selection,
  e.g. if you want to use it, provide config with selectionType property.
*/
export default class EditEntityCommand extends Command {
  getCommandState (params, context) {
    let sel = params.selection
    let newState = {
      disabled: true
    }

    if (sel.isCustomSelection()) {
      if (sel.customType === this.config.selectionType) {
        newState.disabled = false
        newState.nodeId = sel.nodeId
      }
    }

    return newState
  }

  execute (params, context) {
    const appState = context.appState
    const viewName = appState.get('viewName')
    if (viewName !== 'metadata') {
      const sel = params.selection
      const nodeId = sel.nodeId
      context.editor.send('updateViewName', 'metadata')
      // HACK: using the ArticlePanel instance to get to the current editor
      // so that we can dispatch 'executeCommand'
      let editor = context.articlePanel.refs.content
      editor.send('scrollTo', { nodeId })
      // HACK: this is a mess because context.api is a different instance after
      // switching to metadata view
      // TODO: we should extend ArticleAPI to allow for this
      editor.api.selectFirstRequiredPropertyOfMetadataCard(nodeId)
    }
  }
}
<|endoftext|>


<commit_before>
$(document).ready(function() {

    includeLodash();

    setupTextareaResizing();

    resetCoq();

    separateCode();

    makeCodeInteractive();

});

function includeLodash() {

    $("head")
        .append(
            $("


<commit_before>import fs from 'fs';
import path from 'path';
import glob from 'glob';
import test from 'tape';
import documentation from 'documentation';
import camelcase from 'camelcase';
import * as turf from '.';

// Helpers
const directory = path.join(__dirname, '..');
let modules = [];
for (const name of fs.readdirSync(directory)) {
    const pckgPath = path.join(directory, name, 'package.json');
    if (!fs.existsSync(pckgPath)) continue;
    const pckg = JSON.parse(fs.readFileSync(pckgPath));
    modules.push({
        name,
        dir: path.join(directory, name),
        pckg,
        dependencies: pckg.dependencies || {},
        devDependencies: pckg.devDependencies || {}
    });
}
// Exclude main Turf module
modules = modules.filter(({name}) => name !== 'turf');

test('turf -- required files', t => {
    for (const {name, dir} of modules) {
        for (const filename of ['test.js', 'bench.js', 'index.js', 'index.d.ts', 'LICENSE', 'README.md', 'yarn.lock']) {
            if (!fs.existsSync(path.join(dir, filename))) t.fail(`${name} ${filename} is required`);
        }
        // if (!fs.existsSync(path.join(dir, 'types.ts'))) t.fail(`${name} types.ts is required`);
    }
    t.skip('add "types.ts" to all packages');
    t.end();
});

test('turf -- invalid dependencies', t => {
    for (const {name, dependencies, devDependencies} of modules) {
        for (const invalidDependency of ['load-json-file', 'write-json-file', 'tape', 'benchmark', 'glob', 'lerna', 'documentation', 'uglify-js']) {
            if (dependencies[invalidDependency]) t.fail(`${name} ${invalidDependency} should be defined as devDependencies`);
        }
        if (devDependencies['eslint'] || devDependencies['eslint-config-mourner']) t.fail(`${name} eslint is handled at the root level`);
        // if (devDependencies['mkdirp']) t.fail(`${name} tests should not have to create folders`);
    }
    t.skip('remove "mkdirp" from testing');
    t.end();
});

test('turf -- strict version dependencies', t => {
    for (const {name, dependencies} of modules) {
        if (dependencies['jsts'] && dependencies['jsts'] !== '1.4.0') t.fail(`${name} jsts must use v1.3.0`);
    }
    t.end();
});

test('turf -- duplicate dependencies', t => {
    for (const {name, dependencies, devDependencies} of modules) {
        for (const dependency of Object.keys(dependencies)) {
            if (devDependencies[dependency]) t.fail(`${name} ${dependency} is duplicated in devDependencies`);
        }
    }
    t.end();
});

test('turf -- check if files exists', t => {
    for (const {name, dir, pckg} of modules) {
        const {files} = pckg;
        if (!files || !files.length) t.fail(`${name} (files) must be included in package.json`);
        for (const file of files) {
            if (!fs.existsSync(path.join(dir, file))) t.fail(`${name} missing file ${file} in "files"`);
        }
    }
    t.end();
});

test('turf -- MIT license', t => {
    const text = fs.readFileSync(path.join(__dirname, 'LICENSE'), 'utf8');
    for (const {name, dir, pckg} of modules) {
        const {license} = pckg;
        if (license !== 'MIT') t.fail(`${name} (license) must be "MIT"`);
        if (fs.readFileSync(path.join(dir, 'LICENSE'), 'utf8') !== text) t.fail(`${name} (LICENSE) is different from @turf/turf`);
    }
    t.end();
});

test('turf -- contributors', t => {
    for (const {name, pckg} of modules) {
        for (const contributor of pckg.contributors || []) {
            if (!contributor.match(/<@.+>/)) t.fail(`${name} ${contributor} (contributors) should use "Full Name <@GitHub>"`);
        }
    }
    t.end();
});

test('turf -- scoped package name', t => {
    for (const {name, pckg} of modules) {
        const expected = name.replace('turf-', '@turf/');
        if (pckg.name !== expected) t.fail(`${name} (name) must use ${expected} in package.json`);
    }
    t.end();
});

test('turf -- pre-defined attributes in package.json', t => {
    for (const {name, pckg} of modules) {
        if (pckg.author !== 'Turf Authors') t.fail(name + ' (author) should be "Turf Authors"');
        if (pckg.main !== 'dist/index') t.fail(`${name} (main) must be "dist/index" in package.json`);
        if (pckg.module !== 'index') t.fail(`${name} (module) must be "index" in package.json`);
        if (pckg['jsnext:main'] !== 'index') t.fail(`${name} (jsnext:main) must be "index" in package.json`);
        if (pckg.types !== 'index.d.ts') t.fail(`${name} (types) must be "index.d.ts" in package.json`);
        if (!pckg.bugs || pckg.bugs.url !== 'https://github.com/Turfjs/turf/issues') t.fail(`${name} (bugs.url) must be "https://github.com/Turfjs/turf/issues" in package.json`);
        if (pckg.homepage !== 'https://github.com/Turfjs/turf') t.fail(`${name} (homepage) must be "https://github.com/Turfjs/turf" in package.json`);
    }
    t.end();
});

test('turf -- parsing dependencies from index.js', t => {
    for (const {name, dir, dependencies} of modules) {
        const index = fs.readFileSync(path.join(dir, 'index.js'), 'utf8');

        // Read Depedencies from index.js
        const dependenciesUsed = new Set();
        for (const dependency of index.match(/(require\(|from )'[@/a-z-\d]+'/gi) || []) {
            const dependencyName = dependency.split(/'/)[1];
            if (!dependencies[dependencyName]) t.fail(`${name} ${dependencyName} is missing from dependencies`);
            if (dependenciesUsed.has(dependencyName)) t.fail(`${name} ${dependencyName} is duplicated in index.js`);
            dependenciesUsed.add(dependencyName);
        }

        // Read Dependencies from package.json
        for (const dependencyName of Object.keys(dependencies)) {
            // Ignore @turf/helpers since it could be used in Typescript definition
            if (dependencyName === '@turf/helpers') continue;
            if (!dependenciesUsed.has(dependencyName)) t.fail(`${name} ${dependencyName} is not required in index.js`);
        }
    }
    t.end();
});

/**
 * =========================
 * Builds => test.example.js
 * =========================
 * will be run as `posttest`
 */

// File Paths
const testFilePath = path.join(__dirname, 'test.example.js');
const turfModulesPath = path.join(__dirname, '..', 'turf-*', 'index.js');

// Test Strings
const requireString = `const test = require('tape');
const turf = require('.');
`;

/**
 * Generate Test String
 *
 * @param {Object} turfFunction Documentation function object
 * @param {Object} example Documentation example object
 * @returns {string} Test String
 */
function testString(turfFunction, example) {
    const turfName = turfFunction.name;
    const testFunctionName = turfName + 'Test';

    // New modules will be excluded from tests
    if (!turf.hasOwnProperty(turfName)) return `
test('turf-${turfName}', t => {
    t.skip('${turfName}');
    t.end();
});
`;
    return `
test('turf-${turfName}', t => {
    const ${testFunctionName} = () => {
        ${example.description}
    }
    ${testFunctionName}();
    t.pass('${turfName}');
    t.end();
});
`;
}

// // Test for missing modules
// test('turf -- missing modules', t => {
//     const files = {
//         typescript: fs.readFileSync(path.join(__dirname, 'index.d.ts')),
//         modules: fs.readFileSync(path.join(__dirname, 'index.js'))
//     };

//     modules.forEach(({name}) => {
//         name = camelcase(name.replace('turf-', ''));
//         // name exception with linestring => lineString
//         name = name.replace('linestring', 'lineString').replace('Linestring', 'LineString');

//         if (!files.typescript.includes(name)) t.fail(name + ' is missing from index.d.ts');
//         if (!files.modules.includes(name)) t.fail(name + ' is missing from index.js');

//         switch (typeof turf[name]) {
//         case 'function': break;
//         case 'object':
//             Object.keys(turf[name]).forEach(method => {
//                 if (typeof turf[method] !== 'function') t.skip(name + '.' + method + ' is missing from index.js');
//                 if (!files.typescript.includes(method)) t.skip(name + '.' + method + ' is missing from index.d.ts');
//                 if (!files.modules.includes(method)) t.skip(name + '.' + method + ' is missing from index.js');
//             });
//             break;
//         case 'undefined':
//             t.fail(name + ' is missing from index.js');
//         }
//     });
//     t.end();
// });

// Iterate over each module and retrieve @example to build tests from them
glob(turfModulesPath, (err, files) => {
    if (err) throw err;

    // Read each JSDocs from index.js files
    documentation.build(files, {}).then(turfFunctions => {
        if (err) throw err;

        // Write header of test.js
        const writeableStream = fs.createWriteStream(testFilePath);
        writeableStream.write(requireString);
        writeableStream.on('error', err => { throw err; });

        // Retrieve @example
        turfFunctions.forEach(turfFunction => {
            if (turfFunction.examples) {

                // Save to test.js
                turfFunction.examples.forEach(example => {
                    writeableStream.write(testString(turfFunction, example));
                });
            }
        });
        writeableStream.end();
    });
});
<commit_msg>Remove JSDocs example tests (for now)<commit_after>import fs from 'fs';
import path from 'path';
import glob from 'glob';
import test from 'tape';
import documentation from 'documentation';
import camelcase from 'camelcase';
import * as turf from '.';

// Helpers
const directory = path.join(__dirname, '..');
let modules = [];
for (const name of fs.readdirSync(directory)) {
    const pckgPath = path.join(directory, name, 'package.json');
    if (!fs.existsSync(pckgPath)) continue;
    const pckg = JSON.parse(fs.readFileSync(pckgPath));
    modules.push({
        name,
        dir: path.join(directory, name),
        pckg,
        dependencies: pckg.dependencies || {},
        devDependencies: pckg.devDependencies || {}
    });
}
// Exclude main Turf module
modules = modules.filter(({name}) => name !== 'turf');

test('turf -- required files', t => {
    for (const {name, dir} of modules) {
        for (const filename of ['test.js', 'bench.js', 'index.js', 'index.d.ts', 'LICENSE', 'README.md', 'yarn.lock']) {
            if (!fs.existsSync(path.join(dir, filename))) t.fail(`${name} ${filename} is required`);
        }
        // if (!fs.existsSync(path.join(dir, 'types.ts'))) t.fail(`${name} types.ts is required`);
    }
    t.skip('add "types.ts" to all packages');
    t.end();
});

test('turf -- invalid dependencies', t => {
    for (const {name, dependencies, devDependencies} of modules) {
        for (const invalidDependency of ['load-json-file', 'write-json-file', 'tape', 'benchmark', 'glob', 'lerna', 'documentation', 'uglify-js']) {
            if (dependencies[invalidDependency]) t.fail(`${name} ${invalidDependency} should be defined as devDependencies`);
        }
        if (devDependencies['eslint'] || devDependencies['eslint-config-mourner']) t.fail(`${name} eslint is handled at the root level`);
        // if (devDependencies['mkdirp']) t.fail(`${name} tests should not have to create folders`);
    }
    t.skip('remove "mkdirp" from testing');
    t.end();
});

test('turf -- strict version dependencies', t => {
    for (const {name, dependencies} of modules) {
        if (dependencies['jsts'] && dependencies['jsts'] !== '1.4.0') t.fail(`${name} jsts must use v1.3.0`);
    }
    t.end();
});

test('turf -- duplicate dependencies', t => {
    for (const {name, dependencies, devDependencies} of modules) {
        for (const dependency of Object.keys(dependencies)) {
            if (devDependencies[dependency]) t.fail(`${name} ${dependency} is duplicated in devDependencies`);
        }
    }
    t.end();
});

test('turf -- check if files exists', t => {
    for (const {name, dir, pckg} of modules) {
        const {files} = pckg;
        if (!files || !files.length) t.fail(`${name} (files) must be included in package.json`);
        for (const file of files) {
            if (!fs.existsSync(path.join(dir, file))) t.fail(`${name} missing file ${file} in "files"`);
        }
    }
    t.end();
});

test('turf -- MIT license', t => {
    const text = fs.readFileSync(path.join(__dirname, 'LICENSE'), 'utf8');
    for (const {name, dir, pckg} of modules) {
        const {license} = pckg;
        if (license !== 'MIT') t.fail(`${name} (license) must be "MIT"`);
        if (fs.readFileSync(path.join(dir, 'LICENSE'), 'utf8') !== text) t.fail(`${name} (LICENSE) is different from @turf/turf`);
    }
    t.end();
});

test('turf -- contributors', t => {
    for (const {name, pckg} of modules) {
        for (const contributor of pckg.contributors || []) {
            if (!contributor.match(/<@.+>/)) t.fail(`${name} ${contributor} (contributors) should use "Full Name <@GitHub>"`);
        }
    }
    t.end();
});

test('turf -- scoped package name', t => {
    for (const {name, pckg} of modules) {
        const expected = name.replace('turf-', '@turf/');
        if (pckg.name !== expected) t.fail(`${name} (name) must use ${expected} in package.json`);
    }
    t.end();
});

test('turf -- pre-defined attributes in package.json', t => {
    for (const {name, pckg} of modules) {
        if (pckg.author !== 'Turf Authors') t.fail(name + ' (author) should be "Turf Authors"');
        if (pckg.main !== 'dist/index') t.fail(`${name} (main) must be "dist/index" in package.json`);
        if (pckg.module !== 'index') t.fail(`${name} (module) must be "index" in package.json`);
        if (pckg['jsnext:main'] !== 'index') t.fail(`${name} (jsnext:main) must be "index" in package.json`);
        if (pckg.types !== 'index.d.ts') t.fail(`${name} (types) must be "index.d.ts" in package.json`);
        if (!pckg.bugs || pckg.bugs.url !== 'https://github.com/Turfjs/turf/issues') t.fail(`${name} (bugs.url) must be "https://github.com/Turfjs/turf/issues" in package.json`);
        if (pckg.homepage !== 'https://github.com/Turfjs/turf') t.fail(`${name} (homepage) must be "https://github.com/Turfjs/turf" in package.json`);
    }
    t.end();
});

test('turf -- parsing dependencies from index.js', t => {
    for (const {name, dir, dependencies} of modules) {
        const index = fs.readFileSync(path.join(dir, 'index.js'), 'utf8');

        // Read Depedencies from index.js
        const dependenciesUsed = new Set();
        for (const dependency of index.match(/(require\(|from )'[@/a-z-\d]+'/gi) || []) {
            const dependencyName = dependency.split(/'/)[1];
            if (!dependencies[dependencyName]) t.fail(`${name} ${dependencyName} is missing from dependencies`);
            if (dependenciesUsed.has(dependencyName)) t.fail(`${name} ${dependencyName} is duplicated in index.js`);
            dependenciesUsed.add(dependencyName);
        }

        // Read Dependencies from package.json
        for (const dependencyName of Object.keys(dependencies)) {
            // Ignore @turf/helpers since it could be used in Typescript definition
            if (dependencyName === '@turf/helpers') continue;
            if (!dependenciesUsed.has(dependencyName)) t.fail(`${name} ${dependencyName} is not required in index.js`);
        }
    }
    t.end();
});

/**
 * =========================
 * Builds => test.example.js
 * =========================
 * will be run as `posttest`
 */

// File Paths
const testFilePath = path.join(__dirname, 'test.example.js');
const turfModulesPath = path.join(__dirname, '..', 'turf-*', 'index.js');

// Test Strings
const requireString = `const test = require('tape');
const turf = require('.');
`;

/**
 * Generate Test String
 *
 * @param {Object} turfFunction Documentation function object
 * @param {Object} example Documentation example object
 * @returns {string} Test String
 */
function testString(turfFunction, example) {
    const turfName = turfFunction.name;
    const testFunctionName = turfName + 'Test';

    // New modules will be excluded from tests
    if (!turf.hasOwnProperty(turfName)) return `
test('turf-${turfName}', t => {
    t.skip('${turfName}');
    t.end();
});
`;
    return `
test('turf-${turfName}', t => {
    const ${testFunctionName} = () => {
        ${example.description}
    }
    ${testFunctionName}();
    t.pass('${turfName}');
    t.end();
});
`;
}

// // Test for missing modules
// test('turf -- missing modules', t => {
//     const files = {
//         typescript: fs.readFileSync(path.join(__dirname, 'index.d.ts')),
//         modules: fs.readFileSync(path.join(__dirname, 'index.js'))
//     };

//     modules.forEach(({name}) => {
//         name = camelcase(name.replace('turf-', ''));
//         // name exception with linestring => lineString
//         name = name.replace('linestring', 'lineString').replace('Linestring', 'LineString');

//         if (!files.typescript.includes(name)) t.fail(name + ' is missing from index.d.ts');
//         if (!files.modules.includes(name)) t.fail(name + ' is missing from index.js');

//         switch (typeof turf[name]) {
//         case 'function': break;
//         case 'object':
//             Object.keys(turf[name]).forEach(method => {
//                 if (typeof turf[method] !== 'function') t.skip(name + '.' + method + ' is missing from index.js');
//                 if (!files.typescript.includes(method)) t.skip(name + '.' + method + ' is missing from index.d.ts');
//                 if (!files.modules.includes(method)) t.skip(name + '.' + method + ' is missing from index.js');
//             });
//             break;
//         case 'undefined':
//             t.fail(name + ' is missing from index.js');
//         }
//     });
//     t.end();
// });

// // Iterate over each module and retrieve @example to build tests from them
// glob(turfModulesPath, (err, files) => {
//     if (err) throw err;

//     // Read each JSDocs from index.js files
//     documentation.build(files, {}).then(turfFunctions => {
//         if (err) throw err;

//         // Write header of test.js
//         const writeableStream = fs.createWriteStream(testFilePath);
//         writeableStream.write(requireString);
//         writeableStream.on('error', err => { throw err; });

//         // Retrieve @example
//         turfFunctions.forEach(turfFunction => {
//             if (turfFunction.examples) {

//                 // Save to test.js
//                 turfFunction.examples.forEach(example => {
//                     writeableStream.write(testString(turfFunction, example));
//                 });
//             }
//         });
//         writeableStream.end();
//     });
// });
<|endoftext|>


<commit_before>
UI.Component.instantiate = function (parent) {
  var kind = this;

  // check arguments
  if (UI.isComponent(kind)) {
    if (kind.isInited)
      throw new Error("A component kind is required, not an instance");
  } else {
    throw new Error("Expected Component kind");
  }

  var inst = kind.extend(); // XXX args go here
  inst.isInited = true;

  // XXX messy to define this here
  inst.templateInstance = {
    findAll: function (selector) {
      // XXX check that `.dom` exists here?
      return inst.dom.$(selector);
    },
    find: function (selector) {
      var result = this.findAll(selector);
      return result[0] || null;
    },
    firstNode: null,
    lastNode: null,
    data: null,
    __component__: inst
  };

  inst.parent = (parent || null);

  if (inst.init)
    inst.init();

  if (inst.created) {
    updateTemplateInstance(inst);
    inst.created.call(inst.templateInstance);
  }

  return inst;
};

UI.Component.render = function () {
  return null;
};

// Takes a reactive function (call it `inner`) and returns a reactive function
// `outer` which is equivalent except in its reactive behavior.  Specifically,
// `outer` has the following two special properties:
//
// 1. Isolation:  An invocation of `outer()` only invalidates its context
//    when the value of `inner()` changes.  For example, `inner` may be a
//    function that gets one or more Session variables and calculates a
//    true/false value.  `outer` blocks invalidation signals caused by the
//    Session variables changing and sends a signal out only when the value
//    changes between true and false (in this example).  The value can be
//    of any type, and it is compared with `===` unless an `equals` function
//    is provided.
//
// 2. Value Sharing:  The `outer` function returned by `emboxValue` can be
//    shared between different contexts, for example by assigning it to an
//    object as a method that can be accessed at any time, such as by
//    different templates or different parts of a template.  No matter
//    how many times `outer` is called, `inner` is only called once until
//    it changes.  The most recent value is stored internally.
//
// Conceptually, an emboxed value is much like a Session variable which is
// kept up to date by an autorun.  Session variables provide storage
// (value sharing) and they don't notify their listeners unless a value
// actually changes (isolation).  The biggest difference is that such an
// autorun would never be stopped, and the Session variable would never be
// deleted even if it wasn't used any more.  An emboxed value, on the other
// hand, automatically stops computing when it's not being used, and starts
// again when called from a reactive context.  This means that when it stops
// being used, it can be completely garbage-collected.
//
// If a non-function value is supplied to `emboxValue` instead of a reactive
// function, then `outer` is still a function but it simply returns the value.
//
UI.emboxValue = function (funcOrValue, equals) {
  if (typeof funcOrValue === 'function') {
    var func = funcOrValue;

    var curResult = null;
    // There's one shared Dependency and Computation for all callers of
    // our box function.  It gets kicked off if necessary, and when
    // there are no more dependents, it gets stopped to avoid leaking
    // memory.
    var resultDep = null;
    var computation = null;

    return function () {
      if (! computation) {
        if (! Deps.active) {
          // Not in a reactive context.  Just call func, and don't start a
          // computation if there isn't one running already.
          return func();
        }

        // No running computation, so kick one off.  Since this computation
        // will be shared, avoid any association with the current computation
        // by using `Deps.nonreactive`.
        resultDep = new Deps.Dependency;

        computation = Deps.nonreactive(function () {
          return Deps.autorun(function (c) {
            var oldResult = curResult;
            curResult = func();
            if (! c.firstRun) {
              if (! (equals ? equals(curResult, oldResult) :
                     curResult === oldResult))
                resultDep.changed();
            }
          });
        });
      }

      if (Deps.active) {
        var isNew = resultDep.depend();
        if (isNew) {
          // For each new dependent, schedule a task for after that dependent's
          // invalidation time and the subsequent flush. The task checks
          // whether the computation should be torn down.
          Deps.onInvalidate(function () {
            if (resultDep && ! resultDep.hasDependents()) {
              Deps.afterFlush(function () {
                // use a second afterFlush to bump ourselves to the END of the
                // flush, after computation re-runs have had a chance to
                // re-establish their connections to our computation.
                Deps.afterFlush(function () {
                  if (resultDep && ! resultDep.hasDependents()) {
                    computation.stop();
                    computation = null;
                    resultDep = null;
                  }
                });
              });
            }
          });
        }
      }

      return curResult;
    };

  } else {
    var value = funcOrValue;
    var result = function () {
      return value;
    };
    result._isEmboxedConstant = true;
    return result;
  }
};

////////////////////////////////////////

// Insert a DOM node or DomRange into a DOM element or DomRange.
//
// One of three things happens depending on what needs to be inserted into what:
// - `range.add` (anything into DomRange)
// - `UI.DomRange.insert` (DomRange into element)
// - `elem.insertBefore` (node into element)
//
// The optional `before` argument is an existing node or id to insert before in
// the parent element or DomRange.
var insert = function (nodeOrRange, parent, before) {
  if (! parent)
    throw new Error("Materialization parent required");

  if (parent instanceof UI.DomRange) {
    parent.add(nodeOrRange, before);
  } else if (nodeOrRange instanceof UI.DomRange) {
    // parent is an element; inserting a range
    UI.DomRange.insert(nodeOrRange, parent, before);
  } else {
    // parent is an element; inserting an element
    parent.insertBefore(nodeOrRange, before || null); // `null` for IE
  }
};

// Update attributes on `elem` to the dictionary `attrs`, using the
// dictionary of existing `handlers` if provided.
//
// Values in the `attrs` dictionary are in pseudo-DOM form -- a string,
// CharRef, or array of strings and CharRefs -- but they are passed to
// the AttributeHandler in string form.
var updateAttributes = function(elem, newAttrs, handlers) {

  if (handlers) {
    for (var k in handlers) {
      if (! newAttrs.hasOwnProperty(k)) {
        // remove attributes (and handlers) for attribute names
        // that don't exist as keys of `newAttrs` and so won't
        // be visited when traversing it.  (Attributes that
        // exist in the `newAttrs` object but are `null`
        // are handled later.)
        var handler = handlers[k];
        var oldValue = handler.value;
        handler.value = null;
        handler.update(elem, oldValue, null);
        delete handlers[k];
      }
    }
  }

  for (var k in newAttrs) {
    var handler = null;
    var oldValue;
    var value = newAttrs[k];
    if ((! handlers) || (! handlers.hasOwnProperty(k))) {
      if (value !== null) {
        // make new handler
        handler = makeAttributeHandler(elem, k, value);
        if (handlers)
          handlers[k] = handler;
        oldValue = null;
      }
    } else {
      handler = handlers[k];
      oldValue = handler.value;
    }
    if (handler && oldValue !== value) {
      handler.value = value;
      handler.update(elem, oldValue, value);
      if (value === null)
        delete handlers[k];
    }
  }
};

UI.render = function (kind, parentComponent) {
  if (kind.isInited)
    throw new Error("Can't render component instance, only component kind");
  var inst = kind.instantiate(parentComponent);

  var content = (inst.render && inst.render());

  var range = new UI.DomRange;
  inst.dom = range;
  range.component = inst;

  materialize(content, range, null, inst);

  range.removed = function () {
    inst.isDestroyed = true;
    if (inst.destroyed) {
      updateTemplateInstance(inst);
      inst.destroyed.call(inst.templateInstance);
    }
  };

  return inst;
};

var contentEquals = function (a, b) {
  if (a instanceof HTML.Raw) {
    return (b instanceof HTML.Raw) && (a.value === b.value);
  } else if (a == null) {
    return (b == null);
  } else {
    return (a === b) &&
      ((typeof a === 'number') || (typeof a === 'boolean') ||
       (typeof a === 'string'));
  }
};

UI.InTemplateScope = function (tmplInstance, content) {
  if (! (this instanceof UI.InTemplateScope))
    // called without `new`
    return new UI.InTemplateScope(tmplInstance, content);

  var parentPtr = tmplInstance.parent;
  if (parentPtr.__isTemplateWith)
    parentPtr = parentPtr.parent;

  this.parentPtr = parentPtr;
  this.content = content;
};

UI.InTemplateScope.prototype.toHTML = function (parentComponent) {
  return HTML.toHTML(this.content, this.parentPtr);
};

UI.InTemplateScope.prototype.toText = function (textMode, parentComponent) {
  return HTML.toText(this.content, textMode, this.parentPtr);
};

// Convert the pseudoDOM `node` into reactive DOM nodes and insert them
// into the element or DomRange `parent`, before the node or id `before`.
var materialize = function (node, parent, before, parentComponent) {
  // XXX should do more error-checking for the case where user is supplying the tags.
  // For example, check that CharRef has `html` and `str` properties and no content.
  // Check that Comment has a single string child and no attributes.  Etc.

  if (node == null) {
    // null or undefined.
    // do nothinge.
  } else if ((typeof node === 'string') || (typeof node === 'boolean') || (typeof node === 'number')) {
    node = String(node);
    insert(document.createTextNode(node), parent, before);
  } else if (node instanceof Array) {
    for (var i = 0; i < node.length; i++)
      materialize(node[i], parent, before, parentComponent);
  } else if (typeof node === 'function') {

    var range = new UI.DomRange;
    var lastContent = null;
    var rangeUpdater = Deps.autorun(function (c) {
      var content = node();
      // normalize content a little, for easier comparison
      if (HTML.isNully(content))
        content = null;
      else if ((content instanceof Array) && content.length === 1)
        content = content[0];

      // update if content is different from last time
      if (! contentEquals(content, lastContent)) {
        lastContent = content;

        if (! c.firstRun)
          range.removeAll();

        Deps.nonreactive(function () {
          materialize(content, range, null, parentComponent);
        });
      }
    });
    range.removed = function () {
      rangeUpdater.stop();
    };
    insert(range, parent, before);
  } else if (node instanceof HTML.Tag) {
    var tagName = HTML.properCaseTagName(node.tagName);
    var elem;
    if (HTML.isKnownSVGElement(tagName) && (! HTML.isKnownElement(tagName)) &&
        document.createElementNS) {
      elem = document.createElementNS('http://www.w3.org/2000/svg', tagName);
    } else {
      elem = document.createElement(node.tagName);
    }

    var rawAttrs = node.attrs;
    var children = node.children;
    if (node.tagName === 'TEXTAREA') {
      rawAttrs = (rawAttrs || {});
      rawAttrs.value = children;
      children = [];
    };

    if (rawAttrs) {
      var attrUpdater = Deps.autorun(function (c) {
        if (! c.handlers)
          c.handlers = {};

        try {
          var attrs = HTML.evaluateAttributes(rawAttrs, parentComponent);
          var stringAttrs = {};
          if (attrs) {
            for (var k in attrs) {
              stringAttrs[k] = HTML.toText(attrs[k], HTML.TEXTMODE.STRING,
                                           parentComponent);
            }
            updateAttributes(elem, stringAttrs, c.handlers);
          }
        } catch (e) {
          reportUIException(e);
        }
      });
      UI.DomBackend.onRemoveElement(elem, function () {
        attrUpdater.stop();
      });
    }
    materialize(children, elem, null, parentComponent);

    insert(elem, parent, before);
  } else if (typeof node.instantiate === 'function') {
    // component
    var instance = UI.render(node, parentComponent);

    insert(instance.dom, parent, before);
  } else if (node instanceof HTML.CharRef) {
    insert(document.createTextNode(node.str), parent, before);
  } else if (node instanceof HTML.Comment) {
    insert(document.createComment(node.sanitizedValue), parent, before);
  } else if (node instanceof HTML.Raw) {
    // Get an array of DOM nodes by using the browser's HTML parser
    // (like innerHTML).
    var htmlNodes = UI.DomBackend.parseHTML(node.value);
    for (var i = 0; i < htmlNodes.length; i++)
      insert(htmlNodes[i], parent, before);
  } else if (HTML.Special && (node instanceof HTML.Special)) {
    throw new Error("Can't materialize Special tag, it's just an intermediate rep");
  } else if (node instanceof UI.InTemplateScope) {
    materialize(node.content, parent, before, node.parentPtr);
  } else {
    // can't get here
    throw new Error("Unexpected node in htmljs: " + node);
  }
};

// XXX figure out the right names, and namespace, for these.
// for example, maybe some of them go in the HTML package.
UI.materialize = materialize;

UI.body = UI.Component.extend({
  kind: 'body',
  contentParts: [],
  render: function () {
    return this.contentParts;
  },
  // XXX revisit how body works.
  INSTANTIATED: false
});

UI.block = function (renderFunc) {
  return UI.Component.extend({ render: renderFunc });
};

UI.toHTML = function (content, parentComponent) {
  return HTML.toHTML(content, parentComponent);
};

UI.toRawText = function (content, parentComponent) {
  return HTML.toText(content, HTML.TEXTMODE.STRING, parentComponent);
};
<commit_msg>resurrect UI.insert<commit_after>
UI.Component.instantiate = function (parent) {
  var kind = this;

  // check arguments
  if (UI.isComponent(kind)) {
    if (kind.isInited)
      throw new Error("A component kind is required, not an instance");
  } else {
    throw new Error("Expected Component kind");
  }

  var inst = kind.extend(); // XXX args go here
  inst.isInited = true;

  // XXX messy to define this here
  inst.templateInstance = {
    findAll: function (selector) {
      // XXX check that `.dom` exists here?
      return inst.dom.$(selector);
    },
    find: function (selector) {
      var result = this.findAll(selector);
      return result[0] || null;
    },
    firstNode: null,
    lastNode: null,
    data: null,
    __component__: inst
  };

  inst.parent = (parent || null);

  if (inst.init)
    inst.init();

  if (inst.created) {
    updateTemplateInstance(inst);
    inst.created.call(inst.templateInstance);
  }

  return inst;
};

UI.Component.render = function () {
  return null;
};

// Takes a reactive function (call it `inner`) and returns a reactive function
// `outer` which is equivalent except in its reactive behavior.  Specifically,
// `outer` has the following two special properties:
//
// 1. Isolation:  An invocation of `outer()` only invalidates its context
//    when the value of `inner()` changes.  For example, `inner` may be a
//    function that gets one or more Session variables and calculates a
//    true/false value.  `outer` blocks invalidation signals caused by the
//    Session variables changing and sends a signal out only when the value
//    changes between true and false (in this example).  The value can be
//    of any type, and it is compared with `===` unless an `equals` function
//    is provided.
//
// 2. Value Sharing:  The `outer` function returned by `emboxValue` can be
//    shared between different contexts, for example by assigning it to an
//    object as a method that can be accessed at any time, such as by
//    different templates or different parts of a template.  No matter
//    how many times `outer` is called, `inner` is only called once until
//    it changes.  The most recent value is stored internally.
//
// Conceptually, an emboxed value is much like a Session variable which is
// kept up to date by an autorun.  Session variables provide storage
// (value sharing) and they don't notify their listeners unless a value
// actually changes (isolation).  The biggest difference is that such an
// autorun would never be stopped, and the Session variable would never be
// deleted even if it wasn't used any more.  An emboxed value, on the other
// hand, automatically stops computing when it's not being used, and starts
// again when called from a reactive context.  This means that when it stops
// being used, it can be completely garbage-collected.
//
// If a non-function value is supplied to `emboxValue` instead of a reactive
// function, then `outer` is still a function but it simply returns the value.
//
UI.emboxValue = function (funcOrValue, equals) {
  if (typeof funcOrValue === 'function') {
    var func = funcOrValue;

    var curResult = null;
    // There's one shared Dependency and Computation for all callers of
    // our box function.  It gets kicked off if necessary, and when
    // there are no more dependents, it gets stopped to avoid leaking
    // memory.
    var resultDep = null;
    var computation = null;

    return function () {
      if (! computation) {
        if (! Deps.active) {
          // Not in a reactive context.  Just call func, and don't start a
          // computation if there isn't one running already.
          return func();
        }

        // No running computation, so kick one off.  Since this computation
        // will be shared, avoid any association with the current computation
        // by using `Deps.nonreactive`.
        resultDep = new Deps.Dependency;

        computation = Deps.nonreactive(function () {
          return Deps.autorun(function (c) {
            var oldResult = curResult;
            curResult = func();
            if (! c.firstRun) {
              if (! (equals ? equals(curResult, oldResult) :
                     curResult === oldResult))
                resultDep.changed();
            }
          });
        });
      }

      if (Deps.active) {
        var isNew = resultDep.depend();
        if (isNew) {
          // For each new dependent, schedule a task for after that dependent's
          // invalidation time and the subsequent flush. The task checks
          // whether the computation should be torn down.
          Deps.onInvalidate(function () {
            if (resultDep && ! resultDep.hasDependents()) {
              Deps.afterFlush(function () {
                // use a second afterFlush to bump ourselves to the END of the
                // flush, after computation re-runs have had a chance to
                // re-establish their connections to our computation.
                Deps.afterFlush(function () {
                  if (resultDep && ! resultDep.hasDependents()) {
                    computation.stop();
                    computation = null;
                    resultDep = null;
                  }
                });
              });
            }
          });
        }
      }

      return curResult;
    };

  } else {
    var value = funcOrValue;
    var result = function () {
      return value;
    };
    result._isEmboxedConstant = true;
    return result;
  }
};

////////////////////////////////////////

UI.insert = function (renderedTemplate, parentElement, nextNode) {
  if (! renderedTemplate.dom)
    throw new Error("Expected template rendered with UI.render");

  UI.DomRange.insert(renderedTemplate.dom, parentElement, nextNode);
};

// Insert a DOM node or DomRange into a DOM element or DomRange.
//
// One of three things happens depending on what needs to be inserted into what:
// - `range.add` (anything into DomRange)
// - `UI.DomRange.insert` (DomRange into element)
// - `elem.insertBefore` (node into element)
//
// The optional `before` argument is an existing node or id to insert before in
// the parent element or DomRange.
var insert = function (nodeOrRange, parent, before) {
  if (! parent)
    throw new Error("Materialization parent required");

  if (parent instanceof UI.DomRange) {
    parent.add(nodeOrRange, before);
  } else if (nodeOrRange instanceof UI.DomRange) {
    // parent is an element; inserting a range
    UI.DomRange.insert(nodeOrRange, parent, before);
  } else {
    // parent is an element; inserting an element
    parent.insertBefore(nodeOrRange, before || null); // `null` for IE
  }
};

// Update attributes on `elem` to the dictionary `attrs`, using the
// dictionary of existing `handlers` if provided.
//
// Values in the `attrs` dictionary are in pseudo-DOM form -- a string,
// CharRef, or array of strings and CharRefs -- but they are passed to
// the AttributeHandler in string form.
var updateAttributes = function(elem, newAttrs, handlers) {

  if (handlers) {
    for (var k in handlers) {
      if (! newAttrs.hasOwnProperty(k)) {
        // remove attributes (and handlers) for attribute names
        // that don't exist as keys of `newAttrs` and so won't
        // be visited when traversing it.  (Attributes that
        // exist in the `newAttrs` object but are `null`
        // are handled later.)
        var handler = handlers[k];
        var oldValue = handler.value;
        handler.value = null;
        handler.update(elem, oldValue, null);
        delete handlers[k];
      }
    }
  }

  for (var k in newAttrs) {
    var handler = null;
    var oldValue;
    var value = newAttrs[k];
    if ((! handlers) || (! handlers.hasOwnProperty(k))) {
      if (value !== null) {
        // make new handler
        handler = makeAttributeHandler(elem, k, value);
        if (handlers)
          handlers[k] = handler;
        oldValue = null;
      }
    } else {
      handler = handlers[k];
      oldValue = handler.value;
    }
    if (handler && oldValue !== value) {
      handler.value = value;
      handler.update(elem, oldValue, value);
      if (value === null)
        delete handlers[k];
    }
  }
};

UI.render = function (kind, parentComponent) {
  if (kind.isInited)
    throw new Error("Can't render component instance, only component kind");
  var inst = kind.instantiate(parentComponent);

  var content = (inst.render && inst.render());

  var range = new UI.DomRange;
  inst.dom = range;
  range.component = inst;

  materialize(content, range, null, inst);

  range.removed = function () {
    inst.isDestroyed = true;
    if (inst.destroyed) {
      updateTemplateInstance(inst);
      inst.destroyed.call(inst.templateInstance);
    }
  };

  return inst;
};

var contentEquals = function (a, b) {
  if (a instanceof HTML.Raw) {
    return (b instanceof HTML.Raw) && (a.value === b.value);
  } else if (a == null) {
    return (b == null);
  } else {
    return (a === b) &&
      ((typeof a === 'number') || (typeof a === 'boolean') ||
       (typeof a === 'string'));
  }
};

UI.InTemplateScope = function (tmplInstance, content) {
  if (! (this instanceof UI.InTemplateScope))
    // called without `new`
    return new UI.InTemplateScope(tmplInstance, content);

  var parentPtr = tmplInstance.parent;
  if (parentPtr.__isTemplateWith)
    parentPtr = parentPtr.parent;

  this.parentPtr = parentPtr;
  this.content = content;
};

UI.InTemplateScope.prototype.toHTML = function (parentComponent) {
  return HTML.toHTML(this.content, this.parentPtr);
};

UI.InTemplateScope.prototype.toText = function (textMode, parentComponent) {
  return HTML.toText(this.content, textMode, this.parentPtr);
};

// Convert the pseudoDOM `node` into reactive DOM nodes and insert them
// into the element or DomRange `parent`, before the node or id `before`.
var materialize = function (node, parent, before, parentComponent) {
  // XXX should do more error-checking for the case where user is supplying the tags.
  // For example, check that CharRef has `html` and `str` properties and no content.
  // Check that Comment has a single string child and no attributes.  Etc.

  if (node == null) {
    // null or undefined.
    // do nothinge.
  } else if ((typeof node === 'string') || (typeof node === 'boolean') || (typeof node === 'number')) {
    node = String(node);
    insert(document.createTextNode(node), parent, before);
  } else if (node instanceof Array) {
    for (var i = 0; i < node.length; i++)
      materialize(node[i], parent, before, parentComponent);
  } else if (typeof node === 'function') {

    var range = new UI.DomRange;
    var lastContent = null;
    var rangeUpdater = Deps.autorun(function (c) {
      var content = node();
      // normalize content a little, for easier comparison
      if (HTML.isNully(content))
        content = null;
      else if ((content instanceof Array) && content.length === 1)
        content = content[0];

      // update if content is different from last time
      if (! contentEquals(content, lastContent)) {
        lastContent = content;

        if (! c.firstRun)
          range.removeAll();

        Deps.nonreactive(function () {
          materialize(content, range, null, parentComponent);
        });
      }
    });
    range.removed = function () {
      rangeUpdater.stop();
    };
    insert(range, parent, before);
  } else if (node instanceof HTML.Tag) {
    var tagName = HTML.properCaseTagName(node.tagName);
    var elem;
    if (HTML.isKnownSVGElement(tagName) && (! HTML.isKnownElement(tagName)) &&
        document.createElementNS) {
      elem = document.createElementNS('http://www.w3.org/2000/svg', tagName);
    } else {
      elem = document.createElement(node.tagName);
    }

    var rawAttrs = node.attrs;
    var children = node.children;
    if (node.tagName === 'TEXTAREA') {
      rawAttrs = (rawAttrs || {});
      rawAttrs.value = children;
      children = [];
    };

    if (rawAttrs) {
      var attrUpdater = Deps.autorun(function (c) {
        if (! c.handlers)
          c.handlers = {};

        try {
          var attrs = HTML.evaluateAttributes(rawAttrs, parentComponent);
          var stringAttrs = {};
          if (attrs) {
            for (var k in attrs) {
              stringAttrs[k] = HTML.toText(attrs[k], HTML.TEXTMODE.STRING,
                                           parentComponent);
            }
            updateAttributes(elem, stringAttrs, c.handlers);
          }
        } catch (e) {
          reportUIException(e);
        }
      });
      UI.DomBackend.onRemoveElement(elem, function () {
        attrUpdater.stop();
      });
    }
    materialize(children, elem, null, parentComponent);

    insert(elem, parent, before);
  } else if (typeof node.instantiate === 'function') {
    // component
    var instance = UI.render(node, parentComponent);

    insert(instance.dom, parent, before);
  } else if (node instanceof HTML.CharRef) {
    insert(document.createTextNode(node.str), parent, before);
  } else if (node instanceof HTML.Comment) {
    insert(document.createComment(node.sanitizedValue), parent, before);
  } else if (node instanceof HTML.Raw) {
    // Get an array of DOM nodes by using the browser's HTML parser
    // (like innerHTML).
    var htmlNodes = UI.DomBackend.parseHTML(node.value);
    for (var i = 0; i < htmlNodes.length; i++)
      insert(htmlNodes[i], parent, before);
  } else if (HTML.Special && (node instanceof HTML.Special)) {
    throw new Error("Can't materialize Special tag, it's just an intermediate rep");
  } else if (node instanceof UI.InTemplateScope) {
    materialize(node.content, parent, before, node.parentPtr);
  } else {
    // can't get here
    throw new Error("Unexpected node in htmljs: " + node);
  }
};

// XXX figure out the right names, and namespace, for these.
// for example, maybe some of them go in the HTML package.
UI.materialize = materialize;

UI.body = UI.Component.extend({
  kind: 'body',
  contentParts: [],
  render: function () {
    return this.contentParts;
  },
  // XXX revisit how body works.
  INSTANTIATED: false
});

UI.block = function (renderFunc) {
  return UI.Component.extend({ render: renderFunc });
};

UI.toHTML = function (content, parentComponent) {
  return HTML.toHTML(content, parentComponent);
};

UI.toRawText = function (content, parentComponent) {
  return HTML.toText(content, HTML.TEXTMODE.STRING, parentComponent);
};
<|endoftext|>


<commit_before>"use import";

import std.uri as URI;

var doc;
exports.getDoc = function() {
	if (doc) { return doc; }
	try {
		doc = window.ActiveXObject && new ActiveXObject('htmlfile');
		if (doc) {
			doc.open().write('');
			doc.close();
			window.attachEvent('onunload', function() {
				try { doc.body.innerHTML = ''; } catch(e) {}
				doc = null;
			});
		}
	} catch(e) {}

	if (!doc) { doc = document; }
	return doc;
};

var ctor = function() {
	var win = window,
		doc = exports.getDoc();
	//if (doc.parentWindow) { win = doc.parentWindow; }

	return new (ctor = win.XMLHttpRequest ? win.XMLHttpRequest
		: function() { return win.ActiveXObject && new win.ActiveXObject('Msxml2.XMLHTTP') || null; });
};

exports.createXHR = function() { return new ctor(); }

exports.post = function(opts, cb) {
	return exports.get(merge({method: 'POST'}, opts), cb);
}

exports.get = function(opts, cb) {
	if (typeof opts == 'string') { opts = {url: opts}; }
	var method = opts.method || 'GET';
	var url = opts.url;
	var isObject = opts.data && typeof opts.data == 'object';
	if (!opts.url) { logger.error('no url provided'); return; }

	var data = method == 'POST' ? isObject ? JSON.stringify(opts.data) : opts.data : null;
	if (method == 'GET' && opts.data) {
		url = new URI(url).addQuery(isObject ? opts.data : URI.parseQuery(opts.data)).toString();
	}

	var xhr = exports.createXHR();
	xhr.open(method, url, !(opts.async == false));
	xhr.setRequestHeader('Content-Type', 'text/plain');
	if (cb) {
		xhr.onreadystatechange = bind(this, onReadyStateChange, xhr, opts.type, cb);
	}
	xhr.send(data || null);
}

function onReadyStateChange(xhr, type, cb) {
	if (xhr.readyState != 4) { return; }
	// .status will be 0 when requests are filled via app cache on at least iOS 4.x
	if (xhr.status != 200 && xhr.status != 0) {
		cb({status: xhr.status, response: xhr.response}, null);
	} else {
		var data = xhr.responseText;
		if (type == 'json') {
			data = JSON.parse(data);
		}
		cb(null, data);
	}
}
<commit_msg>allow custom headers on ajax<commit_after>"use import";

import std.uri as URI;

var doc;
exports.getDoc = function() {
	if (doc) { return doc; }
	try {
		doc = window.ActiveXObject && new ActiveXObject('htmlfile');
		if (doc) {
			doc.open().write('');
			doc.close();
			window.attachEvent('onunload', function() {
				try { doc.body.innerHTML = ''; } catch(e) {}
				doc = null;
			});
		}
	} catch(e) {}

	if (!doc) { doc = document; }
	return doc;
};

var ctor = function() {
	var win = window,
		doc = exports.getDoc();
	//if (doc.parentWindow) { win = doc.parentWindow; }

	return new (ctor = win.XMLHttpRequest ? win.XMLHttpRequest
		: function() { return win.ActiveXObject && new win.ActiveXObject('Msxml2.XMLHTTP') || null; });
};

exports.createXHR = function() { return new ctor(); }

exports.post = function(opts, cb) {
	return exports.get(merge({method: 'POST'}, opts), cb);
}

exports.get = function(opts, cb) {
	if (typeof opts == 'string') { opts = {url: opts}; }
	var method = opts.method || 'GET';
	var url = opts.url;
	var isObject = opts.data && typeof opts.data == 'object';
	if (!opts.url) { logger.error('no url provided'); return; }

	var data = method == 'POST' ? isObject ? JSON.stringify(opts.data) : opts.data : null;
	if (method == 'GET' && opts.data) {
		url = new URI(url).addQuery(isObject ? opts.data : URI.parseQuery(opts.data)).toString();
	}

	var xhr = exports.createXHR();
	xhr.open(method, url, !(opts.async == false));
	xhr.setRequestHeader('Content-Type', 'text/plain');
	if (opts.headers) {
		for (var key in opts.headers) if (opts.headers.hasOwnProperty(key)) {
			xhr.setRequestHeader(key, opts.headers[key]);
		}
	}
	if (cb) {
		xhr.onreadystatechange = bind(this, onReadyStateChange, xhr, opts.type, cb);
	}
	xhr.send(data || null);
}

function onReadyStateChange(xhr, type, cb) {
	if (xhr.readyState != 4) { return; }
	// .status will be 0 when requests are filled via app cache on at least iOS 4.x
	if (xhr.status != 200 && xhr.status != 0) {
		cb({status: xhr.status, response: xhr.response}, null);
	} else {
		var data = xhr.responseText;
		if (type == 'json') {
			data = JSON.parse(data);
		}
		cb(null, data);
	}
}
<|endoftext|>


<commit_before>// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.

// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".

// import socket from "./socket"
<commit_msg>Remove cruft from app.js<commit_after>import "phoenix_html"

<|endoftext|>