<commit_before>import React, {
  Fragment,
  useState,
  useEffect,
  useCallback,
  useMemo,
  useContext,
  useRef,
} from 'react';
import ReactDOM from 'react-dom';
import {randomID} from 'utility';

const FormContext = React.createContext();

const Form = ({
  formState,
  onChange,
  onEnter,
  errCheck,
  validCheck,
  children,
}) => {
  let error = useMemo(() => {
    if (errCheck) {
      return errCheck(formState);
    }
    return undefined;
  }, [errCheck, formState]);
  let valid = useMemo(() => {
    if (validCheck) {
      return validCheck(formState);
    }
    return undefined;
  }, [validCheck, formState]);
  return (
    <FormContext.Provider value={{formState, onChange, onEnter, error, valid}}>
      {children}
    </FormContext.Provider>
  );
};

const OptionsContainer = ({align, position, fixed, reference, children}) => {
  const [bounds, setBounds] = useState(
    reference.current.getBoundingClientRect(),
  );
  const [scrollY, setScrollY] = useState(window.scrollY);

  useEffect(() => {
    let running = null;
    const handler = () => {
      if (!running) {
        running = window.requestAnimationFrame(() => {
          setBounds(reference.current.getBoundingClientRect());
          setScrollY(window.scrollY);
          running = null;
        });
      }
    };
    window.addEventListener('resize', handler);
    window.addEventListener('scroll', handler);
    return () => {
      window.removeEventListener('resize', handler);
      window.removeEventListener('scroll', handler);
      if (running) {
        window.cancelAnimationFrame(running);
      }
    };
  }, [reference, setBounds, setScrollY]);

  const k = ['input-options'];
  const s = {};

  if (align === 'right') {
    s.left = bounds.right;
    k.push('right');
  } else {
    s.left = bounds.left;
    k.push('left');
  }
  if (position === 'top') {
    s.top = bounds.top;
    k.push('top');
  } else {
    s.top = bounds.bottom;
    k.push('bottom');
  }
  if (fixed) {
    k.push('fixed');
  } else {
    s.top += scrollY;
  }

  const so = {
    width: bounds.right - bounds.left,
  };

  return (

        {children}

  );
};

const preventDefault = (e) => {
  e.preventDefault();
};

const Option = ({
  close,
  reference,
  updateForm,
  name,
  value,
  selected,
  children,
}) => {
  const handler = useCallback(() => {
    if (updateForm) {
      updateForm(name, value);
    }
    close();
    reference.current.blur();
  }, [close, reference, updateForm, name, value]);

  const k = [];
  if (selected) {
    k.push('selected');
  }

  return (

      {children}

  );
};

const max = (a, b) => (a > b ? a : b);
const min = (a, b) => (a  {
  const [hidden, setHidden] = useState(true);
  const [index, setIndex] = useState(0);
  const optelem = useRef(null);

  const setHiddenHandler = useCallback(() => {
    setHidden(true);
    setIndex(0);
  }, [setHidden, setIndex]);

  const setVisibleHandler = useCallback(() => {
    setHidden(false);
    setIndex(0);
  }, [setHidden, setIndex]);

  const handleKeyDown = useCallback(
    (e) => {
      if (e.key === 'ArrowDown') {
        setIndex((i) => min(i + 1, dropdowninput.length - 1));
      } else if (e.key === 'ArrowUp') {
        setIndex((i) => max(i - 1, 0));
      } else if (e.key === 'Enter') {
        if (dropdowninput.length > 0) {
          updateForm(
            name,
            dropdowninput[min(max(index, 0), dropdowninput.length - 1)].value,
          );
        }
      }
    },
    [setIndex, updateForm, name, dropdowninput, index],
  );

  return (
    <Fragment>
      {optelem.current &&
        !hidden &&
        ReactDOM.createPortal(
          <OptionsContainer
            align={align}
            position={position}
            fixed={fixed}
            reference={optelem}
          >
            {dropdowninput.map((i, idx) => (
              <Option
                key={i.value}
                close={setHiddenHandler}
                reference={optelem}
                updateForm={updateForm}
                name={name}
                value={i.value}
                selected={index === idx}
              >
                {i.value}
              </Option>
            ))}
          </OptionsContainer>,
          document.body,
        )}
      <input
        ref={optelem}
        id={id}
        type={type}
        name={name}
        value={value}
        onChange={onChange}
        placeholder=" "
        onFocus={setVisibleHandler}
        onBlur={setHiddenHandler}
        onKeyDown={handleKeyDown}
      />
    </Fragment>
  );
};

const Input = ({
  type,
  name,
  value,
  onChange,
  onEnter,
  label,
  info,
  error,
  valid,
  dropdown,
  multiple,
  dropdowninput,
  textarea,
  toggle,
  accept,
  capture,
  checked,
  wide,
  fullWidth,
}) => {
  const id = useMemo(randomID, []);

  const context = useContext(FormContext);
  if (context) {
    if (context.formState) {
      if (type === 'radio' || type === 'checkbox') {
        checked = checked || context.formState[name];
      } else {
        value = value || context.formState[name];
      }
    }
    onChange = onChange || context.onChange;
    if (!textarea && !dropdowninput) {
      onEnter = onEnter || context.onEnter;
    }
    if (context.error) {
      error = error || context.error[name];
    }
    if (context.valid) {
      valid = valid || context.valid[name];
    }
  }

  const handleChange = useMemo(() => {
    if (!onChange) {
      return () => {};
    }
    switch (type) {
      case 'file':
        return (event) => {
          if (event.target.files.length < 1) {
            onChange(name, undefined);
          } else {
            onChange(name, event.target.files[0]);
          }
        };
      case 'checkbox':
        return (event) => {
          onChange(name, event.target.checked);
        };
      default:
        return (event) => {
          onChange(name, event.target.value);
        };
    }
  }, [type, name, onChange]);

  const handleEnter = useMemo(() => {
    if (!onEnter) {
      return () => {};
    }
    return (e) => {
      if (e.key === 'Enter') {
        onEnter();
      }
    };
  }, [onEnter]);

  const k = ['input'];

  if (valid) {
    k.push('valid');
  } else if (error) {
    k.push('invalid');
  }

  switch (type) {
    case 'file':
    case 'radio':
    case 'checkbox':
      k.push(type);
      break;
    default:
      k.push('normal');
  }

  if (toggle) {
    k.push('toggle');
  }

  if (wide) {
    k.push('wide');
  } else if (fullWidth) {
    k.push('full-width');
  }

  let inp = null;
  if (dropdowninput && Array.isArray(dropdowninput)) {
    inp = (
      <Select
        id={id}
        type={type}
        name={name}
        value={value}
        onChange={handleChange}
        dropdowninput={dropdowninput}
        updateForm={onChange}
      />
    );
  } else if (dropdown && Array.isArray(dropdown)) {
    inp = (
      <select
        id={id}
        value={value}
        multiple={multiple}
        onChange={handleChange}
        onKeyDown={handleEnter}
      >
        {dropdown.map((i) => (
          <option key={i.value} value={i.value}>
            {i.text}
          </option>
        ))}
      </select>
    );
  } else if (textarea) {
    inp = (
      <textarea
        id={id}
        name={name}
        value={value}
        onChange={handleChange}
        onKeyDown={handleEnter}
        placeholder=" "
      />
    );
  } else {
    switch (type) {
      case 'file':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            onChange={handleChange}
            onKeyDown={handleEnter}
            accept={accept}
            capture={capture}
            placeholder=" "
          />
        );
        break;
      case 'radio':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            checked={checked === value}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
        break;
      case 'checkbox':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            checked={checked}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
        break;
      default:
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
    }
  }

  let errDisplay = false;
  if (typeof error !== 'boolean') {
    errDisplay = true;
  }

  return (

      {inp}
      {label}
      {dropdown &&
}
      {!error && info && {info}}
      {error && (

          {!errDisplay && info}
          {errDisplay && error}

      )}

  );
};

const useForm = (initState = {}) => {
  const [formState, setFormState] = useState(initState);
  const updateForm = useCallback(
    (name, val) =>
      setFormState((prev) => Object.assign({}, prev, {[name]: val})),
    [setFormState],
  );
  return [formState, updateForm];
};

const matchChars = (from, to) => {
  let j = 0;
  for (let i = 0; i < from.length; i++) {
    while (j < to.length && to[j] !== from[i]) {
      j++;
    }
    if (j >= to.length) {
      return false;
    }
    j++;
  }
  return true;
};

const fuzzyFilter = (count, options, map, search) => {
  const s = search.toLowerCase();
  const matches = [];
  for (let i = 0; i < options.length && matches.length < count; i++) {
    const k = options[i];
    if (matchChars(s, map(k).toLowerCase())) {
      matches.push(k);
    }
  }
  return matches;
};

export {Input, useForm, fuzzyFilter, Form, Input as default};
<commit_msg>Impl form select wrap around<commit_after>import React, {
  Fragment,
  useState,
  useEffect,
  useCallback,
  useMemo,
  useContext,
  useRef,
} from 'react';
import ReactDOM from 'react-dom';
import {randomID} from 'utility';

const FormContext = React.createContext();

const Form = ({
  formState,
  onChange,
  onEnter,
  errCheck,
  validCheck,
  children,
}) => {
  let error = useMemo(() => {
    if (errCheck) {
      return errCheck(formState);
    }
    return undefined;
  }, [errCheck, formState]);
  let valid = useMemo(() => {
    if (validCheck) {
      return validCheck(formState);
    }
    return undefined;
  }, [validCheck, formState]);
  return (
    <FormContext.Provider value={{formState, onChange, onEnter, error, valid}}>
      {children}
    </FormContext.Provider>
  );
};

const OptionsContainer = ({align, position, fixed, reference, children}) => {
  const [bounds, setBounds] = useState(
    reference.current.getBoundingClientRect(),
  );
  const [scrollY, setScrollY] = useState(window.scrollY);

  useEffect(() => {
    let running = null;
    const handler = () => {
      if (!running) {
        running = window.requestAnimationFrame(() => {
          setBounds(reference.current.getBoundingClientRect());
          setScrollY(window.scrollY);
          running = null;
        });
      }
    };
    window.addEventListener('resize', handler);
    window.addEventListener('scroll', handler);
    return () => {
      window.removeEventListener('resize', handler);
      window.removeEventListener('scroll', handler);
      if (running) {
        window.cancelAnimationFrame(running);
      }
    };
  }, [reference, setBounds, setScrollY]);

  const k = ['input-options'];
  const s = {};

  if (align === 'right') {
    s.left = bounds.right;
    k.push('right');
  } else {
    s.left = bounds.left;
    k.push('left');
  }
  if (position === 'top') {
    s.top = bounds.top;
    k.push('top');
  } else {
    s.top = bounds.bottom;
    k.push('bottom');
  }
  if (fixed) {
    k.push('fixed');
  } else {
    s.top += scrollY;
  }

  const so = {
    width: bounds.right - bounds.left,
  };

  return (

        {children}

  );
};

