<commit_before>/* -----------------------------------------------------------------+ */
/* file:     prejs.js (Mozilla Firefox)                             + */
/* author:   Ypnose - http://ywstd.fr                               + */
/* -----------------------------------------------------------------+ */

/* Put this file in .mozilla/firefox/XXXXXXXX.foo/, when Firefox is
   turned off. It will "enforce" a few parameters. */

user_pref("accessibility.blockautorefresh", true);
user_pref("accessibility.force_disabled", 1);
user_pref("app.normandy.api_url", "");
user_pref("app.normandy.enabled", false);
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("app.update.auto", false);
user_pref("beacon.enabled", false);
user_pref("breakpad.reportURL", "");
user_pref("browser.cache.disk.parent_directory", "/tmp/firefox-cache");
user_pref("browser.cache.offline.capacity", 0);
user_pref("browser.cache.offline.enable", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.disableResetPrompt", true);
user_pref("browser.discovery.enabled", false);
user_pref("browser.download.manager.showWhenStarting", false);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.formfill.enable", false);
user_pref("browser.fullscreen.autohide", false);
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
user_pref("browser.newtabpage.activity-stream.feeds.section.highlights", false);
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
user_pref("browser.newtabpage.activity-stream.feeds.topsites", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeBookmarks", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeDownloads", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeVisited", false);
user_pref("browser.newtabpage.activity-stream.showSearch", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.pagethumbnails.capturing_disabled", true);
user_pref("browser.pocket.api", "");
user_pref("browser.pocket.enabled", false);
user_pref("browser.pocket.oAuthConsumerKey", "");
user_pref("browser.pocket.site", "");
user_pref("browser.search.defaultenginename", "DuckDuckGo");
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");
user_pref("browser.search.selectedEngine", "DuckDuckGo");
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.search.update", false);
user_pref("browser.selfsupport.url", "");
user_pref("browser.send_pings", false);
user_pref("browser.sessionstore.privacy_level", 2);
user_pref("browser.sessionstore.warnOnQuit", true);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.startup.page", 0);
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.urlbar.autocomplete.enabled", false);
user_pref("browser.urlbar.groupLabels.enabled", false);
user_pref("browser.urlbar.quicksuggest.enabled", false);
user_pref("browser.urlbar.speculativeConnect.enabled", false);
user_pref("browser.urlbar.suggest.bookmark", false);
user_pref("browser.urlbar.suggest.engines", false);
user_pref("browser.urlbar.suggest.history", false);
user_pref("browser.urlbar.suggest.openpage", false);
user_pref("browser.urlbar.suggest.topsites", false);
user_pref("browser.urlbar.trimURLs", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("device.sensors.ambientLight.enabled", false);
user_pref("device.sensors.enabled", false);
user_pref("device.sensors.motion.enabled", false);
user_pref("device.sensors.orientation.enabled", false);
user_pref("device.sensors.proximity.enabled", false);
user_pref("dom.battery.enabled", false);
user_pref("dom.disable_window_move_resize", true);
user_pref("dom.event.clipboardevents.enabled", false);
user_pref("dom.security.https_only_mode", true);
user_pref("dom.security.https_only_mode_ever_enabled", true);
/* user_pref("dom.storage.enabled", false); */
user_pref("experiments.activeExperiment", false);
user_pref("experiments.enabled", false);
user_pref("experiments.manifest.uri", "");
user_pref("experiments.supported", false);
user_pref("extensions.formautofill.addresses.enabled", false);
user_pref("extensions.formautofill.available", "off");
user_pref("extensions.formautofill.creditCards.enabled", false);
user_pref("extensions.formautofill.heuristics.enabled", false);
user_pref("extensions.getAddons.cache.enabled", false);
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.pocket.enabled", false);
user_pref("extensions.screenshots.upload-disabled", true);
user_pref("general.smoothScroll", false);
user_pref("geo.enabled", false);
user_pref("geo.provider.use_gpsd", false);
user_pref("geo.wifi.uri", "http://127.0.0.1");
user_pref("keyword.enabled", false)
user_pref("layers.acceleration.disabled", true);
user_pref("layout.spellcheckDefault", 0);
user_pref("loop.enabled", false);
user_pref("loop.server", "");
user_pref("media.autoplay.default", 2);
user_pref("media.eme.enabled", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.peerconnection.enabled", false);
user_pref("media.video_stats.enabled", false);
user_pref("network.IDN_show_punycode", true);
user_pref("network.allow-experiments", false);
user_pref("network.captive-portal-service.enabled", false);
user_pref("network.cookie.cookieBehavior", 2);
user_pref("network.cookie.lifetimePolicy", 0);
user_pref("network.dns.disableIPv6", true);
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);
user_pref("network.http.referer.spoofSource", true);
user_pref("network.http.speculative-parallel-limit", 0);
user_pref("network.predictor.enable-prefetch", false);
user_pref("network.predictor.enabled", false);
user_pref("network.prefetch-next", false);
user_pref("network.trr.mode", 5);
user_pref("places.history.enabled", false);
user_pref("plugin.state.flash", 1);
user_pref("privacy.clearOnShutdown.cache", true);
user_pref("privacy.clearOnShutdown.cookies", true);
user_pref("privacy.clearOnShutdown.downloads", true);
user_pref("privacy.clearOnShutdown.formdata", true);
user_pref("privacy.clearOnShutdown.history", true);
user_pref("privacy.clearOnShutdown.offlineApps", true);
user_pref("privacy.clearOnShutdown.sessions", true);
user_pref("privacy.clearOnShutdown.siteSettings", false);
user_pref("privacy.donottrackheader.enabled", true);
user_pref("privacy.donottrackheader.value", 1);
user_pref("privacy.sanitize.sanitizeOnShutdown", true);
user_pref("privacy.trackingprotection.cryptomining.enabled", true);
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.fingerprinting.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.userContext.enabled", true);
user_pref("privacy.userContext.ui.enabled", true);
user_pref("privacy.usercontext.about_newtab_segregation.enabled", true);
user_pref("security.ssl.disable_session_identifiers", true);
user_pref("services.sync.prefs.sync.browser.newtabpage.activity-stream.showSponsoredTopSite", false);
user_pref("signon.autofillForms", false);
user_pref("signon.management.page.breach-alerts.enabled", false);
user_pref("signon.rememberSignons", false);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.hybridContent.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.prompted", 2);
user_pref("toolkit.telemetry.rejected", true);
user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
user_pref("toolkit.telemetry.server", "");
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.unifiedIsOptIn", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("webgl.disabled", true);
user_pref("webgl.renderer-string-override", " ");
user_pref("webgl.vendor-string-override", " ");
<commit_msg>misc/firefox/prefs.js: disable unnecessary settings<commit_after>/* -----------------------------------------------------------------+ */
/* file:     prejs.js (Mozilla Firefox)                             + */
/* author:   Ypnose - http://ywstd.fr                               + */
/* -----------------------------------------------------------------+ */

/* Put this file in .mozilla/firefox/XXXXXXXX.foo/, when Firefox is
   turned off. It will "enforce" a few parameters. */

user_pref("accessibility.blockautorefresh", true);
user_pref("accessibility.force_disabled", 1);
user_pref("app.normandy.api_url", "");
user_pref("app.normandy.enabled", false);
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("app.update.auto", false);
user_pref("beacon.enabled", false);
user_pref("breakpad.reportURL", "");
user_pref("browser.cache.disk.parent_directory", "/tmp/firefox-cache");
user_pref("browser.cache.offline.capacity", 0);
user_pref("browser.cache.offline.enable", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);
user_pref("browser.crashReports.unsubmittedCheck.enabled", false);
user_pref("browser.disableResetPrompt", true);
user_pref("browser.discovery.enabled", false);
user_pref("browser.download.manager.showWhenStarting", false);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.formfill.enable", false);
user_pref("browser.fullscreen.autohide", false);
user_pref("browser.newtab.preload", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
user_pref("browser.newtabpage.activity-stream.feeds.section.highlights", false);
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
user_pref("browser.newtabpage.activity-stream.feeds.topsites", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeBookmarks", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeDownloads", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includeVisited", false);
user_pref("browser.newtabpage.activity-stream.showSearch", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtabpage.enhanced", false);
user_pref("browser.newtabpage.introShown", true);
user_pref("browser.pagethumbnails.capturing_disabled", true);
user_pref("browser.pocket.api", "");
user_pref("browser.pocket.enabled", false);
user_pref("browser.pocket.oAuthConsumerKey", "");
user_pref("browser.pocket.site", "");
user_pref("browser.search.defaultenginename", "DuckDuckGo");
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");
user_pref("browser.search.selectedEngine", "DuckDuckGo");
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.search.update", false);
user_pref("browser.selfsupport.url", "");
user_pref("browser.send_pings", false);
user_pref("browser.sessionstore.privacy_level", 2);
user_pref("browser.sessionstore.warnOnQuit", true);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.slowStartup.notificationDisabled", true);
user_pref("browser.startup.homepage", "about:blank");
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.startup.page", 0);
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.urlbar.autocomplete.enabled", false);
user_pref("browser.urlbar.groupLabels.enabled", false);
user_pref("browser.urlbar.quicksuggest.enabled", false);
user_pref("browser.urlbar.speculativeConnect.enabled", false);
user_pref("browser.urlbar.suggest.bookmark", false);
user_pref("browser.urlbar.suggest.engines", false);
user_pref("browser.urlbar.suggest.history", false);
user_pref("browser.urlbar.suggest.openpage", false);
user_pref("browser.urlbar.suggest.topsites", false);
user_pref("browser.urlbar.trimURLs", false);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("device.sensors.ambientLight.enabled", false);
user_pref("device.sensors.enabled", false);
user_pref("device.sensors.motion.enabled", false);
user_pref("device.sensors.orientation.enabled", false);
user_pref("device.sensors.proximity.enabled", false);
user_pref("dom.battery.enabled", false);
user_pref("dom.disable_window_move_resize", true);
user_pref("dom.event.clipboardevents.enabled", false);
user_pref("dom.security.https_only_mode", true);
user_pref("dom.security.https_only_mode_ever_enabled", true);
/* user_pref("dom.storage.enabled", false); */
user_pref("experiments.activeExperiment", false);
user_pref("experiments.enabled", false);
user_pref("experiments.manifest.uri", "");
user_pref("experiments.supported", false);
user_pref("extensions.formautofill.addresses.enabled", false);
user_pref("extensions.formautofill.available", "off");
user_pref("extensions.formautofill.creditCards.enabled", false);
user_pref("extensions.formautofill.heuristics.enabled", false);
user_pref("extensions.getAddons.cache.enabled", false);
user_pref("extensions.getAddons.showPane", false);
user_pref("extensions.pocket.enabled", false);
user_pref("extensions.screenshots.upload-disabled", true);
user_pref("general.smoothScroll", false);
user_pref("geo.enabled", false);
user_pref("geo.provider.use_gpsd", false);
user_pref("geo.wifi.uri", "http://127.0.0.1");
user_pref("keyword.enabled", false)
user_pref("layers.acceleration.disabled", true);
user_pref("layout.spellcheckDefault", 0);
user_pref("loop.enabled", false);
user_pref("loop.server", "");
user_pref("media.autoplay.default", 2);
user_pref("media.eme.enabled", false);
user_pref("media.gmp-widevinecdm.enabled", false);
user_pref("media.navigator.enabled", false);
user_pref("media.peerconnection.enabled", false);
user_pref("media.video_stats.enabled", false);
user_pref("network.IDN_show_punycode", true);
user_pref("network.allow-experiments", false);
user_pref("network.captive-portal-service.enabled", false);
user_pref("network.cookie.cookieBehavior", 2);
user_pref("network.cookie.lifetimePolicy", 2);
user_pref("network.dns.disableIPv6", true);
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true);
user_pref("network.http.referer.spoofSource", true);
user_pref("network.http.speculative-parallel-limit", 0);
user_pref("network.predictor.enable-prefetch", false);
user_pref("network.predictor.enabled", false);
user_pref("network.prefetch-next", false);
user_pref("network.trr.mode", 5);
user_pref("places.history.enabled", false);
user_pref("plugin.state.flash", 1);
user_pref("privacy.clearOnShutdown.cache", true);
user_pref("privacy.clearOnShutdown.cookies", true);
user_pref("privacy.clearOnShutdown.downloads", true);
user_pref("privacy.clearOnShutdown.formdata", true);
user_pref("privacy.clearOnShutdown.history", true);
user_pref("privacy.clearOnShutdown.offlineApps", true);
user_pref("privacy.clearOnShutdown.sessions", true);
user_pref("privacy.clearOnShutdown.siteSettings", false);
user_pref("privacy.donottrackheader.enabled", true);
user_pref("privacy.donottrackheader.value", 1);
user_pref("privacy.sanitize.sanitizeOnShutdown", true);
user_pref("privacy.trackingprotection.cryptomining.enabled", true);
user_pref("privacy.trackingprotection.enabled", true);
user_pref("privacy.trackingprotection.fingerprinting.enabled", true);
user_pref("privacy.trackingprotection.pbmode.enabled", true);
user_pref("privacy.userContext.enabled", true);
user_pref("privacy.userContext.ui.enabled", true);
user_pref("privacy.usercontext.about_newtab_segregation.enabled", true);
user_pref("security.ssl.disable_session_identifiers", true);
user_pref("services.sync.prefs.sync.browser.newtabpage.activity-stream.showSponsoredTopSite", false);
user_pref("signon.autofillForms", false);
user_pref("signon.generation.enabled", false);
user_pref("signon.management.page.breach-alerts.enabled", false);
user_pref("signon.rememberSignons", false);
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.cachedClientID", "");
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.hybridContent.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.prompted", 2);
user_pref("toolkit.telemetry.rejected", true);
user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
user_pref("toolkit.telemetry.server", "");
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.unifiedIsOptIn", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("webgl.disabled", true);
user_pref("webgl.renderer-string-override", " ");
user_pref("webgl.vendor-string-override", " ");
<|endoftext|>


<commit_before>minStepsToOne.js
<commit_msg>add desc<commit_after>/*
 *    Minimum Steps to One
 *
 *     Given a positive integer, you can perform any combination of these 3 steps:
 *      1.) Subtract 1 from it.
 *      2.) If its divisible by 2, divide by 2.
 *      3.) If its divisible by 3, divide by 3.
 *
 *     Find the minimum number of steps that it takes get from N to 1
 *
 *  Input: Positive Integer N
 *  Output:Integer
 */
<|endoftext|>


<commit_before>import {
  isPlainObject
}
  from 'uni-shared'

import {
  parseWebviewStyle
} from './parser/webview-style-parser'

import {
  publish
} from '../../bridge'

let id = 2

const WEBVIEW_LISTENERS = {
  'pullToRefresh': 'onPullDownRefresh',
  'titleNViewSearchInputChanged': 'onNavigationBarSearchInputChanged',
  'titleNViewSearchInputConfirmed': 'onNavigationBarSearchInputConfirmed',
  'titleNViewSearchInputClicked': 'onNavigationBarSearchInputClicked'
}

export function createWebview (path, routeOptions) {
  const webviewId = id++
  const webviewStyle = parseWebviewStyle(
    webviewId,
    path,
    routeOptions
  )
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] createWebview`, webviewId, path, webviewStyle)
  }
  const webview = plus.webview.create('', String(webviewId), webviewStyle)

  return webview
}

export function initWebview (webview, routeOptions) {
  if (isPlainObject(routeOptions)) {
    const webviewStyle = parseWebviewStyle(
      parseInt(webview.id),
      '',
      routeOptions
    )
    if (process.env.NODE_ENV !== 'production') {
      console.log(`[uni-app] updateWebview`, webviewStyle)
    }

    webview.setStyle(webviewStyle)
  }

  const {
    on,
    emit
  } = UniServiceJSBridge

  // TODO subNVues
  Object.keys(WEBVIEW_LISTENERS).forEach(name => {
    webview.addEventListener(name, (e) => {
      emit(WEBVIEW_LISTENERS[name], e, parseInt(webview.id))
    })
  })

  webview.addEventListener('resize', ({
    width,
    height
  }) => {
    const res = {
      size: {
        windowWidth: Math.ceil(width),
        windowHeight: Math.ceil(height)
      }
    }
    publish('onViewDidResize', res)
    emit('onResize', res, parseInt(webview.id))
  })

  // TODO 应该结束之前未完成的下拉刷新
  on(webview.id + '.startPullDownRefresh', () => {
    webview.beginPullToRefresh()
  })

  on(webview.id + '.stopPullDownRefresh', () => {
    webview.endPullToRefresh()
  })

  return webview
}
<commit_msg>fix: "renderer": "native" iOS 侧滑关闭后无法触发上一个页面的 onShow<commit_after>import {
  isPlainObject
}
  from 'uni-shared'

import {
  parseWebviewStyle
} from './parser/webview-style-parser'

import {
  publish,
  setStatusBarStyle
} from '../../bridge'

import {
  getLastWebview
} from '../../api/util'

let id = 2

const WEBVIEW_LISTENERS = {
  'pullToRefresh': 'onPullDownRefresh',
  'titleNViewSearchInputChanged': 'onNavigationBarSearchInputChanged',
  'titleNViewSearchInputConfirmed': 'onNavigationBarSearchInputConfirmed',
  'titleNViewSearchInputClicked': 'onNavigationBarSearchInputClicked'
}

export function createWebview (path, routeOptions) {
  const webviewId = id++
  const webviewStyle = parseWebviewStyle(
    webviewId,
    path,
    routeOptions
  )
  if (process.env.NODE_ENV !== 'production') {
    console.log(`[uni-app] createWebview`, webviewId, path, webviewStyle)
  }
  const webview = plus.webview.create('', String(webviewId), webviewStyle)

  return webview
}

export function initWebview (webview, routeOptions) {
  if (isPlainObject(routeOptions)) {
    const webviewStyle = parseWebviewStyle(
      parseInt(webview.id),
      '',
      routeOptions
    )
    if (process.env.NODE_ENV !== 'production') {
      console.log(`[uni-app] updateWebview`, webviewStyle)
    }

    webview.setStyle(webviewStyle)
  }

  const {
    on,
    emit
  } = UniServiceJSBridge

  // TODO subNVues
  Object.keys(WEBVIEW_LISTENERS).forEach(name => {
    webview.addEventListener(name, (e) => {
      emit(WEBVIEW_LISTENERS[name], e, parseInt(webview.id))
    })
  })

  webview.addEventListener('resize', ({
    width,
    height
  }) => {
    const res = {
      size: {
        windowWidth: Math.ceil(width),
        windowHeight: Math.ceil(height)
      }
    }
    publish('onViewDidResize', res)
    emit('onResize', res, parseInt(webview.id))
  })

  webview.addEventListener('popGesture', e => {
    if (e.type === 'start') {
      // 设置下一个页面的 statusBarStyle
      const pages = getCurrentPages()
      const page = pages[pages.length - 2]
      const statusBarStyle = page && page.$page.meta.statusBarStyle
      statusBarStyle && setStatusBarStyle(statusBarStyle)
    } else if (e.type === 'end' && !e.result) {
      // 拖拽未完成,设置为当前状态栏前景色
      setStatusBarStyle()
    } else if (e.type === 'end' && e.result) {
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      page && page.$remove()

      setStatusBarStyle()

      UniServiceJSBridge.emit('onAppRoute', {
        type: 'navigateBack'
      })
    }
  })

  // TODO 应该结束之前未完成的下拉刷新
  on(webview.id + '.startPullDownRefresh', () => {
    webview.beginPullToRefresh()
  })

  on(webview.id + '.stopPullDownRefresh', () => {
    webview.endPullToRefresh()
  })

  return webview
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { observer } from 'mobx-react';
import { browserHistory } from 'react-router';

import UserContext from './Layout/UserContext';
import Menu from './Layout/Menu';

@observer
class Layout extends React.Component {
  constructor() {
    super();

    this.state = {
      enlarged: false,
      showSearch: false,
      searchValue: "",
      searchCallback: null
    };

    browserHistory.listen(() => {
      this.setState({ showSearch: false });
    });
  }

  getChildContext() {
    return {
      toggleSearch: this.toggleSearch.bind(this),
      searchValue: this.state.searchValue
    };
  }

  toggleEnlargedMode() {
    this.setState({ enlarged: !this.state.enlarged });
  }

  toggleSearch(callback) {
    this.setState({
      showSearch: !this.state.showSearch,
      searchCallback: callback
    });
  }

  handleSearchChange(event) {
    this.setState({ searchValue: event.target.value });
    this.state.searchCallback(event.target.value);
  }

  render() {
    document.body.className = this.context.appState.theme;
    let searchField;

    if (this.state.showSearch) {
      searchField = (<input type="text" className="header__search"
        placeholder="Filter..."
        value={this.state.searchValue}
        onChange={this.handleSearchChange.bind(this)} />);
    }

    return (

          <Menu />
          {searchField}

            <UserContext />

        {this.props.children}

    );
  }
}

Layout.propTypes = {
  children: PropTypes.object
};

Layout.contextTypes = {
  appState: PropTypes.object
};

Layout.childContextTypes = {
    toggleSearch: PropTypes.func,
    searchValue: PropTypes.string
};

export default Layout;
<commit_msg>Only show enlarged when logged in<commit_after>import React, { PropTypes } from 'react';
import { observer } from 'mobx-react';
import { browserHistory } from 'react-router';

import UserContext from './Layout/UserContext';
import Menu from './Layout/Menu';

@observer
class Layout extends React.Component {
  constructor() {
    super();

    this.state = {
      enlarged: false,
      showSearch: false,
      searchValue: "",
      searchCallback: null
    };

    browserHistory.listen(() => {
      this.setState({ showSearch: false });
    });
  }

  getChildContext() {
    return {
      toggleSearch: this.toggleSearch.bind(this),
      searchValue: this.state.searchValue
    };
  }

  toggleEnlargedMode() {
    this.setState({ enlarged: !this.state.enlarged });
  }

  toggleSearch(callback) {
    this.setState({
      showSearch: !this.state.showSearch,
      searchCallback: callback
    });
  }

  handleSearchChange(event) {
    this.setState({ searchValue: event.target.value });
    this.state.searchCallback(event.target.value);
  }

  render() {
    document.body.className = this.context.appState.theme;
    let searchField;
    let enlarged;

    if (this.state.showSearch) {
      searchField = (<input type="text" className="header__search"
        placeholder="Filter..."
        value={this.state.searchValue}
        onChange={this.handleSearchChange.bind(this)} />);
    }

    if (this.context.appState.isAuthenticated) {
      enlarged = (

        <UserContext />

);
    }

    return (

          <Menu />
          {searchField}
          {enlarged}

        {this.props.children}

    );
  }
}

Layout.propTypes = {
  children: PropTypes.object
};

Layout.contextTypes = {
  appState: PropTypes.object
};

Layout.childContextTypes = {
    toggleSearch: PropTypes.func,
    searchValue: PropTypes.string
};

export default Layout;
<|endoftext|>


<commit_before>module.exports = function (config) {
  const options =
    {
      files: [
        'src/**/*.ts'
      ],

      frameworks: [
        'mocha',
        'karma-typescript',
      ],

      preprocessors: {
        '**/*.ts': ['karma-typescript'],
      },

      reporters: [],

      customLaunchers: {
        Chrome_travis_ci: {
          base: 'Chrome',
          flags: ['--no-sandbox']
        }
      },

      browsers: [],

      karmaTypescriptConfig: {
        tsconfig: 'tsconfig.json',
        reports: {
          "html": "coverage",
          "lcovonly": "coverage",
        }
      },

      singleRun: true,
    }

  if (process.env.UNIT)
    options.browsers.push('Chrome')

  if (process.env.TRAVIS)
    options.browsers.push('Chrome_travis_ci', 'Firefox')

  if (options.browsers.length === 0)
    options.browsers.push('Chrome', 'Firefox')

  if (options.reporters.length === 0)
    options.reporters.push('progress', 'karma-typescript')

  config.set(options);
}
<commit_msg>chore(karma): add configs for xhr<commit_after>module.exports = function (config) {
  const options =
    {
      files: [
        'src/**/*.ts',
        { pattern: 'src/__test__/locales/**/*.json*', watched: true, included: false, served: true },
      ],

      proxies: {
        '/locales': 'http://localhost:8081/base/src/__test__/locales'
      },

      frameworks: [
        'mocha',
        'karma-typescript',
      ],

      preprocessors: {
        '**/*.ts': ['karma-typescript'],
      },

      reporters: [],

      customLaunchers: {
        Chrome_travis_ci: {
          base: 'Chrome',
          flags: ['--no-sandbox']
        }
      },

      browsers: [],

      karmaTypescriptConfig: {
        tsconfig: 'tsconfig.json',
        reports: {
          "html": "coverage",
          "lcovonly": "coverage",
        }
      },

      singleRun: true,
    }

  if (process.env.UNIT)
    options.browsers.push('Chrome')

  if (process.env.TRAVIS)
    options.browsers.push('Chrome_travis_ci', 'Firefox')

  if (options.browsers.length === 0)
    options.browsers.push('Chrome', 'Firefox')

  if (options.reporters.length === 0)
    options.reporters.push('progress', 'karma-typescript')

  config.set(options);
}
<|endoftext|>


<commit_before>import capitalize from 'capitalize';
import {compose, identity, keys, map, path, tap} from 'ramda';
import React from 'react';
import {connect} from 'react-redux';
import {updateArpeggiatorIsOn,
        updateBpm,
        updateMicrophoneIsOn,
        updateSelectedRootNote,
        updateSelectedScale,
        updateSelectedPattern} from '../../actions';
import Navigation from '../organisms/Navigation';
import CheckboxSelector from '../molecules/CheckboxSelector';
import RangeSelector from '../molecules/RangeSelector';
import noteNameFromPitch from '../../audioHelpers/noteNameFromPitch';
import Selector from '../molecules/Selector';
import ArpeggiatorSelector from '../molecules/ArpeggiatorSelector';
import switchMicrophone from '../../switchMicrophone';
import {
  eventValuePath,
  eventCheckedPath,
} from '../../tools/paths'

const minBpm = 32;

export default connect(identity)(({arpeggiator: {arpeggiatorIsOn, patterns, selectedPattern},
                                   bpm,
                                   dispatch,
                                   microphone,
                                   rootNote,
                                   scale: {scaleName, scales}}) =>

    <Navigation />

Settings

      <RangeSelector output={bpm}
                     max="512"
                     min={minBpm}
                     onChange={compose(dispatch, updateBpm, Number, path(['target', 'value']))}
                     text="BPM"
                     value={bpm} />
     <RangeSelector max="24"
                    min="-36"
                    onChange={compose(dispatch, updateSelectedRootNote, Number, eventValuePath)}
                    output={noteNameFromPitch(rootNote)}
                    text="Root Note"
                    value={rootNote} />
      <Selector defaultValue={scaleName}
                handleChange={compose(dispatch, updateSelectedScale, eventValuePath)}
                label="Scale"
                options={map(value => ({text: capitalize.words(value),
                                        value}), keys(scales))} />
      <CheckboxSelector checked={microphone.isOn}
                        disabled={!microphone.isAvailable}
                        onChange={compose(dispatch, updateMicrophoneIsOn, tap(switchMicrophone(dispatch)), eventCheckedPath)}
                        text="Microphone" />
      <ArpeggiatorSelector arpeggiatorIsOn={arpeggiatorIsOn}
                           dispatch={dispatch}
                           patterns={patterns}
                           selectedPattern={selectedPattern}
                           handleArpeggiatorIsOnChange={compose(dispatch, updateArpeggiatorIsOn, eventCheckedPath)}
                           handlePatternSelect={compose(dispatch, updateSelectedPattern, eventValuePath)} />

);
<commit_msg>style(Settings)<commit_after>import capitalize from 'capitalize'
import {compose, identity, keys, map, tap} from 'ramda'
import React from 'react'
import {connect} from 'react-redux'
import {updateArpeggiatorIsOn,
        updateBpm,
        updateMicrophoneIsOn,
        updateSelectedRootNote,
        updateSelectedScale,
        updateSelectedPattern} from '../../actions'
import Navigation from '../organisms/Navigation'
import CheckboxSelector from '../molecules/CheckboxSelector'
import RangeSelector from '../molecules/RangeSelector'
import noteNameFromPitch from '../../audioHelpers/noteNameFromPitch'
import Selector from '../molecules/Selector'
import ArpeggiatorSelector from '../molecules/ArpeggiatorSelector'
import switchMicrophone from '../../switchMicrophone'
import {
  eventValuePath,
  eventCheckedPath,
} from '../../tools/paths'

const minBpm = 32

export default connect(identity)(({
  arpeggiator: {arpeggiatorIsOn, patterns, selectedPattern},
  bpm,
  dispatch,
  microphone,
  rootNote,
  scale: {scaleName, scales},
}) =>

    <Navigation />

Settings

      <RangeSelector
        max="512"
        min={minBpm}
        onChange={compose(
          dispatch,
          updateBpm,
          Number,
          eventValuePath
        )}
        output={bpm}
        text="BPM"
        value={bpm}
      />
      <RangeSelector
        max="24"
        min="-36"
        onChange={compose(
          dispatch,
          updateSelectedRootNote,
          Number,
          eventValuePath
        )}
        output={noteNameFromPitch(rootNote)}
        text="Root Note"
        value={rootNote}
      />
      <Selector
        defaultValue={scaleName}
        handleChange={compose(dispatch, updateSelectedScale, eventValuePath)}
        label="Scale"
        options={map(
          value => ({text: capitalize.words(value), value}),
          keys(scales)
        )} />
      <CheckboxSelector
        checked={microphone.isOn}
        disabled={!microphone.isAvailable}
        onChange={compose(
          dispatch,
          updateMicrophoneIsOn,
          tap(switchMicrophone(dispatch)),
          eventCheckedPath
        )}
        text="Microphone"
      />
      <ArpeggiatorSelector
        arpeggiatorIsOn={arpeggiatorIsOn}
        dispatch={dispatch}
        patterns={patterns}
        selectedPattern={selectedPattern}
        handleArpeggiatorIsOnChange={compose(
          dispatch,
          updateArpeggiatorIsOn,
          eventCheckedPath
        )}
        handlePatternSelect={compose(
          dispatch,
          updateSelectedPattern,
          eventValuePath
        )}
      />

)
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true, newcap: true */
/*global window, $, Backbone, document, arangoCollection, arangoHelper, dashboardView */

$(document).ready(function() {

  window.Router = Backbone.Router.extend({
    routes: {
      ""                                    : "dashboard",
      "collection/:colid"                   : "collection",
      "collections"                         : "collections",
      "collectionInfo/:colid"               : "collectionInfo",
      "new"                                 : "newCollection",
      "login"                               : "login",
      "collection/:colid/documents/:pageid" : "documents",
      "collection/:colid/:docid"            : "document",
      "collection/:colid/:docid/source"     : "source",
      "shell"                               : "shell",
      "query"                               : "query",
      "logs"                                : "logs",
      "about"                               : "about",
      "api"                                 : "api",
      "databases"                           : "databases",
      "application/installed/:key"          : "applicationEdit",
      "application/available/:key"          : "applicationInstall",
      "applications/installed"              : "applicationsInstalled",
      "applications/available"              : "applicationsAvailable",
      "applications"                        : "applications",
      "application/documentation/:key"      : "appDocumentation",
      "graph"                               : "graph"
    },

    initialize: function () {
      window.activeSession = new window.ArangoSession();

      window.arangoDatabase = new window.ArangoDatabase();

      window.arangoCollectionsStore = new window.arangoCollections();
      window.arangoDocumentsStore = new window.arangoDocuments();
      window.arangoDocumentStore = new window.arangoDocument();

      window.collectionsView = new window.collectionsView({
        collection: window.arangoCollectionsStore
      });
      window.arangoCollectionsStore.fetch();

      window.collectionView = new window.collectionView({
        model: arangoCollection
      });

      window.collectionInfoView = new window.collectionInfoView({
        model: arangoCollection
      });

      window.documentsView = new window.documentsView({
        collection: window.arangoDocuments
      });
      window.documentView = new window.documentView({
        collection: window.arangoDocument
      });
      window.documentSourceView = new window.documentSourceView({
        collection: window.arangoDocument
      });

      window.arangoLogsStore = new window.arangoLogs();
      window.arangoLogsStore.fetch({
        success: function () {
          window.logsView = new window.logsView({
            collection: window.arangoLogsStore
          });
        }
      });

      this.footerView = new window.footerView();
      this.naviView = new window.navigationView();
      this.footerView.render();
      this.naviView.render();
      this.graphView = new window.graphView({
        collection: window.arangoCollectionsStore
      });
    },

    logsAllowed: function () {
      if ($('#databaseName').html() !== '_system') {
        return false;
      }
      return true;
    },

    checkSession: function () {
      if (window.activeSession.models.length === 0) {
        window.App.navigate("login", {trigger: true});
        return false;
      }
      return true;
    },
    login: function () {
      if (!this.loginView) {
        this.loginView = new window.loginView({
          collection: window.activeSession
        });
      }
      this.loginView.render();
      this.naviView.selectMenuItem('');
    },
    collections: function() {
      var naviView = this.naviView;

      //DEV
      //var currentSession = this.checkSession();
      //if (currentSession === false) {
      //  return;
      //}

      window.arangoCollectionsStore.fetch({
        success: function () {
          window.collectionsView.render();
          naviView.selectMenuItem('collections-menu');
        }
      });
    },

    collection: function(colid) {
      window.collectionView.options.colId = colid;
      window.collectionView.render();
    },
    collectionInfo: function(colid) {
      window.collectionInfoView.options.colId = colid;
      window.collectionInfoView.render();
    },
    newCollection: function() {
      if (!this.newCollectionView) {
        this.newCollectionView = new window.newCollectionView({});
      }
      this.newCollectionView.render();
    },

    documents: function(colid, pageid) {
      if (!window.documentsView) {
        window.documentsView.initTable(colid, pageid);
      }
      window.documentsView.collectionID = colid;
      var type = arangoHelper.collectionApiType(colid);
      window.documentsView.colid = colid;
      window.documentsView.pageid = pageid;
      window.documentsView.type = type;
      window.documentsView.render();
      window.arangoDocumentsStore.getDocuments(colid, pageid);
    },

    document: function(colid, docid) {
      if (!window.documentView) {
        window.documentView.initTable();
      }
      window.documentView.colid = colid;
      window.documentView.docid = docid;
      window.documentView.render();
      var type = arangoHelper.collectionApiType(colid);
      window.documentView.type = type;
      window.documentView.typeCheck(type);
    },

    source: function(colid, docid) {
      window.documentSourceView.render();
      window.documentSourceView.colid = colid;
      window.documentSourceView.docid = docid;
      var type = arangoHelper.collectionApiType(colid);
      window.documentSourceView.type = type;
      window.documentSourceView.typeCheck(type);
    },

    shell: function() {
      if (!this.shellView) {
        this.shellView = new window.shellView();
      }
      this.shellView.render();
      this.naviView.selectMenuItem('shell-menu');
    },

    query: function() {
      if (!this.queryView) {
        this.queryView = new window.queryView();
      }
      this.queryView.render();
      this.naviView.selectMenuItem('query-menu');
    },

    api: function() {
      if (!this.apiView) {
        this.apiView = new window.apiView();
      }
      this.apiView.render();
      this.naviView.selectMenuItem('api-menu');
    },

    databases: function() {
      if (!this.databaseView) {
        this.databaseView = new window.databaseView({
          collection: arangoDatabase
        });
      }
      this.databaseView.render();
      this.naviView.selectMenuItem('database-menu');
    },

    about: function() {
      if (!this.aboutView) {
        this.aboutView = new window.aboutView();
      }
      this.aboutView.render();
      this.naviView.selectMenuItem('about-menu');
    },

    logs: function() {
      if (! this.logsAllowed()) {
        return;
      }

      var self = this;
      window.arangoLogsStore.fetch({
        success: function () {
          window.logsView.render();
          $('#logNav a[href="#all"]').tab('show');
          window.logsView.initLogTables();
          window.logsView.drawTable();
          $('#all-switch').click();
        }
      });
      this.naviView.selectMenuItem('logs-menu');
    },

    dashboard: function() {
      this.naviView.selectMenuItem('dashboard-menu');
      if (this.statisticsDescription === undefined) {
        this.statisticsDescription = new window.StatisticsDescription();
        this.statisticsDescription.fetch({
          async:false
        });
      }
      if (this.statistics === undefined) {
        this.statisticsCollection = new window.StatisticsCollection();
      }
      if (this.dashboardView === undefined) {
        this.dashboardView = new dashboardView({
          collection: this.statisticsCollection,
          description: this.statisticsDescription
        });
         }
        this.dashboardView.render();
    },

    graph: function() {
      var self = this;
      window.arangoCollectionsStore.fetch({
        success: function () {
          self.graphView.render();
          self.naviView.selectMenuItem('graphviewer-menu');
        }
      });
    },

    applications: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsView === undefined) {
        this.applicationsView = new window.ApplicationsView({
          collection: this.foxxList
        });
      }
      this.applicationsView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationsAvailable: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsInstalledView === undefined) {
        this.applicationsInstalledView = new window.FoxxInstalledListView({
          collection: this.foxxList
        });
      }
      this.applicationsInstalledView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationsInstalled: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsActiveView === undefined) {
        this.applicationsActiveView = new window.FoxxActiveListView({
          collection: this.foxxList
        });
      }
      this.applicationsActiveView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationEdit: function(appkey) {
      if (this.foxxList === undefined) {
        var self = this;
        this.foxxList = new window.FoxxCollection();
        this.foxxList.fetch({
          success: function() {
            var editAppView = new window.foxxEditView({
              model: self.foxxList.findWhere({_key: appkey})
            });
            editAppView.render();
          }
        });
      } else {
        var editAppView = new window.foxxEditView({model: this.foxxList.findWhere({_key: appkey})});
        editAppView.render();
      }
    },

    applicationInstall: function(appkey) {
      if (this.foxxList === undefined) {
        var self = this;
        this.foxxList = new window.FoxxCollection();
        this.foxxList.fetch({
          success: function() {
            var installAppView = new window.foxxMountView({
              model: self.foxxList.findWhere({_key: appkey})
            });
            installAppView.render();
          }
        });
      } else {
        var installAppView = new window.foxxMountView({
          model: this.foxxList.findWhere({_key: appkey})
        });
        installAppView.render();
      }

    },

    appDocumentation: function(key) {
      var docuView = new window.AppDocumentationView({key: key});
      docuView.render();
      this.naviView.selectMenuItem('applications-menu');
    }

  });

  window.App = new window.Router();
  Backbone.history.start();

});

<commit_msg>jslint<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true, newcap: true */
/*global window, $, Backbone, document, arangoCollection,arangoHelper,dashboardView,arangoDatabase*/

$(document).ready(function() {

  window.Router = Backbone.Router.extend({
    routes: {
      ""                                    : "dashboard",
      "collection/:colid"                   : "collection",
      "collections"                         : "collections",
      "collectionInfo/:colid"               : "collectionInfo",
      "new"                                 : "newCollection",
      "login"                               : "login",
      "collection/:colid/documents/:pageid" : "documents",
      "collection/:colid/:docid"            : "document",
      "collection/:colid/:docid/source"     : "source",
      "shell"                               : "shell",
      "query"                               : "query",
      "logs"                                : "logs",
      "about"                               : "about",
      "api"                                 : "api",
      "databases"                           : "databases",
      "application/installed/:key"          : "applicationEdit",
      "application/available/:key"          : "applicationInstall",
      "applications/installed"              : "applicationsInstalled",
      "applications/available"              : "applicationsAvailable",
      "applications"                        : "applications",
      "application/documentation/:key"      : "appDocumentation",
      "graph"                               : "graph"
    },

    initialize: function () {
      window.activeSession = new window.ArangoSession();

      window.arangoDatabase = new window.ArangoDatabase();

      window.arangoCollectionsStore = new window.arangoCollections();
      window.arangoDocumentsStore = new window.arangoDocuments();
      window.arangoDocumentStore = new window.arangoDocument();

      window.collectionsView = new window.collectionsView({
        collection: window.arangoCollectionsStore
      });
      window.arangoCollectionsStore.fetch();

      window.collectionView = new window.collectionView({
        model: arangoCollection
      });

      window.collectionInfoView = new window.collectionInfoView({
        model: arangoCollection
      });

      window.documentsView = new window.documentsView({
        collection: window.arangoDocuments
      });
      window.documentView = new window.documentView({
        collection: window.arangoDocument
      });
      window.documentSourceView = new window.documentSourceView({
        collection: window.arangoDocument
      });

      window.arangoLogsStore = new window.arangoLogs();
      window.arangoLogsStore.fetch({
        success: function () {
          window.logsView = new window.logsView({
            collection: window.arangoLogsStore
          });
        }
      });

      this.footerView = new window.footerView();
      this.naviView = new window.navigationView();
      this.footerView.render();
      this.naviView.render();
      this.graphView = new window.graphView({
        collection: window.arangoCollectionsStore
      });
    },

    logsAllowed: function () {
      if ($('#databaseName').html() !== '_system') {
        return false;
      }
      return true;
    },

    checkSession: function () {
      if (window.activeSession.models.length === 0) {
        window.App.navigate("login", {trigger: true});
        return false;
      }
      return true;
    },
    login: function () {
      if (!this.loginView) {
        this.loginView = new window.loginView({
          collection: window.activeSession
        });
      }
      this.loginView.render();
      this.naviView.selectMenuItem('');
    },
    collections: function() {
      var naviView = this.naviView;

      //DEV
      //var currentSession = this.checkSession();
      //if (currentSession === false) {
      //  return;
      //}

      window.arangoCollectionsStore.fetch({
        success: function () {
          window.collectionsView.render();
          naviView.selectMenuItem('collections-menu');
        }
      });
    },

    collection: function(colid) {
      window.collectionView.options.colId = colid;
      window.collectionView.render();
    },
    collectionInfo: function(colid) {
      window.collectionInfoView.options.colId = colid;
      window.collectionInfoView.render();
    },
    newCollection: function() {
      if (!this.newCollectionView) {
        this.newCollectionView = new window.newCollectionView({});
      }
      this.newCollectionView.render();
    },

    documents: function(colid, pageid) {
      if (!window.documentsView) {
        window.documentsView.initTable(colid, pageid);
      }
      window.documentsView.collectionID = colid;
      var type = arangoHelper.collectionApiType(colid);
      window.documentsView.colid = colid;
      window.documentsView.pageid = pageid;
      window.documentsView.type = type;
      window.documentsView.render();
      window.arangoDocumentsStore.getDocuments(colid, pageid);
    },

    document: function(colid, docid) {
      if (!window.documentView) {
        window.documentView.initTable();
      }
      window.documentView.colid = colid;
      window.documentView.docid = docid;
      window.documentView.render();
      var type = arangoHelper.collectionApiType(colid);
      window.documentView.type = type;
      window.documentView.typeCheck(type);
    },

    source: function(colid, docid) {
      window.documentSourceView.render();
      window.documentSourceView.colid = colid;
      window.documentSourceView.docid = docid;
      var type = arangoHelper.collectionApiType(colid);
      window.documentSourceView.type = type;
      window.documentSourceView.typeCheck(type);
    },

    shell: function() {
      if (!this.shellView) {
        this.shellView = new window.shellView();
      }
      this.shellView.render();
      this.naviView.selectMenuItem('shell-menu');
    },

    query: function() {
      if (!this.queryView) {
        this.queryView = new window.queryView();
      }
      this.queryView.render();
      this.naviView.selectMenuItem('query-menu');
    },

    api: function() {
      if (!this.apiView) {
        this.apiView = new window.apiView();
      }
      this.apiView.render();
      this.naviView.selectMenuItem('api-menu');
    },

    databases: function() {
      if (!this.databaseView) {
        this.databaseView = new window.databaseView({
          collection: arangoDatabase
        });
      }
      this.databaseView.render();
      this.naviView.selectMenuItem('database-menu');
    },

    about: function() {
      if (!this.aboutView) {
        this.aboutView = new window.aboutView();
      }
      this.aboutView.render();
      this.naviView.selectMenuItem('about-menu');
    },

    logs: function() {
      if (! this.logsAllowed()) {
        return;
      }

      var self = this;
      window.arangoLogsStore.fetch({
        success: function () {
          window.logsView.render();
          $('#logNav a[href="#all"]').tab('show');
          window.logsView.initLogTables();
          window.logsView.drawTable();
          $('#all-switch').click();
        }
      });
      this.naviView.selectMenuItem('logs-menu');
    },

    dashboard: function() {
      this.naviView.selectMenuItem('dashboard-menu');
      if (this.statisticsDescription === undefined) {
        this.statisticsDescription = new window.StatisticsDescription();
        this.statisticsDescription.fetch({
          async:false
        });
      }
      if (this.statistics === undefined) {
        this.statisticsCollection = new window.StatisticsCollection();
      }
      if (this.dashboardView === undefined) {
        this.dashboardView = new dashboardView({
          collection: this.statisticsCollection,
          description: this.statisticsDescription
        });
         }
        this.dashboardView.render();
    },

    graph: function() {
      var self = this;
      window.arangoCollectionsStore.fetch({
        success: function () {
          self.graphView.render();
          self.naviView.selectMenuItem('graphviewer-menu');
        }
      });
    },

    applications: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsView === undefined) {
        this.applicationsView = new window.ApplicationsView({
          collection: this.foxxList
        });
      }
      this.applicationsView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationsAvailable: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsInstalledView === undefined) {
        this.applicationsInstalledView = new window.FoxxInstalledListView({
          collection: this.foxxList
        });
      }
      this.applicationsInstalledView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationsInstalled: function() {
      if (this.foxxList === undefined) {
        this.foxxList = new window.FoxxCollection();
      }
      if (this.applicationsActiveView === undefined) {
        this.applicationsActiveView = new window.FoxxActiveListView({
          collection: this.foxxList
        });
      }
      this.applicationsActiveView.reload();
      this.naviView.selectMenuItem('applications-menu');
    },

    applicationEdit: function(appkey) {
      if (this.foxxList === undefined) {
        var self = this;
        this.foxxList = new window.FoxxCollection();
        this.foxxList.fetch({
          success: function() {
            var editAppView = new window.foxxEditView({
              model: self.foxxList.findWhere({_key: appkey})
            });
            editAppView.render();
          }
        });
      } else {
        var editAppView = new window.foxxEditView({model: this.foxxList.findWhere({_key: appkey})});
        editAppView.render();
      }
    },

    applicationInstall: function(appkey) {
      if (this.foxxList === undefined) {
        var self = this;
        this.foxxList = new window.FoxxCollection();
        this.foxxList.fetch({
          success: function() {
            var installAppView = new window.foxxMountView({
              model: self.foxxList.findWhere({_key: appkey})
            });
            installAppView.render();
          }
        });
      } else {
        var installAppView = new window.foxxMountView({
          model: this.foxxList.findWhere({_key: appkey})
        });
        installAppView.render();
      }

    },

    appDocumentation: function(key) {
      var docuView = new window.AppDocumentationView({key: key});
      docuView.render();
      this.naviView.selectMenuItem('applications-menu');
    }

  });

  window.App = new window.Router();
  Backbone.history.start();

});

<|endoftext|>


<commit_before>import d3 from 'd3';
import {
  find,
  compact
} from '../utils';
import {
  alignText,
  createHelper,
  di,
  getMargins,
  isSeriesData,
  mixin,
  property,
  stack,
  translate
} from '../helpers';
import { StandardLayer } from '../mixins';
import Component from '../Component';
var default_legend_margins = {top: 8, right: 8, bottom: 8, left: 8};

/**
  Legend component that can automatically pull chart and series information from d3.compose

  Notes:

  - To exclude a chart from the legend, use `exclude_from_legend = true` in chart prototype or options
  - To exclude a series from the legend, use `exclude_from_legend = true` in series object
  - To add swatch for custom chart, use `Legend.registerSwatch()`

  ### Extending

  To extend the `Legend` component, the following methods are available:

  - `itemKey`
  - `itemText`
  - `swatchClass`
  - `createSwatch`
  - `onDataBind`
  - `onInsert`
  - `onEnter`
  - `onEnterTransition`
  - `onUpdate`
  - `onUpdateTransition`
  - `onMerge`
  - `onMergeTransition`
  - `onExit`
  - `onExitTransition`

  @example
  ```js
  d3.select('#chart')
    .chart('Compose', function(data) {
      var input = [{key: 'input', name: 'Input', values: data.input}];
      var output = [
        {key: 'output1', name: 'Output 1', values: data.output1},
        {key: 'output2', name: 'Output 2', values: data.output2}
      ];

      return {
        charts: {
          a: {type: 'Lines', data: input}, // ...
          b: {type: 'Bars', data: output} // ...
        },
        components: {
          legend: {
            type: 'Legend',
            charts: ['a', 'b']
          }
        }
      };
    });

  // -> automatically creates legend from series data for 'a' and 'b'
  //    (Lines Swatch) Input
  //    (Bars Swatch) Output 1
  //    (Bars Swatch) Output 2

  // or, manually set data for legend
  return {
    components: {
      legend: {
        type: 'Legend',
        data: [
          {type: 'Lines', text: 'Input', class: 'series-index-0'},
          {type: 'Bars', text: 'Output 1', class: 'series-index-0'},
          {type: 'Bars', text: 'Output 2', class: 'series-index-1'},
        ]
      }
    }
  };
  ```
  @class Legend
  @extends Component, StandardLayer
*/
var Legend = Component.extend('Legend', mixin(StandardLayer, {
  initialize: function() {
    this.legend_base = this.base.append('g').classed('chart-legend', true);
    this.standardLayer('Legend', this.legend_base);
  },

  /**
    Array of chart keys from container to display in legend

    @example
    ```js
    d3.select('#chart')
    .chart('Compose', function(data) {
      return {
        charts: {
          a: {},
          b: {},
          c: {}
        },
        components: {
          legend: {
            type: 'Legend',
            charts: ['a', 'c']
          }
        }
      };
    });
    ```
    @property charts
    @type Array
  */
  charts: property('charts'),

  /**
    Dimensions of "swatch"

    @property swatchDimensions
    @type Object
    @default {width: 20, height: 20}
  */
  swatchDimensions: property('swatchDimensions', {
    default_value: {width: 20, height: 20}
  }),

  /**
    Margins (in pixels) around legend

    @property margins
    @type Object
    @default {top: 8, right: 8, bottom: 8, left: 8}
  */
  margins: property('margins', {
    default_value: default_legend_margins,
    set: function(values) {
      return {
        override: getMargins(values, default_legend_margins)
      };
    }
  }),

  transform: function(data) {
    if (this.charts()) {
      // Pull legend data from charts
      var charts = this.container.charts();
      data = this.charts().reduce(function(combined_data, chart_id) {
        var chart = find(charts, function(find_chart) { return find_chart.id == chart_id; });

        // Check for exclude from legend option
        if (!chart || chart.exclude_from_legend || chart.options().exclude_from_legend)
          return combined_data;

        var chart_data = this.container.demux(chart_id, this.container.data());
        if (!isSeriesData(chart_data))
          chart_data = [chart_data];

        var legend_data = chart_data.reduce(function(memo, series, index) {
          // Check for exclude from legend option on series
          if (series && !series.exclude_from_legend) {
            memo.push({
              text: series.name || 'Series ' + (index + 1),
              key: chart_id + '.' + (series.key || index),
              type: chart.type,
              'class': compact([
                'chart-series',
                'chart-index-' + index,
                chart.options()['class'],
                series['class']
              ]).join(' ')
            });
          }

          return memo;
        }, []);

        return combined_data.concat(legend_data);
      }.bind(this), []);
    }

    return data;
  },

  // Key for legend item (default is key from data)
  itemKey: di(function(chart, d) {
    return d.key;
  }),

  // Text for legend item (default is text from data)
  itemText: di(function(chart, d) {
    return d.text;
  }),

  // Class to apply to swatch (default is class from data)
  swatchClass: di(function(chart, d) {
    return d['class'];
  }),

  // Create swatch (using registered swatches based on type from data)
  createSwatch: di(function(chart, d, i) {
    var selection = d3.select(this);

    // Clear existing swatch
    selection.selectAll('*').remove();
    selection
      .attr('class', chart.swatchClass);

    var swatches = d3.chart('Legend').swatches;
    if (!swatches)
      return;

    if (d && d.type && swatches[d.type])
      swatches[d.type].call(selection, chart, d, i);
    else if (swatches['default'])
      swatches['default'].call(selection, chart, d, i);
  }),

  onDataBind: function onDataBind(selection, data) {
    return selection.selectAll('.chart-legend-group')
      .data(data, this.itemKey);
  },
  onInsert: function onInsert(selection) {
    var groups = selection.append('g')
      .attr('class', 'chart-legend-group');

    groups.append('g')
      .attr('width', this.swatchDimensions().width)
      .attr('height', this.swatchDimensions().height)
      .attr('class', 'chart-legend-swatch');
    groups.append('text')
      .attr('class', 'chart-legend-label');

    return groups;
  },
  onMerge: function onMerge(selection) {
    var swatch = this.swatchDimensions();

    selection.select('g').each(this.createSwatch);
    selection.select('text')
      .text(this.itemText)
      .each(function() {
        // Vertically center text
        var offset = alignText(this, swatch.height);
        d3.select(this)
          .attr('transform', translate(swatch.width + 5, offset));
      });

    // Position groups after positioning everything inside
    var direction_by_position = {
      top: 'horizontal',
      right: 'vertical',
      bottom: 'horizontal',
      left: 'vertical'
    };
    selection.call(stack.bind(selection, {direction: direction_by_position[this.position()], origin: 'top', padding: 5}));
  },
  onExit: function onExit(selection) {
    selection.remove();
  }
}), {
  z_index: 200,
  swatches: {
    'default': function(chart) {
      var swatch_dimensions = chart.swatchDimensions();

      this.append('circle')
        .attr('cx', swatch_dimensions.width / 2)
        .attr('cy', swatch_dimensions.height / 2)
        .attr('r', d3.min([swatch_dimensions.width, swatch_dimensions.height]) / 2)
        .attr('class', 'chart-swatch');
    }
  },

  /**
    Register a swatch create function for the given chart type

    @example
    ```js
    d3.chart('Legend').registerSwatch(['Lines'], function(chart, d, i) {
      var dimensions = chart.swatchDimensions();

      return this.append('line')
        .attr('x1', 0).attr('y1', dimensions.height / 2)
        .attr('x2', dimensions.width).attr('y2', dimensions.height / 2)
        .attr('class', 'chart-line');
    });
    ```
    @method registerSwatch
    @static
    @param {Array|String} types Chart type(s)
    @param {Function} create "di" function that inserts swatch
  */
  registerSwatch: function(types, create) {
    if (!Array.isArray(types))
      types = [types];

    types.forEach(function(type) {
      this.swatches[type] = create;
    }, this);
  }
});

// Create line swatch for Line and LineValues
Legend.registerSwatch(['Lines'], function(chart) {
  var swatch_dimensions = chart.swatchDimensions();

  return this.append('line')
    .attr('x1', 0).attr('y1', swatch_dimensions.height / 2)
    .attr('x2', swatch_dimensions.width).attr('y2', swatch_dimensions.height / 2)
    .attr('class', 'chart-line');
});

// Create bars swatch for Bars and StackedBars
Legend.registerSwatch(['Bars', 'StackedBars', 'HorizontalBars', 'HorizontalStackedBars'], function(chart) {
  var swatch_dimensions = chart.swatchDimensions();

  return this.append('rect')
    .attr('x', 0).attr('y', 0)
    .attr('width', swatch_dimensions.width).attr('height', swatch_dimensions.height)
    .attr('class', 'chart-bar');
});

var legend = createHelper('Legend');

export {
  Legend as default,
  legend
};
<commit_msg>Export property for legend stack direction<commit_after>import d3 from 'd3';
import {
  compact,
  contains,
  find
} from '../utils';
import {
  alignText,
  createHelper,
  di,
  getMargins,
  isSeriesData,
  mixin,
  property,
  stack,
  translate
} from '../helpers';
import { StandardLayer } from '../mixins';
import Component from '../Component';
var default_legend_margins = {top: 8, right: 8, bottom: 8, left: 8};

/**
  Legend component that can automatically pull chart and series information from d3.compose

  Notes:

  - To exclude a chart from the legend, use `exclude_from_legend = true` in chart prototype or options
  - To exclude a series from the legend, use `exclude_from_legend = true` in series object
  - To add swatch for custom chart, use `Legend.registerSwatch()`

  ### Extending

  To extend the `Legend` component, the following methods are available:

  - `itemKey`
  - `itemText`
  - `swatchClass`
  - `createSwatch`
  - `onDataBind`
  - `onInsert`
  - `onEnter`
  - `onEnterTransition`
  - `onUpdate`
  - `onUpdateTransition`
  - `onMerge`
  - `onMergeTransition`
  - `onExit`
  - `onExitTransition`

  @example
  ```js
  d3.select('#chart')
    .chart('Compose', function(data) {
      var input = [{key: 'input', name: 'Input', values: data.input}];
      var output = [
        {key: 'output1', name: 'Output 1', values: data.output1},
        {key: 'output2', name: 'Output 2', values: data.output2}
      ];

      return {
        charts: {
          a: {type: 'Lines', data: input}, // ...
          b: {type: 'Bars', data: output} // ...
        },
        components: {
          legend: {
            type: 'Legend',
            charts: ['a', 'b']
          }
        }
      };
    });

  // -> automatically creates legend from series data for 'a' and 'b'
  //    (Lines Swatch) Input
  //    (Bars Swatch) Output 1
  //    (Bars Swatch) Output 2

  // or, manually set data for legend
  return {
    components: {
      legend: {
        type: 'Legend',
        data: [
          {type: 'Lines', text: 'Input', class: 'series-index-0'},
          {type: 'Bars', text: 'Output 1', class: 'series-index-0'},
          {type: 'Bars', text: 'Output 2', class: 'series-index-1'},
        ]
      }
    }
  };
  ```
  @class Legend
  @extends Component, StandardLayer
*/
var Legend = Component.extend('Legend', mixin(StandardLayer, {
  initialize: function() {
    this.legend_base = this.base.append('g').classed('chart-legend', true);
    this.standardLayer('Legend', this.legend_base);
  },

  /**
    Array of chart keys from container to display in legend

    @example
    ```js
    d3.select('#chart')
    .chart('Compose', function(data) {
      return {
        charts: {
          a: {},
          b: {},
          c: {}
        },
        components: {
          legend: {
            type: 'Legend',
            charts: ['a', 'c']
          }
        }
      };
    });
    ```
    @property charts
    @type Array
  */
  charts: property('charts'),

  /**
    Dimensions of "swatch"

    @property swatchDimensions
    @type Object
    @default {width: 20, height: 20}
  */
  swatchDimensions: property('swatchDimensions', {
    default_value: {width: 20, height: 20}
  }),

  /**
    Margins (in pixels) around legend

    @property margins
    @type Object
    @default {top: 8, right: 8, bottom: 8, left: 8}
  */
  margins: property('margins', {
    default_value: default_legend_margins,
    set: function(values) {
      return {
        override: getMargins(values, default_legend_margins)
      };
    }
  }),

  /**
    Direction to "stack" legend, "vertical" or "horizontal".
    (Default is set based on position: top/bottom = "horizontal", left/right = "vertical")

    @property stackDirection
    @type String
    @default (based on position)
  */
  stackDirection: property('stackDirection', {
    validate: function(value) {
      return contains(['vertical', 'horizontal'], value);
    },
    default_value: function() {
      var direction_by_position = {
        top: 'horizontal',
        right: 'vertical',
        bottom: 'horizontal',
        left: 'vertical'
      };
      return direction_by_position[this.position()];
    }
  }),

  transform: function(data) {
    if (this.charts()) {
      // Pull legend data from charts
      var charts = this.container.charts();
      data = this.charts().reduce(function(combined_data, chart_id) {
        var chart = find(charts, function(find_chart) { return find_chart.id == chart_id; });

        // Check for exclude from legend option
        if (!chart || chart.exclude_from_legend || chart.options().exclude_from_legend)
          return combined_data;

        var chart_data = this.container.demux(chart_id, this.container.data());
        if (!isSeriesData(chart_data))
          chart_data = [chart_data];

        var legend_data = chart_data.reduce(function(memo, series, index) {
          // Check for exclude from legend option on series
          if (series && !series.exclude_from_legend) {
            memo.push({
              text: series.name || 'Series ' + (index + 1),
              key: chart_id + '.' + (series.key || index),
              type: chart.type,
              'class': compact([
                'chart-series',
                'chart-index-' + index,
                chart.options()['class'],
                series['class']
              ]).join(' ')
            });
          }

          return memo;
        }, []);

        return combined_data.concat(legend_data);
      }.bind(this), []);
    }

    return data;
  },

  // Key for legend item (default is key from data)
  itemKey: di(function(chart, d) {
    return d.key;
  }),

  // Text for legend item (default is text from data)
  itemText: di(function(chart, d) {
    return d.text;
  }),

  // Class to apply to swatch (default is class from data)
  swatchClass: di(function(chart, d) {
    return d['class'];
  }),

  // Create swatch (using registered swatches based on type from data)
  createSwatch: di(function(chart, d, i) {
    var selection = d3.select(this);

    // Clear existing swatch
    selection.selectAll('*').remove();
    selection
      .attr('class', chart.swatchClass);

    var swatches = d3.chart('Legend').swatches;
    if (!swatches)
      return;

    if (d && d.type && swatches[d.type])
      swatches[d.type].call(selection, chart, d, i);
    else if (swatches['default'])
      swatches['default'].call(selection, chart, d, i);
  }),

  onDataBind: function onDataBind(selection, data) {
    return selection.selectAll('.chart-legend-group')
      .data(data, this.itemKey);
  },
  onInsert: function onInsert(selection) {
    var groups = selection.append('g')
      .attr('class', 'chart-legend-group');

    groups.append('g')
      .attr('width', this.swatchDimensions().width)
      .attr('height', this.swatchDimensions().height)
      .attr('class', 'chart-legend-swatch');
    groups.append('text')
      .attr('class', 'chart-legend-label');

    return groups;
  },
  onMerge: function onMerge(selection) {
    var swatch = this.swatchDimensions();

    selection.select('g').each(this.createSwatch);
    selection.select('text')
      .text(this.itemText)
      .each(function() {
        // Vertically center text
        var offset = alignText(this, swatch.height);
        d3.select(this)
          .attr('transform', translate(swatch.width + 5, offset));
      });

    // Position groups after positioning everything inside
    selection.call(stack.bind(selection, {direction: this.stackDirection(), origin: 'top', padding: 5}));
  },
  onExit: function onExit(selection) {
    selection.remove();
  }
}), {
  z_index: 200,
  swatches: {
    'default': function(chart) {
      var swatch_dimensions = chart.swatchDimensions();

      this.append('circle')
        .attr('cx', swatch_dimensions.width / 2)
        .attr('cy', swatch_dimensions.height / 2)
        .attr('r', d3.min([swatch_dimensions.width, swatch_dimensions.height]) / 2)
        .attr('class', 'chart-swatch');
    }
  },

  /**
    Register a swatch create function for the given chart type

    @example
    ```js
    d3.chart('Legend').registerSwatch(['Lines'], function(chart, d, i) {
      var dimensions = chart.swatchDimensions();

      return this.append('line')
        .attr('x1', 0).attr('y1', dimensions.height / 2)
        .attr('x2', dimensions.width).attr('y2', dimensions.height / 2)
        .attr('class', 'chart-line');
    });
    ```
    @method registerSwatch
    @static
    @param {Array|String} types Chart type(s)
    @param {Function} create "di" function that inserts swatch
  */
  registerSwatch: function(types, create) {
    if (!Array.isArray(types))
      types = [types];

    types.forEach(function(type) {
      this.swatches[type] = create;
    }, this);
  }
});

// Create line swatch for Line and LineValues
Legend.registerSwatch(['Lines'], function(chart) {
  var swatch_dimensions = chart.swatchDimensions();

  return this.append('line')
    .attr('x1', 0).attr('y1', swatch_dimensions.height / 2)
    .attr('x2', swatch_dimensions.width).attr('y2', swatch_dimensions.height / 2)
    .attr('class', 'chart-line');
});

// Create bars swatch for Bars and StackedBars
Legend.registerSwatch(['Bars', 'StackedBars', 'HorizontalBars', 'HorizontalStackedBars'], function(chart) {
  var swatch_dimensions = chart.swatchDimensions();

  return this.append('rect')
    .attr('x', 0).attr('y', 0)
    .attr('width', swatch_dimensions.width).attr('height', swatch_dimensions.height)
    .attr('class', 'chart-bar');
});

var legend = createHelper('Legend');

export {
  Legend as default,
  legend
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');

// PostCSS plugins
const postCSSImport = require('postcss-import');
const postCSSNext = require('postcss-cssnext');
const postCSSReporter = require('postcss-reporter');
const rucksack = require('rucksack-css');
const cssnano = require('cssnano');
const S3Plugin = require('webpack-s3-plugin');

const ROOT_PATH = path.resolve(__dirname);

const config = {
  debug: true,
  entry: ['babel-polyfill', path.resolve(ROOT_PATH, 'src')],
  output: {
    path: path.resolve(ROOT_PATH, 'build.prod'),
    filename: 'bundle.[hash].js',
  },
  devtool: 'cheap-module-source-map',
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel?cacheDirectory',
        ],
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loaders: ['style', 'css?sourceMap&-minimize&camelCase&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'postcss'],
      }, {
        test: /\.json$/,
        loader: 'json',
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  postcss: wp => [
    postCSSImport({
      path: ['./src/styles'],
    }),
    postCSSNext({
      features: {
        rem: {
          rootValue: '14px',
        },
      },
    }),
    rucksack(),
    cssnano({
      autoprefixer: false,
      discardComments: {
        removeAll: true,
      },
      discardUnused: false,
      mergeIdents: false,
      reduceIdents: false,
      safe: true,
      sourcemap: true,
    }),
    postCSSReporter(),
  ],
  plugins: [
    new CleanPlugin('build.prod'),
    new webpack.DefinePlugin({
      __DEV__: false,
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        APIDOC_HOST: '"http://api.apidoc.me"',
        /* APIDOC_HOST: '""',*/
      },
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'main',
      children: true,
      minChunks: 2,
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.MinChunkSizePlugin({
      minChunkSize: 51200, // ~50kb
    }),
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false,
      },
    }),
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve(ROOT_PATH, 'src/index.html'),
    }),
  ],
};

// Only deploy if required
if (process.env.DEPLOY) {
  console.log('Deploying to S3');
  config.plugins.push(
    new S3Plugin({
      // s3Options are required
      s3Options: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: 'us-west-2',
      },
      s3UploadOptions: {
        Bucket: 'apidoc.me',
      },
    })
  );
}

module.exports = config;
<commit_msg>Fix long urls<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');

// PostCSS plugins
const postCSSImport = require('postcss-import');
const postCSSNext = require('postcss-cssnext');
const postCSSReporter = require('postcss-reporter');
const rucksack = require('rucksack-css');
const cssnano = require('cssnano');
const S3Plugin = require('webpack-s3-plugin');

const ROOT_PATH = path.resolve(__dirname);

const config = {
  debug: true,
  entry: ['babel-polyfill', path.resolve(ROOT_PATH, 'src')],
  output: {
    path: path.resolve(ROOT_PATH, 'build.prod'),
    filename: '/bundle.[hash].js',
  },
  devtool: 'cheap-module-source-map',
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel?cacheDirectory',
        ],
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loaders: ['style', 'css?sourceMap&-minimize&camelCase&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'postcss'],
      }, {
        test: /\.json$/,
        loader: 'json',
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  postcss: wp => [
    postCSSImport({
      path: ['./src/styles'],
    }),
    postCSSNext({
      features: {
        rem: {
          rootValue: '14px',
        },
      },
    }),
    rucksack(),
    cssnano({
      autoprefixer: false,
      discardComments: {
        removeAll: true,
      },
      discardUnused: false,
      mergeIdents: false,
      reduceIdents: false,
      safe: true,
      sourcemap: true,
    }),
    postCSSReporter(),
  ],
  plugins: [
    new CleanPlugin('build.prod'),
    new webpack.DefinePlugin({
      __DEV__: false,
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
        APIDOC_HOST: '"http://api.apidoc.me"',
        /* APIDOC_HOST: '""',*/
      },
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'main',
      children: true,
      minChunks: 2,
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.MinChunkSizePlugin({
      minChunkSize: 51200, // ~50kb
    }),
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false,
      },
    }),
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve(ROOT_PATH, 'src/index.html'),
      favicon: 'src/favicon.ico',
    }),
  ],
};

// Only deploy if required
if (process.env.DEPLOY) {
  console.log('Deploying to S3');
  config.plugins.push(
    new S3Plugin({
      // s3Options are required
      s3Options: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: 'us-west-2',
      },
      s3UploadOptions: {
        Bucket: 'apidoc.me',
      },
    })
  );
}

module.exports = config;
<|endoftext|>


<commit_before>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.formequip = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormEquip");}, gvm);
    gvm.formmethod = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormMethod");}, gvm);

    gvm.userId = null;
    gvm.availableModules = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.availableModules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen !== null) {
                        console.log(item.doelstellingen);
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.availableModules.push(tblObject);
                });
                makeChecklist();
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias !== null) {
                console.log(item.criterias);
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
        makeChecklist();
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
        makeChecklist();
    }
}

function addWorksheetProperties(serialData, wid, callback) {
    var collection = getCheckedFields();
    $.ajax({
        url: "/api/worksheetproperties/" + wid,
        type: "PUT",
        data: serialData,
        success: function(data) {
            console.log(data);
            callback(false);
        },
        error: function(data) {
            callback(true);
        }
    });
    $.ajax({
        url: "/api/worksheetmodules",
        type: "POST",
        data: {id: wid, modules: collection[0], competences: collection[1], criteria: collection[2]},
        success: function(data) {
            console.log('Success');
        },
        error: function(data) {
            console.log('Failure');
        }
    });
}

function makeChecklist() {
    $('.list-group.checked-list-box .list-group-item').each(function () {

        // Settings
        var $widget = $(this),
            $checkbox = $('<input type="checkbox" class="hidden" />'),
            color = ($widget.data('color') ? $widget.data('color') : "primary"),
            style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
            settings = {
                on: {
                    icon: 'glyphicon glyphicon-check'
                },
                off: {
                    icon: 'glyphicon glyphicon-unchecked'
                }
            };

        $widget.css('cursor', 'pointer')
        $widget.append($checkbox);

        // Event Handlers
        $widget.on('click', function () {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change');
            updateDisplay();
        });
        $checkbox.on('change', function () {
            updateDisplay();
        });

        // Actions
        function updateDisplay() {
            var isChecked = $checkbox.is(':checked');

            // Set the button's state
            $widget.data('state', (isChecked) ? "on" : "off");

            // Set the button's icon
            $widget.find('.state-icon')
                .removeClass()
                .addClass('state-icon ' + settings[$widget.data('state')].icon);

            // Update the button's color
            if (isChecked) {
                $widget.addClass(style + color + ' active');
            } else {
                $widget.removeClass(style + color + ' active');
            }
        }

        // Initialization
        function init() {

            if ($widget.data('checked') == true) {
                $checkbox.prop('checked', !$checkbox.is(':checked'));
            }

            updateDisplay();

            // Inject the icon if applicable
            if ($widget.find('.state-icon').length == 0) {
                $widget.prepend('');
            }
        }
        init();
    });
}

function getCheckedFields() {
    var checkedItems = [], counter = 0;
    $("#check-list-box li.active").each(function(idx, li) {
        checkedItems[counter] = $(li).text();
        counter++;
    });
    return filterModules(checkedItems);
}

function filterModules(data) {
    var collection = [];
    var modules = [];
    var comps = [];
    var criteria = [];
    $.each(viewModel.availableModules(), function(i, item) {
        if (data.indexOf(item.modname) > -1) {
            modules.push(item.modid);
        }
        $.each(item.competences, function(i, item) {
            if (data.indexOf(item.comname) > -1) {
                comps.push(item.comid);
            }
            $.each(item.criterias, function(i, item) {
                if (data.indexOf(item.critname) > -1) {
                    criteria.push(item.critid);
                }
            });
        });
    });
    collection.push(modules);
    collection.push(comps);
    collection.push(criteria);
    return collection;
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        var courseid = $('#storage').attr('data-value');
        viewModel.userId = data.id;
        viewModel.updateModules(courseid);
    });

    $('#submit').click(function() {
        var wid = $('#header').attr('data-value');
        addWorksheetProperties($('#worksheetform').serialize(), wid, function() {
            $('#worksheetform').prepend("
There was a problem submitting the form
");
        });
    });
}
<commit_msg>properties van worksheet invullen via formulier<commit_after>// View model for the page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetNameRapport");}, gvm);
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("HomeRapportTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("WorksheetRapportManual");}, gvm);

    gvm.formequip = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormEquip");}, gvm);
    gvm.formmethod = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FormMethod");}, gvm);

    gvm.userId = null;
    gvm.availableModules = ko.observableArray([]);

    gvm.updateModules = function(courseid) {
        $.getJSON('/api/coursestructure/' + courseid, function(data) {
            if (!$.isEmptyObject(data)) {
                gvm.availableModules.removeAll();

                $.each(data, function(i, item) {
                    var tblObject = {modid: item.id, modname: item.name, competences: new Array()};
                    if (item.doelstellingen !== "") {
                        console.log(item.doelstellingen);
                        gvm.updateCompetences(item.doelstellingen, tblObject.competences);
                    }
                    gvm.availableModules.push(tblObject);
                });
                makeChecklist();
            }
        });
    }

    gvm.updateCompetences = function(data, competences) {
        $.each(data, function(i, item) {
            var tblObject = {comid: item.id, comname: item.name, criterias: new Array()}
            if (item.criterias !== "") {
                console.log(item.criterias);
                gvm.updateCriteria(item.criterias, tblObject.criterias);
            }
            competences.push(tblObject);
        });
        makeChecklist();
    }

    gvm.updateCriteria = function(data, criteria) {
        $.each(data, function(i, item){
            var tblObject = {critid: item.id, critname: item.name};
            criteria.push(tblObject);
        });
        makeChecklist();
    }
}

function addWorksheetProperties(serialData, wid, callback) {
    var collection = getCheckedFields();
    $.ajax({
        url: "/api/worksheetproperties/" + wid,
        type: "PUT",
        data: serialData,
        success: function(data) {
            console.log(data);
            callback(false);
        },
        error: function(data) {
            callback(true);
        }
    });
    $.ajax({
        url: "/api/worksheetmodules",
        type: "POST",
        data: {id: wid, modules: collection[0], competences: collection[1], criteria: collection[2]},
        success: function(data) {
            console.log('Success');
        },
        error: function(data) {
            console.log('Failure');
        }
    });
}

function makeChecklist() {
    $('.list-group.checked-list-box .list-group-item').each(function () {

        // Settings
        var $widget = $(this),
            $checkbox = $('<input type="checkbox" class="hidden" />'),
            color = ($widget.data('color') ? $widget.data('color') : "primary"),
            style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
            settings = {
                on: {
                    icon: 'glyphicon glyphicon-check'
                },
                off: {
                    icon: 'glyphicon glyphicon-unchecked'
                }
            };

        $widget.css('cursor', 'pointer')
        $widget.append($checkbox);

        // Event Handlers
        $widget.on('click', function () {
            $checkbox.prop('checked', !$checkbox.is(':checked'));
            $checkbox.triggerHandler('change');
            updateDisplay();
        });
        $checkbox.on('change', function () {
            updateDisplay();
        });

        // Actions
        function updateDisplay() {
            var isChecked = $checkbox.is(':checked');

            // Set the button's state
            $widget.data('state', (isChecked) ? "on" : "off");

            // Set the button's icon
            $widget.find('.state-icon')
                .removeClass()
                .addClass('state-icon ' + settings[$widget.data('state')].icon);

            // Update the button's color
            if (isChecked) {
                $widget.addClass(style + color + ' active');
            } else {
                $widget.removeClass(style + color + ' active');
            }
        }

        // Initialization
        function init() {

            if ($widget.data('checked') == true) {
                $checkbox.prop('checked', !$checkbox.is(':checked'));
            }

            updateDisplay();

            // Inject the icon if applicable
            if ($widget.find('.state-icon').length == 0) {
                $widget.prepend('');
            }
        }
        init();
    });
}

function getCheckedFields() {
    var checkedItems = [], counter = 0;
    $("#check-list-box li.active").each(function(idx, li) {
        checkedItems[counter] = $(li).text();
        counter++;
    });
    return filterModules(checkedItems);
}

function filterModules(data) {
    var collection = [];
    var modules = [];
    var comps = [];
    var criteria = [];
    $.each(viewModel.availableModules(), function(i, item) {
        if (data.indexOf(item.modname) > -1) {
            modules.push(item.modid);
        }
        $.each(item.competences, function(i, item) {
            if (data.indexOf(item.comname) > -1) {
                comps.push(item.comid);
            }
            $.each(item.criterias, function(i, item) {
                if (data.indexOf(item.critname) > -1) {
                    criteria.push(item.critid);
                }
            });
        });
    });
    collection.push(modules);
    collection.push(comps);
    collection.push(criteria);
    return collection;
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        var courseid = $('#storage').attr('data-value');
        viewModel.userId = data.id;
        viewModel.updateModules(courseid);
    });

    $('#submit').click(function() {
        var wid = $('#header').attr('data-value');
        addWorksheetProperties($('#worksheetform').serialize(), wid, function() {
            $('#worksheetform').prepend("
There was a problem submitting the form
");
        });
    });
}
<|endoftext|>


<commit_before>const path = require('path')
const nodeExternals = require('webpack-node-externals')
const CopyPlugin = require('copy-webpack-plugin')

const config = {
  node: {
    __dirname: false,
    __filename: true,
  },
  mode: 'development',
  target: 'electron-main',
  context: path.resolve(__dirname + '/src-electron/main-process/'),
  entry: './electron-main',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'electron-main.js',
  },
  module: {
    noParse: /\/native-require.js$/,
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
          },
          {
            loader: 'eslint-loader',
            options: {
              formatter: require('eslint').CLIEngine.getFormatter('stylish'),
            },
          },
        ],
      },
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'babel-loader',
          },
          {
            loader: 'ts-loader',
            options: {
              compilerOptions: {
                noEmit: false,
              },
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        enforce: 'pre',
        test: /\.sql$/,
        loader: 'file-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  devtool: 'inline-source-map',
  externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: '../db/zap-schema.sql', to: 'backend/db/' },
        { from: '../../zcl-builtin', to: 'backend/zcl-builtin' },
        { from: '../icons', to: 'backend/icons' },
      ],
    }),
  ],
}

module.exports = config
<commit_msg>enable correct line output when exceptions are thrown<commit_after>const path = require('path')
const nodeExternals = require('webpack-node-externals')
const CopyPlugin = require('copy-webpack-plugin')

const config = {
  node: {
    __dirname: false,
    __filename: true,
  },
  mode: 'development',
  target: 'electron-main',
  context: path.resolve(__dirname + '/src-electron/main-process/'),
  entry: './electron-main',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'electron-main.js',
  },
  module: {
    noParse: /\/native-require.js$/,
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'eslint-loader',
            options: {
              formatter: require('eslint').CLIEngine.getFormatter('stylish'),
            },
          },
        ],
      },
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              compilerOptions: {
                noEmit: false,
              },
            },
          },
        ],
        exclude: /node_modules/,
      },
      {
        enforce: 'pre',
        test: /\.sql$/,
        loader: 'file-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  devtool: 'eval-cheap-module-source-map',
  externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: '../db/zap-schema.sql', to: 'backend/db/' },
        { from: '../../zcl-builtin', to: 'backend/zcl-builtin' },
        { from: '../icons', to: 'backend/icons' },
      ],
    }),
  ],
}

module.exports = config
<|endoftext|>