<commit_before>/* @flow */

import path from 'path'

import * as prepAction from './prep_action'
import logger from '../logger'

import type { ContextualizedChokidarFSEvent } from './chokidar_event'
import type {
  PrepAction, PrepAddFile, PrepPutFolder,
  PrepDeleteFile, PrepDeleteFolder, PrepMoveFile, PrepMoveFolder
} from './prep_action'

const log = logger({
  component: 'LocalWatcher'
})
log.chokidar = log.child({
  component: 'Chokidar'
})

export default function sortAndSquash (events: ContextualizedChokidarFSEvent[], pendingActions: PrepAction[])
: PrepAction[] {
  // OPTIMIZE: new Array(events.length)
  const actions: PrepAction[] = []
  const getInode = (e: ContextualizedChokidarFSEvent): ?number => {
    // TODO: Split by type and move to appropriate modules?
    switch (e.type) {
      case 'add':
      case 'addDir':
      case 'change':
        return e.stats.ino
      case 'unlink':
      case 'unlinkDir':
        if (e.old != null) return e.old.ino
    }
  }
  const panic = (context, description) => {
    log.error(context, description)
    throw new Error(description)
  }
  const actionsByInode:Map<number, PrepAction> = new Map()
  const actionsByPath:Map<string, PrepAction> = new Map()
  const getActionByInode = (e) => {
    const ino = getInode(e)
    if (ino) return actionsByInode.get(ino)
    else return null
  }
  const getActionByPath = (e) => {
    return actionsByPath.get(e.path)
  }
  const pushAction = (a: PrepAction) => {
    actionsByPath.set(a.path, a)
    if (a.ino) actionsByInode.set(a.ino, a)
    else actions.push(a)
  }

  if (pendingActions.length > 0) {
    log.warn({actions: pendingActions}, `Prepend ${pendingActions.length} pending action(s)`)
    for (const a of pendingActions) { pushAction(a) }
    pendingActions = []
  }

  log.trace('Analyze events...')

  for (let e: ContextualizedChokidarFSEvent of events) {
    try {
      switch (e.type) {
        case 'add':
          {
            const moveAction: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByInode(e))
            if (moveAction) {
              if (!moveAction.wip) {
                panic({path: e.path, moveAction, event: e},
                  'We should not have both move and add actions since ' +
                  'checksumless adds and inode-less unlink events are dropped')
              }
              moveAction.path = e.path
              moveAction.ino = e.stats.ino // FIXME: useless?
              moveAction.stats = e.stats
              moveAction.md5sum = e.md5sum
              delete moveAction.wip
              log.debug(
                {path: e.path, oldpath: moveAction.old.path, ino: moveAction.stats.ino},
                'File move completing')
              break
            }

            const unlinkAction: ?PrepDeleteFile = prepAction.maybeDeleteFile(getActionByInode(e))
            if (unlinkAction) {
              // New move found
              log.debug({oldpath: unlinkAction.path, path: e.path, ino: unlinkAction.ino}, 'File moved')
              pushAction(prepAction.build('PrepMoveFile', e.path, {stats: e.stats, md5sum: e.md5sum, old: unlinkAction.old, ino: unlinkAction.ino, wip: e.wip}))
            } else {
              pushAction(prepAction.fromChokidar(e))
            }
          }
          break
        case 'addDir':
          {
            const moveAction: ?PrepMoveFolder = prepAction.maybeMoveFolder(getActionByInode(e))
            if (moveAction) {
              // TODO: Reconciliate pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and addDir actions since ' +
                'non-existing addDir and inode-less unlinkDir events are dropped')
            }

            const unlinkAction: ?PrepDeleteFolder = prepAction.maybeDeleteFolder(getActionByInode(e))
            if (unlinkAction) {
              // New move found
              log.debug({oldpath: unlinkAction.path, path: e.path}, 'moveFolder')
              pushAction(prepAction.build('PrepMoveFolder', e.path, {stats: e.stats, old: unlinkAction.old, ino: unlinkAction.ino, wip: e.wip}))
            } else {
              pushAction(prepAction.fromChokidar(e))
            }
          }
          break
        case 'change':
          pushAction(prepAction.fromChokidar(e))
          break
        case 'unlink':
          {
            const moveAction: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByInode(e))
            if (moveAction) {
              // TODO: Pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and unlink actions since ' +
                'checksumless adds and inode-less unlink events are dropped')
            }

            const addAction: ?PrepAddFile = prepAction.maybeAddFile(getActionByInode(e))
            if (addAction) {
              // New move found
              // TODO: pending move
              log.debug({oldpath: e.path, path: addAction.path, ino: addAction.ino}, 'File moved')
              pushAction(prepAction.build('PrepMoveFile', addAction.path, {
                stats: addAction.stats,
                md5sum: addAction.md5sum,
                old: e.old,
                ino: addAction.ino,
                wip: addAction.wip
              }))
              break
            } else if (getInode(e)) {
              pushAction(prepAction.fromChokidar(e))
              break
            }
            const action: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByPath(e))
            if (action && action.md5sum == null) { // FIXME: if action && action.wip?
              log.debug({path: action.old.path, ino: action.ino}, 'File was moved then deleted. Deleting origin directly.')
              // $FlowFixMe
              action.type = 'PrepDeleteFile'
              action.path = action.old.path
              delete action.wip
            }
            // Otherwise, skip unlink event by multiple moves
          }
          break
        case 'unlinkDir':
          {
            const moveAction: ?PrepMoveFolder = prepAction.maybeMoveFolder(getActionByInode(e))
            if (moveAction) {
              // TODO: pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and unlinkDir actions since ' +
                'non-existing addDir and inode-less unlinkDir events are dropped')
            }

            const addAction: ?PrepPutFolder = prepAction.maybePutFolder(getActionByInode(e))
            if (addAction) {
              // New move found
              log.debug({oldpath: e.path, path: addAction.path}, 'moveFolder')
              pushAction(prepAction.build('PrepMoveFolder', addAction.path, {
                stats: addAction.stats,
                old: e.old,
                ino: addAction.ino,
                wip: addAction.wip
              }))
            } else if (getInode(e)) {
              pushAction(prepAction.fromChokidar(e))
            } // else skip
          }
          // TODO: move & delete dir
          break
        default:
          throw new TypeError(`Unknown event type: ${e.type}`)
      }
    } catch (err) {
      log.error({err, path: e.path})
      throw err
    }
    if (process.env.DEBUG) log.trace({currentEvent: e, actions})
  }

  log.trace('Flatten actions map...')

  for (let a of actionsByInode.values()) actions.push(a)

  log.trace('Sort actions before squash...')

  actions.sort((a, b) => {
    if (a.type === 'PrepMoveFolder' || a.type === 'PrepMoveFile') {
      if (b.type === 'PrepMoveFolder' || b.type === 'PrepMoveFile') {
        if (a.path < b.path) return -1
        else if (a.path > b.path) return 1
        else return 0
      } else return -1
    } else if (b.type === 'PrepMoveFolder' || b.type === 'PrepMoveFile') {
      return 1
    } else {
      return 0
    }
  })

  log.trace('Squash moves...')

  for (let i = 0; i < actions.length; i++) {
    let a = actions[i]

    if (a.type !== 'PrepMoveFolder' && a.type !== 'PrepMoveFile') break
    for (let j = i + 1; j < actions.length; j++) {
      let b = actions[j]
      if (b.type !== 'PrepMoveFolder' && b.type !== 'PrepMoveFile') break

      // inline of PrepAction.isChildMove
      if (a.type === 'PrepMoveFolder' &&
      b.path.indexOf(a.path + path.sep) === 0 &&
      a.old && b.old &&
      b.old.path.indexOf(a.old.path + path.sep) === 0) {
        log.debug({oldpath: b.old.path, path: b.path}, 'descendant move')
        a.wip = a.wip || b.wip
        actions.splice(j--, 1)
      }
    }
  }

  log.trace('Reserve actions in progress for next flush...')

  // TODO: Use _.partition()?
  for (let i = actions.length - 1; i >= 0; i--) {
    const action = actions[i]
    if (action.wip) {
      if (action.type === 'PrepMoveFolder' || action.type === 'PrepMoveFile') {
        log.debug({
          action: action.type,
          oldpath: action.old.path,
          path: action.path,
          ino: action.ino
        }, 'incomplete action')
      } else {
        log.debug({action: action.type, path: action.path}, 'incomplete action')
      }
      pendingActions.push(actions[i])
      actions.splice(i, 1)
    }
  }

  log.trace('Final sort...')

  const sorter = (a, b) => {
    // if one action is a child of another, it takes priority
    if (prepAction.isChildAdd(a, b)) return -1
    if (prepAction.isChildDelete(b, a)) return -1
    if (prepAction.isChildAdd(b, a)) return 1
    if (prepAction.isChildDelete(a, b)) return 1

    // otherwise, order by add path
    if (prepAction.lower(prepAction.addPath(a), prepAction.addPath(b))) return -1
    if (prepAction.lower(prepAction.addPath(b), prepAction.addPath(a))) return 1

    // if there isnt 2 add paths, sort by del path
    if (prepAction.lower(prepAction.delPath(b), prepAction.delPath(a))) return -1

    return 1
  }

  actions.sort(sorter)

  log.debug(`Identified ${actions.length} change(s).`)

  return actions
}
<commit_msg>Effectively clear LocalWatcher#pendingActions<commit_after>/* @flow */