const preventDefault = (e) => {
  e.preventDefault();
};

const Option = ({
  close,
  reference,
  updateForm,
  name,
  value,
  selected,
  children,
}) => {
  const handler = useCallback(() => {
    if (updateForm) {
      updateForm(name, value);
    }
    close();
    reference.current.blur();
  }, [close, reference, updateForm, name, value]);

  const k = [];
  if (selected) {
    k.push('selected');
  }

  return (

      {children}

  );
};

const Select = ({
  id,
  type,
  name,
  value,
  onChange,
  align,
  position,
  fixed,
  dropdowninput,
  updateForm,
}) => {
  const [hidden, setHidden] = useState(true);
  const [index, setIndex] = useState(0);
  const optelem = useRef(null);

  const setHiddenHandler = useCallback(() => {
    setHidden(true);
    setIndex(0);
  }, [setHidden, setIndex]);

  const setVisibleHandler = useCallback(() => {
    setHidden(false);
    setIndex(0);
  }, [setHidden, setIndex]);

  const handleKeyDown = useCallback(
    (e) => {
      if (e.key === 'ArrowDown') {
        setIndex((i) => {
          if (i + 1 > dropdowninput.length - 1) {
            return 0;
          }
          return i + 1;
        });
      } else if (e.key === 'ArrowUp') {
        setIndex((i) => {
          if (i - 1 < 0) {
            return dropdowninput.length - 1;
          }
          return i - 1;
        });
      } else if (e.key === 'Enter') {
        if (dropdowninput.length > 0) {
          if (index < 0 || index > dropdowninput.length - 1) {
            updateForm(name, dropdowninput[0].value);
            setIndex(0);
          } else {
            updateForm(name, dropdowninput[index].value);
          }
          setHidden(true);
        }
      }
    },
    [setIndex, setHidden, updateForm, name, dropdowninput, index],
  );

  const handleChange = useCallback(
    (e) => {
      if (index < 0 || index > dropdowninput.length - 1) {
        setIndex(0);
      }
      setHidden(false);
      onChange(e);
    },
    [setIndex, setHidden, onChange, dropdowninput.length, index],
  );

  return (
    <Fragment>
      {optelem.current &&
        !hidden &&
        ReactDOM.createPortal(
          <OptionsContainer
            align={align}
            position={position}
            fixed={fixed}
            reference={optelem}
          >
            {dropdowninput.map((i, idx) => (
              <Option
                key={i.value}
                close={setHiddenHandler}
                reference={optelem}
                updateForm={updateForm}
                name={name}
                value={i.value}
                selected={index === idx}
              >
                {i.value}
              </Option>
            ))}
          </OptionsContainer>,
          document.body,
        )}
      <input
        ref={optelem}
        id={id}
        type={type}
        name={name}
        value={value}
        onChange={handleChange}
        placeholder=" "
        onFocus={setVisibleHandler}
        onBlur={setHiddenHandler}
        onKeyDown={handleKeyDown}
      />
    </Fragment>
  );
};

const Input = ({
  type,
  name,
  value,
  onChange,
  onEnter,
  label,
  info,
  error,
  valid,
  dropdown,
  multiple,
  dropdowninput,
  textarea,
  toggle,
  accept,
  capture,
  checked,
  wide,
  fullWidth,
}) => {
  const id = useMemo(randomID, []);

  const context = useContext(FormContext);
  if (context) {
    if (context.formState) {
      if (type === 'radio' || type === 'checkbox') {
        checked = checked || context.formState[name];
      } else {
        value = value || context.formState[name];
      }
    }
    onChange = onChange || context.onChange;
    if (!textarea && !dropdowninput) {
      onEnter = onEnter || context.onEnter;
    }
    if (context.error) {
      error = error || context.error[name];
    }
    if (context.valid) {
      valid = valid || context.valid[name];
    }
  }

  const handleChange = useMemo(() => {
    if (!onChange) {
      return () => {};
    }
    switch (type) {
      case 'file':
        return (event) => {
          if (event.target.files.length < 1) {
            onChange(name, undefined);
          } else {
            onChange(name, event.target.files[0]);
          }
        };
      case 'checkbox':
        return (event) => {
          onChange(name, event.target.checked);
        };
      default:
        return (event) => {
          onChange(name, event.target.value);
        };
    }
  }, [type, name, onChange]);

  const handleEnter = useMemo(() => {
    if (!onEnter) {
      return () => {};
    }
    return (e) => {
      if (e.key === 'Enter') {
        onEnter();
      }
    };
  }, [onEnter]);

  const k = ['input'];

  if (valid) {
    k.push('valid');
  } else if (error) {
    k.push('invalid');
  }

  switch (type) {
    case 'file':
    case 'radio':
    case 'checkbox':
      k.push(type);
      break;
    default:
      k.push('normal');
  }

  if (toggle) {
    k.push('toggle');
  }

  if (wide) {
    k.push('wide');
  } else if (fullWidth) {
    k.push('full-width');
  }

  let inp = null;
  if (dropdowninput && Array.isArray(dropdowninput)) {
    inp = (
      <Select
        id={id}
        type={type}
        name={name}
        value={value}
        onChange={handleChange}
        dropdowninput={dropdowninput}
        updateForm={onChange}
      />
    );
  } else if (dropdown && Array.isArray(dropdown)) {
    inp = (
      <select
        id={id}
        value={value}
        multiple={multiple}
        onChange={handleChange}
        onKeyDown={handleEnter}
      >
        {dropdown.map((i) => (
          <option key={i.value} value={i.value}>
            {i.text}
          </option>
        ))}
      </select>
    );
  } else if (textarea) {
    inp = (
      <textarea
        id={id}
        name={name}
        value={value}
        onChange={handleChange}
        onKeyDown={handleEnter}
        placeholder=" "
      />
    );
  } else {
    switch (type) {
      case 'file':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            onChange={handleChange}
            onKeyDown={handleEnter}
            accept={accept}
            capture={capture}
            placeholder=" "
          />
        );
        break;
      case 'radio':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            checked={checked === value}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
        break;
      case 'checkbox':
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            checked={checked}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
        break;
      default:
        inp = (
          <input
            id={id}
            type={type}
            name={name}
            value={value}
            onChange={handleChange}
            onKeyDown={handleEnter}
            placeholder=" "
          />
        );
    }
  }

  let errDisplay = false;
  if (typeof error !== 'boolean') {
    errDisplay = true;
  }

  return (

      {inp}
      {label}
      {dropdown &&
}
      {!error && info && {info}}
      {error && (

          {!errDisplay && info}
          {errDisplay && error}

      )}

  );
};

const useForm = (initState = {}) => {
  const [formState, setFormState] = useState(initState);
  const updateForm = useCallback(
    (name, val) =>
      setFormState((prev) => Object.assign({}, prev, {[name]: val})),
    [setFormState],
  );
  return [formState, updateForm];
};

const matchChars = (from, to) => {
  let j = 0;
  for (let i = 0; i < from.length; i++) {
    while (j < to.length && to[j] !== from[i]) {
      j++;
    }
    if (j >= to.length) {
      return false;
    }
    j++;
  }
  return true;
};

const fuzzyFilter = (count, options, map, search) => {
  const s = search.toLowerCase();
  const matches = [];
  for (let i = 0; i < options.length && matches.length < count; i++) {
    const k = options[i];
    if (matchChars(s, map(k).toLowerCase())) {
      matches.push(k);
    }
  }
  return matches;
};

export {Input, useForm, fuzzyFilter, Form, Input as default};
<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import Helmet from 'react-helmet'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import { hot } from 'react-hot-loader'
import { injectGlobalStyle } from '../style'
import Header from './Header'
import Index from '../pages/Index'
import About from '../pages/About'
import NotFound from '../pages/NotFound'

const App = () => {
  injectGlobalStyle()

  return (
    <Router>
      <Fragment>
        <Helmet
          titleTemplate="%s - React Boilerplate"
          defaultTitle="React Boilerplate"
        />
        <Header />
        <Switch>
          <Route exact path="/" component={Index} />
          <Route path="/about" component={About} />
          <Route component={NotFound} />
        </Switch>
      </Fragment>
    </Router>
  )
}

export default hot(module)(App)
<commit_msg>Lazy load all routes<commit_after>import React, { Fragment } from 'react'
import Helmet from 'react-helmet'
import Loadable from 'react-loadable'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { hot } from 'react-hot-loader'
import { injectGlobalStyle } from '../style'
import Header from './Header'

const Loader = () => null

const Index = Loadable({
  loader: () => import('../pages/Index' /* webpackChunkName: "index.route" */),
  loading: Loader,
})

const About = Loadable({
  loader: () => import('../pages/About' /* webpackChunkName: "about.route" */),
  loading: Loader,
})

const NotFound = Loadable({
  loader: () => import('../pages/NotFound' /* webpackChunkName: "404.route" */),
  loading: Loader,
})

const App = () => {
  injectGlobalStyle()

  return (
    <Router>
      <Fragment>
        <Helmet
          titleTemplate="%s - React Boilerplate"
          defaultTitle="React Boilerplate"
        />
        <Header />
        <Switch>
          <Switch>
            <Route exact path="/" component={Index} />
            <Route path="/about" component={About} />
            <Route component={NotFound} />
          </Switch>
        </Switch>
      </Fragment>
    </Router>
  )
}

export default hot(module)(App)
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Class that takes a Matrix Client and flips the m.direct map
 * so the operation of mapping a room ID to which user it's a DM
 * with can be performed efficiently.
 */
export default class DMRoomMap {
    constructor(matrixClient) {
        const mDirectEvent = matrixClient.getAccountData('m.direct');
        if (!mDirectEvent) {
            this.userToRooms = {};
            this.roomToUser = {};
        } else {
            this.userToRooms = mDirectEvent.getContent();
            this.roomToUser = {};
            for (const user of Object.keys(this.userToRooms)) {
                for (const roomId of this.userToRooms[user]) {
                    this.roomToUser[roomId] = user;
                }
            }
        }
    }

    getDMRoomsForUserId(userId) {
        return this.userToRooms[userId];
    }

    getUserIdForRoomId(roomId) {
        return this.roomToUser[roomId];
    }
}
<commit_msg>Don't crash if no DM rooms with someone<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Class that takes a Matrix Client and flips the m.direct map
 * so the operation of mapping a room ID to which user it's a DM
 * with can be performed efficiently.
 */
