<commit_before>'use strict';

var _ = require('./underscore_ext');
var Rx = require('./rx');
var React = require('react');
var ReactDOM = require('react-dom');
let {createDevTools} = require('./controllers/devtools');
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
var nostate = require('./nostate');
var urlParams = require('./urlParams');
var LZ = require('./lz-string');
var {compactState, expandState} = require('./compactData');
var migrateState = require('./migrateState');
var {schemaCheckThrow} = require('./schemaCheck');

function logError(err) {
	if (typeof window === 'object' && typeof window.chrome !== 'undefined') {
		// In Chrome, rethrowing provides better source map support
		setTimeout(() => { throw err; });
	} else {
		console.error(err.stack || err);
	}
}

var dropTransient = state =>
	_.assoc(state, 'wizard', {}, 'datapages', undefined);

// serialization
function stringify(state) {
	return LZ.compressToUTF16(JSON.stringify({
		..._.omit(state, 'computedStates', 'committedState'),
		   committedState: compactState(dropTransient(state.committedState))
	}));
}
function parse(str) {
	var state = JSON.parse(LZ.decompressFromUTF16(str));
	return {
		...state,
		committedState: schemaCheckThrow(expandState(migrateState(state.committedState)))
	};
}

//
var unwrapDevState = state => _.last(state.computedStates).state;

function getSavedState(persist) {
	delete sessionStorage.xena; // Free up space & don't try to share with prod.
	if (persist && nostate('debugSession')) {
		try {
			return parse(sessionStorage.debugSession);
		} catch(err) {
			console.log("Unable to load saved debug session", err);
		}
	}
	return null;
}

var historyObs = Rx.Observable
	.fromEvent(window, 'popstate')
	.map(() => ['history', {path: location.pathname, params: urlParams()}]);

module.exports = function({
	Page,
	controller,
	persist,
	initialState,
	serverBus,
	serverCh,
	uiBus,
	uiCh,
	main,
	selector}) {

	var dom = {main},
		updater = ac => uiBus.next(ac),
		devBus = new Rx.Subject(),
		devCh = devBus,
		devtoolsVisible = false; // Change this to turn on the debug window at start.

	var DevTools = createDevTools(
		<DockMonitor defaultIsVisible={devtoolsVisible}
				select={state => state.spreadsheet.ties}
				toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'>
			<LogMonitor preserveScrollTop={false} expandStateRoot={false}/>
		</DockMonitor>),

		devReducer = DevTools.instrument(controller, initialState),
		savedState = getSavedState(persist),
		// Here we need not just the initial state, but to know if we have a
		// saved state. The initial state is used in devtools as the 'reset'
		// target. So, we can't replace initial state with saved state.
		devInitialState = devReducer(null, savedState ?
			{type: 'IMPORT_STATE', nextLiftedState: savedState} : {});

	// Side-effects (e.g. async) happen here. Ideally we wouldn't call this
	// from 'scan', since 'scan' should be side-effect free. However we've lost
	// the action by the time scan is complete, so we do it in the scan.
	var inEffectsReducer = false;
	var effectsReducer = (state, ac) => {
		if (inEffectsReducer) {
			throw new Error("Reentry in reducer. Reducers must not invoke actions.");
		}
		inEffectsReducer = true;
		var nextState = devReducer(state, ac);
		if (ac.type === 'PERFORM_ACTION') {
			try {
				controller.postAction(serverBus, unwrapDevState(state),
						unwrapDevState(nextState), ac.action);
			} catch(err) {
				logError(err);
			}
		}
		// We have an implicit async action on page load: 'init'. redux-devtools
		// 'RESET' command will return us to the initial state, but never
		// re-issues async actions (which would break the devtools functionality).
		// This leaves our app in an unusable state after RESET: initial state w/o any
		// way of issuing the 'init' action. The effect is the cohort list never
		// loads. Here we intercept the devtools actions & re-issue 'init' on
		// RESET.
		if (ac.type === 'RESET') {
			setTimeout(() => uiBus.next(['init', location.pathname, urlParams()]), 0);
		}

		inEffectsReducer = false;
		return nextState;
	};

	var devStateObs = Rx.Observable.merge(serverCh, uiCh, historyObs)
					.map(ac => ({type: 'PERFORM_ACTION', action: ac}))
					.merge(devCh)
					.scan(effectsReducer, devInitialState) // XXX side effects!
					.share();

	// XXX double check that this expression is doing what we want: don't draw faster
	// than rAF.

	// pass the selector into Page, so we catch errors while rendering & can display an error message.
	devStateObs.debounceTime(0, Rx.Scheduler.animationFrame)
		.subscribe(devState => {
			return ReactDOM.render(

					<Page callback={updater} selector={selector}
							state={unwrapDevState(devState)} />
					<DevTools dispatch={devBus.next.bind(devBus)} {...devState} />

,
				dom.main);
		}, err => console.log('err', err));

	if (persist) {
		// Save state in sessionStorage on page unload.
		devStateObs.sample(Rx.Observable.fromEvent(window, 'beforeunload'))
			.map(state => sessionStorage.saveDevState ? state :
					effectsReducer(state, {type: 'COMMIT'}))
			.subscribe(state => sessionStorage.debugSession = stringify(state));
	}

	// This causes us to always load cohorts on page load. This is important after
	// setting hubs, for example.
	uiBus.next(['init', location.pathname, urlParams()]);
	return dom;
};
<commit_msg>Back out debug setting.<commit_after>'use strict';

var _ = require('./underscore_ext');
var Rx = require('./rx');
var React = require('react');
var ReactDOM = require('react-dom');
let {createDevTools} = require('./controllers/devtools');
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
var nostate = require('./nostate');
var urlParams = require('./urlParams');
var LZ = require('./lz-string');
var {compactState, expandState} = require('./compactData');
var migrateState = require('./migrateState');
var {schemaCheckThrow} = require('./schemaCheck');

function logError(err) {
	if (typeof window === 'object' && typeof window.chrome !== 'undefined') {
		// In Chrome, rethrowing provides better source map support
		setTimeout(() => { throw err; });
	} else {
		console.error(err.stack || err);
	}
}

var dropTransient = state =>
	_.assoc(state, 'wizard', {}, 'datapages', undefined);

// serialization
function stringify(state) {
	return LZ.compressToUTF16(JSON.stringify({
		..._.omit(state, 'computedStates', 'committedState'),
		   committedState: compactState(dropTransient(state.committedState))
	}));
}
function parse(str) {
	var state = JSON.parse(LZ.decompressFromUTF16(str));
	return {
		...state,
		committedState: schemaCheckThrow(expandState(migrateState(state.committedState)))
	};
}

//
var unwrapDevState = state => _.last(state.computedStates).state;

function getSavedState(persist) {
	delete sessionStorage.xena; // Free up space & don't try to share with prod.
	if (persist && nostate('debugSession')) {
		try {
			return parse(sessionStorage.debugSession);
		} catch(err) {
			console.log("Unable to load saved debug session", err);
		}
	}
	return null;
}

var historyObs = Rx.Observable
	.fromEvent(window, 'popstate')
	.map(() => ['history', {path: location.pathname, params: urlParams()}]);

module.exports = function({
	Page,
	controller,
	persist,
	initialState,
	serverBus,
	serverCh,
	uiBus,
	uiCh,
	main,
	selector}) {

	var dom = {main},
		updater = ac => uiBus.next(ac),
		devBus = new Rx.Subject(),
		devCh = devBus,
		devtoolsVisible = false; // Change this to turn on the debug window at start.

	var DevTools = createDevTools(
		<DockMonitor defaultIsVisible={devtoolsVisible}
				toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'>
			<LogMonitor preserveScrollTop={false} expandStateRoot={false}/>
		</DockMonitor>),

		devReducer = DevTools.instrument(controller, initialState),
		savedState = getSavedState(persist),
		// Here we need not just the initial state, but to know if we have a
		// saved state. The initial state is used in devtools as the 'reset'
		// target. So, we can't replace initial state with saved state.
		devInitialState = devReducer(null, savedState ?
			{type: 'IMPORT_STATE', nextLiftedState: savedState} : {});

	// Side-effects (e.g. async) happen here. Ideally we wouldn't call this
	// from 'scan', since 'scan' should be side-effect free. However we've lost
	// the action by the time scan is complete, so we do it in the scan.
	var inEffectsReducer = false;
	var effectsReducer = (state, ac) => {
		if (inEffectsReducer) {
			throw new Error("Reentry in reducer. Reducers must not invoke actions.");
		}
		inEffectsReducer = true;
		var nextState = devReducer(state, ac);
		if (ac.type === 'PERFORM_ACTION') {
			try {
				controller.postAction(serverBus, unwrapDevState(state),
						unwrapDevState(nextState), ac.action);
			} catch(err) {
				logError(err);
			}
		}
		// We have an implicit async action on page load: 'init'. redux-devtools
		// 'RESET' command will return us to the initial state, but never
		// re-issues async actions (which would break the devtools functionality).
		// This leaves our app in an unusable state after RESET: initial state w/o any
		// way of issuing the 'init' action. The effect is the cohort list never
		// loads. Here we intercept the devtools actions & re-issue 'init' on
		// RESET.
		if (ac.type === 'RESET') {
			setTimeout(() => uiBus.next(['init', location.pathname, urlParams()]), 0);
		}

		inEffectsReducer = false;
		return nextState;
	};

	var devStateObs = Rx.Observable.merge(serverCh, uiCh, historyObs)
					.map(ac => ({type: 'PERFORM_ACTION', action: ac}))
					.merge(devCh)
					.scan(effectsReducer, devInitialState) // XXX side effects!
					.share();

	// XXX double check that this expression is doing what we want: don't draw faster
	// than rAF.

	// pass the selector into Page, so we catch errors while rendering & can display an error message.
	devStateObs.debounceTime(0, Rx.Scheduler.animationFrame)
		.subscribe(devState => {
			return ReactDOM.render(

					<Page callback={updater} selector={selector}
							state={unwrapDevState(devState)} />
					<DevTools dispatch={devBus.next.bind(devBus)} {...devState} />

,
				dom.main);
		}, err => console.log('err', err));

	if (persist) {
		// Save state in sessionStorage on page unload.
		devStateObs.sample(Rx.Observable.fromEvent(window, 'beforeunload'))
			.map(state => sessionStorage.saveDevState ? state :
					effectsReducer(state, {type: 'COMMIT'}))
			.subscribe(state => sessionStorage.debugSession = stringify(state));
	}

	// This causes us to always load cohorts on page load. This is important after
	// setting hubs, for example.
	uiBus.next(['init', location.pathname, urlParams()]);
	return dom;
};
<|endoftext|>


<commit_before>var _ = require("underscore");