import path from 'path'

import * as prepAction from './prep_action'
import logger from '../logger'

import type { ContextualizedChokidarFSEvent } from './chokidar_event'
import type {
  PrepAction, PrepAddFile, PrepPutFolder,
  PrepDeleteFile, PrepDeleteFolder, PrepMoveFile, PrepMoveFolder
} from './prep_action'

const log = logger({
  component: 'LocalWatcher'
})
log.chokidar = log.child({
  component: 'Chokidar'
})

export default function sortAndSquash (events: ContextualizedChokidarFSEvent[], pendingActions: PrepAction[])
: PrepAction[] {
  // OPTIMIZE: new Array(events.length)
  const actions: PrepAction[] = []
  const getInode = (e: ContextualizedChokidarFSEvent): ?number => {
    // TODO: Split by type and move to appropriate modules?
    switch (e.type) {
      case 'add':
      case 'addDir':
      case 'change':
        return e.stats.ino
      case 'unlink':
      case 'unlinkDir':
        if (e.old != null) return e.old.ino
    }
  }
  const panic = (context, description) => {
    log.error(context, description)
    throw new Error(description)
  }
  const actionsByInode:Map<number, PrepAction> = new Map()
  const actionsByPath:Map<string, PrepAction> = new Map()
  const getActionByInode = (e) => {
    const ino = getInode(e)
    if (ino) return actionsByInode.get(ino)
    else return null
  }
  const getActionByPath = (e) => {
    return actionsByPath.get(e.path)
  }
  const pushAction = (a: PrepAction) => {
    actionsByPath.set(a.path, a)
    if (a.ino) actionsByInode.set(a.ino, a)
    else actions.push(a)
  }

  if (pendingActions.length > 0) {
    log.warn({actions: pendingActions}, `Prepend ${pendingActions.length} pending action(s)`)
    for (const a of pendingActions) { pushAction(a) }
    pendingActions.length = 0
  }

  log.trace('Analyze events...')

  for (let e: ContextualizedChokidarFSEvent of events) {
    try {
      switch (e.type) {
        case 'add':
          {
            const moveAction: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByInode(e))
            if (moveAction) {
              if (!moveAction.wip) {
                panic({path: e.path, moveAction, event: e},
                  'We should not have both move and add actions since ' +
                  'checksumless adds and inode-less unlink events are dropped')
              }
              moveAction.path = e.path
              moveAction.ino = e.stats.ino // FIXME: useless?
              moveAction.stats = e.stats
              moveAction.md5sum = e.md5sum
              delete moveAction.wip
              log.debug(
                {path: e.path, oldpath: moveAction.old.path, ino: moveAction.stats.ino},
                'File move completing')
              break
            }

            const unlinkAction: ?PrepDeleteFile = prepAction.maybeDeleteFile(getActionByInode(e))
            if (unlinkAction) {
              // New move found
              log.debug({oldpath: unlinkAction.path, path: e.path, ino: unlinkAction.ino}, 'File moved')
              pushAction(prepAction.build('PrepMoveFile', e.path, {stats: e.stats, md5sum: e.md5sum, old: unlinkAction.old, ino: unlinkAction.ino, wip: e.wip}))
            } else {
              pushAction(prepAction.fromChokidar(e))
            }
          }
          break
        case 'addDir':
          {
            const moveAction: ?PrepMoveFolder = prepAction.maybeMoveFolder(getActionByInode(e))
            if (moveAction) {
              // TODO: Reconciliate pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and addDir actions since ' +
                'non-existing addDir and inode-less unlinkDir events are dropped')
            }

            const unlinkAction: ?PrepDeleteFolder = prepAction.maybeDeleteFolder(getActionByInode(e))
            if (unlinkAction) {
              // New move found
              log.debug({oldpath: unlinkAction.path, path: e.path}, 'moveFolder')
              pushAction(prepAction.build('PrepMoveFolder', e.path, {stats: e.stats, old: unlinkAction.old, ino: unlinkAction.ino, wip: e.wip}))
            } else {
              pushAction(prepAction.fromChokidar(e))
            }
          }
          break
        case 'change':
          pushAction(prepAction.fromChokidar(e))
          break
        case 'unlink':
          {
            const moveAction: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByInode(e))
            if (moveAction) {
              // TODO: Pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and unlink actions since ' +
                'checksumless adds and inode-less unlink events are dropped')
            }

            const addAction: ?PrepAddFile = prepAction.maybeAddFile(getActionByInode(e))
            if (addAction) {
              // New move found
              // TODO: pending move
              log.debug({oldpath: e.path, path: addAction.path, ino: addAction.ino}, 'File moved')
              pushAction(prepAction.build('PrepMoveFile', addAction.path, {
                stats: addAction.stats,
                md5sum: addAction.md5sum,
                old: e.old,
                ino: addAction.ino,
                wip: addAction.wip
              }))
              break
            } else if (getInode(e)) {
              pushAction(prepAction.fromChokidar(e))
              break
            }
            const action: ?PrepMoveFile = prepAction.maybeMoveFile(getActionByPath(e))
            if (action && action.md5sum == null) { // FIXME: if action && action.wip?
              log.debug({path: action.old.path, ino: action.ino}, 'File was moved then deleted. Deleting origin directly.')
              // $FlowFixMe
              action.type = 'PrepDeleteFile'
              action.path = action.old.path
              delete action.wip
            }
            // Otherwise, skip unlink event by multiple moves
          }
          break
        case 'unlinkDir':
          {
            const moveAction: ?PrepMoveFolder = prepAction.maybeMoveFolder(getActionByInode(e))
            if (moveAction) {
              // TODO: pending move
              panic({path: e.path, moveAction, event: e},
                'We should not have both move and unlinkDir actions since ' +
                'non-existing addDir and inode-less unlinkDir events are dropped')
            }

            const addAction: ?PrepPutFolder = prepAction.maybePutFolder(getActionByInode(e))
            if (addAction) {
              // New move found
              log.debug({oldpath: e.path, path: addAction.path}, 'moveFolder')
              pushAction(prepAction.build('PrepMoveFolder', addAction.path, {
                stats: addAction.stats,
                old: e.old,
                ino: addAction.ino,
                wip: addAction.wip
              }))
            } else if (getInode(e)) {
              pushAction(prepAction.fromChokidar(e))
            } // else skip
          }
          // TODO: move & delete dir
          break
        default:
          throw new TypeError(`Unknown event type: ${e.type}`)
      }
    } catch (err) {
      log.error({err, path: e.path})
      throw err
    }
    if (process.env.DEBUG) log.trace({currentEvent: e, actions})
  }

  log.trace('Flatten actions map...')

  for (let a of actionsByInode.values()) actions.push(a)

  log.trace('Sort actions before squash...')

  actions.sort((a, b) => {
    if (a.type === 'PrepMoveFolder' || a.type === 'PrepMoveFile') {
      if (b.type === 'PrepMoveFolder' || b.type === 'PrepMoveFile') {
        if (a.path < b.path) return -1
        else if (a.path > b.path) return 1
        else return 0
      } else return -1
    } else if (b.type === 'PrepMoveFolder' || b.type === 'PrepMoveFile') {
      return 1
    } else {
      return 0
    }
  })

  log.trace('Squash moves...')

  for (let i = 0; i < actions.length; i++) {
    let a = actions[i]

    if (a.type !== 'PrepMoveFolder' && a.type !== 'PrepMoveFile') break
    for (let j = i + 1; j < actions.length; j++) {
      let b = actions[j]
      if (b.type !== 'PrepMoveFolder' && b.type !== 'PrepMoveFile') break

      // inline of PrepAction.isChildMove
      if (a.type === 'PrepMoveFolder' &&
      b.path.indexOf(a.path + path.sep) === 0 &&
      a.old && b.old &&
      b.old.path.indexOf(a.old.path + path.sep) === 0) {
        log.debug({oldpath: b.old.path, path: b.path}, 'descendant move')
        a.wip = a.wip || b.wip
        actions.splice(j--, 1)
      }
    }
  }

  log.trace('Reserve actions in progress for next flush...')

  // TODO: Use _.partition()?
  for (let i = actions.length - 1; i >= 0; i--) {
    const action = actions[i]
    if (action.wip) {
      if (action.type === 'PrepMoveFolder' || action.type === 'PrepMoveFile') {
        log.debug({
          action: action.type,
          oldpath: action.old.path,
          path: action.path,
          ino: action.ino
        }, 'incomplete action')
      } else {
        log.debug({action: action.type, path: action.path}, 'incomplete action')
      }
      pendingActions.push(actions[i])
      actions.splice(i, 1)
    }
  }

  log.trace('Final sort...')

  const sorter = (a, b) => {
    // if one action is a child of another, it takes priority
    if (prepAction.isChildAdd(a, b)) return -1
    if (prepAction.isChildDelete(b, a)) return -1
    if (prepAction.isChildAdd(b, a)) return 1
    if (prepAction.isChildDelete(a, b)) return 1

    // otherwise, order by add path
    if (prepAction.lower(prepAction.addPath(a), prepAction.addPath(b))) return -1
    if (prepAction.lower(prepAction.addPath(b), prepAction.addPath(a))) return 1

    // if there isnt 2 add paths, sort by del path
    if (prepAction.lower(prepAction.delPath(b), prepAction.delPath(a))) return -1

    return 1
  }

  actions.sort(sorter)

  log.debug(`Identified ${actions.length} change(s).`)

  return actions
}
<|endoftext|>