export default class DMRoomMap {
    constructor(matrixClient) {
        const mDirectEvent = matrixClient.getAccountData('m.direct');
        if (!mDirectEvent) {
            this.userToRooms = {};
            this.roomToUser = {};
        } else {
            this.userToRooms = mDirectEvent.getContent();
            this.roomToUser = {};
            for (const user of Object.keys(this.userToRooms)) {
                for (const roomId of this.userToRooms[user]) {
                    this.roomToUser[roomId] = user;
                }
            }
        }
    }

    getDMRoomsForUserId(userId) {
        // Here, we return the empty list if there are no rooms,
        // since the number of conversations you have with this user is zero.
        return this.userToRooms[userId] || [];
    }

    getUserIdForRoomId(roomId) {
        // Here, we return undefined if the room is not in the map:
        // the room ID you gave is not a DM room for any user.
        return this.roomToUser[roomId];
    }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Layout from './Layout';
import ThrashWrapper from "./wraps/ThrashWrapper";
class App extends Component {
  render() {
    return (
      <Layout>
        <ThrashWrapper/>
      </Layout>
    );
  }

}
//this is a style that we will probably use, but is not important now
App.propTypes = {
    store: PropTypes.object
}

export default App
<commit_msg>switched to Nas to deconstruct charts<commit_after>import React, { Component, PropTypes } from 'react';
import Layout from './Layout';
import ThrashWrapper from "./wraps/ThrashWrapper";
import NasDashWrapper from "./wraps/NasDashWrapper";
class App extends Component {
  render() {
    return (
      <Layout>
      {/*<ThrashWrapper/>*/}
        <NasDashWrapper/>
      </Layout>
    );
  }

}
//this is a style that we will probably use, but is not important now
App.propTypes = {
    store: PropTypes.object
}

export default App
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50*/
/*global $: false, define: false, brackets: false, FileError: false, InvalidateStateError: false */

define(function (require, exports, module) {
    'use strict';

    /**
     * @private
     * Map an fs error code to a FileError.
     */
    function _browserErrToFileError(err) {
        if (err === brackets.fs.ERR_NOT_FOUND) {
            return FileError.NOT_FOUND_ERR;
        }

        // All other errors are mapped to the generic "security" error
        return FileError.SECURITY_ERR;
    }

    /** openLiveBrowser
     *
     * @param {string} url
     * @return {$.Promise}
     */
    function openLiveBrowser(url, successCallback, errorCallback) {
        var result = new $.Deferred();

        brackets.app.openLiveBrowser(url, function onRun(err) {
            if (!err) {
                result.resolve();
            } else {
                result.fail(_browserErrToFileError(err));
            }
        });

        return result.promise();
    }

    /** closeLiveBrowser
     *
     * @return ($.Promise}
     */
    function closeLiveBrowser(successCallback, errorCallback) {
        var result = new $.Deferred();

        brackets.app.closeLiveBrowser(function (err) {
            if (!err) {
                result.resolve();
            } else {
                result.fail(_browserErrToFileError(err));
            }
        });

        return result.promise();
    }

    // Define public API
    exports.openLiveBrowser = openLiveBrowser;
    exports.closeLiveBrowser = closeLiveBrowser;
});
<commit_msg>minor comment correction<commit_after>/*
 * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved.
 */

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50*/
/*global $: false, define: false, brackets: false, FileError: false, InvalidateStateError: false */

define(function (require, exports, module) {
    'use strict';

    /**
     * @private
     * Map an fs error code to a FileError.
     */
    function _browserErrToFileError(err) {
        if (err === brackets.fs.ERR_NOT_FOUND) {
            return FileError.NOT_FOUND_ERR;
        }

        // All other errors are mapped to the generic "security" error
        return FileError.SECURITY_ERR;
    }

    /** openLiveBrowser
     *
     * @param {string} url
     * @return {$.Promise}
     */
    function openLiveBrowser(url, successCallback, errorCallback) {
        var result = new $.Deferred();

        brackets.app.openLiveBrowser(url, function onRun(err) {
            if (!err) {
                result.resolve();
            } else {
                result.fail(_browserErrToFileError(err));
            }
        });

        return result.promise();
    }

    /** closeLiveBrowser
     *
     * @return {$.Promise}
     */
    function closeLiveBrowser(successCallback, errorCallback) {
        var result = new $.Deferred();

        brackets.app.closeLiveBrowser(function (err) {
            if (!err) {
                result.resolve();
            } else {
                result.fail(_browserErrToFileError(err));
            }
        });

        return result.promise();
    }

    // Define public API
    exports.openLiveBrowser = openLiveBrowser;
    exports.closeLiveBrowser = closeLiveBrowser;
});
<|endoftext|>


<commit_before>const assert = require('assert');
const sinon = require('sinon');
const { startProbeServer, getProbeConfig } =
    require('../../../extensions/replication/queueProcessor/Probe');
const { DEFAULT_LIVE_ROUTE } = require('arsenal').network.probe.ProbeServer;
const http = require('http');

/**
 * @returns {Object} Mock queue processor
*/
function mockQueueProcessor() {
    return {
        handleLiveness: sinon.stub(),
    };
}

describe.only('Probe server', () => {
    afterEach(() => {
        // reset any possible env var set
        delete process.env.CRR_METRICS_PROBE;
    });

    it('is not created when disabled', done => {
        process.env.CRR_METRICS_PROBE = 'false';
        const mockQp = mockQueueProcessor();
        const config = {
            bindAddress: 'localhost',
            port: 52555,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('is not created with no config', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        const config = undefined;
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('calls back with error if one occurred', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        const config = {
            bindAddress: 'httppp://badaddress',
            // inject an error with a bad port
            port: 52525,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.notStrictEqual(err, undefined);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('creates probe server for liveness', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        // return sample error for liveness
        mockQp.handleLiveness.returns('error msg');
        const config = {
            bindAddress: 'localhost',
            port: 52555,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            probeServer.onStop(done);
            http.get(`http://localhost:52555${DEFAULT_LIVE_ROUTE}`, res => {
                assert.strictEqual(res.statusCode, 500);

                const rawData = [];
                res.on('data', chunk => {
                    rawData.push(chunk);
                });
                res.on('end', () => {
                    const data = JSON.parse(rawData.join(''));
                    assert.strictEqual(data.errorMessage, 'error msg');
                    probeServer.stop();
                });
            });
        });
    });

    it('can get config', () => {
        const qpConfig = {
            probeServer: [
                {
                    site: 'sf',
                    bindAddress: 'localhost',
                    port: '4043',
                }, {
                    site: 'us-east-1',
                    bindAddress: 'localhost',
                    port: '4044',
                },
            ],
        };
        const cfg = getProbeConfig(qpConfig, 'us-east-1');
        assert.deepStrictEqual(cfg, {
            site: 'us-east-1',
            bindAddress: 'localhost',
            port: '4044',
        });
    });

    it('returns undefined if site not listed', () => {
        const qpConfig = {
            probeServer: [
                {
                    site: 'sf',
                    bindAddress: 'localhost',
                    port: '4043',
                },
            ],
        };
        const cfg = getProbeConfig(qpConfig, 'missing site');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no sites', () => {
        const qpConfig = {
            probeServer: [],
        };
        const cfg = getProbeConfig(qpConfig, 'no configs');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no probe server config', () => {
        const qpConfig = {};
        const cfg = getProbeConfig(qpConfig, 'no server configs');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no config at all', () => {
        const cfg = getProbeConfig(undefined, 'no server configs');
        assert.deepStrictEqual(cfg, undefined);
    });
});
<commit_msg>feature: S3C-4556 remove only in tests<commit_after>const assert = require('assert');
const sinon = require('sinon');
const { startProbeServer, getProbeConfig } =
    require('../../../extensions/replication/queueProcessor/Probe');
const { DEFAULT_LIVE_ROUTE } = require('arsenal').network.probe.ProbeServer;
const http = require('http');

/**
 * @returns {Object} Mock queue processor
*/
function mockQueueProcessor() {
    return {
        handleLiveness: sinon.stub(),
    };
}

describe('Probe server', () => {
    afterEach(() => {
        // reset any possible env var set
        delete process.env.CRR_METRICS_PROBE;
    });

    it('is not created when disabled', done => {
        process.env.CRR_METRICS_PROBE = 'false';
        const mockQp = mockQueueProcessor();
        const config = {
            bindAddress: 'localhost',
            port: 52555,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('is not created with no config', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        const config = undefined;
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('calls back with error if one occurred', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        const config = {
            bindAddress: 'httppp://badaddress',
            // inject an error with a bad port
            port: 52525,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.notStrictEqual(err, undefined);
            assert.strictEqual(probeServer, undefined);
            done();
        });
    });

    it('creates probe server for liveness', done => {
        process.env.CRR_METRICS_PROBE = 'true';
        const mockQp = mockQueueProcessor();
        // return sample error for liveness
        mockQp.handleLiveness.returns('error msg');
        const config = {
            bindAddress: 'localhost',
            port: 52555,
        };
        startProbeServer(mockQp, config, (err, probeServer) => {
            assert.ifError(err);
            probeServer.onStop(done);
            http.get(`http://localhost:52555${DEFAULT_LIVE_ROUTE}`, res => {
                assert.strictEqual(res.statusCode, 500);

                const rawData = [];
                res.on('data', chunk => {
                    rawData.push(chunk);
                });
                res.on('end', () => {
                    const data = JSON.parse(rawData.join(''));
                    assert.strictEqual(data.errorMessage, 'error msg');
                    probeServer.stop();
                });
            });
        });
    });

    it('can get config', () => {
        const qpConfig = {
            probeServer: [
                {
                    site: 'sf',
                    bindAddress: 'localhost',
                    port: '4043',
                }, {
                    site: 'us-east-1',
                    bindAddress: 'localhost',
                    port: '4044',
                },
            ],
        };
        const cfg = getProbeConfig(qpConfig, 'us-east-1');
        assert.deepStrictEqual(cfg, {
            site: 'us-east-1',
            bindAddress: 'localhost',
            port: '4044',
        });
    });

    it('returns undefined if site not listed', () => {
        const qpConfig = {
            probeServer: [
                {
                    site: 'sf',
                    bindAddress: 'localhost',
                    port: '4043',
                },
            ],
        };
        const cfg = getProbeConfig(qpConfig, 'missing site');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no sites', () => {
        const qpConfig = {
            probeServer: [],
        };
        const cfg = getProbeConfig(qpConfig, 'no configs');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no probe server config', () => {
        const qpConfig = {};
        const cfg = getProbeConfig(qpConfig, 'no server configs');
        assert.deepStrictEqual(cfg, undefined);
    });

    it('returns undefined if no config at all', () => {
        const cfg = getProbeConfig(undefined, 'no server configs');
        assert.deepStrictEqual(cfg, undefined);
    });
});
<|endoftext|>


<commit_before>import React from "react";
import connectToStores from "alt/utils/connectToStores";
import GwasActions from "../actions/GwasActions";
import GwasStore from "../stores/GwasStore";
import {Input, Button, Table, Alert} from "react-bootstrap";
import {LinkContainer} from "react-router-bootstrap";
import {Link, History} from "react-router";

class App extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch = this.onSearch.bind(this);
        this.onClear = this.onClear.bind(this);
    }

    static getStores(props) {
        return [GwasStore];
    }

    static getPropsFromStores(props) {
        return {results: GwasStore.getResults(), traits: GwasStore.getTraits(), count: GwasStore.getCount()};
    }

    componentDidUpdate(prevProps) {
        let oldQ = prevProps.params.q;
        let newQ = this.props.params.q;
        if (newQ !== oldQ) {
            GwasActions.search(this.props.params.q);
        }
    }

    onLinkClick(value, e) {
        GwasActions.search(value);
    }

    onSearch(e) {
        e.preventDefault();
        this.props.history.pushState(null, `/search/${this.refs.query.getValue()}`)
        GwasActions.search(this.refs.query.getValue());
    }

    onClear(e) {
        this.props.history.pushState(null, `/search/`)
        GwasActions.search('');
    }

    rowclass(p) {
        if (p > 0.00000005) {
            return "uninteresting";
        }
    }
    exp(number) {
        if (number && !isNaN(number)) {
            return number.toExponential();
        }
    }
    getYear(datestring) {
        return datestring.split("-").pop();
    }
    renderResults() {
        if (!this.props.params.q) {
            return (

                        Use the search field or select from the traits below if you want to see some results

                    {this.props.traits.map(trait =>

                                                <Link to={`/search/${trait.get("_id")}`}>{trait.get("_id")}</Link>

                                          )}

            );
        }
        else if (this.props.params.q && this.props.params.q.length < 3) {
            return <Alert style={{width: "500px", margin: "0 auto"}} bsStyle="danger">We need at least three characters, or we will crash your browser</Alert>;
        }
        else {
            return (

                            SNP
                            MAF
                            P
                            Position
                            Mapped gene
                            Mapped trait
                            OR or Beta
                            Year
                            First author
                            Pubmed

                        {this.props.results.map(result =>

                                    <Link to={`/search/${result.get("SNP_ID_CURRENT")}`}>
                                        {result.get("SNPS")}
                                    </Link>

                                {result.get("hunt")}

                                    {this.exp(result.get("P-VALUE")) || "0.0" }

                                    {result.get("P-VALUE (TEXT)")}

                                    <Link to={`/search/${result.get("REGION")}`}>
                                        {result.get("REGION")}
                                    </Link>

                                {result.get("CHR_ID") ? `chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}

                                    {result.get("CONTEXT")}

                                    <Link to={`/search/${result.get("MAPPED_GENE")}`}>
                                        {result.get("MAPPED_GENE")}
                                    </Link>

                                {result.get("MAPPED_TRAIT").split(", ").map(trait =>

                                        <Link to={`/search/${trait}`}>
                                            {trait}
                                        </Link>

                                )}

{result.get("OR or BETA")}

{result.get("95% CI (TEXT)")}

{this.getYear(result.get("DATE"))}

{result.get("DATE ADDED TO CATALOG")}

                                <Link to={`/search/${result.get("FIRST AUTHOR")}`}>
                                    {result.get("FIRST AUTHOR")}
                                </Link>

                                <Link to={`/search/${result.get("PUBMEDID")}`}>
                                    {result.get("PUBMEDID")}
                                </Link> <a href={`http://www.ncbi.nlm.nih.gov/pubmed/${result.get("PUBMEDID")}`}>

{result.get("JOURNAL")}

                        )}

            );
        }
    }

    render() {
        //console.log("render", this.props.params.q);
        let button =
<Button type="submit" bsStyle="primary">Search</Button><Button type="reset" bsStyle="link">Clear</Button>
;
        let resultheader =
{this.props.count} results for P < 5x10-8
;
        let examples =
Examples: <Link to="/search/diabetes">diabetes</Link>, <Link to="/search/rs3820706">rs3820706</Link>, <Link to="/search/Chung S">Chung S</Link>, <Link to="/search/2q23.3">2q23.3</Link>, <Link to="/search/CACNB4">CACNB4</Link>
;
        return (

                <form onSubmit={this.onSearch} onReset={this.onClear} style={{width: "500px", margin: "0 auto"}}>

Search HUNT GWAS catalog

                    <Input
                        type="text"
                        ref="query"
                        placeholder={this.props.params.q || "Search"}
                        help={examples}
                        buttonAfter={button}
                    />
                </form>
                {resultheader}
                {this.renderResults()}

        );
    }
}

export default connectToStores(App);
<commit_msg>min size of 600px<commit_after>import React from "react";
import connectToStores from "alt/utils/connectToStores";
import GwasActions from "../actions/GwasActions";
import GwasStore from "../stores/GwasStore";
import {Input, Button, Table, Alert} from "react-bootstrap";
import {LinkContainer} from "react-router-bootstrap";
import {Link, History} from "react-router";

class App extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch = this.onSearch.bind(this);
        this.onClear = this.onClear.bind(this);
    }

    static getStores(props) {
        return [GwasStore];
    }

    static getPropsFromStores(props) {
        return {results: GwasStore.getResults(), traits: GwasStore.getTraits(), count: GwasStore.getCount()};
    }

    componentDidUpdate(prevProps) {
        let oldQ = prevProps.params.q;
        let newQ = this.props.params.q;
        if (newQ !== oldQ) {
            GwasActions.search(this.props.params.q);
        }
    }

    onLinkClick(value, e) {
        GwasActions.search(value);
    }

    onSearch(e) {
        e.preventDefault();
        this.props.history.pushState(null, `/search/${this.refs.query.getValue()}`)
        GwasActions.search(this.refs.query.getValue());
    }

    onClear(e) {
        this.props.history.pushState(null, `/search/`)
        GwasActions.search('');
    }

    rowclass(p) {
        if (p > 0.00000005) {
            return "uninteresting";
        }
    }
    exp(number) {
        if (number && !isNaN(number)) {
            return number.toExponential();
        }
    }
    getYear(datestring) {
        return datestring.split("-").pop();
    }
    renderResults() {
        if (!this.props.params.q) {
            return (

                        Use the search field or select from the traits below if you want to see some results

                    {this.props.traits.map(trait =>

                                                <Link to={`/search/${trait.get("_id")}`}>{trait.get("_id")}</Link>

                                          )}

            );
        }
        else if (this.props.params.q && this.props.params.q.length < 3) {
            return <Alert style={{width: "600px", margin: "0 auto"}} bsStyle="danger">We need at least three characters, or we will crash your browser</Alert>;
        }
        else {
            return (

                            SNP
                            MAF
                            P
                            Position
                            Mapped gene
                            Mapped trait
                            OR or Beta
                            Year
                            First author
                            Pubmed

                        {this.props.results.map(result =>

                                    <Link to={`/search/${result.get("SNP_ID_CURRENT")}`}>
                                        {result.get("SNPS")}
                                    </Link>

                                {result.get("hunt")}

                                    {this.exp(result.get("P-VALUE")) || "0.0" }

                                    {result.get("P-VALUE (TEXT)")}

                                    <Link to={`/search/${result.get("REGION")}`}>
                                        {result.get("REGION")}
                                    </Link>

                                {result.get("CHR_ID") ? `chr${result.get("CHR_ID")}:${result.get("CHR_POS")}` : ""}

                                    {result.get("CONTEXT")}

                                    <Link to={`/search/${result.get("MAPPED_GENE")}`}>
                                        {result.get("MAPPED_GENE")}
                                    </Link>

                                {result.get("MAPPED_TRAIT").split(", ").map(trait =>

                                        <Link to={`/search/${trait}`}>
                                            {trait}
                                        </Link>

                                )}

{result.get("OR or BETA")}

{result.get("95% CI (TEXT)")}

{this.getYear(result.get("DATE"))}

{result.get("DATE ADDED TO CATALOG")}

                                <Link to={`/search/${result.get("FIRST AUTHOR")}`}>
                                    {result.get("FIRST AUTHOR")}
                                </Link>

                                <Link to={`/search/${result.get("PUBMEDID")}`}>
                                    {result.get("PUBMEDID")}
                                </Link> <a href={`http://www.ncbi.nlm.nih.gov/pubmed/${result.get("PUBMEDID")}`}>

{result.get("JOURNAL")}

                        )}

            );
        }
    }

    render() {
        //console.log("render", this.props.params.q);
        let button =
<Button type="submit" bsStyle="primary">Search</Button><Button type="reset" bsStyle="link">Clear</Button>
;
        let resultheader =
{this.props.count} results for P < 5x10-8
;
        let examples =
Examples: <Link to="/search/diabetes">diabetes</Link>, <Link to="/search/rs3820706">rs3820706</Link>, <Link to="/search/Chung S">Chung S</Link>, <Link to="/search/2q23.3">2q23.3</Link>, <Link to="/search/CACNB4">CACNB4</Link>
;
        return (

                <form onSubmit={this.onSearch} onReset={this.onClear} style={{width: "600px", margin: "0 auto"}}>

Search HUNT GWAS catalog

                    <Input
                        type="text"
                        ref="query"
                        placeholder={this.props.params.q || "Search"}
                        help={examples}
                        buttonAfter={button}
                    />
                </form>
                {resultheader}
                {this.renderResults()}

        );
    }
}

export default connectToStores(App);
<|endoftext|>


<commit_before>import React from 'react';

import { Link } from 'react-router'

import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import FlatButton from 'material-ui/FlatButton';

var url = require("file!./../static/branchIcon.svg");
var urlFolder = require("file!./../static/folderIcon.svg");

const constStyles = {
  fontFamily: `apple-system,
          BlinkMacSystemFont,"Segoe UI",
          Roboto,Helvetica,Arial,sans-serif,
          "Apple Color Emoji","Segoe UI Emoji",
          "Segoe UI Symbol"`,
  darkRed: '#b60a0a',
  grey: '#f9f9f9',
  borderGrey: '#7e7e7e',
};

class ListElement extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      focus: false
    };
  }

  toggleFocus = () => {
    this.setState( (prevState) => {
      return {focus: !prevState.focus };
    });
  };

  render = () => {

    // these two objects are not defined under a styles object
    const notFocus = {
      display: 'flex',
      alignItems: 'center',
      fontFamily: constStyles.fontFamily,
      color: 'black',
      padding: 10,
      fontWeight: 500,
      paddingLeft: 40,
      fontSize: 14,
      cursor: 'pointer',
      width: '100%',
        textDecoration: 'none'
    };

    const focus={
      ...notFocus,
      backgroundColor: '#c8c8c8'
    };

    return (
      <Link to='repoOps/commitTree'
      style={this.state.focus?focus:notFocus}
      onMouseEnter={this.toggleFocus} onMouseLeave={this.toggleFocus}
      onClick={this.props.clickCB} >

{this.props.name}
</Link>
    );
  }
}

class SidePanel extends React.Component {
  constructor(props) {
    super(props);
  }

