<commit_before>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');

const Icon = require('./Icon');
const Spin = require('./Spin');

const { buttonTypes, themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor } = require('../utils/Deprecation');

class Button extends React.Component {
  static propTypes = {
    'aria-label': PropTypes.string,
    actionText: PropTypes.string,
    buttonRef: PropTypes.func,
    elementProps: PropTypes.object,
    icon: PropTypes.string,
    isActive: PropTypes.bool,
    onClick: PropTypes.func,
    primaryColor: PropTypes.string,
    style: PropTypes.object,
    theme: themeShape,
    type: PropTypes.oneOf(buttonTypes)
  };

  static defaultProps = {
    elementProps: {},
    onClick () {},
    isActive: false,
    type: 'primary'
  };

  componentDidMount () {
    deprecatePrimaryColor(this.props);
  }

  _windowSizeIsSmall = (theme) => {
    const windowSize = StyleUtils.getWindowSize(theme.BreakPoints);

    return windowSize === 'medium' || windowSize === 'large';
  };

  _childIsVisible = child =>
    !child.props || child.props.className !== 'visuallyHidden';

  _hasVisibleChildren = () => {
    if (!this.props.children) {
      return false;
    }

    if (!Array.isArray(this.props.children)) {
      return this._childIsVisible(this.props.children);
    }

    return this.props.children.some(this._childIsVisible);
  };

  render () {
    // Manually consume everything that isn't going to be passed down to the button so we don't have to keep adding props one at a time.
    // Keep elementProps for backwards compatibility.
    const { actionText, buttonRef, children, elementProps, icon, isActive, primaryColor, style, theme, ...rest } = this.props
    const mergedTheme = StyleUtils.mergeTheme(theme, primaryColor);
    const styles = this.styles(mergedTheme);

    return (
      <button
        ref={buttonRef}
        style={Object.assign({}, styles.component, styles[this.props.type], style)}
        {...rest}
        {...elementProps}
      >

          {(icon && !isActive) && (
            <Icon
              size={20}
              style={styles.icon}
              type={icon}
            />
          )}
          {isActive && (
            <Spin direction='counterclockwise'>
              <Icon size={20} type='spinner' />
            </Spin>
          )}

            {isActive ? actionText : children}

      </button>
    );
  }

  styles = (theme) => {
    const windowSizeIsSmall = this._windowSizeIsSmall(theme);

    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: theme.FontSizes.MEDIUM,
        fontFamily: theme.Fonts.SEMIBOLD,
        cursor: this.props.type === 'disabled' ? 'default' : 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: theme.Colors.PRIMARY,
        borderColor: theme.Colors.PRIMARY,
        color: theme.Colors.WHITE,
        fill: theme.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -15),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.PRIMARY,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.PRIMARY,
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      primaryInverse: {
        backgroundColor: theme.Colors.WHITE,
        borderColor: theme.Colors.WHITE,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.WHITE, -15),
          borderColor: StyleUtils.adjustColor(theme.Colors.WHITE, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.WHITE, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.WHITE, -30),
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_500,
        color: theme.Colors.GRAY_500,
        fill: theme.Colors.GRAY_500,
        transition: 'all .2s ease-in',
        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.GRAY_500,
          borderColor: theme.Colors.GRAY_500,
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.GRAY_500, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.GRAY_500, -30),
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': windowSizeIsSmall ? null : {
          color: StyleUtils.adjustColor(theme.Colors.PRIMARY, -8),
          fill: StyleUtils.adjustColor(theme.Colors.PRIMARY, -8),
          transition: 'all .2s ease-in',
          borderColor: theme.Colors.GRAY_300
        },
        ':active': {
          color: StyleUtils.adjustColor(theme.Colors.PRIMARY, -16),
          fill: StyleUtils.adjustColor(theme.Colors.PRIMARY, -16),
          transition: 'all .2s ease-in',
          backgroundColor: theme.Colors.GRAY_100
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_300,
        borderRadius: 2,
        borderWidth: 1,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.GRAY_100
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.GRAY_100, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_300,
        color: theme.Colors.GRAY_300,
        fill: theme.Colors.GRAY_300
      },
      icon: {
        marginLeft: this._hasVisibleChildren() ? -4 : 0,
        marginRight: this._hasVisibleChildren() ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  };
}

module.exports = Radium(Button);
<commit_msg>Convert to using the disabled attribute for past type matching<commit_after>const React = require('react');
const PropTypes = require('prop-types');
const Radium = require('radium');

const Icon = require('./Icon');
const Spin = require('./Spin');

const { buttonTypes, themeShape } = require('../constants/App');

const StyleUtils = require('../utils/Style');
const { deprecatePrimaryColor } = require('../utils/Deprecation');

class Button extends React.Component {
  static propTypes = {
    'aria-label': PropTypes.string,
    actionText: PropTypes.string,
    buttonRef: PropTypes.func,
    elementProps: PropTypes.object,
    icon: PropTypes.string,
    isActive: PropTypes.bool,
    onClick: PropTypes.func,
    primaryColor: PropTypes.string,
    style: PropTypes.object,
    theme: themeShape,
    type: PropTypes.oneOf(buttonTypes)
  };

  static defaultProps = {
    elementProps: {},
    onClick () {},
    isActive: false,
    type: 'primary'
  };

  componentDidMount () {
    deprecatePrimaryColor(this.props);
  }

  _windowSizeIsSmall = (theme) => {
    const windowSize = StyleUtils.getWindowSize(theme.BreakPoints);

    return windowSize === 'medium' || windowSize === 'large';
  };

  _childIsVisible = child =>
    !child.props || child.props.className !== 'visuallyHidden';

  _hasVisibleChildren = () => {
    if (!this.props.children) {
      return false;
    }

    if (!Array.isArray(this.props.children)) {
      return this._childIsVisible(this.props.children);
    }

    return this.props.children.some(this._childIsVisible);
  };

  render () {
    // Manually consume everything that isn't going to be passed down to the button so we don't have to keep adding props one at a time.
    // Keep elementProps for backwards compatibility.
    const { actionText, buttonRef, children, elementProps, icon, isActive, primaryColor, style, theme, ...rest } = this.props
    const mergedTheme = StyleUtils.mergeTheme(theme, primaryColor);
    const styles = this.styles(mergedTheme);

    return (
      <button
        disabled={this.props.type === 'disabled'}
        ref={buttonRef}
        style={Object.assign({}, styles.component, styles[this.props.type], style)}
        {...rest}
        {...elementProps}
      >

          {(icon && !isActive) && (
            <Icon
              size={20}
              style={styles.icon}
              type={icon}
            />
          )}
          {isActive && (
            <Spin direction='counterclockwise'>
              <Icon size={20} type='spinner' />
            </Spin>
          )}

            {isActive ? actionText : children}

      </button>
    );
  }

  styles = (theme) => {
    const windowSizeIsSmall = this._windowSizeIsSmall(theme);

    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: theme.FontSizes.MEDIUM,
        fontFamily: theme.Fonts.SEMIBOLD,
        cursor: this.props.type === 'disabled' ? 'default' : 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: theme.Colors.PRIMARY,
        borderColor: theme.Colors.PRIMARY,
        color: theme.Colors.WHITE,
        fill: theme.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -15),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.PRIMARY,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.PRIMARY,
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.PRIMARY, -30),
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      primaryInverse: {
        backgroundColor: theme.Colors.WHITE,
        borderColor: theme.Colors.WHITE,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',

        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.WHITE, -15),
          borderColor: StyleUtils.adjustColor(theme.Colors.WHITE, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.WHITE, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.WHITE, -30),
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_500,
        color: theme.Colors.GRAY_500,
        fill: theme.Colors.GRAY_500,
        transition: 'all .2s ease-in',
        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.GRAY_500,
          borderColor: theme.Colors.GRAY_500,
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.GRAY_500, -30),
          borderColor: StyleUtils.adjustColor(theme.Colors.GRAY_500, -30),
          color: theme.Colors.WHITE,
          fill: theme.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': windowSizeIsSmall ? null : {
          color: StyleUtils.adjustColor(theme.Colors.PRIMARY, -8),
          fill: StyleUtils.adjustColor(theme.Colors.PRIMARY, -8),
          transition: 'all .2s ease-in',
          borderColor: theme.Colors.GRAY_300
        },
        ':active': {
          color: StyleUtils.adjustColor(theme.Colors.PRIMARY, -16),
          fill: StyleUtils.adjustColor(theme.Colors.PRIMARY, -16),
          transition: 'all .2s ease-in',
          backgroundColor: theme.Colors.GRAY_100
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_300,
        borderRadius: 2,
        borderWidth: 1,
        color: theme.Colors.PRIMARY,
        fill: theme.Colors.PRIMARY,
        ':hover': windowSizeIsSmall ? null : {
          backgroundColor: theme.Colors.GRAY_100
        },
        ':active': {
          backgroundColor: StyleUtils.adjustColor(theme.Colors.GRAY_100, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: theme.Colors.GRAY_300,
        color: theme.Colors.GRAY_300,
        fill: theme.Colors.GRAY_300
      },
      icon: {
        marginLeft: this._hasVisibleChildren() ? -4 : 0,
        marginRight: this._hasVisibleChildren() ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  };
}

module.exports = Radium(Button);
<|endoftext|>


<commit_before>"use strict";
/* global __static */

import {
  app,
  protocol,
  Menu,
  BrowserWindow,
  shell,
  ipcMain as ipc
} from "electron";
import {
  createProtocol
  /* installVueDevtools */
} from "vue-cli-plugin-electron-builder/lib";

const isDevelopment = process.env.NODE_ENV !== "production";
const os = require("os");

import path from "path";
import fs from "fs";

import LibUnity from "./unity/LibUnity";
import store, { AppStatus } from "./store";

// on vuex-connect send the current state to the renderer
ipc.on("vuex-connect", event => {
  event.sender.send("vuex-connected", store.state);
});

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let winMain;
let winDebug;
let walletPath;
if (os.platform() === "linux") {
  walletPath = path.join(
    app.getPath("home"),
    isDevelopment ? ".novo_dev" : ".novo"
  );
} else {
  walletPath = app.getPath("userData");
  if (isDevelopment) walletPath = walletPath + "_dev";
}

let libUnity = new LibUnity({ walletPath });

/* TODO: refactor into function and add option to libgulden to remove existing wallet folder */
if (isDevelopment) {
  let args = process.argv.slice(2);
  for (var i = 0; i < args.length; i++) {
    switch (args[i].toLowerCase()) {
      case "new-wallet":
        fs.rmdirSync(walletPath, {
          recursive: true
        });
        break;
      default:
        console.error(`unknown argument: ${args[i]}`);
        break;
    }
  }
}

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } }
]);