<commit_before>/** @module liaison/schedule */
define(["requirejs-dplugins/has"], function (has) {
	"use strict";

	has.add("js-setimmediate", typeof setImmediate === "function");
	has.add("dom-mutation-observer",
		typeof MutationObserver !== "undefined"
			&& (/\[\s*native\s+code\s*\]/i.test(MutationObserver) // Avoid polyfill version of MutationObserver
				|| !/^\s*function/.test(MutationObserver)));

	/**
	 * Calls a function at the end of microtask.
	 * @function module:liaison/schedule
	 * @param {Function} callback The function to call at the end of microtask.
	 */

	return (function () {
		/* global setImmediate */
		var SCHEDULEID_PREFIX = "_schedule",
			seq = 0,
			uniqueId = Math.random() + "",
			callbacks = {},
			pseudoDiv = has("dom-mutation-observer") && document.createElement("div");
		function runCallbacks() {
			for (var anyWorkDone = true; anyWorkDone;) {
				anyWorkDone = false;
				for (var id in callbacks) {
					var callback = callbacks[id];
					delete callbacks[id];
					callback();
					anyWorkDone = true;
				}
			}
		}
		if (has("dom-mutation-observer")) {
			pseudoDiv.id = 0;
			new MutationObserver(runCallbacks).observe(pseudoDiv, {attributes: true});
		} else if (!has("js-setimmediate")) {
			window.addEventListener("message", function (event) {
				if (event.data === uniqueId) {
					runCallbacks();
				}
			});
		}
		return function (callback) {
			var id = SCHEDULEID_PREFIX + seq++;
			callbacks[id] = callback;
			has("dom-mutation-observer") ? ++pseudoDiv.id :
				has("js-setimmediate") ? setImmediate(runCallbacks) :
				window.postMessage(uniqueId, "*");
			return {
				remove: function () {
					delete callbacks[id];
				}
			};
		};
	})();
});
<commit_msg>Reduce setImmediate(), etc. callback.<commit_after>/** @module liaison/schedule */
define(["requirejs-dplugins/has"], function (has) {
	"use strict";

	has.add("js-setimmediate", typeof setImmediate === "function");
	has.add("dom-mutation-observer",
		typeof MutationObserver !== "undefined"
			&& (/\[\s*native\s+code\s*\]/i.test(MutationObserver) // Avoid polyfill version of MutationObserver
				|| !/^\s*function/.test(MutationObserver)));

	/**
	 * Calls a function at the end of microtask.
	 * @function module:liaison/schedule
	 * @param {Function} callback The function to call at the end of microtask.
	 */

	return (function () {
		/* global setImmediate */
		var inFlight,
			SCHEDULEID_PREFIX = "_schedule",
			seq = 0,
			uniqueId = Math.random() + "",
			callbacks = {},
			pseudoDiv = has("dom-mutation-observer") && document.createElement("div");
		function runCallbacks() {
			inFlight = false;
			for (var anyWorkDone = true; anyWorkDone;) {
				anyWorkDone = false;
				for (var id in callbacks) {
					var callback = callbacks[id];
					delete callbacks[id];
					callback();
					anyWorkDone = true;
				}
			}
		}
		if (has("dom-mutation-observer")) {
			pseudoDiv.id = 0;
			new MutationObserver(runCallbacks).observe(pseudoDiv, {attributes: true});
		} else if (!has("js-setimmediate")) {
			window.addEventListener("message", function (event) {
				if (event.data === uniqueId) {
					runCallbacks();
				}
			});
		}
		return function (callback) {
			var id = SCHEDULEID_PREFIX + seq++;
			callbacks[id] = callback;
			if (!inFlight) {
				has("dom-mutation-observer") ? ++pseudoDiv.id :
					has("js-setimmediate") ? setImmediate(runCallbacks) :
					window.postMessage(uniqueId, "*");
				inFlight = true;
			}
			return {
				remove: function () {
					delete callbacks[id];
				}
			};
		};
	})();
});
<|endoftext|>


<commit_before>// Hides Dashboard Views
$('.container').hide();

// Navbar button functions
$('.event').click(processEvent);
$('.init').click(processInit);
$('.speak').click(processSpeak);
$('.del-event').click(processDelEvent);
$('.del-init').click(processDelInit);
$('.del-speak').click(processDelSpeak);
$('.events').click(processEvents);
$('.speaker').click(processSpeaker);
$('.speakq').click(processSpeakq);
$('.proj').click(processProj);
$('.pledges').click(processPledges);

function processEvent(){
	$('.add-event').show();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processInit(){
	$('.add-event').hide();
	$('.add-initiative').show();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').show();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelEvent(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').show();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelInit(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').show();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').show();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processEvents(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').show();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeaker(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').show();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeakq(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').show();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processProj(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').show();
	$('.view-pledge').hide();
}
function processPledges(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').show();
}

// Character Limit Function
function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } else {
    limitCount.value = limitNum - limitField.value.length;
  }
}

// Event Functions
$('.btn-send-event').click(sendEvent);
$('.btn-del-event').click(delEvent);

function delEvent(){
	document.getElementById("event-title").value="";
	document.getElementById("event-info").value="";
}

function sendEvent(){
	var title = $('#event-title').val();
	var event = $('#event-info').val();
	database.ref('event/'+ title).update({
  		Title: title,
  		Event: event
 	});
	//code to send event
	delEvent();
}

// Initiative Functions
$('.btn-send-initiative').click(sendInitiative);
$('.btn-del-initiative').click(delInitiative);

function delInitiative(){
	document.getElementById("initiative-title").value="";
	document.getElementById("initiative-info").value="";
}

function sendInitiative(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var title = $('#initiative-title').val();
		var initiative = $('#initiative-info').val();

		database.ref('event/'+ event +'/initiative/'+ title).update({
	  		Title: title,
	  		Initiative: initiative
	 	});
		//code to send initiative
		delInitiative();
	});
}

// Speaker Functions
$('.btn-send-speaker').click(sendSpeaker);
$('.btn-del-speaker').click(delSpeaker);

function delSpeaker(){
	document.getElementById("speaker-name").value="";
	document.getElementById("speaker-info").value="";
}

function sendSpeaker(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var name = $('#speaker-name').val();
		var info = $('#speaker-info').val();

		database.ref('event/'+ event +'/speaker/'+ name).update({
	  		Name: name,
	  		Info: info
	 	});
		//code to send speaker
		delSpeaker();
	});
}

// Delete Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var events = childSnapshot.key;
		deleteEvents(events);
		// console.log(speak);
});

function deleteEvents(events){
		$('.event-list').append('<option title="'+events+'">'+events+'</option');

}

$('.selectevents').click(processDelEvents);

function processDelEvents(){

	var events = $("#sel1 option:selected").text();

	database.ref('event/'+ events).remove();
	$("#sel1 option:selected").remove();
	alert(events + ' Removed!');
}

// Delete Initiative Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/initiative/').on('child_added', function(childSnapshot){
			var init = childSnapshot.key;
			delInit(init);
			// console.log(init);
	});
});

function delInit(init){
		$('.initiative-list').append('<option title="'+init+'">'+init+'</option');

}

$('.selecti').click(processSelecti);

function processSelecti(){
firebase.database().ref('chosen-event/').on('value', function(snapshot){

	var event = snapshot.val().Chosen;

	var init = $("#sel2 option:selected").text();

	database.ref('event/'+ event +'/initiative/' + init).remove();
	$("#sel2 option:selected").remove();
	alert(init + ' Removed!');
	});
}

// Delete Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			delSpeak(speak);
			// console.log(speak);
	});
});

function delSpeak(speak){
		$('.speaker-list').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selects').click(processSelects);

function processSelects(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	var speak = $("#sel3 option:selected").text();

	database.ref('event/'+ event +'/speaker/' + speak).remove();
	$("#sel3 option:selected").remove();
	alert(speak + ' Removed!');
	});
}

// Choose Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var event = childSnapshot.key;
		chooseEvent(event);
		// console.log(speak);
});

function chooseEvent(event){
		$('.event-choose').append('<option title="'+event+'">'+event+'</option');

}

$('.selectevent').click(processSelectEvent);

function processSelectEvent(){
	var event = $("#sel4 option:selected").text();

	database.ref('chosen-event/').update({
		Chosen: event
	});

	alert(event + ' Chosen');
};

// Choose Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			chooseSpeak(speak);
			// console.log(speak);
	});
});

function chooseSpeak(speak){
		$('.speaker-choose').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selectspeaker').click(processSelectSpeaker);

function processSelectSpeaker(){
	var speak = $("#sel5 option:selected").text();

	database.ref('chosen-speaker/').update({
		Chosen: speak
	});

	alert(speak + ' Chosen');
};

// Choose Question Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;
	var speaker = "";
	database.ref('chosen-speaker/').once('value', function(snapshot) {
		speaker = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

firebase.database().ref('chosen-speaker/').on('value', function(snapshot){
	var event = "";
	var speaker = snapshot.val().Chosen;
	database.ref('chosen-event/').once('value', function(snapshot) {
		event = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

function updateSpeakerQuestions(event, speaker) {
	removeAllQuestions($('.question-list'));
	firebase.database().ref('event/' + event + "/speaker-question/" + speaker).once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot) {
			childSnapshot.forEach(function(childSnapshot) {
				var question = childSnapshot.val();
				addQuestion(question, speaker);
			});
		});
	});
}

function removeAllQuestions(dropDown) {
	if (typeof dropDown != 'undefined' && typeof dropDown.options != 'undefined') {
	    while (dropDown.options.length > 0) {
	        dropDown.remove(0);
	    }
	}
}

function addQuestion(question,name){
		$('.question-list').append('<option title="'+question+'">'+question+' '+'('+'question for '+name+')'+'</option');

}

$('.selectq').click(processSelectq);

function processSelectq(){
	var question = $("#sel6 option:selected").text();

	database.ref('chosen-question/').update({
		Chosen: question
	});

	alert(question + " Chosen!")
}

// Change View Function
$('.select').click(processSelect);

function processSelect(){
	var view = $("#sel7 option:selected").text();

	database.ref('view/').update({
		currentView: view
	});

	alert("set view to " + view);
}

// View Pledge Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/' + event + '/pledges/').on('value', function(snapshot){
		snapshot.forEach(function(data){
			var title= data.val().Title;
			var pledge= data.val().Pledge;
			addPledge(title,pledge);
			console.log(title)
		});
	});
});