Parse.Cloud.define("searchAll", function(request, response) {
	var Scope = {
		All: 0,
		Users: 1,
		Posts: 2,
		Albums: 3,
		Groups: 4
	};
	var filter = request.params.filter;
	var probe = request.params.probe;
	var user = request.user;
	var searchResults = [];
	var promises = [];
	function getQuery(className) {
		return new Parse.Query(Parse.Object.extend(className));
	}
	if (filter == Scope.All || filter == Scope.Posts) {
		// search posts and photos from roll
		function queryPostField(field) {
			var query = getQuery("Post");
			query.equalTo("createdBy", user).matches("title", "(?i)" + probe).matches("title", "(?i)" + probe);
			return query.find();
		}
		var tagQuery = getQuery("Tag");
		tagQuery.matches("name", "(?i)" + probe)
		//promises.push(tagQuery);		//TODO: This isn't right. Must find posts that contain these tags
		promises.push(queryPostField("title"));
		promises.push(queryPostField("notes"));
	}
	if (filter == Scope.All || filter == Scope.Albums || filter == Scope.Groups) {
		// search groups and albums
		function queryAlbumGroupField(type, field) {
			var query = getQuery("Album");
			query.equalTo("type", type);
			if (type == "album")
				query.equalTo("createdBy", user);
			query.matches(field,  "(?i)" + probe);
			return query.find()
		}
		if (filter != Scope.Groups) {
			promises.push(queryAlbumGroupField("album", "title"));
			promises.push(queryAlbumGroupField("album", "notes"));
		}
		if (filter != Scope.Albums) {
			promises.push(queryAlbumGroupField("group", "title"));
			promises.push(queryAlbumGroupField("group", "notes"));
		}
	}
	if (filter == Scope.All || filter == Scope.Users) {
		// search users
		function queryUserField(field) {
			var query = getQuery("_User");
			query.matches(field,  "(?i)" + probe);
			return query.find();
		}
		promises.push(queryUserField("username"));
		promises.push(queryUserField("email"));
		promises.push(queryUserField("name"));
	}
	Parse.Promise.when(promises).then(function(results) {
		var finalResults = [];
		try {
			_.each(results, function accum(r) { finalResults = finalResults.concat(r) });
			console.log(JSON.stringify(finalResults[0]));
			finalResults = _.sortBy(_.uniq(finalResults, function (a) { console.log(a["objectId"]); return a["objectId"] }), function(a) { return Date.parse(a["createdAt"]) }).reverse();
		}
		catch (e) {
			console.log(e);
		}
		response.success(finalResults);
	});
});
<commit_msg>Search in back end<commit_after>var _ = require("underscore");

Parse.Cloud.define("searchAll", function(request, response) {
	var Scope = {
		All: 0,
		Users: 1,
		Posts: 2,
		Albums: 3,
		Groups: 4
	};
	var filter = request.params.filter;
	var probe = request.params.probe;
	var user = request.user;
	var searchResults = [];
	var promises = [];
	function getQuery(className) {
		return new Parse.Query(Parse.Object.extend(className));
	}
	if (filter == Scope.All || filter == Scope.Posts) {
		// search posts and photos from roll
		function queryPostField(field) {
			var query = getQuery("Post");
			query.equalTo("createdBy", user).matches("title", "(?i)" + probe).matches("title", "(?i)" + probe);
			return query.find();
		}
		var tagQuery = getQuery("Tag");
		tagQuery.matches("name", "(?i)" + probe)
		//promises.push(tagQuery);		//TODO: This isn't right. Must find posts that contain these tags
		promises.push(queryPostField("title"));
		promises.push(queryPostField("notes"));
	}
	if (filter == Scope.All || filter == Scope.Albums || filter == Scope.Groups) {
		// search groups and albums
		function queryAlbumGroupField(type, field) {
			var query = getQuery("Album");
			query.equalTo("type", type);
			if (type == "album")
				query.equalTo("createdBy", user);
			query.matches(field,  "(?i)" + probe);
			return query.find()
		}
		if (filter != Scope.Groups) {
			promises.push(queryAlbumGroupField("album", "title"));
			promises.push(queryAlbumGroupField("album", "notes"));
		}
		if (filter != Scope.Albums) {
			promises.push(queryAlbumGroupField("group", "title"));
			promises.push(queryAlbumGroupField("group", "notes"));
		}
	}
	if (filter == Scope.All || filter == Scope.Users) {
		// search users
		function queryUserField(field) {
			var query = getQuery("_User");
			query.matches(field,  "(?i)" + probe);
			return query.find();
		}
		promises.push(queryUserField("username"));
		promises.push(queryUserField("email"));
		promises.push(queryUserField("name"));
	}
	Parse.Promise.when(promises).then(function(results) {
		var finalResults = [];
		try {
			_.each(results, function accum(r) { finalResults = finalResults.concat(r) });
			console.log(JSON.stringify(finalResults[0]));
			finalResults = _.sortBy(_.uniq(finalResults, function (a) { console.log(JSON.stringify(a)); return a["objectId"] }), function(a) { return Date.parse(a["createdAt"]) }).reverse();
		}
		catch (e) {
			console.log(e);
		}
		response.success(finalResults);
	});
});
<|endoftext|>


<commit_before>var contentScript = {};

contentScript.setAnchors = function (anchors) {
  this._anchors = anchors;
}.bind(contentScript);

contentScript.getAnchors = function (anchors) {
  return this._anchors;
}.bind(contentScript);

contentScript.handleMessage = function (message) {
  if (message == 'update') {
    this.getAnchors().updateAll();
  }
}.bind(contentScript);

module.exports = contentScript;
<commit_msg>Add contentScript listen function.<commit_after>var contentScript = {};

contentScript.setAnchors = function (anchors) {
  this._anchors = anchors;
}.bind(contentScript);

contentScript.getAnchors = function (anchors) {
  return this._anchors;
}.bind(contentScript);

contentScript.handleMessage = function (message) {
  if (message == 'update') {
    this.getAnchors().updateAll();
  }
}.bind(contentScript);

contentScript.listen = function () {
  chrome.extension.onMessage.addListener(this.handleMessage);
}.bind(contentScript);

module.exports = contentScript;
<|endoftext|>


<commit_before>/**
 * @version 1.0
 * @author Maik Kulbe <info@linux-web-development.de>
 * @copyright (c) 2010 Maik Kulbe
 */
D3content = {
    createDiv: function(title, text)
    {
        text = D3content.base64_decode(text);
        var hr = document.createElement('hr'),
            infoDiv,
            infoText,
            infoHeading,
            infoClipboardCopy,
            backUrl,
            resizeHandle,
            heading,
            closeElem,
            centerBottomResize;

        if(!document.getElementById('D3-inject')) {
            infoDiv           = document.createElement('div');
            infoDiv.id        = 'D3-inject';
            infoDiv.className = 'content';

            backUrl = chrome.extension.getURL("images/grip.png"),

            resizeHandle                        = document.createElement('div');
            resizeHandle.id                     = 'D3-inject_handle';
            resizeHandle.className              = 'handle vertical';
            resizeHandle.style.backgroundColor  = '#333';
            resizeHandle.style.backgroundImage  = 'url(\'' + backUrl + '\')';
            resizeHandle.style.backgroundRepeat = ' no-repeat;';

            heading           = document.createElement('h1');
            heading.id        = 'D3-inject-heading';
            heading.innerText = 'd3coder Output:';

            closeElem           = document.createElement('a');
            closeElem.id        = 'D3-inject-close';
            closeElem.innerText = 'CLOSE [X]';

            document.body.appendChild(resizeHandle);
            document.body.appendChild(infoDiv);
            document.getElementById('D3-inject').appendChild(closeElem);
            document.getElementById('D3-inject').appendChild(heading);
            document.getElementById('D3-inject').appendChild(hr);

            document.getElementById('D3-inject-close').addEventListener('click', function(){
                document.getElementById('D3-inject_handle').parentNode.removeChild();
                document.getElementById('D3-inject').parentNode.removeChild();
                document.getElementById('D3-inject-close').parentNode.removeChild();
            });

var startX, startY, startWidth, startHeight;

function initDrag(e) {
   startX = e.clientX;
   startY = e.clientY;
   startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
   startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
   document.documentElement.addEventListener('mousemove', doDrag, false);
   document.documentElement.addEventListener('mouseup', stopDrag, false);
}

function doDrag(e) {
   document.getElementById('D3-inject_handle').style.width = (startWidth + e.clientX - startX) + 'px';
   document.getElementById('D3-inject_handle').style.height = (startHeight + e.clientY - startY) + 'px';
}

function stopDrag(e) {
    document.documentElement.removeEventListener('mousemove', doDrag, false);
    document.documentElement.removeEventListener('mouseup', stopDrag, false);
}

            document.getElementById('D3-inject_handle').addEventListener('click', function init() {
                document.getElementById('D3-inject_handle').removeEventListener('click', init, false);
                document.getElementById('D3-inject_handle').className = document.getElementById('D3-inject_handle').className + ' resizable';
                var resizer = document.createElement('div');
                resizer.className = 'resizer';
                document.getElementById('D3-inject_handle').appendChild(resizer);
                resizer.addEventListener('mousedown', initDrag, false);
            }, false);
            /*centerBottomResize = new Resizable('D3-inject_handle',{
                invert: true,
                mode: 'vertical',
                cookie: 'centerBottomResize'
            });

            ResizableLimits.attach();*/
        } else {
            infoDiv = document.getElementById('D3-inject');
        }

        infoHeading           = document.createElement('h3');
        infoHeading.className = 'D3-inject-heading';
        infoHeading.innerText = title;

        infoText           = document.createElement('pre');
        infoText.className = 'D3-inject-text';
        infoText.innerText = text;

        infoClipboardCopy              = document.createElement('a');
        infoClipboardCopy.href         = 'javascript:void';
        infoClipboardCopy.innerText    = ' ';
        infoClipboardCopy.style.width  = 20;
        infoClipboardCopy.style.height = 20;
        infoClipboardCopy.style.backgroundImage = 'url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5Ojf/2wBDAQoKCg0MDRoPDxo3JR8lNzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzf/wAARCAAUABQDASIAAhEBAxEB/8QAGAABAAMBAAAAAAAAAAAAAAAAAAQFBgf/xAAmEAABAwQCAQMFAAAAAAAAAAABAgMEAAUGERIhYRMiMQcjY5Gz/8QAFQEBAQAAAAAAAAAAAAAAAAAABAP/xAAcEQACAQUBAAAAAAAAAAAAAAAAAQIDERIx0SL/2gAMAwEAAhEDEQA/AOnZVerjbp1rg2lmOt+cp3an0qUEpQkKOgkgk6J/XmqGdkWR2aG5NdQy+y2pBeS/FcbI2dew70OyOjvXfZq1ydfHNsS8ql/zFQ/qOtQw24FSSPez8j8go8m8Zu+uIvFK8FbfTcUpSkEDPZNjMa9ORpD0yfHejKV6TkZ7gU8hpWjo/OhVCnBIkz7Uy83x9kkcmnZnJKu99jj4pSi1EsxNN+TeNN+kgJ5rX5WdmlKUoMf/2Q==)';
        infoClipboardCopy.style.position = 'absolute';
        infoClipboardCopy.style.top      = 0;
        infoClipboardCopy.style.right    = 0;
        infoClipboardCopy.title          = 'Copy last conversion to clipboard';
        infoClipboardCopy.id             = 'D3-clipboard-button';

        hr = document.createElement('hr');

        infoDiv.appendChild(infoHeading);
        infoDiv.appendChild(infoClipboardCopy);
        infoDiv.appendChild(infoText);
        infoDiv.appendChild(hr);

        document.getElementById('D3-clipboard-button').addEventListener('click', function(){
            chrome.extension.sendRequest({command: "doCopy"}, function(response) {
                console.log(response);
            });

            /*
                var bg = chrome.extension.getBackgroundPage();
                var clipboard = bg.document.getElementById("clipboard");
                clipboard.style.display = "block";
                clipboard.value = text;
                clipboard.select();
                bg.document.execCommand("Copy");
                clipboard.style.display = "none";
            */
        });
    },

    replaceText: function(text)
    {
        var selection, range;

        text = D3content.base64_decode(text);
        if (window.getSelection) {
            selection = window.getSelection();
            if (selection.rangeCount) {
                range = selection.getRangeAt(0);
                range.deleteContents();
                range.insertNode(document.createTextNode(text));
            }
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            range.text = text;
        }
	},

    logConsole: function(text)
    {
	    console.log(D3content.base64_decode(text));
    },
	base64_decode: function (data) {
	    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

	    if (!data) {
	        return data;
	    }

	    data += '';

	    do {  // unpack four hexets into three octets using index points in b64
	        h1 = b64.indexOf(data.charAt(i++));
	        h2 = b64.indexOf(data.charAt(i++));
	        h3 = b64.indexOf(data.charAt(i++));
	        h4 = b64.indexOf(data.charAt(i++));

	        bits = h1<<18 | h2<<12 | h3<<6 | h4;

	        o1 = bits>>16 & 0xff;
	        o2 = bits>>8 & 0xff;
	        o3 = bits & 0xff;

	        if (h3 == 64) {
	            tmp_arr[ac++] = String.fromCharCode(o1);
	        } else if (h4 == 64) {
	            tmp_arr[ac++] = String.fromCharCode(o1, o2);
	        } else {
	            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
	        }
	    } while (i < data.length);

	    dec = tmp_arr.join('');
	    dec = this.utf8_decode(dec);

	    return dec;
	},
	utf8_decode: function ( str_data ) {
	   var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

	    str_data += '';

	    while ( i < str_data.length ) {
	        c1 = str_data.charCodeAt(i);
	        if (c1 < 128) {
	            tmp_arr[ac++] = String.fromCharCode(c1);
	            i++;
	        } else if ((c1 > 191) && (c1 < 224)) {
	            c2 = str_data.charCodeAt(i+1);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
	            i += 2;
	        } else {
	            c2 = str_data.charCodeAt(i+1);
	            c3 = str_data.charCodeAt(i+2);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	            i += 3;
	        }
	    }

	    return tmp_arr.join('');
	}
};
<commit_msg>Resizer needs update to work with pure JS<commit_after>/**
 * @version 1.0
 * @author Maik Kulbe <info@linux-web-development.de>
 * @copyright (c) 2010 Maik Kulbe
 */