import lu from "native-ext-loader!./unity/lib_unity.node";

function createMainWindow() {
  let options = {
    width: 1024,
    minWidth: 800,
    height: 768,
    minHeight: 600,
    show: false,
    title: "Novo",
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true
    }
  };
  if (os.platform() === "linux") {
    options = Object.assign({}, options, {
      icon: path.join(__static, "icon.png")
    });
  }
  winMain = new BrowserWindow(options);

  var menuTemplate = [
    {
      label: "File",
      submenu: [{ role: "quit" }]
    },
    {
      label: "Edit",
      submenu: [{ role: "cut" }, { role: "copy" }, { role: "paste" }]
    }
  ];

  if (isDevelopment) {
    menuTemplate.push({
      label: "Debug",
      submenu: [
        { role: "toggleDevTools" },
        {
          label: "Generate genesis keys",
          click() {
            console.log(libUnity.backend.GenerateGenesisKeys());
          }
        },
        {
          label: "Debug Window",
          click() {
            createDebugWindow();
          }
        },
        {
          label: "RPC test - getpeerinfo",
          click() {
            let RPCController = new lu.NJSIRpcController();
            let RPCListener = new lu.NJSIRpcListener();

            RPCListener.onSuccess = function(filteredCommand, result) {
              console.log("RPC success: " + result);
            };
            RPCListener.onError = function(error) {
              console.log("RPC error: " + error);
            };
            RPCController.execute("getpeerinfo", RPCListener);
          }
        }
      ]
    });
  }

  var menu = Menu.buildFromTemplate(menuTemplate);

  Menu.setApplicationMenu(menu);

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    winMain.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    //if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    winMain.loadURL("app://./index.html");
  }

  winMain.on("ready-to-show", () => {
    winMain.show();
  });

  winMain.on("close", event => {
    console.log("winMain.on:close");
    if (process.platform !== "darwin") {
      EnsureUnityLibTerminated(event);
    }
  });

  winMain.on("closed", () => {
    console.log("winMain.on:closed");
    winMain = null;
  });

  // Force external hrefs to open in external browser
  winMain.webContents.on("new-window", function(e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });
}

function createDebugWindow() {
  if (winDebug) {
    return winDebug.show();
  }

  let options = {
    width: 600,
    minWidth: 400,
    height: 600,
    minHeight: 400,
    show: false,
    parent: winMain,
    title: "Novo Debug Window",
    skipTaskBar: true,
    autoHideMenuBar: true,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true
    }
  };
  if (os.platform() === "linux") {
    options = Object.assign({}, options, {
      icon: path.join(__static, "icon.png")
    });
  }
  winDebug = new BrowserWindow(options);

  let url = process.env.WEBPACK_DEV_SERVER_URL
    ? `${process.env.WEBPACK_DEV_SERVER_URL}#/debug`
    : `app://./index.html#/debug`;

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    winDebug.loadURL(url);
    //if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    winDebug.loadURL(url);
  }

  winDebug.on("ready-to-show", () => {
    winDebug.show();
  });

  winDebug.on("close", event => {
    console.log("winDebug.on:close");
    if (libUnity === null || libUnity.isTerminated) return;
    event.preventDefault();
    winDebug.hide();
  });

  winDebug.on("closed", () => {
    console.log("winDebug.on:closed");
    winDebug = null;
  });
}

app.on("will-quit", event => {
  console.log("app.on:will-quit");
  if (libUnity === null || libUnity.isTerminated) return;
  store.dispatch({ type: "SET_STATUS", status: AppStatus.shutdown });
  event.preventDefault();
  libUnity.TerminateUnityLib();
});

// Quit when all windows are closed.
app.on("window-all-closed", event => {
  console.log("app.on:window-all-closed");
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    EnsureUnityLibTerminated(event);
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (winMain === null) {
    createMainWindow();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // Devtools extensions are broken in Electron 6.0.0 and greater
    // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
    // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
    // If you are not using Windows 10 dark mode, you may uncomment these lines
    // In addition, if the linked issue is closed, you can upgrade electron and uncomment these lines
    // try {
    //   await installVueDevtools()
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }
  }

  store.dispatch({ type: "SET_WALLET_VERSION", version: app.getVersion() });
  libUnity.Initialize();

  createMainWindow();
});

function EnsureUnityLibTerminated(event) {
  if (libUnity === null || libUnity.isTerminated) return;
  store.dispatch({ type: "SET_STATUS", status: AppStatus.shutdown });
  event.preventDefault();
  libUnity.TerminateUnityLib();
}

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", data => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
<commit_msg>set default width/height to 800x600<commit_after>"use strict";
/* global __static */

import {
  app,
  protocol,
  Menu,
  BrowserWindow,
  shell,
  ipcMain as ipc
} from "electron";
import {
  createProtocol
  /* installVueDevtools */
} from "vue-cli-plugin-electron-builder/lib";

const isDevelopment = process.env.NODE_ENV !== "production";
const os = require("os");

import path from "path";
import fs from "fs";

import LibUnity from "./unity/LibUnity";
import store, { AppStatus } from "./store";

// on vuex-connect send the current state to the renderer
ipc.on("vuex-connect", event => {
  event.sender.send("vuex-connected", store.state);
});

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let winMain;
let winDebug;
let walletPath;
if (os.platform() === "linux") {
  walletPath = path.join(
    app.getPath("home"),
    isDevelopment ? ".novo_dev" : ".novo"
  );
} else {
  walletPath = app.getPath("userData");
  if (isDevelopment) walletPath = walletPath + "_dev";
}

let libUnity = new LibUnity({ walletPath });

/* TODO: refactor into function and add option to libgulden to remove existing wallet folder */
if (isDevelopment) {
  let args = process.argv.slice(2);
  for (var i = 0; i < args.length; i++) {
    switch (args[i].toLowerCase()) {
      case "new-wallet":
        fs.rmdirSync(walletPath, {
          recursive: true
        });
        break;
      default:
        console.error(`unknown argument: ${args[i]}`);
        break;
    }
  }
}

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } }
]);

import lu from "native-ext-loader!./unity/lib_unity.node";

function createMainWindow() {
  let options = {
    width: 800,
    minWidth: 800,
    height: 600,
    minHeight: 600,
    show: false,
    title: "Novo",
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true
    }
  };
  if (os.platform() === "linux") {
    options = Object.assign({}, options, {
      icon: path.join(__static, "icon.png")
    });
  }
  winMain = new BrowserWindow(options);

  var menuTemplate = [
    {
      label: "File",
      submenu: [{ role: "quit" }]
    },
    {
      label: "Edit",
      submenu: [{ role: "cut" }, { role: "copy" }, { role: "paste" }]
    }
  ];

  if (isDevelopment) {
    menuTemplate.push({
      label: "Debug",
      submenu: [
        { role: "toggleDevTools" },
        {
          label: "Generate genesis keys",
          click() {
            console.log(libUnity.backend.GenerateGenesisKeys());
          }
        },
        {
          label: "Debug Window",
          click() {
            createDebugWindow();
          }
        },
        {
          label: "RPC test - getpeerinfo",
          click() {
            let RPCController = new lu.NJSIRpcController();
            let RPCListener = new lu.NJSIRpcListener();

            RPCListener.onSuccess = function(filteredCommand, result) {
              console.log("RPC success: " + result);
            };
            RPCListener.onError = function(error) {
              console.log("RPC error: " + error);
            };
            RPCController.execute("getpeerinfo", RPCListener);
          }
        }
      ]
    });
  }

  var menu = Menu.buildFromTemplate(menuTemplate);

  Menu.setApplicationMenu(menu);

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    winMain.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    //if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    winMain.loadURL("app://./index.html");
  }

  winMain.on("ready-to-show", () => {
    winMain.show();
  });

  winMain.on("close", event => {
    console.log("winMain.on:close");
    if (process.platform !== "darwin") {
      EnsureUnityLibTerminated(event);
    }
  });

  winMain.on("closed", () => {
    console.log("winMain.on:closed");
    winMain = null;
  });

  // Force external hrefs to open in external browser
  winMain.webContents.on("new-window", function(e, url) {
    e.preventDefault();
    shell.openExternal(url);
  });
}