function addPledge(title,pledge){
		$('.pledge-list').append('<option title="'+title+'">'+title+' '+'('+'Pledge: '+pledge+')'+'</option');

}

$('.selectp').click(processSelectP);

function processSelectP(){
	var question = $("#sel8 option:selected").text();
}<commit_msg>Added dashboard to recognise pledges in database<commit_after>// Hides Dashboard Views
$('.container').hide();

// Navbar button functions
$('.event').click(processEvent);
$('.init').click(processInit);
$('.speak').click(processSpeak);
$('.del-event').click(processDelEvent);
$('.del-init').click(processDelInit);
$('.del-speak').click(processDelSpeak);
$('.events').click(processEvents);
$('.speaker').click(processSpeaker);
$('.speakq').click(processSpeakq);
$('.proj').click(processProj);
$('.pledges').click(processPledges);

function processEvent(){
	$('.add-event').show();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processInit(){
	$('.add-event').hide();
	$('.add-initiative').show();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').show();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelEvent(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').show();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelInit(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').show();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').show();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processEvents(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').show();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeaker(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').show();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeakq(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').show();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processProj(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').show();
	$('.view-pledge').hide();
}
function processPledges(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').show();
}

// Character Limit Function
function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } else {
    limitCount.value = limitNum - limitField.value.length;
  }
}

// Event Functions
$('.btn-send-event').click(sendEvent);
$('.btn-del-event').click(delEvent);

function delEvent(){
	document.getElementById("event-title").value="";
	document.getElementById("event-info").value="";
}

function sendEvent(){
	var title = $('#event-title').val();
	var event = $('#event-info').val();
	database.ref('event/'+ title).update({
  		Title: title,
  		Event: event
 	});
	//code to send event
	delEvent();
}

// Initiative Functions
$('.btn-send-initiative').click(sendInitiative);
$('.btn-del-initiative').click(delInitiative);

function delInitiative(){
	document.getElementById("initiative-title").value="";
	document.getElementById("initiative-info").value="";
}

function sendInitiative(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var title = $('#initiative-title').val();
		var initiative = $('#initiative-info').val();

		database.ref('event/'+ event +'/initiative/'+ title).update({
	  		Title: title,
	  		Initiative: initiative
	 	});
		//code to send initiative
		delInitiative();
	});
}

// Speaker Functions
$('.btn-send-speaker').click(sendSpeaker);
$('.btn-del-speaker').click(delSpeaker);

function delSpeaker(){
	document.getElementById("speaker-name").value="";
	document.getElementById("speaker-info").value="";
}

function sendSpeaker(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var name = $('#speaker-name').val();
		var info = $('#speaker-info').val();

		database.ref('event/'+ event +'/speaker/'+ name).update({
	  		Name: name,
	  		Info: info
	 	});
		//code to send speaker
		delSpeaker();
	});
}

// Delete Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var events = childSnapshot.key;
		deleteEvents(events);
		// console.log(speak);
});

function deleteEvents(events){
		$('.event-list').append('<option title="'+events+'">'+events+'</option');

}

$('.selectevents').click(processDelEvents);

function processDelEvents(){

	var events = $("#sel1 option:selected").text();

	database.ref('event/'+ events).remove();
	$("#sel1 option:selected").remove();
	alert(events + ' Removed!');
}

// Delete Initiative Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/initiative/').on('child_added', function(childSnapshot){
			var init = childSnapshot.key;
			delInit(init);
			// console.log(init);
	});
});

function delInit(init){
		$('.initiative-list').append('<option title="'+init+'">'+init+'</option');

}

$('.selecti').click(processSelecti);

function processSelecti(){
firebase.database().ref('chosen-event/').on('value', function(snapshot){

	var event = snapshot.val().Chosen;

	var init = $("#sel2 option:selected").text();

	database.ref('event/'+ event +'/initiative/' + init).remove();
	$("#sel2 option:selected").remove();
	alert(init + ' Removed!');
	});
}

// Delete Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			delSpeak(speak);
			// console.log(speak);
	});
});

function delSpeak(speak){
		$('.speaker-list').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selects').click(processSelects);

function processSelects(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	var speak = $("#sel3 option:selected").text();

	database.ref('event/'+ event +'/speaker/' + speak).remove();
	$("#sel3 option:selected").remove();
	alert(speak + ' Removed!');
	});
}

// Choose Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var event = childSnapshot.key;
		chooseEvent(event);
		// console.log(speak);
});

function chooseEvent(event){
		$('.event-choose').append('<option title="'+event+'">'+event+'</option');

}

$('.selectevent').click(processSelectEvent);

function processSelectEvent(){
	var event = $("#sel4 option:selected").text();

	database.ref('chosen-event/').update({
		Chosen: event
	});

	alert(event + ' Chosen');
};

// Choose Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			chooseSpeak(speak);
			// console.log(speak);
	});
});

function chooseSpeak(speak){
		$('.speaker-choose').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selectspeaker').click(processSelectSpeaker);

function processSelectSpeaker(){
	var speak = $("#sel5 option:selected").text();

	database.ref('chosen-speaker/').update({
		Chosen: speak
	});

	alert(speak + ' Chosen');
};

// Choose Question Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;
	var speaker = "";
	database.ref('chosen-speaker/').once('value', function(snapshot) {
		speaker = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

firebase.database().ref('chosen-speaker/').on('value', function(snapshot){
	var event = "";
	var speaker = snapshot.val().Chosen;
	database.ref('chosen-event/').once('value', function(snapshot) {
		event = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

function updateSpeakerQuestions(event, speaker) {
	removeAllQuestions($('.question-list'));
	firebase.database().ref('event/' + event + "/speaker-question/" + speaker).once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot) {
			childSnapshot.forEach(function(childSnapshot) {
				var question = childSnapshot.val();
				addQuestion(question, speaker);
			});
		});
	});
}

function removeAllQuestions(dropDown) {
	if (typeof dropDown != 'undefined' && typeof dropDown.options != 'undefined') {
	    while (dropDown.options.length > 0) {
	        dropDown.remove(0);
	    }
	}
}

function addQuestion(question,name){
		$('.question-list').append('<option title="'+question+'">'+question+' '+'('+'question for '+name+')'+'</option');

}

$('.selectq').click(processSelectq);

function processSelectq(){
	var question = $("#sel6 option:selected").text();

	database.ref('chosen-question/').update({
		Chosen: question
	});

	alert(question + " Chosen!")
}

// Change View Function
$('.select').click(processSelect);

function processSelect(){
	var view = $("#sel7 option:selected").text();

	database.ref('view/').update({
		currentView: view
	});

	alert("set view to " + view);
}

// View Pledge Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/' + event + '/pledges/').on('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			childSnapshot.forEach(function(childSnapshot){
			var title= childSnapshot.val().Title;
			var pledge= childSnapshot.val().Pledge;
			addPledge(title,pledge);
			console.log(title)
			});
		});
	});
});

function addPledge(title,pledge){
		$('.pledge-list').append('<option title="'+title+'">'+title+' '+'('+'Pledge: '+pledge+')'+'</option');

}

$('.selectp').click(processSelectP);

function processSelectP(){
	var question = $("#sel8 option:selected").text();
}<|endoftext|>


<commit_before>const InstagramError = require('./InstagramError')
const InstagramErrorMaxRequests = require('./InstagramErrorMaxRequests')
const get = require('lodash/get')

function errorHandler (error, instagramNodeApi) {
  let err = get(error, 'response.body')
  if (err.code === 429) {
    instagramNodeApi.emit('err', new InstagramErrorMaxRequests(get(error, 'response.body')))
  } else {
    instagramNodeApi.emit('err', new InstagramError(get(error, 'response.body')))
  }
}

module.exports = errorHandler
<commit_msg>:art: error handler refactoring<commit_after>const InstagramError = require('./InstagramError')
const InstagramErrorMaxRequests = require('./InstagramErrorMaxRequests')
const get = require('lodash/get')

function errorHandler (error, instagramNodeApi) {
  let err = get(error, 'response.body')
  if (err.code === 429) {
    instagramNodeApi.emit('err', new InstagramErrorMaxRequests(err))
  } else {
    instagramNodeApi.emit('err', new InstagramError(err))
  }
}

module.exports = errorHandler
<|endoftext|>


<commit_before>import {h, Component}					from 'preact/preact';
import ContentNavButton					from 'com/content-nav/nav-button';