D3content = {
    createDiv: function(title, text)
    {
        text = D3content.base64_decode(text);
        var hr = document.createElement('hr'),
            infoDiv,
            infoText,
            infoHeading,
            infoClipboardCopy,
            backUrl,
            resizeHandle,
            heading,
            closeElem,
            centerBottomResize;

        if(!document.getElementById('D3-inject')) {
            infoDiv           = document.createElement('div');
            infoDiv.id        = 'D3-inject';
            infoDiv.className = 'content';

            backUrl = chrome.extension.getURL("images/grip.png"),

            resizeHandle                        = document.createElement('div');
            resizeHandle.id                     = 'D3-inject_handle';
            resizeHandle.className              = 'handle vertical';
            resizeHandle.style.backgroundColor  = '#333';
            resizeHandle.style.backgroundImage  = 'url(\'' + backUrl + '\')';
            resizeHandle.style.backgroundRepeat = ' no-repeat;';

            heading           = document.createElement('h1');
            heading.id        = 'D3-inject-heading';
            heading.innerText = 'd3coder Output:';

            closeElem           = document.createElement('a');
            closeElem.id        = 'D3-inject-close';
            closeElem.innerText = 'CLOSE [X]';

            document.body.appendChild(resizeHandle);
            document.body.appendChild(infoDiv);
            document.getElementById('D3-inject').appendChild(closeElem);
            document.getElementById('D3-inject').appendChild(heading);
            document.getElementById('D3-inject').appendChild(hr);

            document.getElementById('D3-inject-close').addEventListener('click', function(){
                document.getElementById('D3-inject').parentNode.removeChild();
                document.getElementById('D3-inject-close').parentNode.removeChild();
            });

            document.getElementById('D3-inject_handle').addEventListener('click', function init() {
                document.getElementById('D3-inject_handle').removeEventListener('click', init, false);
                document.getElementById('D3-inject_handle').className = document.getElementById('D3-inject_handle').className + ' resizable';
                var resizer = document.createElement('div');
                resizer.className = 'resizer';
                document.getElementById('D3-inject_handle').appendChild(resizer);
                resizer.addEventListener('mousedown', initDrag, false);
            }, false);

var startX, startY, startWidth, startHeight;

            function initDrag(e) {
               startX = e.clientX;
               startY = e.clientY;
               startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
               startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
               document.documentElement.addEventListener('mousemove', doDrag, false);
               document.documentElement.addEventListener('mouseup', stopDrag, false);
            }

            function doDrag(e) {
               document.getElementById('D3-inject_handle').style.width = (startWidth + e.clientX - startX) + 'px';
               document.getElementById('D3-inject_handle').style.height = (startHeight + e.clientY - startY) + 'px';
            }

            function stopDrag(e) {
                document.documentElement.removeEventListener('mousemove', doDrag, false);
                document.documentElement.removeEventListener('mouseup', stopDrag, false);
            }
        } else {
            infoDiv = document.getElementById('D3-inject');
        }

        infoHeading           = document.createElement('h3');
        infoHeading.className = 'D3-inject-heading';
        infoHeading.innerText = title;

        infoText           = document.createElement('pre');
        infoText.className = 'D3-inject-text';
        infoText.innerText = text;

        infoClipboardCopy              = document.createElement('a');
        infoClipboardCopy.href         = 'javascript:void';
        infoClipboardCopy.innerText    = ' ';
        infoClipboardCopy.style.width  = 20;
        infoClipboardCopy.style.height = 20;
        infoClipboardCopy.style.backgroundImage = 'url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5Ojf/2wBDAQoKCg0MDRoPDxo3JR8lNzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzf/wAARCAAUABQDASIAAhEBAxEB/8QAGAABAAMBAAAAAAAAAAAAAAAAAAQFBgf/xAAmEAABAwQCAQMFAAAAAAAAAAABAgMEAAUGERIhYRMiMQcjY5Gz/8QAFQEBAQAAAAAAAAAAAAAAAAAABAP/xAAcEQACAQUBAAAAAAAAAAAAAAAAAQIDERIx0SL/2gAMAwEAAhEDEQA/AOnZVerjbp1rg2lmOt+cp3an0qUEpQkKOgkgk6J/XmqGdkWR2aG5NdQy+y2pBeS/FcbI2dew70OyOjvXfZq1ydfHNsS8ql/zFQ/qOtQw24FSSPez8j8go8m8Zu+uIvFK8FbfTcUpSkEDPZNjMa9ORpD0yfHejKV6TkZ7gU8hpWjo/OhVCnBIkz7Uy83x9kkcmnZnJKu99jj4pSi1EsxNN+TeNN+kgJ5rX5WdmlKUoMf/2Q==)';
        infoClipboardCopy.style.position = 'absolute';
        infoClipboardCopy.style.top      = 0;
        infoClipboardCopy.style.right    = 0;
        infoClipboardCopy.title          = 'Copy last conversion to clipboard';
        infoClipboardCopy.id             = 'D3-clipboard-button';

        hr = document.createElement('hr');

        infoDiv.appendChild(infoHeading);
        infoDiv.appendChild(infoClipboardCopy);
        infoDiv.appendChild(infoText);
        infoDiv.appendChild(hr);

        document.getElementById('D3-clipboard-button').addEventListener('click', function(){
            chrome.extension.sendRequest({command: "doCopy"}, function(response) {
                console.log(response);
            });

            /*
                var bg = chrome.extension.getBackgroundPage();
                var clipboard = bg.document.getElementById("clipboard");
                clipboard.style.display = "block";
                clipboard.value = text;
                clipboard.select();
                bg.document.execCommand("Copy");
                clipboard.style.display = "none";
            */
        });
    },

    replaceText: function(text)
    {
        var selection, range;

        text = D3content.base64_decode(text);
        if (window.getSelection) {
            selection = window.getSelection();
            if (selection.rangeCount) {
                range = selection.getRangeAt(0);
                range.deleteContents();
                range.insertNode(document.createTextNode(text));
            }
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            range.text = text;
        }
	},

    logConsole: function(text)
    {
	    console.log(D3content.base64_decode(text));
    },
	base64_decode: function (data) {
	    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];

	    if (!data) {
	        return data;
	    }

	    data += '';

	    do {  // unpack four hexets into three octets using index points in b64
	        h1 = b64.indexOf(data.charAt(i++));
	        h2 = b64.indexOf(data.charAt(i++));
	        h3 = b64.indexOf(data.charAt(i++));
	        h4 = b64.indexOf(data.charAt(i++));

	        bits = h1<<18 | h2<<12 | h3<<6 | h4;

	        o1 = bits>>16 & 0xff;
	        o2 = bits>>8 & 0xff;
	        o3 = bits & 0xff;

	        if (h3 == 64) {
	            tmp_arr[ac++] = String.fromCharCode(o1);
	        } else if (h4 == 64) {
	            tmp_arr[ac++] = String.fromCharCode(o1, o2);
	        } else {
	            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
	        }
	    } while (i < data.length);

	    dec = tmp_arr.join('');
	    dec = this.utf8_decode(dec);

	    return dec;
	},
	utf8_decode: function ( str_data ) {
	   var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

	    str_data += '';

	    while ( i < str_data.length ) {
	        c1 = str_data.charCodeAt(i);
	        if (c1 < 128) {
	            tmp_arr[ac++] = String.fromCharCode(c1);
	            i++;
	        } else if ((c1 > 191) && (c1 < 224)) {
	            c2 = str_data.charCodeAt(i+1);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
	            i += 2;
	        } else {
	            c2 = str_data.charCodeAt(i+1);
	            c3 = str_data.charCodeAt(i+2);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	            i += 3;
	        }
	    }

	    return tmp_arr.join('');
	}
};
<|endoftext|>


<commit_before>'use strict';

var DEBUG = false;
var _logName = 'arXiv Titler: ';

function log() {
    if (DEBUG) {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(_logName);
        console.log.apply(console, args);
    }
}

function warn() {
    if (DEBUG) {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(_logName);
        console.log.apply(console, args);
    }
}

function getPaperTitle(feed) {
    var paperTitle = null;
    Array.prototype.slice.call(feed.children).forEach(function (child) {
        if (child.nodeName.toLowerCase() === 'entry') {
            var entry = child;
            Array.prototype.slice.call(entry.children).forEach(function (field) {
                if (field.nodeName.toLowerCase() === 'title') {
                    var title = field;
                    paperTitle = title.childNodes[0].wholeText;
                }
            });
        }
    });

    return (paperTitle === null) ? "Unknown title." : paperTitle;
}

function addTitleToHead(paperTitle) {
    var title = document.createElement('title');
    title.appendChild(document.createTextNode(paperTitle));

    var head = null;
    if (document.head) {
        warn('Document already had <head> element.');
        Array.prototype.slice.call(document.head.children).forEach(function (child) {
            if (child.nodeName.toLowerCase() === 'title') {
                document.head.removeChild(child);
            }
        });
        document.head.appendChild(title);
    } else {
        var head = document.createElement('head');
        head.appendChild(title);
        var html = document.body.parentElement;
        html.insertBefore(head, document.body);
    }
}

var paperId = null;

try {
    var pathComponents = window.location.pathname.split('/');
    var pdfName = pathComponents[pathComponents.length - 1];
    paperId = /([^v]*)(v[0-9]*)?\.pdf/.exec(pdfName)[1];
} catch(e) {
    warn("Could not get submission ID. Error: ", e);
}