function createDebugWindow() {
  if (winDebug) {
    return winDebug.show();
  }

  let options = {
    width: 600,
    minWidth: 400,
    height: 600,
    minHeight: 400,
    show: false,
    parent: winMain,
    title: "Novo Debug Window",
    skipTaskBar: true,
    autoHideMenuBar: true,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      enableRemoteModule: true
    }
  };
  if (os.platform() === "linux") {
    options = Object.assign({}, options, {
      icon: path.join(__static, "icon.png")
    });
  }
  winDebug = new BrowserWindow(options);

  let url = process.env.WEBPACK_DEV_SERVER_URL
    ? `${process.env.WEBPACK_DEV_SERVER_URL}#/debug`
    : `app://./index.html#/debug`;

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    winDebug.loadURL(url);
    //if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    winDebug.loadURL(url);
  }

  winDebug.on("ready-to-show", () => {
    winDebug.show();
  });

  winDebug.on("close", event => {
    console.log("winDebug.on:close");
    if (libUnity === null || libUnity.isTerminated) return;
    event.preventDefault();
    winDebug.hide();
  });

  winDebug.on("closed", () => {
    console.log("winDebug.on:closed");
    winDebug = null;
  });
}

app.on("will-quit", event => {
  console.log("app.on:will-quit");
  if (libUnity === null || libUnity.isTerminated) return;
  store.dispatch({ type: "SET_STATUS", status: AppStatus.shutdown });
  event.preventDefault();
  libUnity.TerminateUnityLib();
});

// Quit when all windows are closed.
app.on("window-all-closed", event => {
  console.log("app.on:window-all-closed");
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    EnsureUnityLibTerminated(event);
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (winMain === null) {
    createMainWindow();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // Devtools extensions are broken in Electron 6.0.0 and greater
    // See https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/378 for more info
    // Electron will not launch with Devtools extensions installed on Windows 10 with dark mode
    // If you are not using Windows 10 dark mode, you may uncomment these lines
    // In addition, if the linked issue is closed, you can upgrade electron and uncomment these lines
    // try {
    //   await installVueDevtools()
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }
  }

  store.dispatch({ type: "SET_WALLET_VERSION", version: app.getVersion() });
  libUnity.Initialize();

  createMainWindow();
});

function EnsureUnityLibTerminated(event) {
  if (libUnity === null || libUnity.isTerminated) return;
  store.dispatch({ type: "SET_STATUS", status: AppStatus.shutdown });
  event.preventDefault();
  libUnity.TerminateUnityLib();
}

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", data => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
<|endoftext|>


<commit_before>const React = require('react');
const Radium = require('radium');

const Spin = require('./Spin');

const StyleConstants = require('../constants/Style');

const Icon = require('../components/Icon');

const Button = React.createClass({
  propTypes: {
    actionText: React.PropTypes.string,
    icon: React.PropTypes.string,
    isActive: React.PropTypes.bool,
    onClick: React.PropTypes.func,
    primaryColor: React.PropTypes.string,
    style: React.PropTypes.object,
    type: React.PropTypes.oneOf([
      'base',
      'disabled',
      'neutral',
      'primary',
      'primaryOutline',
      'secondary'
    ])
  },

  getDefaultProps () {
    return {
      onClick () {},
      isActive: false,
      primaryColor: StyleConstants.Colors.PRIMARY,
      type: 'primary'
    };
  },

  render () {
    const styles = this.styles();

    return (

          {(this.props.icon && !this.props.isActive) ? <Icon size={20} style={styles.icon} type={this.props.icon} /> : null}
          {this.props.isActive ? (
            <Spin direction='counterclockwise'>
              <Icon size={20} type='spinner' />
            </Spin>
          ) : null }

            {this.props.isActive ? this.props.actionText : this.props.children}

    );
  },

  styles () {
    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: StyleConstants.FontSizes.MEDIUM,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        cursor: 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: this.props.primaryColor,
        borderColor: this.props.primaryColor,
        color: StyleConstants.Colors.WHITE,
        fill: StyleConstants.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: this.props.primaryColor,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: this.props.primaryColor,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.ASH,
        color: StyleConstants.Colors.ASH,
        fill: StyleConstants.Colors.ASH,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: StyleConstants.Colors.ASH,
          borderColor: StyleConstants.Colors.ASH,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -8),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -8),
          transition: 'all .2s ease-in',
          borderColor: StyleConstants.Colors.FOG
        },
        ':active': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -16),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -16),
          transition: 'all .2s ease-in',
          backgroundColor: StyleConstants.Colors.PORCELAIN
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        borderRadius: 2,
        borderWidth: 1,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        ':hover': {
          backgroundColor: StyleConstants.Colors.PORCELAIN
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.PORCELAIN, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        color: StyleConstants.Colors.FOG,
        fill: StyleConstants.Colors.FOG
      },
      icon: {
        marginLeft: this.props.children ? -4 : 0,
        marginRight: this.props.children ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  }
});

module.exports = Radium(Button);
<commit_msg>alters cursor for disabled buttons<commit_after>const React = require('react');
const Radium = require('radium');

const Spin = require('./Spin');

const StyleConstants = require('../constants/Style');

const Icon = require('../components/Icon');

const Button = React.createClass({
  propTypes: {
    actionText: React.PropTypes.string,
    icon: React.PropTypes.string,
    isActive: React.PropTypes.bool,
    onClick: React.PropTypes.func,
    primaryColor: React.PropTypes.string,
    style: React.PropTypes.object,
    type: React.PropTypes.oneOf([
      'base',
      'disabled',
      'neutral',
      'primary',
      'primaryOutline',
      'secondary'
    ])
  },

  getDefaultProps () {
    return {
      onClick () {},
      isActive: false,
      primaryColor: StyleConstants.Colors.PRIMARY,
      type: 'primary'
    };
  },

  render () {
    const styles = this.styles();

    return (

          {(this.props.icon && !this.props.isActive) ? <Icon size={20} style={styles.icon} type={this.props.icon} /> : null}
          {this.props.isActive ? (
            <Spin direction='counterclockwise'>
              <Icon size={20} type='spinner' />
            </Spin>
          ) : null }

            {this.props.isActive ? this.props.actionText : this.props.children}

    );
  },

  styles () {
    return {
      component: Object.assign({
        borderRadius: 2,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: 'transparent',
        boxSizing: 'border-box',
        display: 'inline-block',
        padding: '4px 14px',
        fontSize: StyleConstants.FontSizes.MEDIUM,
        fontFamily: StyleConstants.Fonts.SEMIBOLD,
        cursor: this.props.type === 'disabled' ? 'default' : 'pointer',
        transition: 'all .2s ease-in',
        minWidth: 16,
        position: 'relative'
      }, this.props.style),
      children: {
        justifyContent: 'center',
        display: 'flex',
        alignItems: 'center',
        lineHeight: '20px'
      },
      primary: {
        backgroundColor: this.props.primaryColor,
        borderColor: this.props.primaryColor,
        color: StyleConstants.Colors.WHITE,
        fill: StyleConstants.Colors.WHITE,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -15),
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          transition: 'all .2s ease-in'
        }
      },
      primaryOutline: {
        backgroundColor: 'transparent',
        borderColor: this.props.primaryColor,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: this.props.primaryColor,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          borderColor: StyleConstants.adjustColor(this.props.primaryColor, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      secondary: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.ASH,
        color: StyleConstants.Colors.ASH,
        fill: StyleConstants.Colors.ASH,
        transition: 'all .2s ease-in',

        ':hover': {
          backgroundColor: StyleConstants.Colors.ASH,
          borderColor: StyleConstants.Colors.ASH,
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          borderColor: StyleConstants.adjustColor(StyleConstants.Colors.ASH, -30),
          color: StyleConstants.Colors.WHITE,
          fill: StyleConstants.Colors.WHITE,
          transition: 'all .2s ease-in'
        }
      },
      base: {
        backgroundColor: 'transparent',
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        transition: 'all .2s ease-in',
        borderColor: 'transparent',
        borderRadius: 2,
        borderWidth: 1,
        ':hover': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -8),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -8),
          transition: 'all .2s ease-in',
          borderColor: StyleConstants.Colors.FOG
        },
        ':active': {
          color: StyleConstants.adjustColor(this.props.primaryColor, -16),
          fill: StyleConstants.adjustColor(this.props.primaryColor, -16),
          transition: 'all .2s ease-in',
          backgroundColor: StyleConstants.Colors.PORCELAIN
        }
      },
      neutral: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        borderRadius: 2,
        borderWidth: 1,
        color: this.props.primaryColor,
        fill: this.props.primaryColor,
        ':hover': {
          backgroundColor: StyleConstants.Colors.PORCELAIN
        },
        ':active': {
          backgroundColor: StyleConstants.adjustColor(StyleConstants.Colors.PORCELAIN, -15)
        }
      },
      disabled: {
        backgroundColor: 'transparent',
        borderColor: StyleConstants.Colors.FOG,
        color: StyleConstants.Colors.FOG,
        fill: StyleConstants.Colors.FOG
      },
      icon: {
        marginLeft: this.props.children ? -4 : 0,
        marginRight: this.props.children ? 5 : 0
      },
      buttonText: {
        marginLeft: (this.props.isActive && this.props.actionText) ? 10 : 0
      }
    };
  }
});