export default class PageNavEvent extends Component {
	render( props ) {
		let {node, parent, superparent, author, user, path, extra} = props;

		// Build paths
		let FullPath = ((extra && extra.length) ? ('/' + extra.join('/')) : '');
		FullPath = FullPath ? FullPath : '/';
		let FirstPath = FullPath.split('/', 2).join('/');

		// Begin populating the list of Nav Buttons
		let NavButtons = [];

		NavButtons.push(<ContentNavButton path={path+FullPath} icon="previous" href="/" />);

		let IsHome = (FullPath == '/');
		let IsLoggedIn = user && (user.id !== 0);
		let IsMe = ['/my'].includes(FirstPath);

		NavButtons.push(<ContentNavButton path={path+FullPath} light={true} icon="trophy" href={path+'/'}>{node.name}</ContentNavButton>);

		NavButtons.push(<ContentNavButton path={path+FirstPath} icon="gamepad" href={path+'/games'}>Games</ContentNavButton>);
		NavButtons.push(<ContentNavButton path={path+FirstPath} icon="ticket" href={path+'/theme'}>Theme</ContentNavButton>);
		NavButtons.push(<ContentNavButton path={path+FullPath} icon="stats" href={path+'/stats'}>Stats</ContentNavButton>);

		if ( IsLoggedIn ) {
			/* light={FirstPath == '/my'} */
			NavButtons.push(<ContentNavButton path={path+FirstPath} icon="user" href={path+'/my'}>Me</ContentNavButton>);
		}

//		// "Me" User Button (if home or logged in)
//		if ( IsMe ) {
//			if ( user && (user.id !== 0) ) {
//				NavButtons.push(<ContentNavButton path={path+FullPath} icon="star-half" href={path+'/my/grades'}>My Grades</ContentNavButton>);
//			}
//		}

		return (

				{NavButtons}

		);
	}
}
<commit_msg>now checking for event mode to show results tab<commit_after>import {h, Component}					from 'preact/preact';
import ContentNavButton					from 'com/content-nav/nav-button';

export default class PageNavEvent extends Component {
	render( props ) {
		let {node, parent, superparent, author, user, path, extra} = props;

		// Build paths
		let FullPath = ((extra && extra.length) ? ('/' + extra.join('/')) : '');
		FullPath = FullPath ? FullPath : '/';
		let FirstPath = FullPath.split('/', 2).join('/');

		// Begin populating the list of Nav Buttons
		let NavButtons = [];

		NavButtons.push(<ContentNavButton path={path+FullPath} icon="previous" href="/" />);

		let IsHome = (FullPath == '/');
		let IsLoggedIn = user && (user.id !== 0);
		let IsMe = ['/my'].includes(FirstPath);
		let ThemeMode = (node.meta['theme-mode']) ? parseInt(node.meta['theme-mode']) : 0;

		NavButtons.push(<ContentNavButton path={path+FullPath} light={true} icon="trophy" href={path+'/'}>{node.name}</ContentNavButton>);

		if ( ThemeMode >= 8 ) {
			NavButtons.push(<ContentNavButton path={path+FirstPath} icon="gamepad" href={path+'/results'}>Results</ContentNavButton>);
		}

		NavButtons.push(<ContentNavButton path={path+FirstPath} icon="gamepad" href={path+'/games'}>Games</ContentNavButton>);
		NavButtons.push(<ContentNavButton path={path+FirstPath} icon="ticket" href={path+'/theme'}>Theme</ContentNavButton>);
		NavButtons.push(<ContentNavButton path={path+FullPath} icon="stats" href={path+'/stats'}>Stats</ContentNavButton>);

		if ( IsLoggedIn ) {
			/* light={FirstPath == '/my'} */
			NavButtons.push(<ContentNavButton path={path+FirstPath} icon="user" href={path+'/my'}>Me</ContentNavButton>);
		}

//		// "Me" User Button (if home or logged in)
//		if ( IsMe ) {
//			if ( user && (user.id !== 0) ) {
//				NavButtons.push(<ContentNavButton path={path+FullPath} icon="star-half" href={path+'/my/grades'}>My Grades</ContentNavButton>);
//			}
//		}

		return (

				{NavButtons}

		);
	}
}
<|endoftext|>


<commit_before>// (function() {
    var app = angular.module("vackerApp", []);

    var YearController = function($scope, $http) {

        var onYearsComplete = function(response) {
            $scope.years = response.data;
        };
        var onHttpError = function(reason) {
            alert("HTTP error: " + reason);
        };

        $http.get("http://localhost:5000/years")
            .then(onYearsComplete, onHttpError);

        $scope.get_thumbnail_url = function (year) {
            return "http://localhost:5000/years/" + year + "/thumbnail";
        };

    };

    app.controller("YearController", YearController);
// })
<commit_msg>Remove angular module from global scope<commit_after>(function() {
    var app = angular.module("vackerApp", []);

    var YearController = function($scope, $http) {

        var onYearsComplete = function(response) {
            $scope.years = response.data;
        };
        var onHttpError = function(reason) {
            alert("HTTP error: " + reason);
        };

        $http.get("http://localhost:5000/years")
            .then(onYearsComplete, onHttpError);

        $scope.get_thumbnail_url = function (year) {
            return "http://localhost:5000/years/" + year + "/thumbnail";
        };

    };

    app.controller("YearController", YearController);
})();
<|endoftext|>


<commit_before><commit_msg>Update project js-data-angular to 3.2.0<commit_after><|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

describe('Capture (navigator.device.capture)', function () {
    it("capture.spec.1 should exist", function() {
        expect(navigator.device).toBeDefined();
        expect(navigator.device.capture).toBeDefined();
    });

    it("capture.spec.2 should have the correct properties ", function() {
        expect(navigator.device.capture.supportedAudioModes).toBeDefined();
        expect(navigator.device.capture.supportedImageModes).toBeDefined();
        expect(navigator.device.capture.supportedVideoModes).toBeDefined();
    });

    it("capture.spec.3 should contain a captureAudio function", function() {
        expect(navigator.device.capture.captureAudio).toBeDefined();
        expect(typeof navigator.device.capture.captureAudio == 'function').toBe(true);
    });

    it("capture.spec.4 should contain a captureImage function", function() {
        expect(navigator.device.capture.captureImage).toBeDefined();
        expect(typeof navigator.device.capture.captureImage == 'function').toBe(true);
    });

    it("capture.spec.5 should contain a captureVideo function", function() {
        expect(navigator.device.capture.captureVideo).toBeDefined();
        expect(typeof navigator.device.capture.captureVideo == 'function').toBe(true);
    });

    describe('CaptureAudioOptions', function () {
        it("capture.spec.6 CaptureAudioOptions constructor should exist", function() {
            var options = new CaptureAudioOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
            expect(options.duration).toBeDefined();
        });
    });

    describe('CaptureImageOptions', function () {
        it("capture.spec.7 CaptureImageOptions constructor should exist", function() {
            var options = new CaptureImageOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
        });
    });

    describe('CaptureVideoOptions', function () {
        it("capture.spec.8 CaptureVideoOptions constructor should exist", function() {
            var options = new CaptureVideoOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
            expect(options.duration).toBeDefined();
        });
    });

    describe('CaptureError interface', function () {
        it("capture.spec.9 CaptureError constants should be defined", function() {
            expect(CaptureError.CAPTURE_INTERNAL_ERR).toBe(0);
            expect(CaptureError.CAPTURE_APPLICATION_BUSY).toBe(1);
            expect(CaptureError.CAPTURE_INVALID_ARGUMENT).toBe(2);
            expect(CaptureError.CAPTURE_NO_MEDIA_FILES).toBe(3);
        });

        it("capture.spec.10 CaptureError properties should exist", function() {
            var error = new CaptureError();
            expect(error).toBeDefined();
            expect(error.code).toBeDefined();
        });
    });

    describe('MediaFileData', function () {
        it("capture.spec.11 MediaFileData constructor should exist", function() {
            var fileData = new MediaFileData();
            expect(fileData).toBeDefined();
            expect(fileData.bitrate).toBeDefined();
            expect(fileData.codecs).toBeDefined();
            expect(fileData.duration).toBeDefined();
            expect(fileData.height).toBeDefined();
            expect(fileData.width).toBeDefined();
        });
    });

    describe('MediaFile', function () {
        it("capture.spec.12 MediaFile constructor should exist", function() {
            var fileData = new MediaFile();
            expect(fileData).toBeDefined();
            expect(fileData.name).toBeDefined();
            expect(fileData.fullPath).toBeDefined();
            expect(fileData.type).toBeDefined();
            expect(fileData.lastModifiedDate).toBeDefined();
            expect(fileData.size).toBeDefined();
        });
    });
});
<commit_msg>sync cordova-mobile-spec test into cordova-plugin-media-capture<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