chrome.runtime.onMessage.addListener(function () {
    log('Got message!');
});

if (paperId !== null) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var paperTitle = getPaperTitle(xhr.responseXML.childNodes[0]);
                    addTitleToHead(paperTitle);
                    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
                        log('Running on-message.');
                        addTitleToHead(paperTitle);
                    });
                } catch (e) {
                    warn("Unable to determine title of paper. Error: ", e);
                }
            } else {
                warn("Cannot handle response with status ", xhr.status);
            }
        }
    }
    xhr.onerror = function () {
        warn("Unable to fetch paper data from arXiv API.");
    }
    xhr.open("GET", "http://export.arxiv.org/api/query?id_list=" + paperId);
    xhr.responseType = "document";
    xhr.send();
}
<commit_msg>Keep trying to change the title for first 15 minutes.<commit_after>(function () {
'use strict';

var DEBUG = false;
var _logName = 'arXiv Titler: ';

function log() {
    if (DEBUG) {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(_logName);
        console.log.apply(console, args);
    }
}

function warn() {
    if (DEBUG) {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(_logName);
        console.log.apply(console, args);
    }
}

function getPaperTitle(feed) {
    var paperTitle = null;
    Array.prototype.slice.call(feed.children).forEach(function (child) {
        if (child.nodeName.toLowerCase() === 'entry') {
            var entry = child;
            Array.prototype.slice.call(entry.children).forEach(function (field) {
                if (field.nodeName.toLowerCase() === 'title') {
                    var title = field;
                    paperTitle = title.childNodes[0].wholeText;
                }
            });
        }
    });

    return (paperTitle === null) ? "Unknown title." : paperTitle;
}

function addTitleToHead(paperTitle) {
    var title = document.createElement('title');
    title.appendChild(document.createTextNode(paperTitle));

    var head = null;
    if (document.head) {
        warn('Document already had <head> element.');
        Array.prototype.slice.call(document.head.children).forEach(function (child) {
            if (child.nodeName.toLowerCase() === 'title') {
                document.head.removeChild(child);
            }
        });
        document.head.appendChild(title);
    } else {
        head = document.createElement('head');
        head.appendChild(title);
        var html = document.body.parentElement;
        html.insertBefore(head, document.body);
    }
}

var paperId = null;

try {
    var pathComponents = window.location.pathname.split('/');
    var pdfName = pathComponents[pathComponents.length - 1];
    paperId = /([^v]*)(v[0-9]*)?\.pdf/.exec(pdfName)[1];
} catch(e) {
    warn("Could not get submission ID. Error: ", e);
}

chrome.runtime.onMessage.addListener(function () {
    log('Got message!');
});

var stretchFactor = 1.5,
    initialTimeout = 100;

/* With the settings, stretchFactor = 1.5 and initialTimeout = 100, the plugin
 * will be run ~ 25 times.
 */
function exponentialBackoff(paperTitle, timeout) {
    setTimeout(function () {
        addTitleToHead(paperTitle);
        // If the paper hasn't loaded after 15 minutes, just give up.
        if (timeout < 900000) {
            exponentialBackoff(paperTitle, stretchFactor * timeout);
        }
    }, timeout);
}

if (paperId !== null) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var paperTitle = getPaperTitle(xhr.responseXML.childNodes[0]);
                    exponentialBackoff(paperTitle, 100);
                    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
                        log('Running on-message.');
                        addTitleToHead(paperTitle);
                    });
                } catch (e) {
                    warn("Unable to determine title of paper. Error: ", e);
                }
            } else {
                warn("Cannot handle response with status ", xhr.status);
            }
        }
    };

    xhr.onerror = function () {
        warn("Unable to fetch paper data from arXiv API.");
    };

    xhr.open("GET", "http://export.arxiv.org/api/query?id_list=" + paperId);
    xhr.responseType = "document";
    xhr.send();
}})();
<|endoftext|>


<commit_before>/*
	Author: Danilo de Moura Chenchi

	Require materialize css
*/

/* Each image have a respective title. So it's a 1-to-1 relation of the two arrays */
var images_array = [
					"You gonna love it HD.png",
					"Quote cite.png",
					"hello.png",
					"Lisp lists of lists.png",
					];
var titles_array = [
					"You gonna love IT",
					"Quote someone today",
					"Hello World!",
					"Lisp lists of lists of...",
					];

/* Add all the images registered in the array to the gallery */
function initGallery() {
	var i = 0;
	for (i = 0; i < images_array.length; i++) {
		addThumbnail( images_array[i], titles_array[i]);
	}

	// Reset materialboxed
	$('.materialboxed').materialbox();
}