module.exports = Radium(Button);
<|endoftext|>


<commit_before>'use strict'

const { css } = require('glamor')
const propTypes = require('prop-types')

const h = require('../utils/h')
const { BORDER_RADIUS } = require('../constants/sizes')
const { MID } = require('../constants/colors')

const IconSearch = require('./IconSearch')

// DOM Element reference must be used to select the whole input content
// on focus. The event of onFocus can't be used after a delay.
let elem

const style = {

	self: css({
		position: 'relative',
		display: 'flex',
		alignItems: 'center',
		padding: '1.05em 1.2em',
		width: '100%',
		background: MID,
		borderRadius: BORDER_RADIUS
	}),

	icon: css({
		margin: '0 0 1px',
		width: '1em',
		height: '1em'
	}),

	input: css({
		position: 'absolute',
		top: '0',
		left: '0',
		padding: '0 0 0 2.7em',
		width: '100%',
		height: '100%',
		background: 'transparent',
		color: 'currentcolor',
		font: 'inherit',
		outline: 'none',
		border: '0'
	})

}

module.exports = ({ filter, setFilter }) => (

	h('div', { className: style.self.toString() },
		h('div', { className: style.icon.toString() },
			h(IconSearch)
		),
		h('input', {
			id: 'filter',
			className: style.input.toString(),
			placeholder: 'Search…',
			value: filter,
			ref: (_elem) => elem = _elem,
			onFocus: () => requestAnimationFrame(() => elem.select()),
			onChange: (e) => setFilter(e.target.value)
		})
	)

)

module.exports.displayName = 'Filter'

module.exports.propTypes = {

	filter: propTypes.string.isRequired,
	setFilter: propTypes.func.isRequired

}<commit_msg>Use React.createRef<commit_after>'use strict'

const { createRef } = require('react')
const { css } = require('glamor')
const propTypes = require('prop-types')

const h = require('../utils/h')
const { BORDER_RADIUS } = require('../constants/sizes')
const { MID } = require('../constants/colors')

const IconSearch = require('./IconSearch')

const style = {

	self: css({
		position: 'relative',
		display: 'flex',
		alignItems: 'center',
		padding: '1.05em 1.2em',
		width: '100%',
		background: MID,
		borderRadius: BORDER_RADIUS
	}),

	icon: css({
		margin: '0 0 1px',
		width: '1em',
		height: '1em'
	}),

	input: css({
		position: 'absolute',
		top: '0',
		left: '0',
		padding: '0 0 0 2.7em',
		width: '100%',
		height: '100%',
		background: 'transparent',
		color: 'currentcolor',
		font: 'inherit',
		outline: 'none',
		border: '0'
	})

}

module.exports = ({ filter, setFilter }) => {

	// DOM Element reference must be used to select the whole input content
	// on focus. The event of onFocus can't be used after a delay.
	const elem = createRef()

	return (
		h('div', { className: style.self.toString() },
			h('div', { className: style.icon.toString() },
				h(IconSearch)
			),
			h('input', {
				id: 'filter',
				className: style.input.toString(),
				placeholder: 'Search…',
				value: filter,
				ref: elem,
				onFocus: () => requestAnimationFrame(() => elem.current.select()),
				onChange: (e) => setFilter(e.target.value)
			})
		)
	)

}

module.exports.displayName = 'Filter'

module.exports.propTypes = {

	filter: propTypes.string.isRequired,
	setFilter: propTypes.func.isRequired

}<|endoftext|>


<commit_before>import React from 'react';
import links from '../constants/links';

const Footer = (props) => {
  return (

© 2017 Adopt A Family

 |

          Privacy Policy

          Contact Us

  );
};

export default Footer;<commit_msg>AAF-54 Fix security issue with noopener referrer<commit_after>import React from 'react';
import links from '../constants/links';

const Footer = (props) => {
  return (

© 2017 Adopt A Family

 |

          Privacy Policy

          Contact Us

  );
};

export default Footer;<|endoftext|>


<commit_before>import React from 'react';
import Interactive from 'react-interactive';
import { Link } from 'react-router-dom';
//import { Code } from '../styles/style';
//import s from '../styles/home.style';

function Header() {

// different hights for different screen sizes fixes problem with background sometimes covers all content or sometimes goes after the screensize
    if (window.innerWidth>1093 && window.innerHeight<590){
          var oh = "auto";
          var h = "auto";
          var o = "100%"
          console.log("1");
    }

    else if (window.innerWidth>1093 && window.innerHeight>590){
          var oh = "100%";
          var h = "auto";
          var o = "100%"
          console.log("2");
    }

    else if(window.innerWidth<window.innerHeight && window.innerWidth<1093) {
          var oh = "100%";
          var h = 500+"px";
          var o = "100%";
          var k = "auto";
          console.log("3");
    }

    else {
      var oh = "auto";
      var h = 500+"px";
      var o = "100%"
      console.log("4");
    }

    return (

Evelina Laroussi

Who am i?

Hi, I am a student at KTH in Stockholm Sweden, doing my best to become a great engineer with a master in interactive mediatechnology. I am currently at the last (5th) year and will soon be looking for the next chapter in my career. I like front-end developing, but i also have a thing for interaction design. Some say you can't do both... I say of course you can!

<Link to={`/About`}>
About
</Link><Link to={`/work`}>
Work
</Link><Link to={`/contact`}>
Contact
</Link>

    );
};

export default Header;
<commit_msg>testing<commit_after>import React from 'react';
import Interactive from 'react-interactive';
import { Link } from 'react-router-dom';
//import { Code } from '../styles/style';
//import s from '../styles/home.style';

function Header() {

// different hights for different screen sizes fixes problem with background sometimes covers all content or sometimes goes after the screensize
    if (window.innerWidth>1093 && window.innerHeight<590){
          var oh = "auto";
          var h = "auto";
          var o = "100%"
          console.log("1");
    }

    else if (window.innerWidth>1093 && window.innerHeight>590){
          var oh = "100%";
          var h = "auto";
          var o = "100%"
          console.log("2");
    }

    else if(window.innerWidth<window.innerHeight && window.innerWidth<1093) {
          var oh = "100%";
          var h = 500+"px";
          var o = "100%";
          var k = "auto";
          console.log("3");
    }

    else {
      var oh = "auto";
      var h = 500+"px";
      var o = "100%"
      console.log("4");
    }

    return (

Evelina Laroussi

Who am i?

Hi, I am a student at KTH in Stockholm Sweden, doing my best to become a great engineer with a master in interactive mediatechnology. I am currently at the last (5th) year and will soon be looking for the next chapter in my career. I like front-end developing, but i also have a thing for interaction design. Some say you can not do both... I say of course you can!

<Link to={`/About`}>
About
</Link><Link to={`/work`}>
Work
</Link><Link to={`/contact`}>
Contact
</Link>

    );
};

export default Header;
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import styled from 'styled-components';

import icons from '../icons';

const Wrapper = styled.div`
  display: flex;
  align-items: center;
  height: 10vh;
`;

const Title = styled.h1`
  display: inline-block;
  margin: 20px 20px;
  color: #FFF;
  flex-grow: 1;
`;

const Label = styled.label`
  color: #FFF;
  margin-right: 10px;
  font-size: 20px;
`;

const SubInput = styled.input`
  margin-right: 20px;
  width: 175px;
  height: 30px;
  padding: 1px 5px;
  background-color: transparent;
  border: 1px solid #FFF;
  border-radius: 2px;
  font-size: 20px;
  color: #FFF;
  appearance: none;

  &:focus {
    outline: none;
  }
`;

const Icon = styled.img`
  cursor: pointer;
  margin-right: 20px;
`;

class Header extends Component {

  render() {
    return (
      <Wrapper>
        <Title>V</Title>
        <form
          autoComplete="off"
          onSubmit={e => {
            e.preventDefault();
            this.props.changeSub(e.target['sub'].value);
            e.target['sub'].blur();
          }}>
          /r/
          <SubInput
            autocomplete="off"
            name="sub"
            placeholder="videos"/>
        </form>
        <Icon
          src={icons.settings}
          alt="settings icon"
          onClick={this.props.toggleSettings} />
      </Wrapper>
    );
  }
}

export default Header;
<commit_msg>realign header items<commit_after>import React, {Component} from 'react';
import styled from 'styled-components';

import icons from '../icons';

const Wrapper = styled.div`
  display: flex;
  align-items: center;
  height: 10vh;
  justify-content: space-between;
`;

const Title = styled.h1`
  display: inline-block;
  margin: 20px 20px;
  color: #FFF;
`;