  listItemClick = (ref) => {
    this.props.setCurrentBranchCB(ref);
  }

  componentWillReceiveProps = (newprops) => {
  }

  render = () => {

    let locals = [];
    let remotes = [];
    let remoteNames = [];

    this.props.refsData.forEach( (ref, index) => {

      const listItem =
      <ListElement
      name={ref.name}
      link='repoOps/commitTree'
      key={index}
      clickCB={() => {this.listItemClick(ref);}} />;

      if(ref.type === 'LOCAL')
        locals.push(listItem);
      else if(ref.name.match(/\/+/g)) {
        let remoteName = ref.name.split('/')[0];
        const index = remoteNames.indexOf(remoteName);
        if(index === -1) {
          remoteNames.push(remoteName);
          remotes.push([]);
        }
        else {
         remotes[index].push(React.cloneElement(listItem,{name: ref.name.split('/')[1]}));
        }
      }
    });

    const styles = {
      main: {
        ...this.props.styleInherited,
        // border: '2px solid'+constStyles.borderGrey,
        fontFamily: constStyles.fontFamily,
        backgroundColor: constStyles.grey,
        overflow: 'scroll',
        height: 450
      },
      listComponent: {
        fontFamily: constStyles.fontFamily,
        color: 'black',
        fontSize: 15,
        fontWeight: 600,
      },
      listRemote: {
        fontSize: 14,
        fontWeight: 600,
      },
      listItem: {
        display: 'flex',
        alignItems: 'center',
        fontFamily: constStyles.fontFamily,
        fontWeight: 600,
        color: 'black',
        padding: 10,
        paddingLeft: 40,
        fontSize: 14,
        cursor: 'pointer',
      }
    };

    const listRemotes = remoteNames.map( (remoteName, index) => {
      if(remotes[index].length > 0) {
        return <ListItem primaryText={remoteName} primaryTogglesNestedList={true}
        leftIcon={}
        nestedItems={remotes[index]} key={index}
        style={styles.listRemote}/>;
      }
    });

    return (

    <List>
      <List>
        <Subheader style={styles.listComponent}>Working Directory</Subheader>
        <ListItem
          primaryText='Staging Area'
          style={styles.listItem}
          containerElement={<Link to='repoOps/stagingArea' />}
          linkButton={true} />
      </List>
      <Divider />
      <List>
        <Subheader style={styles.listComponent}>Branches</Subheader>
          <List>
            <Subheader style={styles.listComponent}>Local</Subheader>
            {locals}
          </List>
          <List>
            <Subheader style={styles.listComponent}>Remotes</Subheader>
            {listRemotes}
          </List>
      </List>
    </List>

    );
  }
}

export default SidePanel;<commit_msg>View: Changed height of SidePanel component<commit_after>import React from 'react';

import { Link } from 'react-router'

import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import FlatButton from 'material-ui/FlatButton';

var url = require("file!./../static/branchIcon.svg");
var urlFolder = require("file!./../static/folderIcon.svg");

const constStyles = {
  fontFamily: `apple-system,
          BlinkMacSystemFont,"Segoe UI",
          Roboto,Helvetica,Arial,sans-serif,
          "Apple Color Emoji","Segoe UI Emoji",
          "Segoe UI Symbol"`,
  darkRed: '#b60a0a',
  grey: '#f9f9f9',
  borderGrey: '#7e7e7e',
};

class ListElement extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      focus: false
    };
  }

  toggleFocus = () => {
    this.setState( (prevState) => {
      return {focus: !prevState.focus };
    });
  };

  render = () => {

    // these two objects are not defined under a styles object
    const notFocus = {
      display: 'flex',
      alignItems: 'center',
      fontFamily: constStyles.fontFamily,
      color: 'black',
      padding: 10,
      fontWeight: 500,
      paddingLeft: 40,
      fontSize: 14,
      cursor: 'pointer',
      width: '100%',
        textDecoration: 'none'
    };

    const focus={
      ...notFocus,
      backgroundColor: '#c8c8c8'
    };

    return (
      <Link to='repoOps/commitTree'
      style={this.state.focus?focus:notFocus}
      onMouseEnter={this.toggleFocus} onMouseLeave={this.toggleFocus}
      onClick={this.props.clickCB} >

{this.props.name}
</Link>
    );
  }
}