describe('Capture (navigator.device.capture)', function () {
    it("capture.spec.1 should exist", function() {
        expect(navigator.device).toBeDefined();
        expect(navigator.device.capture).toBeDefined();
    });

    it("capture.spec.2 should have the correct properties ", function() {
        expect(navigator.device.capture.supportedAudioModes).toBeDefined();
        expect(navigator.device.capture.supportedImageModes).toBeDefined();
        expect(navigator.device.capture.supportedVideoModes).toBeDefined();
    });

    it("capture.spec.3 should contain a captureAudio function", function() {
        expect(navigator.device.capture.captureAudio).toBeDefined();
        expect(typeof navigator.device.capture.captureAudio == 'function').toBe(true);
    });

    it("capture.spec.4 should contain a captureImage function", function() {
        expect(navigator.device.capture.captureImage).toBeDefined();
        expect(typeof navigator.device.capture.captureImage == 'function').toBe(true);
    });

    it("capture.spec.5 should contain a captureVideo function", function() {
        expect(navigator.device.capture.captureVideo).toBeDefined();
        expect(typeof navigator.device.capture.captureVideo == 'function').toBe(true);
    });

    describe('CaptureAudioOptions', function () {
        it("capture.spec.6 CaptureAudioOptions constructor should exist", function() {
            var options = new CaptureAudioOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
            expect(options.duration).toBeDefined();
        });
    });

    describe('CaptureImageOptions', function () {
        it("capture.spec.7 CaptureImageOptions constructor should exist", function() {
            var options = new CaptureImageOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
        });
    });

    describe('CaptureVideoOptions', function () {
        it("capture.spec.8 CaptureVideoOptions constructor should exist", function() {
            var options = new CaptureVideoOptions();
            expect(options).toBeDefined();
            expect(options.limit).toBeDefined();
            expect(options.duration).toBeDefined();
        });
    });

    describe('CaptureError interface', function () {
        it("capture.spec.9 CaptureError constants should be defined", function() {
            expect(CaptureError.CAPTURE_INTERNAL_ERR).toBe(0);
            expect(CaptureError.CAPTURE_APPLICATION_BUSY).toBe(1);
            expect(CaptureError.CAPTURE_INVALID_ARGUMENT).toBe(2);
            expect(CaptureError.CAPTURE_NO_MEDIA_FILES).toBe(3);
        });

        it("capture.spec.10 CaptureError properties should exist", function() {
            var error = new CaptureError();
            expect(error).toBeDefined();
            expect(error.code).toBeDefined();
        });
    });

    describe('MediaFileData', function () {
        it("capture.spec.11 MediaFileData constructor should exist", function() {
            var fileData = new MediaFileData();
            expect(fileData).toBeDefined();
            expect(fileData.bitrate).toBeDefined();
            expect(fileData.codecs).toBeDefined();
            expect(fileData.duration).toBeDefined();
            expect(fileData.height).toBeDefined();
            expect(fileData.width).toBeDefined();
        });
    });

    describe('MediaFile', function () {
        it("capture.spec.12 MediaFile constructor should exist", function() {
            var fileData = new MediaFile();
            expect(fileData).toBeDefined();
            expect(fileData.name).toBeDefined();
            expect(fileData.type).toBeDefined();
            expect(fileData.lastModifiedDate).toBeDefined();
            expect(fileData.size).toBeDefined();
        });
    });
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { toastr } from 'react-redux-toastr';
import isEmpty from 'lodash/isEmpty';

// components
import Field from 'components/form/Field';
import Input from 'components/form/Input';
import TextArea from 'components/form/TextArea';
import FileImage from 'components/form/FileImage';
import Checkbox from 'components/form/Checkbox';
import TemplateSelector from 'components/dashboards/template-selector';

// Wysiwyg
import Wysiwyg from 'components/form/VizzWysiwyg';
import WidgetBlock from 'components/wysiwyg/widget-block';
import WidgetBlockEdition from 'components/wysiwyg/widget-block-edition';

// constants
import { FORM_ELEMENTS } from 'components/dashboards/form/constants';
import { TEMPLATES } from 'components/dashboards/template-selector/constants';

class Step1 extends PureComponent {
  static propTypes = {
    form: PropTypes.object,
    basic: PropTypes.bool,
    user: PropTypes.object.isRequired,
    mode: PropTypes.string,
    onChange: PropTypes.func.isRequired
  }

  static defaultProps = {
    form: {},
    basic: false,
    mode: 'new'
  }

  state = {
    form: {
      ...this.props.form,
      content: TEMPLATES[0].content
    }
  };

  componentDidMount() {
    const { child: wysiwyg } = FORM_ELEMENTS.elements.content;

    if (!isEmpty(this.props.form.content)) {
      wysiwyg.setValue(this.props.form.content);
    } else {
      wysiwyg.setValue(JSON.stringify(TEMPLATES[0].content));
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ form: nextProps.form });
  }

  onChangeTemplate(nextTemplate) {
    const { child: wysiwyg } = FORM_ELEMENTS.elements.content;
    const { content } = nextTemplate;

    wysiwyg.setValue(JSON.stringify(content));
  }

  render() {
    const { mode } = this.props;
    // Reset FORM_ELEMENTS
    FORM_ELEMENTS.elements = {};

    return (

        <fieldset className="c-field-container">
          {/* NAME */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.name = c; }}
            onChange={value => this.props.onChange({ name: value })}
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'name',
              label: 'Name',
              type: 'text',
              required: true,
              default: this.state.form.name
            }}
          >
            {Input}
          </Field>

          {/* SUMMARY */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.summary = c; }}
            onChange={value => this.props.onChange({ summary: value })}
            className="-fluid"
            properties={{
              name: 'summary',
              label: 'Summary',
              rows: '6',
              default: this.state.form.summary
            }}
          >
            {TextArea}
          </Field>

          {/* DESCRIPTION */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
            onChange={value => this.props.onChange({ description: value })}
            className="-fluid"
            properties={{
              name: 'description',
              label: 'Description',
              rows: '6',
              default: this.state.form.description
            }}
          >
            {TextArea}
          </Field>

          {/* THUMBNAIL */}

                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.photo = c; }}
                  onChange={(value) => {
                    if (value) {
                      this.props.onChange({ photo: value });
                    } else {
                      this.props.onChange({ photo: null });
                    }
                  }}
                  className="-fluid"
                  properties={{
                    name: 'photo',
                    label: 'Photo',
                    placeholder: 'Browse file',
                    baseUrl: process.env.STATIC_SERVER_URL,
                    default: this.state.form.photo
                  }}
                >
                  {FileImage}
                </Field>

          {/* PUBLISHED */}
          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.published = c; }}
              onChange={value => this.props.onChange({
                published: value.checked,
                private: !value.checked
              })}
              properties={{
                name: 'published',
                label: 'Do you want to set this dasboard as published?',
                value: 'published',
                title: 'Published',
                defaultChecked: this.props.form.published,
                checked: this.props.form.published
              }}
            >
              {Checkbox}
            </Field>
          }

          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.preproduction = c; }}
              onChange={value => this.props.onChange({ preproduction: value.checked })}
              properties={{
                name: 'preproduction',
                label: 'Do you want to set this dashboard as pre-production?',
                value: 'preproduction',
                title: 'Pre-production',
                defaultChecked: this.props.form.preproduction,
                checked: this.props.form.preproduction
              }}
            >
              {Checkbox}
            </Field>
          }

          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.production = c; }}
              onChange={value => this.props.onChange({ production: value.checked })}
              properties={{
                name: 'production',
                label: 'Do you want to set this dashboard as production?',
                value: 'production',
                title: 'Production',
                defaultChecked: this.props.form.production,
                checked: this.props.form.production
              }}
            >
              {Checkbox}
            </Field>
          }

          {/* IS-HIGHLIGHTED */}
          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements['is-highlighted'] = c; }}
              onChange={value => this.props.onChange({ 'is-highlighted': value.checked })}
              properties={{
                name: 'is-highlighted',
                label: 'Highlight in Dashboards gallery',
                value: 'is-highlighted',
                title: 'Is Highlighted',
                defaultChecked: this.props.form['is-highlighted'],
                checked: this.props.form['is-highlighted']
              }}
            >
              {Checkbox}
            </Field>
          }
        </fieldset>

        <fieldset className="c-field-container">
          {/* templates */}
          {mode === 'new' && (
            <TemplateSelector onChange={this.onChangeTemplate} />)}

          {/* CONTENT */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.content = c; }}
            onChange={value => this.props.onChange({ content: value })}
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'content',
              label: 'Content',
              required: true,
              default: this.state.form.content,
              blocks: {
                widget: {
                  Component: WidgetBlock,
                  EditionComponent: WidgetBlockEdition,
                  icon: 'icon-widget',
                  label: 'Visualization',
                  renderer: 'modal'
                }
              },
              onUploadImage: files => new Promise((resolve, reject) => {
                const file = files[0];
                const formData = new FormData();
                formData.append('image', file);

                fetch(`${process.env.WRI_API_URL}/temporary_content_image`, {
                  method: 'POST',
                  headers: { Authorization: this.props.user.token },
                  body: formData
                })
                  .then(response => response.json())
                  .then((response) => {
                    resolve(response.url);
                  })
                  .catch((e) => {
                    toastr.error('Error', 'We couldn\'t upload the image. Try again');
                    reject(e);
                  });
              })
            }}
          >
            {Wysiwyg}
          </Field>
        </fieldset>

    );
  }
}

export default Step1;
<commit_msg>Is highlighted checkbox labex fix<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { toastr } from 'react-redux-toastr';
import isEmpty from 'lodash/isEmpty';

// components
import Field from 'components/form/Field';
import Input from 'components/form/Input';
import TextArea from 'components/form/TextArea';
import FileImage from 'components/form/FileImage';
import Checkbox from 'components/form/Checkbox';
import TemplateSelector from 'components/dashboards/template-selector';

// Wysiwyg
import Wysiwyg from 'components/form/VizzWysiwyg';
import WidgetBlock from 'components/wysiwyg/widget-block';
import WidgetBlockEdition from 'components/wysiwyg/widget-block-edition';