const Label = styled.label`
  color: #FFF;
  margin-right: 10px;
  font-size: 20px;
`;

const SubInput = styled.input`
  margin-right: 20px;
  width: 175px;
  height: 30px;
  padding: 1px 5px;
  background-color: transparent;
  border: 1px solid #FFF;
  border-radius: 2px;
  font-size: 20px;
  color: #FFF;
  appearance: none;

  &:focus {
    outline: none;
  }
`;

const Icon = styled.img`
  cursor: pointer;
  margin-right: 20px;
`;

class Header extends Component {

  render() {
    return (
      <Wrapper>
        <Title>V</Title>
        <form
          autoComplete="off"
          onSubmit={e => {
            e.preventDefault();
            this.props.changeSub(e.target['sub'].value);
            e.target['sub'].blur();
          }}>
          /r/
          <SubInput
            autocomplete="off"
            name="sub"
            placeholder="videos"/>
        </form>
        <Icon
          src={icons.settings}
          alt="settings icon"
          onClick={this.props.toggleSettings} />
      </Wrapper>
    );
  }
}

export default Header;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { FacebookLikeButton, FacebookShareButton, TwitterButton } from 'react-social-buttons'
if (process.env.BROWSER) {
        require("./Header.css");
}

export default class Header extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        let url = "https://www.twreporter.org/";
        return (

                <FacebookShareButton url={url} />

        )
    }
}

Header.propTypes = { }
<commit_msg>remove the social button package<commit_after>import React, { Component, PropTypes } from 'react'
if (process.env.BROWSER) {
        require("./Header.css");
}

export default class Header extends Component {
    constructor(props) {
        super(props)
    }
    render() {
        let url = "https://www.twreporter.org/";
        return (

        )
    }
}

Header.propTypes = { }
<|endoftext|>


<commit_before>/**
 * Created by epotignano on 19/02/16.
 */

import React, {PropTypes} from 'react';
import { connect } from 'react-redux';
import { Link } from "react-router";
import UserAvatar  from './userAvatar';
import { changeLanguage } from '../actions/UserActions';
import { UidRef, UserLanguage } from '../constants/Commons';

var uid = localStorage.getItem(UidRef);
var language = localStorage.getItem(UserLanguage);

class NavBar extends React.Component {
  componentDidMount() {
    const { dispatch } = this.props;

    /*$('.ui.dropdown').dropdown({
      onChange: function(value, text, $selectedItem) {
        dispatch(changeLanguage(value));
        localStorage.setItem(UserLanguage, value);
      }
    });*/
  }

  componentDidUpdate() {
    /*$('.ui.dropdown').dropdown('refresh')*/
  }
  render() {
    const { router } = this.context;
    var { user } = this.props;
    var languageJson = user.languageJson ? user.languageJson : {};
    var defaultText = language ? language : 'Idioma';

    return (

              {defaultText}

es-PA

es-AR

en-US

    )
  }
}

NavBar.contextTypes = {
  router: PropTypes.any
};
NavBar.propTypes = {
  dispatch: PropTypes.func.isRequired
};

var mapStateProps = function(state) {
  const { auth, user } = state;

  return  {
    auth,user
  }
};

export default connect(mapStateProps)(NavBar);
<commit_msg>Remuevo dependencias de jquery<commit_after>/**
 * Created by epotignano on 19/02/16.
 */

import React, {PropTypes} from "react";
import {connect} from "react-redux";
import {UidRef, UserLanguage} from "../constants/Commons";
import { changeLanguage } from '../actions/UserActions';
import getMuiTheme from "material-ui/styles/getMuiTheme";
import AppTheme from "../settings/AppTheme";

import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';

var uid = localStorage.getItem(UidRef);
var language = localStorage.getItem(UserLanguage);
console.log(language);
class NavBar extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      value: language || 'es-PA'
    }
  }

  getChildContext() {
    return {muiTheme: getMuiTheme(AppTheme)};
  }

  componentDidMount() {
    const { dispatch } = this.props;
  }

  componentDidUpdate() {
  }

  render() {
    const { router } = this.context;
    var { user } = this.props;
    var languageJson = user.languageJson ? user.languageJson : {};
    var defaultText = language ? language : 'Idioma';

    return (

            <DropDownMenu value={this.state.value} onChange={(event, index, value) =>{
              const { dispatch } = this.props;
              dispatch(changeLanguage(value));
              localStorage.setItem(UserLanguage, value);
              this.setState({value})
            }} openImmediately={false}>
              <MenuItem value={'es-PA'} primaryText="es-PA" />
              <MenuItem value={'es-AR'} primaryText="es-AR" />
              <MenuItem value={'en-US'} primaryText="en-US" />
            </DropDownMenu>

    )
  }
}

NavBar.contextTypes = {
  router: PropTypes.any
};
NavBar.propTypes = {
  dispatch: PropTypes.func.isRequired
};

NavBar.childContextTypes = {
  muiTheme: React.PropTypes.object.isRequired,
};

var mapStateProps = function(state) {
  const { auth, user } = state;

  return  {
    auth,user
  }
};

export default connect(mapStateProps)(NavBar);
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'

import AppBar from 'material-ui/lib/app-bar'
import IconButton from 'material-ui/lib/icon-button'
import NavigationHome from 'material-ui/lib/svg-icons/action/home'
import ToothIcon from '../images/tooth-icon.js'
import IconMenu from 'material-ui/lib/menus/icon-menu'
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'
import MenuItem from 'material-ui/lib/menus/menu-item'
import Isvg from 'react-inlinesvg'
import { Link } from 'react-router'

//<ToothIcon />

export default React.createClass({
  render() {
    return (
      <AppBar
        title="TOOTH & PAIL"
        iconElementLeft={<Link to={'/'}><IconButton><NavigationHome/></IconButton></Link>}
        iconElementRight={
          <IconMenu
            iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
            targetOrigin={{horizontal: 'right', vertical: 'top'}}
            anchorOrigin={{horizontal: 'right', vertical: 'top'}}
          >
            <MenuItem primaryText="Donate Teeth" />
            <MenuItem primaryText="Buy Used Teeth" />
            <MenuItem primaryText="Perform Amature Sergery" />
            <MenuItem primaryText="Sign out" />
          </IconMenu>
        }
      />
    )
  }
})
<commit_msg>Delete uneeded require<commit_after>import React from 'react'
import ReactDOM from 'react-dom'

import AppBar from 'material-ui/lib/app-bar'
import IconButton from 'material-ui/lib/icon-button'
import NavigationHome from 'material-ui/lib/svg-icons/action/home'
import ToothIcon from '../images/tooth-icon.js'
import IconMenu from 'material-ui/lib/menus/icon-menu'
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'
import MenuItem from 'material-ui/lib/menus/menu-item'
import { Link } from 'react-router'

//<ToothIcon />

export default React.createClass({
  render() {
    return (
      <AppBar
        title="TOOTH & PAIL"
        iconElementLeft={<Link to={'/'}><IconButton><NavigationHome/></IconButton></Link>}
        iconElementRight={
          <IconMenu
            iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
            targetOrigin={{horizontal: 'right', vertical: 'top'}}
            anchorOrigin={{horizontal: 'right', vertical: 'top'}}
          >
            <MenuItem primaryText="Donate Teeth" />
            <MenuItem primaryText="Buy Used Teeth" />
            <MenuItem primaryText="Perform Amature Sergery" />
            <MenuItem primaryText="Sign out" />
          </IconMenu>
        }
      />
    )
  }
})
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {Nav, Navbar, NavItem} from "react-bootstrap";

import packageJson from '../../package.json';

export default class Header extends Component {

  render() {
    return (
      <Navbar inverse fixedTop>
        <Navbar.Header>
          <Navbar.Brand>
            <a href=${process.env.PUBLIC_URL} title={`Okapi Longhorn JS Client ${packageJson.version}`}>Okapi Longhorn JS Client
          </Navbar.Brand>
          <Navbar.Toggle />
        </Navbar.Header>
        <Navbar.Collapse>

            <NavItem href="http://okapiframework.org/wiki/index.php?title=Longhorn" target="blank">Longhorn Wiki</NavItem>

        </Navbar.Collapse>
      </Navbar>
    );
  }
};<commit_msg>Fixed typo<commit_after>import React, {Component} from 'react';
import {Nav, Navbar, NavItem} from "react-bootstrap";

import packageJson from '../../package.json';

export default class Header extends Component {

  render() {
    return (
      <Navbar inverse fixedTop>
        <Navbar.Header>
          <Navbar.Brand>
            <a href={process.env.PUBLIC_URL} title={`Okapi Longhorn JS Client ${packageJson.version}`}>Okapi Longhorn JS Client
          </Navbar.Brand>
          <Navbar.Toggle />
        </Navbar.Header>
        <Navbar.Collapse>

            <NavItem href="http://okapiframework.org/wiki/index.php?title=Longhorn" target="blank">Longhorn Wiki</NavItem>

        </Navbar.Collapse>
      </Navbar>
    );
  }
};<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import Appbar from 'muicss/lib/react/appbar';
import { logout } from '../helpers/auth'