class SidePanel extends React.Component {
  constructor(props) {
    super(props);
  }

  listItemClick = (ref) => {
    this.props.setCurrentBranchCB(ref);
  }

  componentWillReceiveProps = (newprops) => {
  }

  render = () => {

    let locals = [];
    let remotes = [];
    let remoteNames = [];

    this.props.refsData.forEach( (ref, index) => {

      const listItem =
      <ListElement
      name={ref.name}
      link='repoOps/commitTree'
      key={index}
      clickCB={() => {this.listItemClick(ref);}} />;

      if(ref.type === 'LOCAL')
        locals.push(listItem);
      else if(ref.name.match(/\/+/g)) {
        let remoteName = ref.name.split('/')[0];
        const index = remoteNames.indexOf(remoteName);
        if(index === -1) {
          remoteNames.push(remoteName);
          remotes.push([]);
        }
        else {
         remotes[index].push(React.cloneElement(listItem,{name: ref.name.split('/')[1]}));
        }
      }
    });

    const styles = {
      main: {
        ...this.props.styleInherited,
        // border: '2px solid'+constStyles.borderGrey,
        fontFamily: constStyles.fontFamily,
        backgroundColor: constStyles.grey,
        overflow: 'scroll',
        height: '100%'
      },
      listComponent: {
        fontFamily: constStyles.fontFamily,
        color: 'black',
        fontSize: 15,
        fontWeight: 600,
      },
      listRemote: {
        fontSize: 14,
        fontWeight: 600,
      },
      listItem: {
        display: 'flex',
        alignItems: 'center',
        fontFamily: constStyles.fontFamily,
        fontWeight: 600,
        color: 'black',
        padding: 10,
        paddingLeft: 40,
        fontSize: 14,
        cursor: 'pointer',
      }
    };

    const listRemotes = remoteNames.map( (remoteName, index) => {
      if(remotes[index].length > 0) {
        return <ListItem primaryText={remoteName} primaryTogglesNestedList={true}
        leftIcon={}
        nestedItems={remotes[index]} key={index}
        style={styles.listRemote}/>;
      }
    });

    return (

    <List>
      <List>
        <Subheader style={styles.listComponent}>Working Directory</Subheader>
        <ListItem
          primaryText='Staging Area'
          style={styles.listItem}
          containerElement={<Link to='repoOps/stagingArea' />}
          linkButton={true} />
      </List>
      <Divider />
      <List>
        <Subheader style={styles.listComponent}>Branches</Subheader>
          <List>
            <Subheader style={styles.listComponent}>Local</Subheader>
            {locals}
          </List>
          <List>
            <Subheader style={styles.listComponent}>Remotes</Subheader>
            {listRemotes}
          </List>
      </List>
    </List>

    );
  }
}

export default SidePanel;<|endoftext|>


<commit_before>import firebase from 'firebase';
import React from 'react';
import styled from 'styled-components';

import ChallengeImportForm from './ChallengeImportForm';
import ChallengeList from './ChallengeList';
import Header from './Header';
import request from '../utils/request';

const Content = styled.main`
  margin: 0 auto;
  max-width: 45rem;
  padding-top: 1.5rem;
`;

const StyledButtonLink = styled.button`
  background: none;
  border: none;
  color: #00bcd4;

  &:hover {
    color: #1ed4d4;
    cursor: pointer;
    text-decoration: underline;
  }
`;

export default class App extends React.Component {
  state = {
    challenges: [],
    url: '',
    user: null,
  };

  setUser(user) { // eslint-disable-line react/sort-comp
    if (/umich\.edu$/i.test(user.email)) {
      const { displayName, email, photoURL, uid } = user;
      this.setState({
        user: { displayName, email, photoURL, uid },
      });
    } else {
      console.log('You must be part of the "umich.edu" domain to use this app.');
    }
  }

  componentDidMount() {
    this.challengesRef = firebase.database().ref('challenges');
    this.challengesRef.on('value', (snapshot) => {
      const challenges = snapshot.val() || {};
      this.setState({
        challenges: Object.values(challenges),
      });
    });

    this.auth = firebase.auth();
    this.auth.onAuthStateChanged((user) => {
      if (user) {
        this.setUser(user);
      }
    });
  }

  componentWillUnmount() {
    this.challengesRef.off();
  }

  signIn = async () => {
    try {
      const google = new firebase.auth.GoogleAuthProvider();
      const { user } = await this.auth.signInWithPopup(google);
      this.setUser(user);
    } catch (error) {
      console.log(error.message);
    }
  }

  signOut = async () => {
    try {
      await this.auth.signOut();
      this.setState({
        user: null,
      });
    } catch (error) {
      console.log(error.message);
    }
  }

  async importChallenge() {
    try {
      const [, slug] = this.state.url.match(/codewars.com\/kata\/([^/]+)/i);
      const data = await request(`/codewars/code-challenges/${slug}`);
      if (!this.state.challenges.find(challenge => challenge.id === data.id)) {
        const { description, id, name, rank, tags, url } = data;
        const challenge = {
          createdAt: firebase.database.ServerValue.TIMESTAMP,
          description,
          id,
          name,
          points: rank.name,
          tags,
          url,
        };
        this.challengesRef.push(challenge);
        this.setState({
          url: '',
        });
      }
    } catch (error) {
      console.log(error.message);
    }
  }

  handleSubmit = async (event) => {
    event.preventDefault();

    if (this.state.user) {
      this.importChallenge();
    } else {
      await this.signIn();
      if (this.state.user) {
        this.importChallenge();
      }
    }
  }

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  }

  renderAuthLink() {
    if (this.state.user) {
      return ;
    }

    return ;
  }

  render() {
    return (

        <Content>
          <ChallengeImportForm
            handleChange={this.handleChange}
            handleSubmit={this.handleSubmit}
            url={this.state.url}
          />
          <ChallengeList challenges={this.state.challenges} />
        </Content>

    );
  }
}
<commit_msg>Save users to database on sign in/up<commit_after>import firebase from 'firebase';
import React from 'react';
import styled from 'styled-components';