/*
Thumbnail

			title

*/
function addThumbnail(image_name, title) {
// Initialize card divs
	var column = $("

");
	var card_small = $("

");
	var card_image = $("

");
	var card_content = $("

");

// Add classes to style the card
	column.addClass("col s12 m6 l4");
	card_small.addClass("card");
	card_image.addClass("card-image");
	card_content.addClass("card-content");

// Add image
	var thumb_image = $("");
	thumb_image.addClass("materialboxed");
	thumb_image.attr("data-caption", title);
	thumb_image.attr("src", "imgs/" + image_name);

// Add title
	var thumb_title = $("");
	thumb_title.addClass("card-title");
	thumb_title.text(title);

// Structure the card html tree bottom-up
	card_image.append(thumb_image);
	card_image.append(thumb_title);
	card_small.append(card_image);
	column.append(card_small);

	$("#thumb-galley").append(column);
}
<commit_msg>Added Smooth animation<commit_after>/*
	Author: Danilo de Moura Chenchi

	Require materialize css
*/

/* Each image have a respective title. So it's a 1-to-1 relation of the two arrays */
var images_array = [
					"You gonna love it HD.png",
					"Quote cite.png",
					"hello.png",
					"Lisp lists of lists.png",
					];
var titles_array = [
					"You gonna love IT",
					"Quote someone today",
					"Hello World!",
					"Lisp lists of lists of...",
					];

/* Add all the images registered in the array to the gallery */
function initGallery() {
	var i = 0;
	for (i = 0; i < images_array.length; i++) {
		addThumbnail( images_array[i], titles_array[i]);
	}

	// Reset materialboxed
	$('.materialboxed').materialbox();
}

/*
Thumbnail

			title

*/
function addThumbnail(image_name, title) {
// Initialize card divs
	var column = $("

");
	var card_small = $("

");
	var card_image = $("

");
	var card_content = $("

");

// Add classes to style the card
	column.addClass("col s12 m6 l4");
	card_small.addClass("card");
	card_image.addClass("card-image");
	card_content.addClass("card-content");

// Add image
	var thumb_image = $("");
	thumb_image.addClass("materialboxed");
	thumb_image.attr("data-caption", title);
	thumb_image.attr("src", "imgs/" + image_name);

// Add title
	var thumb_title = $("");
	thumb_title.addClass("card-title");
	thumb_title.text(title);

// Structure the card html tree bottom-up
	card_image.append(thumb_image);
	card_image.append(thumb_title);
	card_small.append(card_image);
	column.append(card_small);

	$("#thumb-galley").append(column);
}

$('a[href^="#"]').on('click', function(event) {
	var target = $( $(this).attr('href') );

	if( target.length ) {
		event.preventDefault();
		$('html, body').animate({
			scrollTop: target.offset().top
		}, {duration: 400, queue: false, easing: 'easeOutCubic'});
	}
	console.log($('body').scrollTop());
});
<|endoftext|>


<commit_before>var events = require('./github/users/taylorfoster90/events.json');
var assert = require('assert')
var _ = require('lodash');

//variables for my 'answers'
var pushEvents = events.filter(function(item){
	return item.type == 'PushEvent'
});
var otherEvents = events.filter(function(item){
	return item.type != 'PushEvent'
});
var createEvent = events.filter(function(item){
	return item.type == 'CreateEvent'
});
var issueEvent = events.filter(function(item){
	return item.type == 'IssuesEvent'
});
var deleteEvent = events.filter(function(item){
	return item.type == 'DeleteEvent'
});
var prEvent = events.filter(function(item){
	return item.type == 'PullRequestEvent'
});
function getDate(a){
	return _.map(a, 'created_at')
}
function getDiff(a,b){
	return _.first(a).substring(0.10).localeCompare(_.last(b).substring(0.10)) + 1;
}
function avg(item) {
	var diff = getDiff(getDate(events),getDate(events));
	return item.length / diff

}

function answer(){
	return {
		total: events.length,
		PushEvent: {
			total: pushEvents.length,
			perDay: avg(pushEvents)
		},
		CreateEvent: {
			total: createEvent.length,
			perDay: avg(createEvent)
		},
		IssueEvent: {
			total: issueEvent.length,
			perDay: avg(issueEvent)
		},
		DeleteEvent: {
			total: deleteEvent.length,
			perDay: avg(deleteEvent)
		},
		PullRequestEvent: {
			total: prEvent.length,
			perDay: avg(prEvent)
		}
}
}
console.log(answer());

<commit_msg>finishing up gymnastics<commit_after>var events = require('./github/users/taylorfoster90/events.json');
var assert = require('assert')
var _ = require('lodash');

//variables for my 'answers'
var pushEvents = events.filter(function(item){
	return item.type == 'PushEvent'
});
var otherEvents = events.filter(function(item){
	return item.type != 'PushEvent'
});
var createEvent = events.filter(function(item){
	return item.type == 'CreateEvent'
});
var issueEvent = events.filter(function(item){
	return item.type == 'IssuesEvent'
});
var deleteEvent = events.filter(function(item){
	return item.type == 'DeleteEvent'
});
var prEvent = events.filter(function(item){
	return item.type == 'PullRequestEvent'
});
function getDate(a){
	return _.map(a, 'created_at')
}
function getDiff(a,b){
	return _.first(a).substring(0.10).localeCompare(_.last(b).substring(0.10)) + 1;
}
function avg(item) {
	var diff = getDiff(getDate(events),getDate(events));
	return item.length / diff

}

function answer(){
	return {
		total: events.length,
		PushEvent: {
			total: pushEvents.length,
			perDay: avg(pushEvents)
		},
		CreateEvent: {
			total: createEvent.length,
			perDay: avg(createEvent)
		},
		IssueEvent: {
			total: issueEvent.length,
			perDay: avg(issueEvent)
		},
		DeleteEvent: {
			total: deleteEvent.length,
			perDay: avg(deleteEvent)
		},
		PullRequestEvent: {
			total: prEvent.length,
			perDay: avg(prEvent)
		}
}
}

<|endoftext|>


<commit_before>
(function($) {

    var default_options = {
        template          : "<editor/><panel><button/></panel>",

        className         : "emojionearea",
        editorClassName   : "emojionearea-editor",
        panelClassName    : "emojionearea-panel",
        buttonClassName   : "emojionearea-button",

        dir               : "ltr",
        spellcheck        : true,
        autocomplete      : "off",
        autocorrect       : "off",
        autocapitalize    : "off"
    };

    var EmojioneArea = function(element, options) {
        this.element = element;
        this.options = $.extend({}, default_options, options);
        this.events = {};

        this.init();
    };

    EmojioneArea.prototype.on = function(events, handler) {
        if (!!events && !!handler && Array.prototype.toString.call(handler) == '[object Function]') {
            $.each(events.split(' '), $.proxy(function(i, event) {
                if (!this.events[event]) {
                    this.events[event] = [];
                }
                this.events[event].push(handler);
            }, this));
        }
        return this;
    };

    EmojioneArea.prototype.off = function(events, handler) {
        if (!!events) {
            if (!!handler) {
                if (Array.prototype.toString.call(handler) == '[object Function]') {
                    $.each(events.split(' '), $.proxy(function(i, event) {
                        if (!!this.events[event] && !!this.events[event].length) {
                            $.each(this.events[event], $.proxy(function(j, attachedHandler) {
                                if (attachedHandler === handler) {
                                    this.events[event] = this.events[event].splice(j, 1);
                                }
                            }, this));
                        }
                    }, this));
                }
            } else {
                $.each(events.split(' '), $.proxy(function(i, event) {
                    this.events[event] = [];
                }, this));
            }
        }
        return this;
    };

    EmojioneArea.prototype.trigger = function() {
        console.log(arguments);
        var result = true;
        if (!!arguments.length) {
            var args = Array.prototype.slice.call(arguments);
            args = args.slice(1);
            $.each(arguments[0].split(' '), $.proxy(function(i, event) {
                if (!!this.events[event] && !!this.events[event].length) {
                    $.each(this.events[event], function (i, f) {
                        result = f.apply(f, args);
                        return result !== false;
                    });
                }
                return result !== false;
            }, this));
        }
        return result !== false;
    };

    EmojioneArea.prototype.attach = function(element, elementEvents, events) {
        element.on(elementEvents, $.proxy(function() {
            console.log([elementEvents, events]);
            return this.trigger((!!events ? events : elementEvents), arguments)
        }, this));

        return this;
    };

    EmojioneArea.prototype.setText = function(content) {
        content = content
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(/(?:\r\n|\r|\n)/g, '\n')
            .replace(/(\n+)/g, '
$1
')
            .replace(/\n/g, '
')
            .replace(/
<\/div>/g, '
');

        var emojioneImageType = emojione.imageType;
        emojione.imageType = 'png';
        content = emojione.unicodeToImage(content);
        emojione.imageType = emojioneImageType;

        this.editor.html('
' + content + '
');
        this.content = this.editor.html();
        this.trigger('emojioneArea.change change', this.content);
    }

    EmojioneArea.prototype.getText = function() {
        return this.editor.html()
            .replace(/]+)"[^>]+>/ig, '$1')
            .replace(/\n/g, '')
            .replace(/
]+)?>/ig, '\n')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/div>)+/ig, '
')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/p>)+/ig, '
')
            .replace(/\n
<\/div>/ig, '\n')
            .replace(/
<\/div>\n/ig, '\n')
            .replace(/(?:
)+<\/div>/ig, '\n')
            .replace(/([^\n])<\/div>
/ig, '$1\n')
            .replace(/(?:<\/div>)+/ig, '')
            .replace(/([^\n])
/ig, '$1\n')
            .replace(/\n
/ig, '\n')
            .replace(/
\n/ig, '\n\n')
            .replace(/<(?:[^>]+)?>/ig, '');
    }

    EmojioneArea.prototype.init = function() {
        this.type = this.element.is("INPUT") ? 'val' : 'text';

        var html = this.options.template
            .replace("<editor/>", '

')
            .replace("<button/>", '

')
            .replace("<panel>", '
').replace("</panel>", '
');

        $.each(["editorClassName", "buttonClassName", "panelClassName"], $.proxy(function(i, name) {
            html = html.replace("{{" + name + "}}", this.options[name]);
        }, this));

        html = $('
' + html + '
').addClass(this.options.className).attr("role", "application");

        this.editor = html.find("." + this.options.editorClassName).attr("contenteditable", "true");
        this.button = html.find("." + this.options.buttonClassName);
        this.panel  = html.find("." + this.options.panelClassName);

        $.each(["dir", "spellcheck", "autocomplete", "autocorrect", "autocapitalize"], $.proxy(function(i, name) {
            this.editor.attr(name, this.options[name]);
        }, this));

        this.panel.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.button.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.attach(this.editor, "mousedown")
            .attach(this.editor, "mouseup")
            .attach(this.editor, "focus", "emojioneArea.focus focus")
            .attach(this.editor, "blur", "emojioneArea.blur blur")
            .attach(this.editor, "click")
            .attach(this.editor, "keyup")
            .attach(this.editor, "keydown");

        this.on("emojioneArea.change", $.proxy(function() {
            this.element[this.type](this.getText());
        }, this)).on("emojioneArea.focus", function() {
            html.addClass("focused");
        }).on("emojioneArea.blur", $.proxy(function() {
            html.removeClass("focused");
            var content = this.editor.html();
            if (this.content !== content) {
                this.content = content;
                this.trigger('emojioneArea.change change', this.content);
            }
        }, this));

        html.insertAfter(this.element);
        this.element.hide();
        this.setText(this.element[this.type]());
    };

    $.fn.emojioneArea = function(options) {
        return this.each(function(){
            if (!!this.emojioneArea) return this.emojioneArea;
            return this.emojioneArea = new EmojioneArea($(this), options);
        });
    };

}) (jQuery);

// smiles
// fa-smile-o, fa-clock-o, (fa-flag fa-flag-checkered fa-flag-o), fa-leaf, fa-track, fa-cutlery,  fa-trophy,  fa-gift, fa-heart,  fa-ellipsis-h<commit_msg>Update emojione-area.js<commit_after>
(function($) {

    var default_options = {
        template          : "<editor/><panel><button/></panel>",

        className         : "emojionearea",
        editorClassName   : "emojionearea-editor",
        panelClassName    : "emojionearea-panel",
        buttonClassName   : "emojionearea-button",

        dir               : "ltr",
        spellcheck        : true,
        autocomplete      : "off",
        autocorrect       : "off",
        autocapitalize    : "off"
    };

    var EmojioneArea = function(element, options) {
        this.element = element;
        this.options = $.extend({}, default_options, options);
        this.events = {};

        this.init();
    };

    EmojioneArea.prototype.on = function(events, handler) {
        if (!!events && !!handler && Array.prototype.toString.call(handler) == '[object Function]') {
            $.each(events.split(' '), $.proxy(function(i, event) {
                if (!this.events[event]) {
                    this.events[event] = [];
                }
                this.events[event].push(handler);
            }, this));
        }
        return this;
    };

    EmojioneArea.prototype.off = function(events, handler) {
        if (!!events) {
            if (!!handler) {
                if (Array.prototype.toString.call(handler) == '[object Function]') {
                    $.each(events.split(' '), $.proxy(function(i, event) {
                        if (!!this.events[event] && !!this.events[event].length) {
                            $.each(this.events[event], $.proxy(function(j, attachedHandler) {
                                if (attachedHandler === handler) {
                                    this.events[event] = this.events[event].splice(j, 1);
                                }
                            }, this));
                        }
                    }, this));
                }
            } else {
                $.each(events.split(' '), $.proxy(function(i, event) {
                    this.events[event] = [];
                }, this));
            }
        }
        return this;
    };

    EmojioneArea.prototype.trigger = function() {
        var result = true;
        if (!!arguments.length) {
            var args = Array.prototype.slice.call(arguments);
            args = args.slice(1);
            $.each(arguments[0].split(' '), $.proxy(function(i, event) {
                if (!!this.events[event] && !!this.events[event].length) {
                    $.each(this.events[event], function (i, f) {
                        result = f.apply(f, args);
                        return result !== false;
                    });
                }
                return result !== false;
            }, this));
        }
        return result !== false;
    };

    EmojioneArea.prototype.attach = function(element, elementEvents, events) {
        element.on(elementEvents, $.proxy(function() {
            return this.trigger((!!events ? events : elementEvents), arguments)
        }, this));

        return this;
    };

    EmojioneArea.prototype.setText = function(content) {
        content = content
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(/(?:\r\n|\r|\n)/g, '\n')
            .replace(/(\n+)/g, '
$1
')
            .replace(/\n/g, '
')
            .replace(/
<\/div>/g, '
');

        var emojioneImageType = emojione.imageType;
        emojione.imageType = 'png';
        content = emojione.unicodeToImage(content);
        emojione.imageType = emojioneImageType;

        this.editor.html('
' + content + '
');
        this.content = this.editor.html();
        this.trigger('emojioneArea.change change', this.content);
    }

    EmojioneArea.prototype.getText = function() {
        return this.editor.html()
            .replace(/]+)"[^>]+>/ig, '$1')
            .replace(/\n/g, '')
            .replace(/
]+)?>/ig, '\n')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/div>)+/ig, '
')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/p>)+/ig, '
')
            .replace(/\n
<\/div>/ig, '\n')
            .replace(/
<\/div>\n/ig, '\n')
            .replace(/(?:
)+<\/div>/ig, '\n')
            .replace(/([^\n])<\/div>
/ig, '$1\n')
            .replace(/(?:<\/div>)+/ig, '')
            .replace(/([^\n])
/ig, '$1\n')
            .replace(/\n
/ig, '\n')
            .replace(/
\n/ig, '\n\n')
            .replace(/<(?:[^>]+)?>/ig, '');
    }

    EmojioneArea.prototype.init = function() {
        this.type = this.element.is("INPUT") ? 'val' : 'text';

        var html = this.options.template
            .replace("<editor/>", '

')
            .replace("<button/>", '

')
            .replace("<panel>", '
').replace("</panel>", '
');

        $.each(["editorClassName", "buttonClassName", "panelClassName"], $.proxy(function(i, name) {
            html = html.replace("{{" + name + "}}", this.options[name]);
        }, this));

        html = $('
' + html + '
').addClass(this.options.className).attr("role", "application");

        this.editor = html.find("." + this.options.editorClassName).attr("contenteditable", "true");
        this.button = html.find("." + this.options.buttonClassName);
        this.panel  = html.find("." + this.options.panelClassName);

        $.each(["dir", "spellcheck", "autocomplete", "autocorrect", "autocapitalize"], $.proxy(function(i, name) {
            this.editor.attr(name, this.options[name]);
        }, this));

        this.panel.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.button.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.attach(this.editor, "mousedown")
            .attach(this.editor, "mouseup")
            .attach(this.editor, "focus", "emojioneArea.focus focus")
            .attach(this.editor, "blur", "emojioneArea.blur blur")
            .attach(this.editor, "click")
            .attach(this.editor, "keyup")
            .attach(this.editor, "keydown");

        this.on("emojioneArea.change", $.proxy(function() {
            this.element[this.type](this.getText());
        }, this)).on("emojioneArea.focus", function() {
            html.addClass("focused");
        }).on("emojioneArea.blur", $.proxy(function() {
            html.removeClass("focused");
            var content = this.editor.html();
            if (this.content !== content) {
                this.content = content;
                this.trigger('emojioneArea.change change', this.content);
            }
        }, this));

        html.insertAfter(this.element);
        this.element.hide();
        this.setText(this.element[this.type]());
    };

    $.fn.emojioneArea = function(options) {
        return this.each(function(){
            if (!!this.emojioneArea) return this.emojioneArea;
            return this.emojioneArea = new EmojioneArea($(this), options);
        });
    };

}) (jQuery);

// smiles
// fa-smile-o, fa-clock-o, (fa-flag fa-flag-checkered fa-flag-o), fa-leaf, fa-track, fa-cutlery,  fa-trophy,  fa-gift, fa-heart,  fa-ellipsis-h<|endoftext|>


<commit_before>import { onMounted, onBeforeUnmount } from 'vue';
import { f7ready, f7 } from './f7';
import { extend } from './utils';

export const useSmartSelect = (props, setInstance, getEl) => {
  let f7SmartSelect;
  onMounted(() => {
    f7ready(() => {
      if (props.smartSelect) {
        const ssParams = extend({ el: getEl() }, props.smartSelectParams || {});
        f7SmartSelect = f7.smartSelect.create(ssParams);
        setInstance(f7SmartSelect);
      }
    });
  });
  onBeforeUnmount(() => {
    if (f7SmartSelect.value && f7SmartSelect.value.destroy) {
      f7SmartSelect.destroy();
    }
    f7SmartSelect = null;
    setInstance(f7SmartSelect);
  });
};
<commit_msg>v6: Vue - tweak smart select helper<commit_after>import { onMounted, onBeforeUnmount } from 'vue';
import { f7ready, f7 } from './f7';
import { extend } from './utils';

export const useSmartSelect = (props, setInstance, getEl) => {
  let f7SmartSelect;
  onMounted(() => {
    f7ready(() => {
      if (props.smartSelect) {
        const ssParams = extend({ el: getEl() }, props.smartSelectParams || {});
        f7SmartSelect = f7.smartSelect.create(ssParams);
        setInstance(f7SmartSelect);
      }
    });
  });
  onBeforeUnmount(() => {
    if (f7SmartSelect && f7SmartSelect.destroy) {
      f7SmartSelect.destroy();
    }
    f7SmartSelect = null;
    setInstance(f7SmartSelect);
  });
};
<|endoftext|>


<commit_before>var argv = require('minimist')(process.argv.slice(2));

var R = require('ramda');
var c = require('chalk');
var u = require('util');
var ppp = require('prttty');

var pp = {
	render: R.compose(
		ppp.render.bind(ppp),
		R.omit(argv.verbose ? [] : ['doc','params']))
}

exports.pp = pp;

var arrow = c.gray('=>');
var twidle = c.gray('~')

var log = (argv.stfu && function() {}) || console.log.bind(console);

var log2 = function(a,b){
	log(a,arrow,b,'\n');
}
var log3 = function(a,b,c){
	log(a,twidle,b,arrow,c,'\n');
}

var log4 = function(a,b,c,d){
	log(a,twidle,b,arrow,'\n',c,'\nparams:',d,'\n');
}

var logObj = R.curry(function(color, thing, json) {
	log2(color(thing), pp.render(json));
});

var logErr = function(err) {
	log2(c.red("ERR"), err.message);
	console.error(err.stack);
};

var opColors = {
	add: c.bgGreen,
	update: c.bgYellow,
	remove: c.bgRed,
};

var logOp = R.curry(function(color, thing, op, json) {
	log3(color(thing), opColors[op](op), pp.render(json))
})

var logQuery = R.curry(function(color, thing, op, query, params) {
	log4(color(thing), c.bgBlue(op), c.underline(query), pp.render(params))
})

// json -> logmsg
exports.REQ = logObj(c.magenta, "REQ")
exports.ARGS = function() {} //logObj(R.compose(c.underline, c.blue), "ARGS")
exports.DATASET = function() {} // logObj(R.compose(c.underline, c.magenta), "DATASET")
exports.TYPE = function() {} //logObj(R.compose(c.underline, c.gray), "TYPE")

exports.INPUT = logObj(R.compose(c.underline, c.yellow), "INPUT")

// op, json -> logmsg
exports.NEO = logOp(R.compose(c.underline, c.yellow), "Neo4J")
exports.Elastic = logOp(R.compose(c.underline, c.magenta), "Elastic")

// op, query, params -> logmsg
exports.QUERY = logQuery(R.compose(c.underline, c.magenta), "QUERY")
exports.STRUCTURE = logQuery(R.compose(c.bgYellow, c.black));

// err -> logmsg
exports.ERR = logErr;

<commit_msg>simple log<commit_after>var argv = require('minimist')(process.argv.slice(2));
//
//var R = require('ramda');
//var c = require('chalk');
//var u = require('util');
//var ppp = require('prttty');
//
//var pp = {
//	render: R.compose(
//		ppp.render.bind(ppp),
//		R.omit(argv.verbose ? [] : ['doc','params']))
//}
//
//exports.pp = pp;
//
//var arrow = c.gray('=>');
//var twidle = c.gray('~')
//
//var log = (argv.stfu && function() {}) || console.log.bind(console);
//
//var log2 = function(a,b){
//	log(a,arrow,b,'\n');
//}
//var log3 = function(a,b,c){
//	log(a,twidle,b,arrow,c,'\n');
//}
//
//var log4 = function(a,b,c,d){
//	log(a,twidle,b,arrow,'\n',c,'\nparams:',d,'\n');
//}
//
//var logObj = R.curry(function(color, thing, json) {
//	log2(color(thing), pp.render(json));
//});
//
//var logErr = function(err) {
//	log2(c.red("ERR"), err.message);
//	console.error(err.stack);
//};
//
//
//var opColors = {
//	add: c.bgGreen,
//	update: c.bgYellow,
//	remove: c.bgRed,
//};
//
//var logOp = R.curry(function(color, thing, op, json) {
//	log3(color(thing), opColors[op](op), pp.render(json))
//})
//
//var logQuery = R.curry(function(color, thing, op, query, params) {
//	log4(color(thing), c.bgBlue(op), c.underline(query), pp.render(params))
//})
//
//
//
//// json -> logmsg
//exports.REQ = logObj(c.magenta, "REQ")
//exports.ARGS = function() {} //logObj(R.compose(c.underline, c.blue), "ARGS")
//exports.DATASET = function() {} // logObj(R.compose(c.underline, c.magenta), "DATASET")
//exports.TYPE = function() {} //logObj(R.compose(c.underline, c.gray), "TYPE")
//
//exports.INPUT = logObj(R.compose(c.underline, c.yellow), "INPUT")
//
//// op, json -> logmsg
//exports.NEO = logOp(R.compose(c.underline, c.yellow), "Neo4J")
//exports.Elastic = logOp(R.compose(c.underline, c.magenta), "Elastic")
//
//// op, query, params -> logmsg
//exports.QUERY = logQuery(R.compose(c.underline, c.magenta), "QUERY")
//exports.STRUCTURE = logQuery(R.compose(c.bgYellow, c.black));
//
//// err -> logmsg
//exports.ERR = logErr;
//
//var argv = require('minimist')(process.argv.slice(2));
var log = argv.stfu ? function(){} : console.log.bind(console);

module.exports = log;
<|endoftext|>


<commit_before>/**
 * Gist Previewer
 *
 * Copyright 2013 David Orr
 *
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// References
// -----------------------------------------------------------------------------

var jsFiles = [];
var cssFiles = [];
var previewWindowContainerDiv;
var previewWindowDiv;
var previewIFrame;
var previewWindowPanel;
var theatreOverlayDiv;
var bottomResizeDiv;
var parentDocument = document;
var prevBrowserWidth = window.outerWidth;
var prevBrowserHeight = window.outerHeight;

// File
// -----------------------------------------------------------------------------

function File(url) {
  this.url = url;
};

function initFileObjects(sourceCode) {
  var fileboxDivs = document.getElementsByClassName('file-box');
  for (var i = 0; i < fileboxDivs.length; i++) {
    var fileboxDiv = fileboxDivs[i];
    var metaDiv = getFirstChildWithClass(fileboxDiv, 'meta');
    var fileActionsDiv = getFirstChildWithClass(metaDiv, 'file-actions');
    var filetype = getFirstChildWithClass(fileActionsDiv, 'file-language').innerHTML;

    if (filetype === "JavaScript" || filetype === "CSS") {
      var buttonGroupDiv = getFirstChildWithClass(fileActionsDiv, 'button-group');
      var buttons = buttonGroupDiv.children;
      var linkURL = undefined;
      for (var j = 0; j < buttons.length; j++) {
        if (linkURL === undefined) {
          linkURL = getFirstChildWithClass(buttons[j], 'raw-url');
        }
      }

      var file = new File(linkURL.href);
      filetype === 'JavaScript' ? jsFiles.push(file) : cssFiles.push(file);
    }
  }
  retrieveJs(sourceCode);
};

// Inject the JavaScript and CSS code into the HTML file
// -----------------------------------------------------------------------------

function retrieveJs(sourceCode) {
  if (jsFiles.length === 0) {
    retrieveCss(sourceCode);
    return;
  }
  var pos = sourceCode.indexOf('');

  if (pos === -1) {
    pos = sourceCode.indexOf('');
  }
  if (pos === -1) {
    pos = sourceCode.length;
  }

  for (var i = 0; i < jsFiles.length; i++) {
    var file = jsFiles[i];
    var xhReq = new XMLHttpRequest();
    xhReq.onreadystatechange = function() {
      if (xhReq.readyState === 4 && xhReq.status === 200) {
        sourceCode = addJs(sourceCode, xhReq.responseText, pos);
        if (cssFiles.length === 0) {
          displayWindow(sourceCode);
        } else {
          retrieveCss(sourceCode);
        }
      }
    };
    xhReq.open('GET', file.url, false);
    xhReq.send(null);
  }
};

function addJs(sourceCode, jsCode, pos) {
  if (normalizeCode(sourceCode).indexOf(normalizeCode(jsCode)) > -1) {
    return sourceCode;
  }
  return stringSplice(sourceCode, pos, '');
};

// removes a lot of unneccesary stuff in the code,
// such as extra spaces, blank lines, etc.
// we use this in cases where one of html file in the gist repo
// contains another js or css file in it that is also in the repo.
function normalizeCode(code) {
  // remove lines that contain only spaces
  var split = code.split('\n');
  for (var i = 0; i < split.length; i++) {
    var empty = true;
    var line = split[i];
    for (var j = 0; j < line.length; j++) {
      if (line.charAt(j) !== ' ') {
        empty = false;
        break;
      }
    }
    if (empty) {
      split.splice(i, 1);
    }
  }
  code = split.join('');

  // convert multiple blank lines into a single blank line
  // and multiple tab chars into single tab char
  code = code.replace(/\n{2,}/g, '\n').replace(/\t{2,}/g, '\t');

  return code;
};

function retrieveCss(sourceCode) {
  if (cssFiles.length === 0) {
    displayWindow(sourceCode);
    return;
  }
  var pos = sourceCode.indexOf('');

  if (pos === -1) {
    var pos = sourceCode.indexOf('');
    if (pos !== -1) {
      pos += 6;
    }
    pos = pos;
  }
  if (pos === -1) {
    pos = 0;
  }

  for (var i = 0; i < cssFiles.length; i++) {
    var file = cssFiles[i];
    var xhReq = new XMLHttpRequest();
    xhReq.onreadystatechange = function() {
      if (xhReq.readyState === 4 && xhReq.status === 200) {
        sourceCode = addCss(sourceCode, xhReq.responseText, pos);
        if (i === cssFiles.length-1) {
          displayWindow(sourceCode);
        }
      }
    };
    xhReq.open('GET', file.url, false);
    xhReq.send(null);
  }
};

function addCss(sourceCode, cssCode, pos) {
  if (normalizeCode(sourceCode).indexOf(normalizeCode(cssCode)) > -1) {
    return sourceCode;
  }
  return stringSplice(sourceCode, pos, '

');
};

// Inject the 'Preview HTML' button at the top of each file
// -----------------------------------------------------------------------------

function injectPreviewHTMLButtons() {
  var fileboxDivs = document.getElementsByClassName('file-box');
  for (var i = 0; i < fileboxDivs.length; i++) {
    var metaDiv = getFirstChildWithClass(fileboxDivs[i], 'meta');
    var fileActionsDiv = getFirstChildWithClass(metaDiv, 'file-actions');
    var filetype = getFirstChildWithClass(fileActionsDiv, 'file-language').innerHTML;
    if (filetype === 'HTML') {
      var buttonGroupDiv = getFirstChildWithClass(fileActionsDiv, 'button-group');
      var buttons = buttonGroupDiv.children;
      var linkURL = undefined;
      for (var j = 0; j < buttons.length; j++) {
        if (linkURL === undefined) {
          linkURL = getFirstChildWithClass(buttons[j], 'raw-url');
        }
      }
      linkURL = linkURL.href;
      var previewButtonLi = document.createElement('li');
      var previewButtonSpan = document.createElement('span');
      previewButtonSpan.className = 'gistpreview-runButton';
      previewButtonSpan['data-linkURL'] = linkURL;
      previewButtonSpan.innerHTML = 'Preview HTML';
      previewButtonLi.appendChild(previewButtonSpan);
      buttonGroupDiv.appendChild(previewButtonLi);

      previewButtonSpan.addEventListener('mousedown', runButtonHandler, false);
    }
  }
};

// Window UI
// -----------------------------------------------------------------------------

function displayWindow(sourceCode) {;
  completeHTMLSource = sourceCode;
  previewWindowDiv = document.createElement('div');
  previewIFrame = document.createElement('iframe');
  previewWindowPanel = buildPanel();
  theatreOverlayDiv = document.createElement('div');
  bottomResizeDiv = document.createElement('div');

  previewWindowDiv.id = 'gistpreview-window';
  theatreOverlayDiv.id = 'gistpreview-overlay';
  bottomResizeDiv.id = 'gistpreview-resizer';
  previewWindowPanel.className = 'gistpreview-panel';
  previewIFrame.id = 'gistpreview-iframe';
  previewIFrame.srcdoc = sourceCode;

  previewWindowDiv.appendChild(previewWindowPanel);
  previewWindowDiv.appendChild(previewIFrame);
  previewWindowDiv.appendChild(bottomResizeDiv);
  document.body.insertBefore(previewWindowDiv);
  document.body.insertBefore(theatreOverlayDiv);
  fadeInDiv(theatreOverlayDiv, 0.6);

  previewIFrame.addEventListener('load', setIFrameHeight, false);
  bottomResizeDiv.addEventListener('mousedown', startResize, false);

  repositionPreviewWindow(null, true);
  window.onresize = repositionPreviewWindow;
};

function buildPanel() {
  var div = document.createElement('div');
  div.className = 'gistpreview-panel';
  var closeButton = buildPanelButton('Close', 'gistpreview-close');
  closeButton.addEventListener('mousedown', closeButtonHandler, false);
  div.appendChild(closeButton);

  return div;
};

function buildPanelButton(text, id) {
  var div = document.createElement('div');
  div.className = 'gistpreview-panelButton';
  div.innerHTML = text;
  div.id = id;

  return div;
};

function setIFrameHeight() {
  var body = this.contentDocument.body;
  var height = Math.max(body.scrollHeight, body.offsetHeight);
  height += 35; // little cushion
  this.style.height = height + 'px';
};

// Repositioning when browser size changes
// -----------------------------------------------------------------------------

// force : force the function to execute
function repositionPreviewWindow(evt, force) {
  var windowOuterHeight = window.outerHeight;
  var windowOuterWidth = window.outerWidth;

  if (prevBrowserHeight === windowOuterHeight &&
        prevBrowserWidth === windowOuterWidth &&
        !force) {
    return;
  }
  prevBrowserHeight = windowOuterHeight;
  prevBrowserWidth = windowOuterWidth;

  var top = window.innerHeight/10+window.scrollY;
  var left = window.innerWidth/10;

  previewWindowDiv.style.top = top + 'px';
  previewWindowDiv.style.left = left + 'px';
};

// Fade effects
// -----------------------------------------------------------------------------

function fadeInDiv(div, max, callback) {
  fadeDiv(div, max, 0.04, callback);
};

function fadeOutDiv(div, callback) {
  fadeDiv(div, 0, -0.04, callback)
};

function fadeDiv(div, max, step, callback) {
  div.style.opacity = (+(div.style.opacity) + step).toFixed(2);
  var opacity = step > 0 ? +div.style.opacity : -div.style.opacity;
  if (opacity < max) {
    setTimeout(function() {
      fadeDiv(div, max, step, callback);
    }, 2);
  } else {
    if (typeof callback === 'function') {
      callback();
    }
  }
};

// Button Handlers
// -----------------------------------------------------------------------------

function runButtonHandler(e) {
  // when the request is complete, starts a chain
  // initFileObjects -> retrieveJs -> [retrieveCss] -> displayWindow
  var xhReq = new XMLHttpRequest();
  xhReq.onreadystatechange = function() {
    if (xhReq.readyState === 4 && xhReq.status === 200) {
      initFileObjects(xhReq.responseText);
    }
  };
  xhReq.open('GET', this['data-linkURL'], false);
  xhReq.send(null);

  return false;
};

function closeButtonHandler(e) {
  previewWindowDiv.parentNode.removeChild(previewWindowDiv);
  fadeOutDiv(theatreOverlayDiv, function() {
    theatreOverlayDiv.parentNode.removeChild(theatreOverlayDiv)
  });
  jsFiles.length = 0;
  cssFiles.length = 0;
};

// Resizing the window
// -----------------------------------------------------------------------------

var startY, startHeight;
function startResize(e) {
  startY = e.clientY;
  startHeight = parseInt(previewIFrame.style.height.slice(0, -2));

  document.addEventListener('mousemove', doResize, false);
  previewIFrame.contentDocument.addEventListener('mousemove', doResize, false);
  document.addEventListener('mouseup', stopResize, false);
};

function doResize(e) {
  var height = previewIFrame.style.height.slice(0, -2);
  var newHeight;

  if (e.srcElement === bottomResizeDiv ||
      e.srcElement === document ||
      e.srcElement === previewWindowDiv ||
      e.srcElement === theatreOverlayDiv) {
    newHeight = startHeight + e.clientY - startY;
  } else {
    newHeight = e.clientY;
  }

  if (newHeight > 45) {
    previewIFrame.style.height = newHeight + 'px';
  }
};

function stopResize(e) {
  document.removeEventListener('mousemove', doResize, false);
  previewIFrame.contentDocument.removeEventListener('mousemove', doResize, false);
  document.removeEventListener('mouseup', stopResize, false);
};

// Util
// -----------------------------------------------------------------------------

function getFirstChildWithClass(parentDiv, className) {
  var children = parentDiv.children;
  for (var i = 0; i < children.length; i++) {
    if (children[i].className.indexOf(className) > -1) {
      return children[i];
    }
  }
};

function stringSplice(str, idx, insertStr) {
  if (idx > 0) {
    return str.slice(0, idx) + insertStr + str.slice(idx, str.length);
  } else {
    return insertStr + str;
  }
}

// Init
// -----------------------------------------------------------------------------

try {
  injectPreviewHTMLButtons();
} catch (e) {

}<commit_msg>Fixed issue with having to reload page to run script again.<commit_after>/**
 * Gist Previewer
 *
 * Copyright 2013 David Orr
 *
 * Released under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// References
// -----------------------------------------------------------------------------

var jsFiles = [];
var cssFiles = [];
var previewWindowContainerDiv;
var previewWindowDiv;
var previewIFrame;
var previewWindowPanel;
var theatreOverlayDiv;
var bottomResizeDiv;
var parentDocument = document;
var prevBrowserWidth = window.outerWidth;
var prevBrowserHeight = window.outerHeight;

// File
// -----------------------------------------------------------------------------

function File(url) {
  this.url = url;
};

function initFileObjects(sourceCode) {
  var fileboxDivs = document.getElementsByClassName('file-box');
  for (var i = 0; i < fileboxDivs.length; i++) {
    var fileboxDiv = fileboxDivs[i];
    var metaDiv = getFirstChildWithClass(fileboxDiv, 'meta');
    var fileActionsDiv = getFirstChildWithClass(metaDiv, 'file-actions');
    var filetype = getFirstChildWithClass(fileActionsDiv, 'file-language').innerHTML;

    if (filetype === "JavaScript" || filetype === "CSS") {
      var buttonGroupDiv = getFirstChildWithClass(fileActionsDiv, 'button-group');
      var buttons = buttonGroupDiv.children;
      var linkURL = undefined;
      for (var j = 0; j < buttons.length; j++) {
        if (linkURL === undefined) {
          linkURL = getFirstChildWithClass(buttons[j], 'raw-url');
        }
      }

      var file = new File(linkURL.href);
      filetype === 'JavaScript' ? jsFiles.push(file) : cssFiles.push(file);
    }
  }
  retrieveJs(sourceCode);
};

// Inject the JavaScript and CSS code into the HTML file
// -----------------------------------------------------------------------------

function retrieveJs(sourceCode) {
  if (jsFiles.length === 0) {
    retrieveCss(sourceCode);
    return;
  }
  var pos = sourceCode.indexOf('');

  if (pos === -1) {
    pos = sourceCode.indexOf('');
  }
  if (pos === -1) {
    pos = sourceCode.length;
  }

  for (var i = 0; i < jsFiles.length; i++) {
    var file = jsFiles[i];
    var xhReq = new XMLHttpRequest();
    xhReq.onreadystatechange = function() {
      if (xhReq.readyState === 4 && xhReq.status === 200) {
        sourceCode = addJs(sourceCode, xhReq.responseText, pos);
        if (cssFiles.length === 0) {
          displayWindow(sourceCode);
        } else {
          retrieveCss(sourceCode);
        }
      }
    };
    xhReq.open('GET', file.url, false);
    xhReq.send(null);
  }
};

function addJs(sourceCode, jsCode, pos) {
  if (normalizeCode(sourceCode).indexOf(normalizeCode(jsCode)) > -1) {
    return sourceCode;
  }
  return stringSplice(sourceCode, pos, '');
};

// removes a lot of unneccesary stuff in the code,
// such as extra spaces, blank lines, etc.
// we use this in cases where one of html file in the gist repo
// contains another js or css file in it that is also in the repo.
function normalizeCode(code) {
  // remove lines that contain only spaces
  var split = code.split('\n');
  for (var i = 0; i < split.length; i++) {
    var empty = true;
    var line = split[i];
    for (var j = 0; j < line.length; j++) {
      if (line.charAt(j) !== ' ') {
        empty = false;
        break;
      }
    }
    if (empty) {
      split.splice(i, 1);
    }
  }
  code = split.join('');

  // convert multiple blank lines into a single blank line
  // and multiple tab chars into single tab char
  code = code.replace(/\n{2,}/g, '\n').replace(/\t{2,}/g, '\t');

  return code;
};

function retrieveCss(sourceCode) {
  if (cssFiles.length === 0) {
    displayWindow(sourceCode);
    return;
  }
  var pos = sourceCode.indexOf('');

  if (pos === -1) {
    var pos = sourceCode.indexOf('');
    if (pos !== -1) {
      pos += 6;
    }
    pos = pos;
  }
  if (pos === -1) {
    pos = 0;
  }

  for (var i = 0; i < cssFiles.length; i++) {
    var file = cssFiles[i];
    var xhReq = new XMLHttpRequest();
    xhReq.onreadystatechange = function() {
      if (xhReq.readyState === 4 && xhReq.status === 200) {
        sourceCode = addCss(sourceCode, xhReq.responseText, pos);
        if (i === cssFiles.length-1) {
          displayWindow(sourceCode);
        }
      }
    };
    xhReq.open('GET', file.url, false);
    xhReq.send(null);
  }
};

function addCss(sourceCode, cssCode, pos) {
  if (normalizeCode(sourceCode).indexOf(normalizeCode(cssCode)) > -1) {
    return sourceCode;
  }
  return stringSplice(sourceCode, pos, '

');
};

// Inject the 'Preview HTML' button at the top of each file
// -----------------------------------------------------------------------------

function injectPreviewHTMLButtons(interval) {
  var fileboxDivs = document.getElementsByClassName('file-box');
  for (var i = 0; i < fileboxDivs.length; i++) {
    var metaDiv = getFirstChildWithClass(fileboxDivs[i], 'meta');
    if (!metaDiv) {
      return;
    }
    clearInterval(interval);
    var fileActionsDiv = getFirstChildWithClass(metaDiv, 'file-actions');
    var filetype = getFirstChildWithClass(fileActionsDiv, 'file-language').innerHTML;
    if (filetype === 'HTML') {
      var buttonGroupDiv = getFirstChildWithClass(fileActionsDiv, 'button-group');
      var buttons = buttonGroupDiv.children;
      var linkURL = undefined;
      for (var j = 0; j < buttons.length; j++) {
        if (linkURL === undefined) {
          linkURL = getFirstChildWithClass(buttons[j], 'raw-url');
        }
      }
      linkURL = linkURL.href;
      // make sure we haven't already added it
      if (!getFirstChildWithClass(buttonGroupDiv, 'gistpreview-li')) {
        var previewButtonLi = document.createElement('li');
        previewButtonLi.className = 'gistpreview-li';
        var previewButtonSpan = document.createElement('span');
        previewButtonSpan.className = 'gistpreview-runButton';
        previewButtonSpan['data-linkURL'] = linkURL;
        previewButtonSpan.innerHTML = 'Preview HTML';
        previewButtonLi.appendChild(previewButtonSpan);
        buttonGroupDiv.appendChild(previewButtonLi);

        previewButtonSpan.addEventListener('mousedown', runButtonHandler, false);
      }
    }
  }
};

// Window UI
// -----------------------------------------------------------------------------

function displayWindow(sourceCode) {
  completeHTMLSource = sourceCode;
  previewWindowDiv = document.createElement('div');
  previewIFrame = document.createElement('iframe');
  previewWindowPanel = buildPanel();
  theatreOverlayDiv = document.createElement('div');
  bottomResizeDiv = document.createElement('div');

  previewWindowDiv.id = 'gistpreview-window';
  theatreOverlayDiv.id = 'gistpreview-overlay';
  bottomResizeDiv.id = 'gistpreview-resizer';
  previewWindowPanel.className = 'gistpreview-panel';
  previewIFrame.id = 'gistpreview-iframe';
  previewIFrame.srcdoc = sourceCode;

  previewWindowDiv.appendChild(previewWindowPanel);
  previewWindowDiv.appendChild(previewIFrame);
  previewWindowDiv.appendChild(bottomResizeDiv);
  document.body.insertBefore(previewWindowDiv);
  document.body.insertBefore(theatreOverlayDiv);
  fadeInDiv(theatreOverlayDiv, 0.6);

  previewIFrame.addEventListener('load', setIFrameHeight, false);
  bottomResizeDiv.addEventListener('mousedown', startResize, false);

  repositionPreviewWindow(null, true);
  window.onresize = repositionPreviewWindow;
};

function buildPanel() {
  var div = document.createElement('div');
  div.className = 'gistpreview-panel';
  var closeButton = buildPanelButton('Close', 'gistpreview-close');
  closeButton.addEventListener('mousedown', closeButtonHandler, false);
  div.appendChild(closeButton);

  return div;
};

function buildPanelButton(text, id) {
  var div = document.createElement('div');
  div.className = 'gistpreview-panelButton';
  div.innerHTML = text;
  div.id = id;

  return div;
};

function setIFrameHeight() {
  var body = this.contentDocument.body;
  var height = Math.max(body.scrollHeight, body.offsetHeight);
  height += 35; // little cushion
  this.style.height = height + 'px';
};

// Repositioning when browser size changes
// -----------------------------------------------------------------------------

// force : force the function to execute
function repositionPreviewWindow(evt, force) {
  var windowOuterHeight = window.outerHeight;
  var windowOuterWidth = window.outerWidth;

  if (prevBrowserHeight === windowOuterHeight &&
        prevBrowserWidth === windowOuterWidth &&
        !force) {
    return;
  }
  prevBrowserHeight = windowOuterHeight;
  prevBrowserWidth = windowOuterWidth;

  var top = window.innerHeight/10+window.scrollY;
  var left = window.innerWidth/10;

  previewWindowDiv.style.top = top + 'px';
  previewWindowDiv.style.left = left + 'px';
};

// Fade effects
// -----------------------------------------------------------------------------

function fadeInDiv(div, max, callback) {
  fadeDiv(div, max, 0.04, callback);
};

function fadeOutDiv(div, callback) {
  fadeDiv(div, 0, -0.04, callback)
};

function fadeDiv(div, max, step, callback) {
  div.style.opacity = (+(div.style.opacity) + step).toFixed(2);
  var opacity = step > 0 ? +div.style.opacity : -div.style.opacity;
  if (opacity < max) {
    setTimeout(function() {
      fadeDiv(div, max, step, callback);
    }, 2);
  } else {
    if (typeof callback === 'function') {
      callback();
    }
  }
};

// Button Handlers
// -----------------------------------------------------------------------------

function runButtonHandler(e) {
  // when the request is complete, starts a chain
  // initFileObjects -> retrieveJs -> [retrieveCss] -> displayWindow
  var xhReq = new XMLHttpRequest();
  xhReq.onreadystatechange = function() {
    if (xhReq.readyState === 4 && xhReq.status === 200) {
      initFileObjects(xhReq.responseText);
    }
  };
  xhReq.open('GET', this['data-linkURL'], false);
  xhReq.send(null);

  return false;
};

function closeButtonHandler(e) {
  previewWindowDiv.parentNode.removeChild(previewWindowDiv);
  fadeOutDiv(theatreOverlayDiv, function() {
    theatreOverlayDiv.parentNode.removeChild(theatreOverlayDiv)
  });
  jsFiles.length = 0;
  cssFiles.length = 0;
};

// Resizing the window
// -----------------------------------------------------------------------------

var startY, startHeight;
function startResize(e) {
  startY = e.clientY;
  startHeight = parseInt(previewIFrame.style.height.slice(0, -2));

  document.addEventListener('mousemove', doResize, false);
  previewIFrame.contentDocument.addEventListener('mousemove', doResize, false);
  document.addEventListener('mouseup', stopResize, false);
};

function doResize(e) {
  var height = previewIFrame.style.height.slice(0, -2);
  var newHeight;

  if (e.srcElement === bottomResizeDiv ||
      e.srcElement === document ||
      e.srcElement === previewWindowDiv ||
      e.srcElement === theatreOverlayDiv) {
    newHeight = startHeight + e.clientY - startY;
  } else {
    newHeight = e.clientY;
  }

  if (newHeight > 45) {
    previewIFrame.style.height = newHeight + 'px';
  }
};

function stopResize(e) {
  document.removeEventListener('mousemove', doResize, false);
  previewIFrame.contentDocument.removeEventListener('mousemove', doResize, false);
  document.removeEventListener('mouseup', stopResize, false);
};

// Util
// -----------------------------------------------------------------------------

function getFirstChildWithClass(parentDiv, className) {
  var children = parentDiv.children;
  for (var i = 0; i < children.length; i++) {
    if (children[i].className.indexOf(className) > -1) {
      return children[i];
    }
  }
};

function stringSplice(str, idx, insertStr) {
  if (idx > 0) {
    return str.slice(0, idx) + insertStr + str.slice(idx, str.length);
  } else {
    return insertStr + str;
  }
}

// Init
// -----------------------------------------------------------------------------

function init() {
  var interval = setInterval(function() {
    injectPreviewHTMLButtons(interval);
  }, 500);
}

// returns true if a link was clicked
function urlChanged(target) {
  if (!target) {
    return false;
  }

  if (target.tagName === 'A') {
    return true;
  } else {
    return urlChanged(target.parentNode);
  }
}

function handleUrlChange(e) {
  if (urlChanged(e.target)) {
    init();
  }
}

// GitHub changes pages using ajax, so we catch when a link is clicked
window.addEventListener('mousedown', handleUrlChange, false);
window.addEventListener('keydown', handleUrlChange, false);

// if the gist is reached directly
init();<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';

import { useStripes } from '@folio/stripes/core';
import { ViewCustomFieldsSettings, EditCustomFieldsSettings } from '@folio/stripes/smart-components';

const propTypes = {
  history: PropTypes.shape({
    push: PropTypes.func.isRequired,
    replace: PropTypes.func.isRequired,
  }).isRequired,
};

const CustomFieldsSettings = ({
  history,
}) => {
  const stripes = useStripes();

  const base = '/settings/users/custom-fields';

  const redirectToEdit = () => {
    history.push(`${base}/edit`);
  };

  const redirectToView = () => {
    history.push(`${base}`);
  };

  const permissions = {
    canView: stripes.hasPerm('ui-users.settings.customfields.view'),
    canEdit: stripes.hasPerm('ui-users.settings.customfields.edit'),
    canDelete: stripes.hasPerm('ui-users.settings.customfields.all'),
  };

  const backendModuleName = 'users';
  const entityType = 'user';

  if (!permissions.canView) {
    history.replace('/settings/users');
  }

  return (
    <Switch>
      <Route exact path={base}>
        <ViewCustomFieldsSettings
          backendModuleName={backendModuleName}
          entityType={entityType}
          redirectToEdit={redirectToEdit}
          permissions={permissions}
        />
      </Route>
      <Route exact path={`${base}/edit`}>
        <EditCustomFieldsSettings
          backendModuleName={backendModuleName}
          entityType={entityType}
          redirectToView={redirectToView}
          permissions={permissions}
        />
      </Route>
    </Switch>
  );
};

CustomFieldsSettings.propTypes = propTypes;

export default CustomFieldsSettings;
<commit_msg>UIU-1594 Fix after comments<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';

import { useStripes } from '@folio/stripes/core';
import { ViewCustomFieldsSettings, EditCustomFieldsSettings } from '@folio/stripes/smart-components';

const propTypes = {
  history: PropTypes.shape({
    push: PropTypes.func.isRequired,
    replace: PropTypes.func.isRequired,
  }).isRequired,
};

const CustomFieldsSettings = ({
  history,
}) => {
  const stripes = useStripes();

  const base = '/settings/users/custom-fields';

  const permissions = {
    canView: stripes.hasPerm('ui-users.settings.customfields.view'),
    canEdit: stripes.hasPerm('ui-users.settings.customfields.edit'),
    canDelete: stripes.hasPerm('ui-users.settings.customfields.all'),
  };

  const backendModuleName = 'users';
  const entityType = 'user';

  if (!permissions.canView) {
    history.replace('/settings/users');
  }

  return (
    <Switch>
      <Route exact path={base}>
        <ViewCustomFieldsSettings
          backendModuleName={backendModuleName}
          entityType={entityType}
          editRoute={`${base}/edit`}
          permissions={permissions}
        />
      </Route>
      <Route exact path={`${base}/edit`}>
        <EditCustomFieldsSettings
          backendModuleName={backendModuleName}
          entityType={entityType}
          viewRoute={base}
          permissions={permissions}
        />
      </Route>
    </Switch>
  );
};

CustomFieldsSettings.propTypes = propTypes;

export default CustomFieldsSettings;
<|endoftext|>