export default class join extends Component {
  state = {
    authed: false,
    loading: true
  }
  render() {
    var styles = {
      white: {
        color: "white"
      }
    };
    return (
      <Appbar>

              <Link
                style={styles.white}
                to="/">Werewolf</Link>

                {this.props.authed
                  ?  {
                      logout()
                    } }
                    className="navbar-brand">Logout
                  :
                    <Link
                      style={styles.white}
                      to="/login">Login</Link>
                    <Link
                      style={styles.white}
                      to="/register">Register</Link>
                  }

      </Appbar>
    )
  }
}
<commit_msg>reworked appbar for M-UI<commit_after>import React, {Component} from 'react'
import {Link} from 'react-router-dom'
import { withRouter } from 'react-router-dom'
import {logout} from '../helpers/auth'
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';

class navbar extends Component {

  constructor(props) {
    super(props)
    this.state = {
      authed: false,
      loading: true
    };
  }
  goHome() {
    this.props.history.push('/main')
  }
  goLogin() {
    logout()
    this.props.history.push('/login')
  }
  render() {
    return (
      <AppBar
        title={  Werwolves }

        iconElementRight={this.props.authed
        ?
        <FlatButton label="Logout"/>
        :
        <FlatButton label="Login"/>
        }
        onTitleTouchTap={this
        .goHome
        .bind(this)}
        onRightIconButtonTouchTap={this
        .goLogin
        .bind(this)}
        showMenuIconButton={false}/>
    )
  }
}

export default withRouter(navbar)
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import ReactPlayer from 'react-player';
import {connect} from 'react-redux';

import {
  togglePlayer, toggleControls,
  setVolume, updatePlayed,
  seek, setDuration
} from '../redux/actions/playerActions';

import icons from '../icons';

import {
  Wrapper,
  ControlBar,
  Progress,
  ProgressFilled,
  Time,
  Controls,
  Toggle,
  Volume,
  PrevButton,
  NextButton
} from './PlayerStyles';

import {secToFormat} from '../lib/utils';

class Player extends Component {
  toggleControls(e) {
    if(e.type === 'mouseenter') {
      this.props.dispatch(toggleControls(true));
    } else {
      this.props.dispatch(toggleControls(false));
    }
  }

  scrub(e) {
    const seekTo = parseFloat(e.nativeEvent.offsetX / e.target.parentNode.offsetWidth);
    this.player.seekTo(seekTo);
    this.props.dispatch(updatePlayed(seekTo));
  }

  render() {
    // redux variables
    const {
      playing,
      played,
      volume,
      seeking,
      showControls,
      duration,
      dispatch,
      getPrevNextPost,
      url
    } = this.props;

    // functions
    const {
      toggleControls,
      scrub
    } = this;

    return (
      <Wrapper
        onMouseEnter={toggleControls.bind(this)}
        onMouseLeave={toggleControls.bind(this)}>
        <ReactPlayer
          ref={player => {this.player = player}}
          url={url}
          progressFrequency={250}
          playing={playing}
          volume={volume}
          onPlay={() => dispatch(togglePlayer(true))}
          onPause={() => dispatch(togglePlayer(false))}
          onProgress={({played}) => !seeking && dispatch(updatePlayed(played))}
          onDuration={(duration) => dispatch(setDuration(duration))}
          onEnded={() => {
            // reset the player and start the next post
            dispatch(updatePlayed(0));
            getPrevNextPost(true);
          }}
          width="100%"
          height="100%"
          // this doesn't work with the default showinfo=0 option
          // thank google for that but it's either the title bar or small logo
          youtubeConfig={{playerVars: {modestbranding: 1}}} />
        <ControlBar visible={showControls}>
          <Progress
            extend={showControls}
            onClick={scrub.bind(this)}
            onMouseMove={seeking && scrub.bind(this)}
            onMouseDown={() => {
              dispatch(seek(true), togglePlayer(false));
            }}
            onMouseUp={() => {
              dispatch(seek(false), togglePlayer(true));
            }}
            onMouseLeave={() => seeking && dispatch(seek(false), togglePlayer(true))}
            >
            <ProgressFilled played={played} />
          </Progress>
          <Controls>
            <Toggle
              src={playing ? icons.pause : icons.play_arrow}
              onClick={() => dispatch(togglePlayer(!playing))}
            />
            <Time>{secToFormat(played * duration)} / {secToFormat(duration)}</Time>
            <Volume
              onChange={(e) => dispatch(setVolume(parseFloat(e.target.value)))}
              type="range"
              name="volume"
              min={0} max={1} step={0.05}
              value={volume} />
          </Controls>
        </ControlBar>
        <PrevButton
          visible={showControls}
          onClick={() => getPrevNextPost(false)}
          src={icons.chevron_left} />
        <NextButton
          visible={showControls}
          onClick={() => getPrevNextPost(true)}
          src={icons.chevron_right} />
      </Wrapper>
    );
  }
}

Player.propTypes = {
  playing: PropTypes.bool.isRequired,
  played: PropTypes.number.isRequired,
  volume: PropTypes.number.isRequired,
  seeking: PropTypes.bool.isRequired,
  showControls: PropTypes.bool.isRequired,
  duration: PropTypes.number,
  dispatch: PropTypes.func.isRequired
}

const mapStateToProps = ({playerReducer}, ownProps) => {
  return {
    playing: playerReducer.playing,
    played: playerReducer.played,
    volume: playerReducer.volume,
    seeking: playerReducer.seeking,
    showControls: playerReducer.showControls,
    duration: playerReducer.duration,
  }
}

export default connect(mapStateToProps)(Player);
<commit_msg>smoother and updated progress bar<commit_after>import React, {Component, PropTypes} from 'react';
import ReactPlayer from 'react-player';
import {connect} from 'react-redux';

import {
  togglePlayer, toggleControls,
  setVolume, updatePlayed,
  seek, setDuration
} from '../redux/actions/playerActions';

import icons from '../icons';

import {
  Wrapper,
  ControlBar,
  Progress,
  ProgressFilled,
  Time,
  Controls,
  Toggle,
  Volume,
  PrevButton,
  NextButton
} from './PlayerStyles';

import {secToFormat} from '../lib/utils';

class Player extends Component {
  componentWillReceiveProps(nextProps) {
    // checks if a new video is being loaded
    if(nextProps.url !== this.props.url) {
      // reset the progress and time
      this.props.dispatch(updatePlayed(0));
      this.props.dispatch(setDuration(0));
    }
  }

  toggleControls(e) {
    if(e.type === 'mouseenter') {
      this.props.dispatch(toggleControls(true));
    } else {
      this.props.dispatch(toggleControls(false));
    }
  }

  scrub(e) {
    const seekTo = parseFloat(e.nativeEvent.offsetX / e.target.parentNode.offsetWidth);
    this.player.seekTo(seekTo);
    this.props.dispatch(updatePlayed(seekTo));
  }

  render() {
    // redux variables
    const {
      playing,
      played,
      volume,
      seeking,
      showControls,
      duration,
      dispatch,
      getPrevNextPost,
      url
    } = this.props;

    // functions
    const {
      toggleControls,
      scrub
    } = this;

    return (
      <Wrapper
        onMouseEnter={toggleControls.bind(this)}
        onMouseLeave={toggleControls.bind(this)}>
        <ReactPlayer
          ref={player => {this.player = player}}
          url={url}
          playing={playing}
          volume={volume}
          // this is pretty dodgy because this means we're updating
          // the state alot, but it does give us a smooth bar
          progressFrequency={duration < 1000 ? duration : 1000}
          onPlay={() => dispatch(togglePlayer(true))}
          onPause={() => dispatch(togglePlayer(false))}
          onProgress={({played}) => !seeking && dispatch(updatePlayed(played))}
          onDuration={(duration) => dispatch(setDuration(duration))}
          onEnded={() => {
            // reset the player and start the next post
            dispatch(updatePlayed(0));
            getPrevNextPost(true);
          }}
          width="100%"
          height="100%"
          // this doesn't work with the default showinfo=0 option
          // thank google for that but it's either the title bar or small logo
          youtubeConfig={{playerVars: {modestbranding: 1}}} />
        <ControlBar visible={showControls}>
          <Progress
            extend={showControls}
            onClick={scrub.bind(this)}
            onMouseMove={seeking && scrub.bind(this)}
            onMouseDown={() => {
              dispatch(seek(true));
              dispatch(togglePlayer(false));
            }}
            onMouseUp={() => {
              dispatch(seek(false));
              dispatch(togglePlayer(true));
            }}
            onMouseLeave={() => seeking && dispatch(seek(false), togglePlayer(true))}
            >
            <ProgressFilled played={played} />
          </Progress>
          <Controls>
            <Toggle
              src={playing ? icons.pause : icons.play_arrow}
              onClick={() => dispatch(togglePlayer(!playing))}
            />
            <Time>{secToFormat(played * duration)} / {secToFormat(duration)}</Time>
            <Volume
              onChange={(e) => dispatch(setVolume(parseFloat(e.target.value)))}
              type="range"
              name="volume"
              min={0} max={1} step={0.05}
              value={volume} />
          </Controls>
        </ControlBar>
        <PrevButton
          visible={showControls}
          onClick={() => getPrevNextPost(false)}
          src={icons.chevron_left} />
        <NextButton
          visible={showControls}
          onClick={() => getPrevNextPost(true)}
          src={icons.chevron_right} />
      </Wrapper>
    );
  }
}