import ChallengeImportForm from './ChallengeImportForm';
import ChallengeList from './ChallengeList';
import Header from './Header';
import request from '../utils/request';

const Content = styled.main`
  margin: 0 auto;
  max-width: 45rem;
  padding-top: 1.5rem;
`;

const StyledButtonLink = styled.button`
  background: none;
  border: none;
  color: #00bcd4;

  &:hover {
    color: #1ed4d4;
    cursor: pointer;
    text-decoration: underline;
  }
`;

export default class App extends React.Component {
  state = {
    challenges: [],
    url: '',
    user: null,
  };

  setUser(userData) { // eslint-disable-line react/sort-comp
    if (/umich\.edu$/i.test(userData.email)) {
      const { displayName, email, photoURL, uid } = userData;
      const user = { displayName, email, photoURL, uid };
      this.usersRef.child(uid).set(user);
      this.setState({ user });
    } else {
      console.log('You must be part of the "umich.edu" domain to use this app.');
    }
  }

  componentDidMount() {
    this.usersRef = firebase.database().ref('users');

    this.challengesRef = firebase.database().ref('challenges');
    this.challengesRef.on('value', (snapshot) => {
      const challenges = snapshot.val() || {};
      this.setState({
        challenges: Object.values(challenges),
      });
    });

    this.auth = firebase.auth();
    this.auth.onAuthStateChanged((user) => {
      if (user) {
        this.setUser(user);
      }
    });
  }

  componentWillUnmount() {
    this.usersRef.off();
    this.challengesRef.off();
  }

  signIn = async () => {
    try {
      const google = new firebase.auth.GoogleAuthProvider();
      const { user } = await this.auth.signInWithPopup(google);
      this.setUser(user);
    } catch (error) {
      console.log(error.message);
    }
  }

  signOut = async () => {
    try {
      await this.auth.signOut();
      this.setState({
        user: null,
      });
    } catch (error) {
      console.log(error.message);
    }
  }

  async importChallenge() {
    try {
      const [, slug] = this.state.url.match(/codewars.com\/kata\/([^/]+)/i);
      const data = await request(`/codewars/code-challenges/${slug}`);
      if (!this.state.challenges.find(challenge => challenge.id === data.id)) {
        const { description, id, name, rank, tags, url } = data;
        this.challengesRef.child(id).set({
          createdAt: firebase.database.ServerValue.TIMESTAMP,
          description,
          id,
          name,
          points: rank.name,
          tags,
          url,
        });
        this.setState({
          url: '',
        });
      }
    } catch (error) {
      console.log(error.message);
    }
  }

  handleSubmit = async (event) => {
    event.preventDefault();

    if (this.state.user) {
      this.importChallenge();
    } else {
      await this.signIn();
      if (this.state.user) {
        this.importChallenge();
      }
    }
  }

  handleChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  }

  renderAuthLink() {
    if (this.state.user) {
      return ;
    }

    return ;
  }

  render() {
    return (

        <Content>
          <ChallengeImportForm
            handleChange={this.handleChange}
            handleSubmit={this.handleSubmit}
            url={this.state.url}
          />
          <ChallengeList challenges={this.state.challenges} />
        </Content>

    );
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from '../actions/song';

import TabStaff from './TabStaff';

class App extends Component {
  constructor(props) {
    super(props);

    if (typeof window !== 'undefined') {
      window.addEventListener('keydown', this.handleKeyPress);
    }

    let audioContext;
    try {
      audioContext = new AudioContext();
    } catch(e) {
      audioContext = new webkitAudioContext();
    }

    this.state = {
      currentPlayingNote: {
        measure: 0,
        noteIndex: 0
      },
      currentEditingIndex: {
        measureIndex: 0,
        noteIndex: 0,
        stringIndex: 0
      },
      audioContext: audioContext,
      isPlaying: false,
      bpm: 120
    };
  }

  getSpeedFromBpm = (bpm) => {
    return 60000 / bpm;
  }

  startPlayback = () => {
    let startTimestamp = Date.now();
    this.playCurrentNote();

    this.setState({
      timer: requestAnimationFrame(() => {
        this.loopThroughSong(startTimestamp);
      })
    });
  }

  getReplaySpeedForNote = (note, bpm) => {
    let noteLength = note.duration;

    let replaySpeed = this.getSpeedFromBpm(bpm);
    if(noteLength === 'h') {
      replaySpeed = replaySpeed * 2;
    } else if(noteLength === 'w') {
      replaySpeed = replaySpeed * 4;
    } else if(noteLength === 'e') {
      replaySpeed = replaySpeed / 2;
    } else if(noteLength === 's') {
      replaySpeed = replaySpeed / 4;
    }

    return replaySpeed;
  }

  loopThroughSong = (startTimestamp) => {
    let { currentPlayingNote, bpm } = this.state;
    let { measure, noteIndex } = currentPlayingNote;
    let { song } = this.props;

    let currentTimestamp = Date.now();
    let replayDiff = currentTimestamp - startTimestamp;
    let replaySpeed = this.getReplaySpeedForNote(song[currentPlayingNote.measure].notes[noteIndex], bpm);

    if(replayDiff >= replaySpeed) {
      if(measure === song.length - 1 && noteIndex === song[measure].notes.length - 1) {
        this.handleStop();
      } else if(measure !== song.length - 1 && noteIndex === song[measure].notes.length - 1) {
        this.setState({
          currentPlayingNote: {
            measure: measure + 1,
            noteIndex: 0
          },
          timer: requestAnimationFrame(() => {
            this.loopThroughSong(currentTimestamp);
          })
        }, this.playCurrentNote);
      } else {
        this.setState({
          currentPlayingNote: {
            measure: measure,
            noteIndex: noteIndex + 1
          },
          timer: requestAnimationFrame(() => {
            this.loopThroughSong(currentTimestamp);
          })
        }, this.playCurrentNote);
      }
    } else {
      this.setState({
        timer: requestAnimationFrame(() => {
          this.loopThroughSong(startTimestamp);
        })
      });
    }
  }

  playCurrentNote = () => {
    let noteToPlay = this.props.song[this.state.currentPlayingNote.measure].notes[this.state.currentPlayingNote.noteIndex];
    let replaySpeed = this.getReplaySpeedForNote(noteToPlay, this.state.bpm);

    if(noteToPlay.fret[0] === 'rest') {
      this.play(this.state.audioContext, this.state.audioContext.currentTime, 'rest', replaySpeed);
    } else {
      this.playNoteAtTime(noteToPlay, this.state.audioContext.currentTime, replaySpeed);
    }
  }

  playNoteAtTime = (currentNote, playTime, duration) => {
    for(let i = 0; i < currentNote.string.length; i++) {
      let pitch = currentNote.fret[i] + (5 * currentNote.string[i]);
      if(currentNote.string[i] >= 4) {
        pitch = pitch - 1;
      }

      this.play(this.state.audioContext, playTime, pitch, duration / 1000);
    }
  }

  play = (audioContext, startTime, pitch, duration) => {
    let endTime = startTime + duration;

    let oscillator = this.state.audioContext.createOscillator();
    let gainNode = audioContext.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    if(pitch !== 'rest') {
      oscillator.type = 'square';
      oscillator.detune.value = (pitch - 29) * 100;

      gainNode.gain.value = 0.025;
    } else {
      gainNode.gain.value = 0;
    }

    oscillator.start(startTime);
    oscillator.stop(endTime);
  }

  handleStop = () => {
    cancelAnimationFrame(this.state.timer);

    this.setState({
      isPlaying: false,
      currentPlayingNote: {
        measure: 0,
        noteIndex: 0
      }
    });
  }

  handlePlay = (event) => {
    if(this.state.isPlaying) {
      return;
    }

    this.setState({
      isPlaying: true,
      startTime: this.state.audioContext.currentTime + .005,
    }, () => {
      this.startPlayback();
    });
  }

  getNextNote = (measureIndex, noteIndex) => {
    const { song } = this.props;

    if(measureIndex === song.length - 1 && noteIndex === song[measureIndex].notes.length - 1) {
      return { measureIndex, noteIndex };
    } else if(noteIndex === song[measureIndex].notes.length - 1) {
      return {
        measureIndex: measureIndex + 1,
        noteIndex: 0
      };
    } else {
      return {
        measureIndex,
        noteIndex: noteIndex + 1
      };
    }
  }

  getPrevNote = (measureIndex, noteIndex) => {
    const { song } = this.props;

    if(measureIndex === 0 && noteIndex === 0) {
      return { measureIndex, noteIndex };
    } else if(noteIndex === 0) {
      return {
        measureIndex: measureIndex - 1,
        noteIndex: song[measureIndex - 1].notes.length - 1
      };
    } else {
      return {
        measureIndex,
        noteIndex: noteIndex - 1
      };
    }
  }

  getUpperString = (stringIndex) => {
    return stringIndex === 5 ? 0 : stringIndex + 1;
  }

  getLowerString = (stringIndex) => {
    return stringIndex === 0 ? 5 : stringIndex - 1;
  }

  navigateCursor = (event) => {
    let { measureIndex, noteIndex, stringIndex } = this.state.currentEditingIndex;

    if(event.keyCode === 39) { // right arrow
      let newEditingIndex = this.getNextNote(measureIndex, noteIndex);
      newEditingIndex.stringIndex = stringIndex;
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 37) { // left arrow
      let newEditingIndex = this.getPrevNote(measureIndex, noteIndex);
      newEditingIndex.stringIndex = stringIndex;
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 38) { // up arrow
      event.preventDefault();
      let newEditingIndex = {
        stringIndex: this.getUpperString(stringIndex),
        noteIndex,
        measureIndex
      };
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 40) { // down arrow
      event.preventDefault();
      let newEditingIndex = {
        stringIndex: this.getLowerString(stringIndex),
        noteIndex,
        measureIndex
      };
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    }
  }

  editNote = (fret) => {
    this.props.dispatch({
      type: 'CHANGE_NOTE',
      fret,
      index: this.state.currentEditingIndex
    });
  }

  handleKeyPress = (event) => {
    if(event.keyCode <= 57 && event.keyCode >= 48) {
      return this.editNote(event.keyCode - 48);
    } else if(event.keyCode === 82 && !event.metaKey) {
      this.props.dispatch({
        type: 'CHANGE_NOTE',
        fret: 'rest',
        index: this.state.currentEditingIndex
      });
    }
    return this.navigateCursor(event);
  }

  bpmChanged = (event) => {
    this.setState({
      bpm: event.target.value
    });
  }

  render() {
    return (

          BPM:
          <input onChange={this.bpmChanged} value={this.state.bpm} />
          <button onClick={this.handlePlay}>Play</button>
          <button onClick={this.handleStop}>Stop</button>

        <TabStaff song={this.props.song}
          currentEditingIndex={this.state.currentEditingIndex}
          currentPlayingNote={this.state.currentPlayingNote}
          isPlaying={this.state.isPlaying}
        />

    );
  }
}

function mapStateToProps(state) {
  return {
    song: state.song
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  };
}

export default connect(mapStateToProps)(App);
<commit_msg>disable ctrl+r from changing the note to a rest<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from '../actions/song';

import TabStaff from './TabStaff';

class App extends Component {
  constructor(props) {
    super(props);

    if (typeof window !== 'undefined') {
      window.addEventListener('keydown', this.handleKeyPress);
    }

    let audioContext;
    try {
      audioContext = new AudioContext();
    } catch(e) {
      audioContext = new webkitAudioContext();
    }

    this.state = {
      currentPlayingNote: {
        measure: 0,
        noteIndex: 0
      },
      currentEditingIndex: {
        measureIndex: 0,
        noteIndex: 0,
        stringIndex: 0
      },
      audioContext: audioContext,
      isPlaying: false,
      bpm: 120
    };
  }

  getSpeedFromBpm = (bpm) => {
    return 60000 / bpm;
  }

  startPlayback = () => {
    let startTimestamp = Date.now();
    this.playCurrentNote();

    this.setState({
      timer: requestAnimationFrame(() => {
        this.loopThroughSong(startTimestamp);
      })
    });
  }

  getReplaySpeedForNote = (note, bpm) => {
    let noteLength = note.duration;

    let replaySpeed = this.getSpeedFromBpm(bpm);
    if(noteLength === 'h') {
      replaySpeed = replaySpeed * 2;
    } else if(noteLength === 'w') {
      replaySpeed = replaySpeed * 4;
    } else if(noteLength === 'e') {
      replaySpeed = replaySpeed / 2;
    } else if(noteLength === 's') {
      replaySpeed = replaySpeed / 4;
    }

    return replaySpeed;
  }

  loopThroughSong = (startTimestamp) => {
    let { currentPlayingNote, bpm } = this.state;
    let { measure, noteIndex } = currentPlayingNote;
    let { song } = this.props;

    let currentTimestamp = Date.now();
    let replayDiff = currentTimestamp - startTimestamp;
    let replaySpeed = this.getReplaySpeedForNote(song[currentPlayingNote.measure].notes[noteIndex], bpm);

    if(replayDiff >= replaySpeed) {
      if(measure === song.length - 1 && noteIndex === song[measure].notes.length - 1) {
        this.handleStop();
      } else if(measure !== song.length - 1 && noteIndex === song[measure].notes.length - 1) {
        this.setState({
          currentPlayingNote: {
            measure: measure + 1,
            noteIndex: 0
          },
          timer: requestAnimationFrame(() => {
            this.loopThroughSong(currentTimestamp);
          })
        }, this.playCurrentNote);
      } else {
        this.setState({
          currentPlayingNote: {
            measure: measure,
            noteIndex: noteIndex + 1
          },
          timer: requestAnimationFrame(() => {
            this.loopThroughSong(currentTimestamp);
          })
        }, this.playCurrentNote);
      }
    } else {
      this.setState({
        timer: requestAnimationFrame(() => {
          this.loopThroughSong(startTimestamp);
        })
      });
    }
  }

  playCurrentNote = () => {
    let noteToPlay = this.props.song[this.state.currentPlayingNote.measure].notes[this.state.currentPlayingNote.noteIndex];
    let replaySpeed = this.getReplaySpeedForNote(noteToPlay, this.state.bpm);

    if(noteToPlay.fret[0] === 'rest') {
      this.play(this.state.audioContext, this.state.audioContext.currentTime, 'rest', replaySpeed);
    } else {
      this.playNoteAtTime(noteToPlay, this.state.audioContext.currentTime, replaySpeed);
    }
  }

  playNoteAtTime = (currentNote, playTime, duration) => {
    for(let i = 0; i < currentNote.string.length; i++) {
      let pitch = currentNote.fret[i] + (5 * currentNote.string[i]);
      if(currentNote.string[i] >= 4) {
        pitch = pitch - 1;
      }

      this.play(this.state.audioContext, playTime, pitch, duration / 1000);
    }
  }

  play = (audioContext, startTime, pitch, duration) => {
    let endTime = startTime + duration;

    let oscillator = this.state.audioContext.createOscillator();
    let gainNode = audioContext.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);

    if(pitch !== 'rest') {
      oscillator.type = 'square';
      oscillator.detune.value = (pitch - 29) * 100;

      gainNode.gain.value = 0.025;
    } else {
      gainNode.gain.value = 0;
    }

    oscillator.start(startTime);
    oscillator.stop(endTime);
  }

  handleStop = () => {
    cancelAnimationFrame(this.state.timer);

    this.setState({
      isPlaying: false,
      currentPlayingNote: {
        measure: 0,
        noteIndex: 0
      }
    });
  }

  handlePlay = (event) => {
    if(this.state.isPlaying) {
      return;
    }

    this.setState({
      isPlaying: true,
      startTime: this.state.audioContext.currentTime + .005,
    }, () => {
      this.startPlayback();
    });
  }

  getNextNote = (measureIndex, noteIndex) => {
    const { song } = this.props;

    if(measureIndex === song.length - 1 && noteIndex === song[measureIndex].notes.length - 1) {
      return { measureIndex, noteIndex };
    } else if(noteIndex === song[measureIndex].notes.length - 1) {
      return {
        measureIndex: measureIndex + 1,
        noteIndex: 0
      };
    } else {
      return {
        measureIndex,
        noteIndex: noteIndex + 1
      };
    }
  }

  getPrevNote = (measureIndex, noteIndex) => {
    const { song } = this.props;

    if(measureIndex === 0 && noteIndex === 0) {
      return { measureIndex, noteIndex };
    } else if(noteIndex === 0) {
      return {
        measureIndex: measureIndex - 1,
        noteIndex: song[measureIndex - 1].notes.length - 1
      };
    } else {
      return {
        measureIndex,
        noteIndex: noteIndex - 1
      };
    }
  }

  getUpperString = (stringIndex) => {
    return stringIndex === 5 ? 0 : stringIndex + 1;
  }

  getLowerString = (stringIndex) => {
    return stringIndex === 0 ? 5 : stringIndex - 1;
  }

  navigateCursor = (event) => {
    let { measureIndex, noteIndex, stringIndex } = this.state.currentEditingIndex;

    if(event.keyCode === 39) { // right arrow
      let newEditingIndex = this.getNextNote(measureIndex, noteIndex);
      newEditingIndex.stringIndex = stringIndex;
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 37) { // left arrow
      let newEditingIndex = this.getPrevNote(measureIndex, noteIndex);
      newEditingIndex.stringIndex = stringIndex;
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 38) { // up arrow
      event.preventDefault();
      let newEditingIndex = {
        stringIndex: this.getUpperString(stringIndex),
        noteIndex,
        measureIndex
      };
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    } else if(event.keyCode === 40) { // down arrow
      event.preventDefault();
      let newEditingIndex = {
        stringIndex: this.getLowerString(stringIndex),
        noteIndex,
        measureIndex
      };
      this.setState({
        currentEditingIndex: newEditingIndex
      });
    }
  }

  editNote = (fret) => {
    this.props.dispatch({
      type: 'CHANGE_NOTE',
      fret,
      index: this.state.currentEditingIndex
    });
  }

  handleKeyPress = (event) => {
    if(event.keyCode <= 57 && event.keyCode >= 48) {
      return this.editNote(event.keyCode - 48);
    } else if(event.keyCode === 82 && !event.metaKey && !event.ctrlKey) {
      this.props.dispatch({
        type: 'CHANGE_NOTE',
        fret: 'rest',
        index: this.state.currentEditingIndex
      });
    }
    return this.navigateCursor(event);
  }

  bpmChanged = (event) => {
    this.setState({
      bpm: event.target.value
    });
  }

  render() {
    return (

          BPM:
          <input onChange={this.bpmChanged} value={this.state.bpm} />
          <button onClick={this.handlePlay}>Play</button>
          <button onClick={this.handleStop}>Stop</button>

        <TabStaff song={this.props.song}
          currentEditingIndex={this.state.currentEditingIndex}
          currentPlayingNote={this.state.currentPlayingNote}
          isPlaying={this.state.isPlaying}
        />

    );
  }
}

function mapStateToProps(state) {
  return {
    song: state.song
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  };
}

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


<commit_before>import React, { Component} from 'react';
import PropTypes from 'prop-types';
import styles from '../styles/Nav.css';

class Nav extends Component {
    constructor(props) {
        super(props);
        this.state = {
            nav_element_class: "hidden-nav"
        };
        this.toggleNav = this.toggleNav.bind(this);
    }
    toggleNav() {
        this.setState({
            nav_element_class: (this.state.nav_element_class === "hidden-nav") ?
            "shown-nav" : "hidden-nav"
        });
    }
    render() {
        return (

Practice Buddy

# Modes

# Chords

# Charts

# About

Practice Buddy

        );
    }
}

export default Nav;
<commit_msg>Add click outside to exit nav functionality<commit_after>import React, { Component} from 'react';
import PropTypes from 'prop-types';
import styles from '../styles/Nav.css';

class Nav extends Component {
    constructor(props) {
        super(props);
        this.state = {
            nav_element_class: "hidden-nav"
        };
        this.toggleNav = this.toggleNav.bind(this);
        this.setWrapperRef = this.setWrapperRef.bind(this);
        this.handleClickOutside = this.handleClickOutside.bind(this);
    }
    toggleNav() {
        this.setState({
            nav_element_class: (this.state.nav_element_class === "hidden-nav") ?
            "shown-nav" : "hidden-nav"
        });
    }
    componentDidMount() {
        document.addEventListener('mousedown', this.handleClickOutside);
    }

    componentWillUnmount() {
        document.removeEventListener('mousedown', this.handleClickOutside);
    }
    setWrapperRef(node) {
        this.wrapperRef = node;
    }
    handleClickOutside(event) {
        if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
        this.setState({
            nav_element_class:  "hidden-nav"
        });

        }
    }
    render() {
        return (

Practice Buddy

# Modes

# Chords

# Charts

# About

Practice Buddy

        );
    }
}

export default Nav;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { Box, Flex, Link as A, Container, Icon } from '@hackclub/design-system'
import Flag from 'components/Flag'
import Link from 'gatsby-link'
import ScrollLock from 'react-scrolllock'