// constants
import { FORM_ELEMENTS } from 'components/dashboards/form/constants';
import { TEMPLATES } from 'components/dashboards/template-selector/constants';

class Step1 extends PureComponent {
  static propTypes = {
    form: PropTypes.object,
    basic: PropTypes.bool,
    user: PropTypes.object.isRequired,
    mode: PropTypes.string,
    onChange: PropTypes.func.isRequired
  }

  static defaultProps = {
    form: {},
    basic: false,
    mode: 'new'
  }

  state = {
    form: {
      ...this.props.form,
      content: TEMPLATES[0].content
    }
  };

  componentDidMount() {
    const { child: wysiwyg } = FORM_ELEMENTS.elements.content;

    if (!isEmpty(this.props.form.content)) {
      wysiwyg.setValue(this.props.form.content);
    } else {
      wysiwyg.setValue(JSON.stringify(TEMPLATES[0].content));
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ form: nextProps.form });
  }

  onChangeTemplate(nextTemplate) {
    const { child: wysiwyg } = FORM_ELEMENTS.elements.content;
    const { content } = nextTemplate;

    wysiwyg.setValue(JSON.stringify(content));
  }

  render() {
    const { mode } = this.props;
    // Reset FORM_ELEMENTS
    FORM_ELEMENTS.elements = {};

    return (

        <fieldset className="c-field-container">
          {/* NAME */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.name = c; }}
            onChange={value => this.props.onChange({ name: value })}
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'name',
              label: 'Name',
              type: 'text',
              required: true,
              default: this.state.form.name
            }}
          >
            {Input}
          </Field>

          {/* SUMMARY */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.summary = c; }}
            onChange={value => this.props.onChange({ summary: value })}
            className="-fluid"
            properties={{
              name: 'summary',
              label: 'Summary',
              rows: '6',
              default: this.state.form.summary
            }}
          >
            {TextArea}
          </Field>

          {/* DESCRIPTION */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
            onChange={value => this.props.onChange({ description: value })}
            className="-fluid"
            properties={{
              name: 'description',
              label: 'Description',
              rows: '6',
              default: this.state.form.description
            }}
          >
            {TextArea}
          </Field>

          {/* THUMBNAIL */}

                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.photo = c; }}
                  onChange={(value) => {
                    if (value) {
                      this.props.onChange({ photo: value });
                    } else {
                      this.props.onChange({ photo: null });
                    }
                  }}
                  className="-fluid"
                  properties={{
                    name: 'photo',
                    label: 'Photo',
                    placeholder: 'Browse file',
                    baseUrl: process.env.STATIC_SERVER_URL,
                    default: this.state.form.photo
                  }}
                >
                  {FileImage}
                </Field>

          {/* PUBLISHED */}
          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.published = c; }}
              onChange={value => this.props.onChange({
                published: value.checked,
                private: !value.checked
              })}
              properties={{
                name: 'published',
                label: 'Do you want to set this dasboard as published?',
                value: 'published',
                title: 'Published',
                defaultChecked: this.props.form.published,
                checked: this.props.form.published
              }}
            >
              {Checkbox}
            </Field>
          }

          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.preproduction = c; }}
              onChange={value => this.props.onChange({ preproduction: value.checked })}
              properties={{
                name: 'preproduction',
                label: 'Do you want to set this dashboard as pre-production?',
                value: 'preproduction',
                title: 'Pre-production',
                defaultChecked: this.props.form.preproduction,
                checked: this.props.form.preproduction
              }}
            >
              {Checkbox}
            </Field>
          }

          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements.production = c; }}
              onChange={value => this.props.onChange({ production: value.checked })}
              properties={{
                name: 'production',
                label: 'Do you want to set this dashboard as production?',
                value: 'production',
                title: 'Production',
                defaultChecked: this.props.form.production,
                checked: this.props.form.production
              }}
            >
              {Checkbox}
            </Field>
          }

          {/* IS-HIGHLIGHTED */}
          {!this.props.basic &&
            <Field
              ref={(c) => { if (c) FORM_ELEMENTS.elements['is-highlighted'] = c; }}
              onChange={value => this.props.onChange({ 'is-highlighted': value.checked })}
              properties={{
                name: 'is-highlighted',
                label: 'Highlight in Dashboards gallery',
                value: 'is-highlighted',
                title: 'Is highlighted',
                defaultChecked: this.props.form['is-highlighted'],
                checked: this.props.form['is-highlighted']
              }}
            >
              {Checkbox}
            </Field>
          }
        </fieldset>

        <fieldset className="c-field-container">
          {/* templates */}
          {mode === 'new' && (
            <TemplateSelector onChange={this.onChangeTemplate} />)}

          {/* CONTENT */}
          <Field
            ref={(c) => { if (c) FORM_ELEMENTS.elements.content = c; }}
            onChange={value => this.props.onChange({ content: value })}
            validations={['required']}
            className="-fluid"
            properties={{
              name: 'content',
              label: 'Content',
              required: true,
              default: this.state.form.content,
              blocks: {
                widget: {
                  Component: WidgetBlock,
                  EditionComponent: WidgetBlockEdition,
                  icon: 'icon-widget',
                  label: 'Visualization',
                  renderer: 'modal'
                }
              },
              onUploadImage: files => new Promise((resolve, reject) => {
                const file = files[0];
                const formData = new FormData();
                formData.append('image', file);

                fetch(`${process.env.WRI_API_URL}/temporary_content_image`, {
                  method: 'POST',
                  headers: { Authorization: this.props.user.token },
                  body: formData
                })
                  .then(response => response.json())
                  .then((response) => {
                    resolve(response.url);
                  })
                  .catch((e) => {
                    toastr.error('Error', 'We couldn\'t upload the image. Try again');
                    reject(e);
                  });
              })
            }}
          >
            {Wysiwyg}
          </Field>
        </fieldset>

    );
  }
}

export default Step1;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import './style.css';
import '../../sbadmin2.css';
import Block from './../Block';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Grid } from 'react-bootstrap'
//import { Grid, Row, Col, Table } from 'react-bootstrap'
import Moment from 'react-moment';

class Home extends Component {
    apiBaseUrl = 'http://localhost:9000';

    constructor() {
        super();
        this.state={latestBlock:{}, blocks:[]};
    }

    componentDidMount() {
        this.getLatestBlocks(15);
    }

    getLatestBlocks(numberOfBlocks) {
        fetch(`${this.apiBaseUrl}/api/query/block/latest`, { mode: 'cors' })
            .then(result => result.json())
            .then(latestBlock => this.setState({ latestBlock }))
            .then(async _ => {
                for (let i = 0; i < numberOfBlocks; i++) {
                    var currentTime = new Date().getTime();
                    while (currentTime + 10 >= new Date().getTime()) {
                        //stupid 10ms delay to help enforce order
                    }
                    let blockNum = this.state.latestBlock.blockIndex - i;
                    //console.log(this.state.latestBlock);
                    let url = `${this.apiBaseUrl}/api/query/block/Index/${blockNum}`;
                    await fetch(url, { mode: 'cors' })
                        .then(result => result.json())
                        .then(block => this.setState({ blocks: this.state.blocks.concat(block) }));
                }
            });
    }

    render() {
        return (
            <Grid>

{this.state.latestBlock.coinTag} Block explorer

{this.state.latestBlock.blockIndex}

Block Height

                                <Link to={"/block/" +  this.state.latestBlock.blockIndex }> View latest </Link>

                {/*

$???.??m

Market Cap

                                View Details

?

Known Peers

                                View Details

{parseInt(this.state.latestBlock.blockIndex) + 6000000000 }

Total supply of {this.state.latestBlock.coinTag}

                                View Details

 */}

                            Current height: <Link to={"/block/" +  this.state.latestBlock.blockIndex }> {this.state.latestBlock.blockIndex}</Link>
                            <Route path="/block/:blockIndex"  component={Block}/>

                                Height
                                Age
                                Hash
                                Tx Count
                                Size

                            {this.state.blocks
                            .map(function(object, i){
                                return

                                    <Link to={"/block/" +  object.blockIndex }> {object.blockIndex}</Link>
                                    <Moment fromNow ago unix>{object.blockTime}</Moment>
                                    {object.blockHash}
                                    {object.transactionCount}
                                    {object.blockSize} bytes

                             } )}

            </Grid>
        );
    }
}

export default Home;<commit_msg>remove base url (as this is only for local)<commit_after>import React, { Component } from 'react';
import './style.css';
import '../../sbadmin2.css';
import Block from './../Block';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Grid } from 'react-bootstrap'
//import { Grid, Row, Col, Table } from 'react-bootstrap'
import Moment from 'react-moment';

class Home extends Component {
    apiBaseUrl = '';

    constructor() {
        super();
        this.state={latestBlock:{}, blocks:[]};
    }

    componentDidMount() {
        this.getLatestBlocks(15);
    }

    getLatestBlocks(numberOfBlocks) {
        fetch(`${this.apiBaseUrl}/api/query/block/latest`, { mode: 'cors' })
            .then(result => result.json())
            .then(latestBlock => this.setState({ latestBlock }))
            .then(async _ => {
                for (let i = 0; i < numberOfBlocks; i++) {
                    var currentTime = new Date().getTime();
                    while (currentTime + 10 >= new Date().getTime()) {
                        //stupid 10ms delay to help enforce order
                    }
                    let blockNum = this.state.latestBlock.blockIndex - i;
                    //console.log(this.state.latestBlock);
                    let url = `${this.apiBaseUrl}/api/query/block/Index/${blockNum}`;
                    await fetch(url, { mode: 'cors' })
                        .then(result => result.json())
                        .then(block => this.setState({ blocks: this.state.blocks.concat(block) }));
                }
            });
    }