Player.propTypes = {
  playing: PropTypes.bool.isRequired,
  played: PropTypes.number.isRequired,
  volume: PropTypes.number.isRequired,
  seeking: PropTypes.bool.isRequired,
  showControls: PropTypes.bool.isRequired,
  duration: PropTypes.number,
  dispatch: PropTypes.func.isRequired
}

const mapStateToProps = ({playerReducer}, ownProps) => {
  return {
    playing: playerReducer.playing,
    played: playerReducer.played,
    volume: playerReducer.volume,
    seeking: playerReducer.seeking,
    showControls: playerReducer.showControls,
    duration: playerReducer.duration,
  }
}

export default connect(mapStateToProps)(Player);
<|endoftext|>


<commit_before>import React, { Component, Children } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import klass from '../cssClasses';
import { outerWidth } from '../dimensions';
import CSSTranslate from '../CSSTranslate';
import Swipe from 'react-easy-swipe';

class Thumbs extends Component {
    static displayName = 'Thumbs';

    static propsTypes = {
        children: PropTypes.element.isRequired,
        transitionTime: PropTypes.number,
        selectedItem: PropTypes.number,
        thumbWidth: PropTypes.number
    };

    static defaultProps = {
        selectedItem: 0,
        transitionTime: 350,
        axis: 'horizontal'
    };

    constructor(props) {
        super(props);

        this.state = {
            selectedItem: props.selectedItem,
            hasMount: false,
            firstItem: 0,
            itemSize: null,
            visibleItems: 0,
            lastPosition: 0,
            showArrows: false,
            images: this.getImages()
        }
    }

    componentDidMount(nextProps) {
        this.setupThumbs();
    }

    componentWillReceiveProps(props, state) {
        if (props.selectedItem !== this.state.selectedItem) {
            this.setState({
                selectedItem: props.selectedItem,
                firstItem: this.getFirstItem(props.selectedItem)
            });
        }
        if (props.children !== this.props.children) {
            this.setState({
               images: this.getImages()
            });
        }
    }

    componentDidUpdate(prevProps) {
        if (this.props.children === prevProps.children) {
            return;
        }

        // This will capture any size changes for arrow adjustments etc.
        // usually in the same render cycle so we don't see any flickers
        this.updateSizes();
    }

    componentWillUnmount() {
        this.destroyThumbs();
    }

    setItemsWrapperRef = node => {
        this.itemsWrapperRef = node;
    }

    setItemsListRef = node => {
        this.itemsListRef = node;
    }

    setThumbsRef = (node, index) => {
        if (!this.thumbsRef) {
            this.thumbsRef = [];
        }
        this.thumbsRef[index] = node;
    }

    setupThumbs() {
        // as the widths are calculated, we need to resize
        // the carousel when the window is resized
        window.addEventListener("resize", this.updateSizes);
        // issue #2 - image loading smaller
        window.addEventListener("DOMContentLoaded", this.updateSizes);

        // when the component is rendered we need to calculate
        // the container size to adjust the responsive behaviour
        this.updateSizes();
    }

    destroyThumbs() {
        // removing listeners
        window.removeEventListener("resize", this.updateSizes);
        window.removeEventListener("DOMContentLoaded", this.updateSizes);
    }

    updateSizes = () => {
        if (!this.props.children || !this.itemsWrapperRef) {
            return;
        }

        const total = this.props.children.length;
        const wrapperSize = this.itemsWrapperRef.clientWidth;
        const itemSize = this.props.thumbWidth ? this.props.thumbWidth : outerWidth(this.thumbsRef[0]);
        const visibleItems = Math.floor(wrapperSize / itemSize);
        const lastPosition = total - visibleItems;
        const showArrows = visibleItems < total;
        this.setState({
            itemSize,
            visibleItems,
            firstItem: showArrows ? this.getFirstItem(this.props.selectedItem) : 0,
            lastPosition,
            showArrows
        })
    }

    getImages() {
        const images = Children.map(this.props.children, (item, index) => {
            let img = item;

            // if the item is not an image, try to find the first image in the item's children.
            if (item.type !== "img") {
                img = Children.toArray(item.props.children).filter((children) => children.type === "img")[0];
            }

            if (!img || img.length === 0) {
                return null;
            }

            return img;
        });

        if (images.filter(image => image !== null).length === 0) {
            console.warn(`No images found! Can't build the thumb list without images. If you don't need thumbs, set showThumbs={false} in the Carousel. Note that it's not possible to get images rendered inside custom components. More info at https://github.com/leandrowd/react-responsive-carousel/blob/master/TROUBLESHOOTING.md`);

            return null;
        }

        return images;
    }

    setMountState = () => {
        this.setState({hasMount: true});
        this.updateSizes();
    }

    handleClickItem = (index, item) => {
        const handler = this.props.onSelectItem;

        if (typeof handler === 'function') {
            handler(index, item);
        }
    }

    onSwipeStart = () => {
        this.setState({
            swiping: true
        });
    }

    onSwipeEnd = () => {
        this.setState({
            swiping: false
        });
    }

    onSwipeMove = (deltaX) => {
        const leftBoundary = 0;

        const currentPosition = - this.state.firstItem * this.state.itemSize;
        const lastLeftBoundary = - this.state.visibleItems * this.state.itemSize;

        // prevent user from swiping left out of boundaries
        if (currentPosition === leftBoundary && deltaX > 0) {
            deltaX = 0;
        }

        // prevent user from swiping right out of boundaries
        if (currentPosition === lastLeftBoundary && deltaX < 0) {
            deltaX = 0;
        }

        const wrapperSize = this.itemsWrapperRef.clientWidth;
        const position = currentPosition + (100 / (wrapperSize / deltaX)) + '%';

        // if 3d isn't available we will use left to move
        [
            'WebkitTransform',
            'MozTransform',
            'MsTransform',
            'OTransform',
            'transform',
            'msTransform'
        ].forEach((prop) => {
            this.itemsListRef.style[prop] = CSSTranslate(position, this.props.axis);
        });
    }

    slideRight = (positions) => {
        this.moveTo(this.state.firstItem - (typeof positions === 'number' ? positions : 1));
    }

    slideLeft = (positions) => {
        this.moveTo(this.state.firstItem + (typeof positions === 'number' ? positions : 1));
    }

    moveTo = (position) => {
        // position can't be lower than 0
        position = position < 0 ? 0 : position;
        // position can't be higher than last postion
        position = position >= this.lastPosition ? this.lastPosition : position;

        this.setState({
            firstItem: position,
            // if it's not a slider, we don't need to set position here
            selectedItem: this.state.selectedItem
        });
    }

    getFirstItem (selectedItem) {
        let firstItem = selectedItem;

        if (selectedItem >= this.state.lastPosition) {
            firstItem = this.state.lastPosition;
        }

        if (selectedItem < (this.state.firstItem + this.state.visibleItems)) {
            firstItem = this.state.firstItem;
        }

        if (selectedItem < this.state.firstItem) {
            firstItem = selectedItem;
        }

        return firstItem;
    }

    renderItems () {
        return this.state.images.map((img, index) => {
            const itemClass = klass.ITEM(false, index === this.state.selectedItem && this.state.hasMount);

            const thumbProps = {
                key: index,
                ref: e => this.setThumbsRef(e, index),
                className: itemClass,
                onClick: this.handleClickItem.bind(this, index, this.props.children[index])
            };

            if (index === 0) {
                img = React.cloneElement(img, {
                    onLoad: this.setMountState
                });
            }

            return (

                    { img }

            );
        });
    }

    render () {
        if (!this.props.children) {
            return null;
        }

        // show left arrow?
        const hasPrev = this.state.showArrows && this.state.firstItem > 0;
        // show right arrow
        const hasNext = this.state.showArrows && this.state.firstItem < this.state.lastPosition;
        // obj to hold the transformations and styles
        let itemListStyles = {};

        const currentPosition = - this.state.firstItem * this.state.itemSize + 'px';

        const transformProp = CSSTranslate(currentPosition, this.props.axis);

        const transitionTime = this.props.transitionTime + 'ms';

        itemListStyles = {
                    'WebkitTransform': transformProp,
                       'MozTransform': transformProp,
                        'MsTransform': transformProp,
                         'OTransform': transformProp,
                          'transform': transformProp,
                        'msTransform': transformProp,
           'WebkitTransitionDuration': transitionTime,
              'MozTransitionDuration': transitionTime,
               'MsTransitionDuration': transitionTime,
                'OTransitionDuration': transitionTime,
                 'transitionDuration': transitionTime,
               'msTransitionDuration': transitionTime
        };

        return (

                    <button type="button" className={klass.ARROW_PREV(!hasPrev)} onClick={this.slideRight} />
                    <Swipe tagName="ul"
                        selectedItem={this.state.selectedItem}
                        className={klass.SLIDER(false, this.state.swiping)}
                        onSwipeLeft={this.slideLeft}
                        onSwipeRight={this.slideRight}
                        onSwipeMove={this.onSwipeMove}
                        onSwipeStart={this.onSwipeStart}
                        onSwipeEnd={this.onSwipeEnd}
                        style={itemListStyles}
                        ref={this.setItemsListRef}>
                        { this.renderItems() }
                    </Swipe>
                    <button type="button" className={klass.ARROW_NEXT(!hasNext)} onClick={this.slideLeft} />

        );
    }
}