const Root = Box.withComponent('header').extend`
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1000;

  ${props =>
    (props.scrolled || props.toggled || props.fixed) &&
    css`
      position: fixed;
      background-color: rgba(${props.bgColor[0]}, ${props.bgColor[1]}, ${props.bgColor[2]}, 0.96875);
      border-bottom: 1px solid rgba(51, 51, 51, 0.1);
      @supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
        background-color: rgba(${props.bgColor[0]}, ${props.bgColor[1]}, ${props.bgColor[2]}, 0.75);
        -webkit-backdrop-filter: saturate(180%) blur(16px);
      }
      ${({ theme }) => theme.mediaQueries.reduceTransparency} {
        -webkit-backdrop-filter: auto !important;
      }
    `}
`

const Content = Container.extend`
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding-left: ${({ theme }) => theme.space[3]}px;
  ${({ theme }) => theme.mediaQueries.md} {
    padding: 0 ${({ theme }) => theme.space[4]}px;
  }
`

const hoverColor = name =>
  ({
    white: 'smoke',
    smoke: 'muted',
    muted: 'slate',
    slate: 'black',
    black: 'slate',
    primary: 'error'
  }[name] || 'black')

const NavBar = Box.withComponent('nav').extend`
  display: none;
  a {
    color: ${props => props.theme.cx(props.color)};
    margin-left: ${({ theme }) => theme.space[2]}px;
    padding: ${({ theme }) => theme.space[2]}px;
    text-decoration: none;
  }
  ${props =>
    props.isMobile
      ? css`
          display: ${props => (props.toggled ? 'flex' : 'none')};
          flex-direction: column;
          overflow-y: scroll;
          text-align: left;
          height: 100vh;
          a {
            padding: 0;
            margin: 0 auto;
            height: 64px;
            line-height: 64px;
            font-weight: bold;
            width: 100%;
            max-width: 18rem;
            color: ${({ theme }) => theme.colors.black};
            &:not(:last-child) {
              border-bottom: 1px solid rgba(51, 51, 51, 0.1);
            }
            @media screen and (max-width: 22em) {
              max-width: 16rem;
            }
          }
        `
      : css`
          @media (min-width: 56em) {
            display: flex;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
          }
          a {
            font-size: ${({ theme }) => theme.fontSizes[1]}px;
            text-transform: uppercase;
            &:hover {
              color: ${({ theme }) => theme.cx(hoverColor(props.color))};
            }
          }
        `};
`

const Navigation = props => (
  <NavBar role="navigation" {...props}>
    <Link to="/team" children="Team" />
    <Link to="/donate" children="Donate" />
    <Link to="/challenge" children="Challenge" />
    <Link to="/workshops" children="Workshops" />

    <Link to="/bank" children="Bank" />
    <Link to="/start" children="Get Started »" />
  </NavBar>
)

const ToggleContainer = styled(Flex)`
  align-items: center;
  justify-content: center;
  min-width: 64px;
  min-height: 44px;
  cursor: pointer;
  user-select: none;
  margin-left: auto;
`

const Toggle = styled(Icon)`
  display: block;
  ${({ theme }) => theme.mediaQueries.md} {
    display: none;
  }
`

class Header extends Component {
  state = {
    scrolled: false,
    toggled: false
  }

  propTypes = {
    color: PropTypes.string,
    fixed: PropTypes.bool
  }

  componentDidMount() {
    this.bindScroll(true)
    if (typeof window !== 'undefined') {
      const mobileQuery = window.matchMedia('(max-width: 56em)')
      mobileQuery.addListener(() => {
        this.setState({ toggled: false })
      })
    }
  }

  componentWillUnmount = () => {
    this.bindScroll(false)
  }

  bindScroll = add => {
    if (typeof window !== 'undefined') {
      window[add ? 'addEventListener' : 'removeEventListener'](
        'scroll',
        this.onScroll
      )
    }
  }

  onScroll = () => {
    const newState = window.scrollY >= 16
    const { scrolled: oldState } = this.state

    if (newState !== oldState) {
      this.setState({
        scrolled: newState
      })
    }
  }

  handleToggleMenu = () => {
    this.setState(state => ({
      toggled: !state.toggled
    }))
  }

  render() {
    const {
      color = 'white',
      bgColor = [255, 255, 255],
      fixed,
      ...props
    } = this.props
    const { scrolled, toggled } = this.state
    const baseColor = (color === 'white' && scrolled) ? 'black' : color
    const toggleColor = (toggled || (color === 'white' && scrolled)) ? 'slate' : color

    return (
      <Root {...props} fixed={fixed} scrolled={scrolled} toggled={toggled} bgColor={bgColor}>
        <Content>
          <Flag scrolled={scrolled || fixed} />
          <Navigation color={baseColor} />
          <ToggleContainer color={toggleColor} onClick={this.handleToggleMenu}>
            <Toggle
              name={toggled ? 'close' : 'drag_handle'}
              toggled={toggled}
            />
          </ToggleContainer>
        </Content>
        <Navigation isMobile toggled={toggled} />
        {toggled && <ScrollLock />}
      </Root>
    )
  }
}

export default Header
<commit_msg>Fix instance declaration of proptypes<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'
import { Box, Flex, Link as A, Container, Icon } from '@hackclub/design-system'
import Flag from 'components/Flag'
import Link from 'gatsby-link'
import ScrollLock from 'react-scrolllock'

const Root = Box.withComponent('header').extend`
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1000;

  ${props =>
    (props.scrolled || props.toggled || props.fixed) &&
    css`
      position: fixed;
      background-color: rgba(${props.bgColor[0]}, ${props.bgColor[1]}, ${props.bgColor[2]}, 0.96875);
      border-bottom: 1px solid rgba(51, 51, 51, 0.1);
      @supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
        background-color: rgba(${props.bgColor[0]}, ${props.bgColor[1]}, ${props.bgColor[2]}, 0.75);
        -webkit-backdrop-filter: saturate(180%) blur(16px);
      }
      ${({ theme }) => theme.mediaQueries.reduceTransparency} {
        -webkit-backdrop-filter: auto !important;
      }
    `}
`

const Content = Container.extend`
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding-left: ${({ theme }) => theme.space[3]}px;
  ${({ theme }) => theme.mediaQueries.md} {
    padding: 0 ${({ theme }) => theme.space[4]}px;
  }
`

const hoverColor = name =>
  ({
    white: 'smoke',
    smoke: 'muted',
    muted: 'slate',
    slate: 'black',
    black: 'slate',
    primary: 'error'
  }[name] || 'black')

const NavBar = Box.withComponent('nav').extend`
  display: none;
  a {
    color: ${props => props.theme.cx(props.color)};
    margin-left: ${({ theme }) => theme.space[2]}px;
    padding: ${({ theme }) => theme.space[2]}px;
    text-decoration: none;
  }
  ${props =>
    props.isMobile
      ? css`
          display: ${props => (props.toggled ? 'flex' : 'none')};
          flex-direction: column;
          overflow-y: scroll;
          text-align: left;
          height: 100vh;
          a {
            padding: 0;
            margin: 0 auto;
            height: 64px;
            line-height: 64px;
            font-weight: bold;
            width: 100%;
            max-width: 18rem;
            color: ${({ theme }) => theme.colors.black};
            &:not(:last-child) {
              border-bottom: 1px solid rgba(51, 51, 51, 0.1);
            }
            @media screen and (max-width: 22em) {
              max-width: 16rem;
            }
          }
        `
      : css`
          @media (min-width: 56em) {
            display: flex;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
          }
          a {
            font-size: ${({ theme }) => theme.fontSizes[1]}px;
            text-transform: uppercase;
            &:hover {
              color: ${({ theme }) => theme.cx(hoverColor(props.color))};
            }
          }
        `};
`

const Navigation = props => (
  <NavBar role="navigation" {...props}>
    <Link to="/team" children="Team" />
    <Link to="/donate" children="Donate" />
    <Link to="/challenge" children="Challenge" />
    <Link to="/workshops" children="Workshops" />

    <Link to="/bank" children="Bank" />
    <Link to="/start" children="Get Started »" />
  </NavBar>
)

const ToggleContainer = styled(Flex)`
  align-items: center;
  justify-content: center;
  min-width: 64px;
  min-height: 44px;
  cursor: pointer;
  user-select: none;
  margin-left: auto;
`

const Toggle = styled(Icon)`
  display: block;
  ${({ theme }) => theme.mediaQueries.md} {
    display: none;
  }
`

class Header extends Component {
  state = {
    scrolled: false,
    toggled: false
  }

  componentDidMount() {
    this.bindScroll(true)
    if (typeof window !== 'undefined') {
      const mobileQuery = window.matchMedia('(max-width: 56em)')
      mobileQuery.addListener(() => {
        this.setState({ toggled: false })
      })
    }
  }

  componentWillUnmount = () => {
    this.bindScroll(false)
  }

  bindScroll = add => {
    if (typeof window !== 'undefined') {
      window[add ? 'addEventListener' : 'removeEventListener'](
        'scroll',
        this.onScroll
      )
    }
  }

  onScroll = () => {
    const newState = window.scrollY >= 16
    const { scrolled: oldState } = this.state

    if (newState !== oldState) {
      this.setState({
        scrolled: newState
      })
    }
  }

  handleToggleMenu = () => {
    this.setState(state => ({
      toggled: !state.toggled
    }))
  }

  render() {
    const {
      color = 'white',
      bgColor = [255, 255, 255],
      fixed,
      ...props
    } = this.props
    const { scrolled, toggled } = this.state
    const baseColor = (color === 'white' && scrolled) ? 'black' : color
    const toggleColor = (toggled || (color === 'white' && scrolled)) ? 'slate' : color

    return (
      <Root {...props} fixed={fixed} scrolled={scrolled} toggled={toggled} bgColor={bgColor}>
        <Content>
          <Flag scrolled={scrolled || fixed} />
          <Navigation color={baseColor} />
          <ToggleContainer color={toggleColor} onClick={this.handleToggleMenu}>
            <Toggle
              name={toggled ? 'close' : 'drag_handle'}
              toggled={toggled}
            />
          </ToggleContainer>
        </Content>
        <Navigation isMobile toggled={toggled} />
        {toggled && <ScrollLock />}
      </Root>
    )
  }
}
Header.propTypes = {
  color: PropTypes.string,
  fixed: PropTypes.bool
}

export default Header
<|endoftext|>


<commit_before><commit_msg>added basic functionality<commit_after>
$(document).ready(function(){
  var ans = new Array;
    $.get('preceed_with_an.txt', function(data){
            var array = data.split('\n');
            console.log(ans);
        });
});

$(document).on('input',$('#givenWord'),function () {
  console.log($('#givenWord').val())

});
<|endoftext|>