    render() {
        return (
            <Grid>

{this.state.latestBlock.coinTag} Block explorer

{this.state.latestBlock.blockIndex}

Block Height

                                <Link to={"/block/" +  this.state.latestBlock.blockIndex }> View latest </Link>

                {/*

$???.??m

Market Cap

                                View Details

?

Known Peers

                                View Details

{parseInt(this.state.latestBlock.blockIndex) + 6000000000 }

Total supply of {this.state.latestBlock.coinTag}

                                View Details

 */}

                            Current height: <Link to={"/block/" +  this.state.latestBlock.blockIndex }> {this.state.latestBlock.blockIndex}</Link>
                            <Route path="/block/:blockIndex"  component={Block}/>

                                Height
                                Age
                                Hash
                                Tx Count
                                Size

                            {this.state.blocks
                            .map(function(object, i){
                                return

                                    <Link to={"/block/" +  object.blockIndex }> {object.blockIndex}</Link>
                                    <Moment fromNow ago unix>{object.blockTime}</Moment>
                                    {object.blockHash}
                                    {object.transactionCount}
                                    {object.blockSize} bytes

                             } )}

            </Grid>
        );
    }
}

export default Home;
<|endoftext|>


<commit_before>/*global define*/

/**
 * @author Joppe Aarts <joppe@apestaartje.info>
 * @copyright Apestaartje <http://apestaartje.info>
 */

define(
    [
        'underscore',
        'backbone',
        'lib/lang/class',
        'jquery'
    ],
    function (
        _,
        Backbone,
        Class,
        $
    ) {
        'use strict';

        var Connection;

        Connection = Class.createClass({
            /**
             * @param {string} csrf
             */
            setCsrf: function (csrf) {
                this.csrf = csrf;
            }
        });

        _.extend(Connection.prototype, Backbone.Events, {
            /**
             * @param {string} method
             * @param {Backbone,Model} model
             * @param {Object} options
             */
            sync: function (method, model, options) {
                var jqXHR,
                    success = options.success || function () {},
                    error = options.error || function () {},
                    url = model.url(),
                    data = {
                        csrf: this.csrf,
                        data: _.isFunction(model.getData) ? model.getData() : model.attributes
                    };

                if (this.csrf && method === 'read') {
                    url += '?csrf=' + this.csrf;
                }

                this.trigger('sync', jqXHR);

                jqXHR = $.ajax({
                    url: url,
                    dataType: 'json',
                    type: method === 'read' ? 'GET' : 'POST',
                    data: method === 'read' ? '' : data,
                    processData: false,
                    contentType: false
                }).done(_.bind(function (response) {
                    if (response.error) {
                        this.trigger('error', response);
                        error(response);
                    } else {
                        success(response.data ? response.data : response);
                    }
                }, this)).fail(_.bind(function (jqXHR, textStatus) {
                    this.trigger('error', textStatus);
                    error(textStatus);
                }, this));

                return jqXHR;
            }
        });

        return Connection;
    }
);<commit_msg>fix to add csrf token to form data<commit_after>/*global define*/

/**
 * @author Joppe Aarts <joppe@apestaartje.info>
 * @copyright Apestaartje <http://apestaartje.info>
 */

define(
    [
        'underscore',
        'backbone',
        'lib/lang/class',
        'jquery'
    ],
    function (
        _,
        Backbone,
        Class,
        $
    ) {
        'use strict';

        var Connection;

        Connection = Class.createClass({
            /**
             * @param {string} csrf
             */
            setCsrf: function (csrf) {
                this.csrf = csrf;
            }
        });

        _.extend(Connection.prototype, Backbone.Events, {
            /**
             * @param {string} method
             * @param {Backbone,Model} model
             * @param {Object} options
             */
            sync: function (method, model, options) {
                var jqXHR,
                    success = options.success || function () {},
                    error = options.error || function () {},
                    url = model.url(),
                    data = _.isFunction(model.getData) ? model.getData() : model.attributes;

                if (this.csrf) {
                    if (method === 'read') {
                        url += '?csrf=' + this.csrf;
                    } else {
                        data.append('csrf', this.csrf);
                    }
                }

                this.trigger('sync', jqXHR);

                jqXHR = $.ajax({
                    url: url,
                    type: method === 'read' ? 'GET' : 'POST',
                    data: method === 'read' ? '' : data,
                    processData: false,
                    contentType: false
                }).done(_.bind(function (response) {
                    if (response.error) {
                        this.trigger('error', response);
                        error(response);
                    } else {
                        success(response.data ? response.data : response);
                    }
                }, this)).fail(_.bind(function (jqXHR, textStatus) {
                    this.trigger('error', textStatus);
                    error(textStatus);
                }, this));

                return jqXHR;
            }
        });

        return Connection;
    }
);<|endoftext|>


<commit_before>var grid = grid || {};

grid.Cell = Backbone.Model.extend({
  defaults: function() {
    return {
      value: '',
      row: '',
      column: '',
      group: '',
      selected: false,
      possible: [1,2,3,4,5,6,7,8,9],
    }
  },
});

grid.CellCollection = Backbone.Collection.extend({
  model: grid.Cell
});

grid.CellView = Backbone.View.extend({
  tagName: 'td',
  template: _.template($('#cell-template').html()),
  className: function() {
    return "row_" + this.model.get('row') +
      " column_" + this.model.get('column') +
      " group_" + this.model.get('group');
  },
  events: {
    'click ': 'select',
  },

  initialize: function() {
    this.listenTo(this.model, 'change', this.render);
  },

  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    if (this.model.get('selected')) {
      this.$el.addClass('selected');
    } else {
      this.$el.removeClass('selected');
    }
    return this;
  },

  select: function() {
    App.cells.forEach(function(cell) {
      cell.set('selected', false)
    });
    this.model.set('selected', true);
  },
});

grid.AppView = Backbone.View.extend({
  el: '#gridapp',

  initialize: function() {
    var rowTemplate = _.template('<tr id="grid_row_<%= row %>">
');
    this.cells = new grid.CellCollection();
    var cells = this.cells;
    _.times(9, function(row) {
      $('#grid').append(rowTemplate({row: row}));
      _.times(9, function(column) {
        var cell = new grid.Cell({
          row: row,
          column: column,
          group: (Math.floor(column / 3)) + (Math.floor(row / 3) * 3),
        });
        cells.add(cell);
        var view = new grid.CellView({model: cell});
        $('#grid_row_' + row).append(view.render().el);
      });
    });
  },
});

$(function() {
  App = new grid.AppView();
  $('body').keydown(function(event) {
    // 49 is key code for 1, 57 is key code for 9
    if (event.keyCode > 57 || event.keyCode < 49) {
      return;
    }
    var key = event.keyCode - 48; // 48 is keycode for 0
    var selected = App.cells.findWhere({selected: true});
    if (selected) {
      selected.set({value: key});
    }
  });
});
<commit_msg>space can clear a cell now<commit_after>var grid = grid || {};

grid.Cell = Backbone.Model.extend({
  defaults: function() {
    return {
      value: '',
      row: '',
      column: '',
      group: '',
      selected: false,
      possible: [1,2,3,4,5,6,7,8,9],
    }
  },
});

grid.CellCollection = Backbone.Collection.extend({
  model: grid.Cell
});

grid.CellView = Backbone.View.extend({
  tagName: 'td',
  template: _.template($('#cell-template').html()),
  className: function() {
    return "row_" + this.model.get('row') +
      " column_" + this.model.get('column') +
      " group_" + this.model.get('group');
  },
  events: {
    'click ': 'select',
  },

  initialize: function() {
    this.listenTo(this.model, 'change', this.render);
  },

  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    if (this.model.get('selected')) {
      this.$el.addClass('selected');
    } else {
      this.$el.removeClass('selected');
    }
    return this;
  },

  select: function() {
    App.cells.forEach(function(cell) {
      cell.set('selected', false)
    });
    this.model.set('selected', true);
  },
});

grid.AppView = Backbone.View.extend({
  el: '#gridapp',

  initialize: function() {
    var rowTemplate = _.template('<tr id="grid_row_<%= row %>">
');
    this.cells = new grid.CellCollection();
    var cells = this.cells;
    _.times(9, function(row) {
      $('#grid').append(rowTemplate({row: row}));
      _.times(9, function(column) {
        var cell = new grid.Cell({
          row: row,
          column: column,
          group: (Math.floor(column / 3)) + (Math.floor(row / 3) * 3),
        });
        cells.add(cell);
        var view = new grid.CellView({model: cell});
        $('#grid_row_' + row).append(view.render().el);
      });
    });
  },
});

$(function() {
  App = new grid.AppView();
  $('body').keydown(function(event) {
    // 49 is key code for 1, 57 is key code for 9, 32 for space
    if (event.keyCode == 32 || (event.keyCode <= 57 && event.keyCode >= 49)) {
      var key = event.keyCode - 48; // 48 is keycode for 0
      if (event.keyCode == 32) {
        key = '';
      }
      var selected = App.cells.findWhere({selected: true});
      if (selected) {
        selected.set({enteredValue: key});
      }
    }
  });
});
<|endoftext|>