export default Thumbs;
<commit_msg>Handle null item list ref<commit_after>import React, { Component, Children } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import klass from '../cssClasses';
import { outerWidth } from '../dimensions';
import CSSTranslate from '../CSSTranslate';
import Swipe from 'react-easy-swipe';

class Thumbs extends Component {
    static displayName = 'Thumbs';

    static propsTypes = {
        children: PropTypes.element.isRequired,
        transitionTime: PropTypes.number,
        selectedItem: PropTypes.number,
        thumbWidth: PropTypes.number
    };

    static defaultProps = {
        selectedItem: 0,
        transitionTime: 350,
        axis: 'horizontal'
    };

    constructor(props) {
        super(props);

        this.state = {
            selectedItem: props.selectedItem,
            hasMount: false,
            firstItem: 0,
            itemSize: null,
            visibleItems: 0,
            lastPosition: 0,
            showArrows: false,
            images: this.getImages()
        }
    }

    componentDidMount(nextProps) {
        this.setupThumbs();
    }

    componentWillReceiveProps(props, state) {
        if (props.selectedItem !== this.state.selectedItem) {
            this.setState({
                selectedItem: props.selectedItem,
                firstItem: this.getFirstItem(props.selectedItem)
            });
        }
        if (props.children !== this.props.children) {
            this.setState({
               images: this.getImages()
            });
        }
    }

    componentDidUpdate(prevProps) {
        if (this.props.children === prevProps.children) {
            return;
        }

        // This will capture any size changes for arrow adjustments etc.
        // usually in the same render cycle so we don't see any flickers
        this.updateSizes();
    }

    componentWillUnmount() {
        this.destroyThumbs();
    }

    setItemsWrapperRef = node => {
        this.itemsWrapperRef = node;
    }

    setItemsListRef = node => {
        this.itemsListRef = node;
    }

    setThumbsRef = (node, index) => {
        if (!this.thumbsRef) {
            this.thumbsRef = [];
        }
        this.thumbsRef[index] = node;
    }

    setupThumbs() {
        // as the widths are calculated, we need to resize
        // the carousel when the window is resized
        window.addEventListener("resize", this.updateSizes);
        // issue #2 - image loading smaller
        window.addEventListener("DOMContentLoaded", this.updateSizes);

        // when the component is rendered we need to calculate
        // the container size to adjust the responsive behaviour
        this.updateSizes();
    }

    destroyThumbs() {
        // removing listeners
        window.removeEventListener("resize", this.updateSizes);
        window.removeEventListener("DOMContentLoaded", this.updateSizes);
    }

    updateSizes = () => {
        if (!this.props.children || !this.itemsWrapperRef) {
            return;
        }

        const total = this.props.children.length;
        const wrapperSize = this.itemsWrapperRef.clientWidth;
        const itemSize = this.props.thumbWidth ? this.props.thumbWidth : outerWidth(this.thumbsRef[0]);
        const visibleItems = Math.floor(wrapperSize / itemSize);
        const lastPosition = total - visibleItems;
        const showArrows = visibleItems < total;
        this.setState({
            itemSize,
            visibleItems,
            firstItem: showArrows ? this.getFirstItem(this.props.selectedItem) : 0,
            lastPosition,
            showArrows
        })
    }

    getImages() {
        const images = Children.map(this.props.children, (item, index) => {
            let img = item;

            // if the item is not an image, try to find the first image in the item's children.
            if (item.type !== "img") {
                img = Children.toArray(item.props.children).filter((children) => children.type === "img")[0];
            }

            if (!img || img.length === 0) {
                return null;
            }

            return img;
        });

        if (images.filter(image => image !== null).length === 0) {
            console.warn(`No images found! Can't build the thumb list without images. If you don't need thumbs, set showThumbs={false} in the Carousel. Note that it's not possible to get images rendered inside custom components. More info at https://github.com/leandrowd/react-responsive-carousel/blob/master/TROUBLESHOOTING.md`);

            return null;
        }

        return images;
    }

    setMountState = () => {
        this.setState({hasMount: true});
        this.updateSizes();
    }

    handleClickItem = (index, item) => {
        const handler = this.props.onSelectItem;

        if (typeof handler === 'function') {
            handler(index, item);
        }
    }

    onSwipeStart = () => {
        this.setState({
            swiping: true
        });
    }

    onSwipeEnd = () => {
        this.setState({
            swiping: false
        });
    }

    onSwipeMove = (deltaX) => {
        const leftBoundary = 0;

        const currentPosition = - this.state.firstItem * this.state.itemSize;
        const lastLeftBoundary = - this.state.visibleItems * this.state.itemSize;

        // prevent user from swiping left out of boundaries
        if (currentPosition === leftBoundary && deltaX > 0) {
            deltaX = 0;
        }

        // prevent user from swiping right out of boundaries
        if (currentPosition === lastLeftBoundary && deltaX < 0) {
            deltaX = 0;
        }

        const wrapperSize = this.itemsWrapperRef.clientWidth;
        const position = currentPosition + (100 / (wrapperSize / deltaX)) + '%';

        // if 3d isn't available we will use left to move
        if (this.itemsListRef) {
            [
                'WebkitTransform',
                'MozTransform',
                'MsTransform',
                'OTransform',
                'transform',
                'msTransform'
            ].forEach((prop) => {
                this.itemsListRef.style[prop] = CSSTranslate(position, this.props.axis);
            });
        }
    }

    slideRight = (positions) => {
        this.moveTo(this.state.firstItem - (typeof positions === 'number' ? positions : 1));
    }

    slideLeft = (positions) => {
        this.moveTo(this.state.firstItem + (typeof positions === 'number' ? positions : 1));
    }

    moveTo = (position) => {
        // position can't be lower than 0
        position = position < 0 ? 0 : position;
        // position can't be higher than last postion
        position = position >= this.lastPosition ? this.lastPosition : position;

        this.setState({
            firstItem: position,
            // if it's not a slider, we don't need to set position here
            selectedItem: this.state.selectedItem
        });
    }

    getFirstItem (selectedItem) {
        let firstItem = selectedItem;

        if (selectedItem >= this.state.lastPosition) {
            firstItem = this.state.lastPosition;
        }

        if (selectedItem < (this.state.firstItem + this.state.visibleItems)) {
            firstItem = this.state.firstItem;
        }

        if (selectedItem < this.state.firstItem) {
            firstItem = selectedItem;
        }

        return firstItem;
    }

    renderItems () {
        return this.state.images.map((img, index) => {
            const itemClass = klass.ITEM(false, index === this.state.selectedItem && this.state.hasMount);

            const thumbProps = {
                key: index,
                ref: e => this.setThumbsRef(e, index),
                className: itemClass,
                onClick: this.handleClickItem.bind(this, index, this.props.children[index])
            };

            if (index === 0) {
                img = React.cloneElement(img, {
                    onLoad: this.setMountState
                });
            }

            return (

                    { img }

            );
        });
    }

    render () {
        if (!this.props.children) {
            return null;
        }

        // show left arrow?
        const hasPrev = this.state.showArrows && this.state.firstItem > 0;
        // show right arrow
        const hasNext = this.state.showArrows && this.state.firstItem < this.state.lastPosition;
        // obj to hold the transformations and styles
        let itemListStyles = {};

        const currentPosition = - this.state.firstItem * this.state.itemSize + 'px';

        const transformProp = CSSTranslate(currentPosition, this.props.axis);

        const transitionTime = this.props.transitionTime + 'ms';

        itemListStyles = {
                    'WebkitTransform': transformProp,
                       'MozTransform': transformProp,
                        'MsTransform': transformProp,
                         'OTransform': transformProp,
                          'transform': transformProp,
                        'msTransform': transformProp,
           'WebkitTransitionDuration': transitionTime,
              'MozTransitionDuration': transitionTime,
               'MsTransitionDuration': transitionTime,
                'OTransitionDuration': transitionTime,
                 'transitionDuration': transitionTime,
               'msTransitionDuration': transitionTime
        };

        return (

                    <button type="button" className={klass.ARROW_PREV(!hasPrev)} onClick={this.slideRight} />
                    <Swipe tagName="ul"
                        selectedItem={this.state.selectedItem}
                        className={klass.SLIDER(false, this.state.swiping)}
                        onSwipeLeft={this.slideLeft}
                        onSwipeRight={this.slideRight}
                        onSwipeMove={this.onSwipeMove}
                        onSwipeStart={this.onSwipeStart}
                        onSwipeEnd={this.onSwipeEnd}
                        style={itemListStyles}
                        ref={this.setItemsListRef}>
                        { this.renderItems() }
                    </Swipe>
                    <button type="button" className={klass.ARROW_NEXT(!hasNext)} onClick={this.slideLeft} />

        );
    }
}

export default Thumbs;
<|endoftext|>