<commit_before>import 'ui/assets/stylesheets/components/request-details.scss';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { map } from 'lodash';
import { Tabs, Tab, TextField, RaisedButton } from 'material-ui';

import { RequestActions } from 'ui/components/request-details/request-actions';
import { RequestInfo } from 'ui/components/request-details/request-info';
import { Editor } from 'ui/components/editor';

import { navigate } from 'ui/actions/location';
import { mockRequest, updateMock } from 'ui/actions/api';
import { get as _get }  from 'lodash';

class RequestDetails extends Component {

  constructor(props) {
    super(props);

    this.state = this._initRequest(props);
  }

  _initRequest(props) {
    return {
      selectedScenario: this.getCurrentScenario(props.mock) || _get(props.scenarios[0], 'id'),
      originalScenario: this.getCurrentScenario(props.mock) || _get(props.scenarios[0], 'id'),
      url: _get(props.mock, 'url', props.url),
      headers: _get(props.mock, 'headers', props.response.headers),
      status: _get(props.mock, 'response.status', props.response.status),
      delay: _get(props.mock, 'response.delay', props.response.delay),
      responseBody: _get(props.mock, 'response.body', props.response.body)
    };
  }

  getCurrentScenario(mock) {
    if (!mock) {
      return null;
    }

    const scenario = this.props.scenarios
      .filter(scenario => scenario.mockedRequests
        .filter(request => request === mock).length
      )[0];

    return _get(scenario, 'id', null);
  }

  componentWillReceiveProps(props) {
    this.setState(this._initRequest(props));
  }

  _handleCancel() {
    this.props.navigate('scenarios');
  }

  _handleSave() {
    if (this.props.mock && this.state.selectedScenario === this.state.originalScenario) {
      this.props.updateMock(this.state.selectedScenario, this.props.mock.id, {
        url: this.state.url,
        headers: this.state.headers,
        response: {
          delay: this.state.delay,
          status: this.state.status,
          body: this.state.responseBody
        }
      });
    } else {
      this.props.mockRequest(this.state.selectedScenario, {
        requestId: this.props.id,
        active: true,
        url: this.state.url,
        method: this.props.method,
        headers: this.state.headers,
        params: this.props.params,
        response: {
          delay: _get(this.props, 'response.delay', 0),
          status: _get(this.props, 'response.status', 200),
          body: this.state.responseBody
        }
      });
    }

    this.props.navigate('scenarios');
  }

  _selectScenario(selectedScenario) {
    this.setState({ selectedScenario });
  }

  _headersChange(key, type, event) {
    const headers = this.state.headers;

    if (type === 'key') {
      const oldValue = headers[key];
      delete headers[key];
      const newKey = event.target.value;

      headers[newKey] = oldValue;
    }

    if (type === 'value') {
      headers[key] = event.target.value;
    }

    this.setState({ headers });
  }

  _responseBodyChange(responseBody) {
    this.setState({ responseBody });
  }

  _requestInfoChange(key, event) {
    this.setState({ [key]: event.target ? event.target.value : event });
  }

  _getContentType(type) {
    switch (type) {
      case 'html':
        return 'text/html';

      case 'xml':
        return 'text/xml';

      case 'json':
        return 'application/json';

      case 'text':
        return 'text/plain'
    }
  }

  _setHeaderPreset(preset) {
    this.setState({
      headers: {
        pragma: 'no-cache',
        'content-type': `${this._getContentType(preset)}; charset=utf-8`,
        'cache-control': 'no-cache',
        expires: -1
      }
    })
  }

  _renderHeaders() {
    return map(this.state.headers, (value, key) => {
      return (

            <TextField
              hintText="Header"
              value={ key }
              onChange={ this._headersChange.bind(this, key, 'key') }
            />

            <TextField
              hintText="Value"
              style={{ width: '80%' }}
              value={ value }
              onChange={ this._headersChange.bind(this, key, 'value') }/>

      );
    });
  }

  render() {
    const { method, params, scenarios, mock } = this.props;

    return (

        <RequestActions
          onCancel={ this._handleCancel.bind(this) }
          onSave={ this._handleSave.bind(this) }
          onChange={ this._selectScenario.bind(this) }
          scenarios={ scenarios }
          mocked={ !!mock }
          selectedScenario={ this.state.selectedScenario }/>

        <RequestInfo url={ this.state.url }
                     method={ method }
                     params={ params }
                     status={ this.state.status }
                     delay={ this.state.delay }
                     onUrlChange={ this._requestInfoChange.bind(this, 'url') }
                     onDelayChange={ this._requestInfoChange.bind(this, 'delay') }
                     onStatusChange={ this._requestInfoChange.bind(this, 'status') }/>

              Response Body

              <Editor mode="javascript"
                      value={ this.state.responseBody }
                      onChange={ this._responseBodyChange.bind(this) }/>

            <Tabs inkBarStyle={ { backgroundColor: '#52B665' }}
                  tabItemContainerStyle={ {
                    backgroundColor: '#fff',
                    borderBottom: '1px solid #52B665'
                  }}>
              <Tab label="Response Headers" value="a" style={{ color: '#000' }}>

                    Header Presets
                    <RaisedButton label="JSON" onClick={ () => this._setHeaderPreset('json') } />
                    <RaisedButton label="XML" onClick={ () => this._setHeaderPreset('xml') } />
                    <RaisedButton label="HTML" onClick={ () => this._setHeaderPreset('html') } />
                    <RaisedButton label="Text" onClick={ () => this._setHeaderPreset('text') } />

                   { this._renderHeaders() }
              </Tab>
            </Tabs>

    );
  }

}

const mapStateToProps = (state) => ({
  scenarios: state.scenarios
});

export default connect(mapStateToProps, {
  navigate,
  mockRequest,
  updateMock
})(RequestDetails);
<commit_msg>implement add header button<commit_after>import 'ui/assets/stylesheets/components/request-details.scss';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { map } from 'lodash';
import { Tabs, Tab, TextField, RaisedButton, FloatingActionButton } from 'material-ui';
import ContentAdd from 'material-ui/lib/svg-icons/content/add';

import { RequestActions } from 'ui/components/request-details/request-actions';
import { RequestInfo } from 'ui/components/request-details/request-info';
import { Editor } from 'ui/components/editor';

import { navigate } from 'ui/actions/location';
import { mockRequest, updateMock } from 'ui/actions/api';
import { get as _get }  from 'lodash';

class RequestDetails extends Component {

  constructor(props) {
    super(props);

    this.state = this._initRequest(props);
  }

  _initRequest(props) {
    return {
      selectedScenario: this.getCurrentScenario(props.mock) || _get(props.scenarios[0], 'id'),
      originalScenario: this.getCurrentScenario(props.mock) || _get(props.scenarios[0], 'id'),
      url: _get(props.mock, 'url', props.url),
      headers: _get(props.mock, 'headers', props.response.headers),
      status: _get(props.mock, 'response.status', props.response.status),
      delay: _get(props.mock, 'response.delay', props.response.delay),
      responseBody: _get(props.mock, 'response.body', props.response.body)
    };
  }

  getCurrentScenario(mock) {
    if (!mock) {
      return null;
    }

    const scenario = this.props.scenarios
      .filter(scenario => scenario.mockedRequests
        .filter(request => request === mock).length
      )[0];

    return _get(scenario, 'id', null);
  }

  componentWillReceiveProps(props) {
    this.setState(this._initRequest(props));
  }

  _handleCancel() {
    this.props.navigate('scenarios');
  }

  _handleSave() {
    if (this.props.mock && this.state.selectedScenario === this.state.originalScenario) {
      this.props.updateMock(this.state.selectedScenario, this.props.mock.id, {
        url: this.state.url,
        headers: this.state.headers,
        response: {
          delay: this.state.delay,
          status: this.state.status,
          body: this.state.responseBody
        }
      });
    } else {
      this.props.mockRequest(this.state.selectedScenario, {
        requestId: this.props.id,
        active: true,
        url: this.state.url,
        method: this.props.method,
        headers: this.state.headers,
        params: this.props.params,
        response: {
          delay: _get(this.props, 'response.delay', 0),
          status: _get(this.props, 'response.status', 200),
          body: this.state.responseBody
        }
      });
    }

    this.props.navigate('scenarios');
  }

  _selectScenario(selectedScenario) {
    this.setState({ selectedScenario });
  }

  _headersChange(key, type, event) {
    const headers = this.state.headers;

    if (type === 'key') {
      const oldValue = headers[key];
      delete headers[key];
      const newKey = event.target.value;

      headers[newKey] = oldValue;
    }

    if (type === 'value') {
      headers[key] = event.target.value;
    }

    this.setState({ headers });
  }

  _responseBodyChange(responseBody) {
    this.setState({ responseBody });
  }

  _requestInfoChange(key, event) {
    this.setState({ [key]: event.target ? event.target.value : event });
  }

  _getContentType(type) {
    switch (type) {
      case 'html':
        return 'text/html';

      case 'xml':
        return 'text/xml';

      case 'json':
        return 'application/json';

      case 'text':
        return 'text/plain'
    }
  }

  _setHeaderPreset(preset) {
    this.setState({
      headers: {
        pragma: 'no-cache',
        'content-type': `${this._getContentType(preset)}; charset=utf-8`,
        'cache-control': 'no-cache',
        expires: -1
      }
    })
  }

  addHeader() {
    const headers = Object.assign({}, this.state.headers, { '': '' });
    this.setState({ headers });
  }

  _renderHeaders() {
    return map(this.state.headers, (value, key, collection, index) => {
      return (

            <TextField
              hintText="Header"
              value={ key }
              onChange={ this._headersChange.bind(this, key, 'key') }
            />

            <TextField
              hintText="Value"
              style={{ width: '80%' }}
              value={ value }
              onChange={ this._headersChange.bind(this, key, 'value') }/>

      );
    });
  }

  render() {
    const { method, params, scenarios, mock } = this.props;

    return (

        <RequestActions
          onCancel={ this._handleCancel.bind(this) }
          onSave={ this._handleSave.bind(this) }
          onChange={ this._selectScenario.bind(this) }
          scenarios={ scenarios }
          mocked={ !!mock }
          selectedScenario={ this.state.selectedScenario }/>

        <RequestInfo url={ this.state.url }
                     method={ method }
                     params={ params }
                     status={ this.state.status }
                     delay={ this.state.delay }
                     onUrlChange={ this._requestInfoChange.bind(this, 'url') }
                     onDelayChange={ this._requestInfoChange.bind(this, 'delay') }
                     onStatusChange={ this._requestInfoChange.bind(this, 'status') }/>

              Response Body

              <Editor mode="javascript"
                      value={ this.state.responseBody }
                      onChange={ this._responseBodyChange.bind(this) }/>

            <Tabs inkBarStyle={ { backgroundColor: '#52B665' }}
                  tabItemContainerStyle={ {
                    backgroundColor: '#fff',
                    borderBottom: '1px solid #52B665'
                  }}>
              <Tab label="Response Headers" value="a" style={{ color: '#000' }}>

                    Header Presets
                    <RaisedButton label="JSON" onClick={ () => this._setHeaderPreset('json') } />
                    <RaisedButton label="XML" onClick={ () => this._setHeaderPreset('xml') } />
                    <RaisedButton label="HTML" onClick={ () => this._setHeaderPreset('html') } />
                    <RaisedButton label="Text" onClick={ () => this._setHeaderPreset('text') } />

                   { this._renderHeaders() }

                     <FloatingActionButton mini={true} onClick={ () => this.addHeader() }>
                       <ContentAdd />
                     </FloatingActionButton>

              </Tab>
            </Tabs>

    );
  }

}

const mapStateToProps = (state) => ({
  scenarios: state.scenarios
});

export default connect(mapStateToProps, {
  navigate,
  mockRequest,
  updateMock
})(RequestDetails);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * 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.
 */
/*jslint sub: true */
var p = $A.ns.Util.prototype;
exp(p,
    "isIE", p.isIE,
    "isIOSWebView", p.isIOSWebView,
    "isArray", p.isArray,
    "isBoolean", p.isBoolean,
    "isObject", p.isObject,
    "isError", p.isError,
    "isFunction", p.isFunction,
    "isNumber", p.isNumber,
    "isFiniteNumber", p.isFiniteNumber,
    "isString", p.isString,
    "isUndefined", p.isUndefined,
    "isUndefinedOrNull", p.isUndefinedOrNull,
    "isEmpty", p.isEmpty,
    "getElement", p.getElement,
    "getBooleanValue", p.getBooleanValue,
    "hasClass", p.hasClass,
    "addClass", p.addClass,
    "removeClass", p.removeClass,
    "toggleClass", p.toggleClass,
    "swapClass", p.swapClass,
    "insertFirst", p.insertFirst,
    "insertBefore", p.insertBefore,
    "insertAfter", p.insertAfter,
    "removeElement", p.removeElement,
    "attachToDocumentBody", p.attachToDocumentBody,
    "stringEndsWith",p.stringEndsWith,
    "urlDecode", p.urlDecode,
    "trim", p.trim,
    "truncate", p.truncate,
    "on", p.on,
    "removeOn", p.removeOn,
    "formToMap", p.formToMap,
    "getSelectValue", p.getSelectValue,
    "addValueToMap", p.addValueToMap,
    "addMapValueToMap", p.addMapValueToMap,
    "isSubDef", p.isSubDef,
    "getElementAttributeValue", p.getElementAttributeValue,
    "getDataAttribute", p.getDataAttribute,
    "setDataAttribute", p.setDataAttribute,
    "hasDataAttribute", p.hasDataAttribute,
    "createTimeoutCallback", p.createTimeoutCallback,
    "arrayIndexOf", p.arrayIndexOf,
    "contains", p.contains,
    "squash", p.squash,
    "stripTags", p.stripTags,
    "getWindowSize", p.getWindowSize,
    "isComponent", p.isComponent,
    "isValue", p.isValue,
    "instanceOf", p.instanceOf,
    "supportsTouchEvents", p.supportsTouchEvents,
    "estimateSize", p.estimateSize,
    "createPromise", p.createPromise,
    "when", p.when,
    "lookup", p.lookup,
    "map", p.map,
    "reduce", p.reduce,
    "forEach", p.forEach,
    "merge", p.merge,
    "every", p.every,
    "some", p.some,
    "filter", p.filter,
    "keys", p.keys,
    "bind", p.bind,
    "includeScript", p.includeScript,
    "equalBySource", p.equalBySource

    //#if {"excludeModes" : ["PRODUCTION", "PRODUCTIONDEBUG"]}
	    ,
	    "getDebugToolComponent", p.getDebugToolComponent,
	    "setDebugToolWindow", p.setDebugToolWindow,
	    "getDebugToolsAuraInstance",  p.getDebugToolsAuraInstance,
	    "getUrl", p.getUrl,
	    "getText", p.getText,
	    "errorBasedOnMode", p.errorBasedOnMode
    //#end
);

<commit_msg>Linear enumeration of exports, instead of exp(), because closure doesn't do the loop unrolling needed to reserve words for the exported names. The function does expose the right symbols, but doesn't prevent collisions.<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * 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.
 */
/*jslint sub: true */
var p = $A.ns.Util.prototype;
p["isIE"] = p.isIE;
p["isIOSWebView"] = p.isIOSWebView;
p["isArray"] = p.isArray;
p["isBoolean"] = p.isBoolean;
p["isObject"] = p.isObject;
p["isError"] = p.isError;
p["isFunction"] = p.isFunction;
p["isNumber"] = p.isNumber;
p["isFiniteNumber"] = p.isFiniteNumber;
p["isString"] = p.isString;
p["isUndefined"] = p.isUndefined;
p["isUndefinedOrNull"] = p.isUndefinedOrNull;
p["isEmpty"] = p.isEmpty;
p["getElement"] = p.getElement;
p["getBooleanValue"] = p.getBooleanValue;
p["hasClass"] = p.hasClass;
p["addClass"] = p.addClass;
p["removeClass"] = p.removeClass;
p["toggleClass"] = p.toggleClass;
p["swapClass"] = p.swapClass;
p["insertFirst"] = p.insertFirst;
p["insertBefore"] = p.insertBefore;
p["insertAfter"] = p.insertAfter;
p["removeElement"] = p.removeElement;
p["attachToDocumentBody"] = p.attachToDocumentBody;
p["stringEndsWith"] = p.stringEndsWith;
p["urlDecode"] = p.urlDecode;
p["trim"] = p.trim;
p["truncate"] = p.truncate;
p["on"] = p.on;
p["removeOn"] = p.removeOn;
p["formToMap"] = p.formToMap;
p["getSelectValue"] = p.getSelectValue;
p["addValueToMap"] = p.addValueToMap;
p["addMapValueToMap"] = p.addMapValueToMap;
p["isSubDef"] = p.isSubDef;
p["getElementAttributeValue"] = p.getElementAttributeValue;
p["getDataAttribute"] = p.getDataAttribute;
p["setDataAttribute"] = p.setDataAttribute;
p["hasDataAttribute"] = p.hasDataAttribute;
p["createTimeoutCallback"] = p.createTimeoutCallback;
p["arrayIndexOf"] = p.arrayIndexOf;
p["contains"] = p.contains;
p["squash"] = p.squash;
p["stripTags"] = p.stripTags;
p["getWindowSize"] = p.getWindowSize;
p["isComponent"] = p.isComponent;
p["isValue"] = p.isValue;
p["instanceOf"] = p.instanceOf;
p["supportsTouchEvents"] = p.supportsTouchEvents;
p["estimateSize"] = p.estimateSize;
p["createPromise"] = p.createPromise;
p["when"] = p.when;
p["lookup"] = p.lookup;
p["map"] = p.map;
p["reduce"] = p.reduce;
p["forEach"] = p.forEach;
p["merge"] = p.merge;
p["every"] = p.every;
p["some"] = p.some;
p["filter"] = p.filter;
p["keys"] = p.keys;
p["bind"] = p.bind;
p["includeScript"] = p.includeScript;
p["equalBySource"] = p.equalBySource;

//#if {"excludeModes" : ["PRODUCTION", "PRODUCTIONDEBUG"]}
p["getDebugToolComponent"] = p.getDebugToolComponent;
p["setDebugToolWindow"] = p.setDebugToolWindow;
p["getDebugToolsAuraInstance"] = p.getDebugToolsAuraInstance;
p["getUrl"] = p.getUrl;
p["getText"] = p.getText;
p["errorBasedOnMode"] = p.errorBasedOnMode;
//#end

<|endoftext|>


<commit_before>/** @jsx jsx */
import { jsx } from '@emotion/core';
import { useRef, Fragment, useLayoutEffect, useMemo, useState } from 'react';
import { Editor } from 'slate-react';
import { Block } from 'slate';
import { getVisibleSelectionRect } from 'get-selection-range';
import { createPortal } from 'react-dom';
import { Popper } from 'react-popper';
import { marks, markTypes, plugins as markPlugins } from './marks';
import { type as defaultType } from './block-types/paragraph';
import AddBlock from './AddBlock';
import { ToolbarCheckbox, ToolbarButton } from './toolbar-components';
import { A11yText } from '@voussoir/ui/src/primitives/typography';
import { CircleSlashIcon } from '@voussoir/icons';
import ResizeObserver from 'resize-observer-polyfill';
import { selectionReference } from './utils';
import { useStateWithEqualityCheck } from './hooks';

function getSchema(blocks) {
  const schema = {
    document: {
      last: { type: defaultType },
      normalize: (editor, { code, node }) => {
        switch (code) {
          case 'last_child_type_invalid': {
            const paragraph = Block.create(defaultType);
            return editor.insertNodeByKey(node.key, node.nodes.size, paragraph);
          }
        }
      },
    },
    blocks: {},
  };
  Object.keys(blocks).forEach(type => {
    if (blocks[type].schema !== undefined) {
      schema.blocks[type] = blocks[type].schema;
    }
  });
  return schema;
}

function useHasSelection() {
  let [hasSelection, setHasSelection] = useState(false);
  useLayoutEffect(() => {
    const rect = getVisibleSelectionRect();
    let newValue = rect && rect.width !== 0;
    if (newValue !== hasSelection) {
      setHasSelection(newValue);
    }
  });
  return hasSelection;
}

let stopPropagation = e => {
  e.stopPropagation();
};

export function useContainerQuery(ref) {
  const [height, setHeight] = useState(0);
  const [width, setWidth] = useState(0);

  // bail early without ref
  if (!ref) {
    throw new Error('You must pass a valid ref as the first argument.');
  }

  // Updates scheduled inside useLayoutEffect will be flushed synchronously,
  // before the browser has a chance to paint.
  useLayoutEffect(() => {
    // prepare the resize handler
    let resizeObserver = new ResizeObserver(([entry]) => {
      setHeight(entry.target.offsetHeight);
      setWidth(entry.target.offsetWidth);
    });

    // bind the observer to the consumer DOM node
    resizeObserver.observe(ref.current);

    // cleanup after ourselves
    return () => {
      resizeObserver.disconnect(ref.current);
    };
  });

  return { height, width };
}

// to use hooks inside of class components
let Render = ({ children }) => children();

function Stories({ value: editorState, onChange, blocks }) {
  let schema = useMemo(
    () => {
      return getSchema(blocks);
    },
    [blocks]
  );

  let plugins = useMemo(
    () => {
      let combinedPlugins = [
        ...markPlugins,
        {
          renderNode(props, editor) {
            let block = blocks[props.node.type];
            if (block) {
              return block.renderNode(props, editor);
            }
            // we don't want to define how how nodes are rendered in any other place
            throw new Error('Cannot render node of type: ' + props.node.type);
          },
        },
      ];

      Object.keys(blocks).forEach(type => {
        let blockTypePlugins = blocks[type].plugins;
        if (blockTypePlugins !== undefined) {
          combinedPlugins.push(...blockTypePlugins);
        }
      });
      return combinedPlugins;
    },
    [blocks]
  );

  let editorRef = useRef(null);
  let containerRef = useRef(null);
  return (

      <Editor
        schema={schema}
        ref={editorRef}
        plugins={plugins}
        value={editorState}
        onChange={({ value }) => {
          onChange(value);
        }}
      />
      <AddBlock editor={editorRef.current} editorState={editorState} blocks={blocks} />
      <Popper placement="top" referenceElement={selectionReference}>
        {({ style, ref, scheduleUpdate }) => {
          return (
            <Render>
              {() => {
                useLayoutEffect(scheduleUpdate, [editorState]);

                let shouldShowToolbar = useHasSelection();

                let [toolbarElement, setToolbarElement] = useStateWithEqualityCheck(null);

                let observerRef = useRef(null);

                useLayoutEffect(
                  () => {
                    if (toolbarElement !== null) {
                      let rect = toolbarElement.getBoundingClientRect();
                      let previousHeight = Math.round(rect.height);
                      let previousWidth = Math.round(rect.width);
                      observerRef.current = new ResizeObserver(entries => {
                        let entry = entries[0];
                        let { height, width } = entry.contentRect;
                        height = Math.round(height);
                        width = Math.round(width);
                        if (
                          (height !== previousHeight || width !== previousWidth) &&
                          height !== 0 &&
                          width !== 0
                        ) {
                          previousHeight = Math.round(entry.contentRect.height);
                          previousWidth = Math.round(entry.contentRect.width);
                          scheduleUpdate();
                        }
                      });
                    }
                  },
                  [scheduleUpdate, toolbarElement]
                );

                useLayoutEffect(
                  () => {
                    if (shouldShowToolbar && toolbarElement !== null) {
                      let observer = observerRef.current;
                      observer.observe(toolbarElement);
                      return () => {
                        observer.unobserve(toolbarElement);
                      };
                    }
                  },
                  [shouldShowToolbar, toolbarElement, scheduleUpdate]
                );

                return createPortal(
                  <div
                    onMouseDown={stopPropagation}
                    ref={ref}
                    style={style}
                    css={{
                      backgroundColor: 'black',
                      padding: 8,
                      borderRadius: 6,
                      width: 'auto',
                      position: 'absolute',
                      display: shouldShowToolbar ? 'flex' : 'none',
                      left: 0,
                      top: 0,
                      // this isn't as nice of a transition as i'd like since the time is fixed
                      // i think it would better if it was physics based but that would probably
                      // be a lot of work for little gain
                      // maybe base the transition time on the previous value?
                      transition: 'transform 100ms',
                    }}
                  >
                    {shouldShowToolbar && (

                        {Object.keys(blocks)
                          .map(x => blocks[x].Toolbar)
                          .filter(x => x)
                          .reduce(
                            (children, Toolbar) => {
                              return (
                                <Toolbar editor={editorRef.current} editorState={editorState}>
                                  {children}
                                </Toolbar>
                              );
                            },
                            <Fragment>
                              {Object.keys(marks).map(name => {
                                let Icon = marks[name].icon;
                                return (
                                  <ToolbarCheckbox
                                    isActive={editorState.activeMarks.some(
                                      mark => mark.type === name
                                    )}
                                    onChange={() => {
                                      editorRef.current.toggleMark(name);
                                    }}
                                    key={name}
                                  >
                                    <Icon />
                                    <A11yText>{marks[name].label}</A11yText>
                                  </ToolbarCheckbox>
                                );
                              })}
                              <ToolbarButton
                                onClick={() => {
                                  markTypes.forEach(mark => {
                                    editorRef.current.removeMark(mark);
                                  });
                                }}
                              >
                                <CircleSlashIcon title="Remove Formatting" />
                              </ToolbarButton>

                              {Object.keys(blocks).map(type => {
                                let ToolbarElement = blocks[type].ToolbarElement;
                                if (ToolbarElement === undefined) {
                                  return null;
                                }
                                return (
                                  <ToolbarElement
                                    key={type}
                                    editor={editorRef.current}
                                    editorState={editorState}
                                  />
                                );
                              })}
                            </Fragment>
                          )}

                    )}

,
                  document.body
                );
              }}
            </Render>
          );
        }}
      </Popper>

  );
}

export default Stories;
<commit_msg>Fix toolbar focus stuff<commit_after>/** @jsx jsx */
import { jsx } from '@emotion/core';
import { useRef, Fragment, useLayoutEffect, useMemo, useState } from 'react';
import { Editor } from 'slate-react';
import { Block } from 'slate';
import { getVisibleSelectionRect } from 'get-selection-range';
import { createPortal } from 'react-dom';
import { Popper } from 'react-popper';
import { marks, markTypes, plugins as markPlugins } from './marks';
import { type as defaultType } from './block-types/paragraph';
import AddBlock from './AddBlock';
import { ToolbarCheckbox, ToolbarButton } from './toolbar-components';
import { A11yText } from '@voussoir/ui/src/primitives/typography';
import { CircleSlashIcon } from '@voussoir/icons';
import ResizeObserver from 'resize-observer-polyfill';
import { selectionReference } from './utils';
import { useStateWithEqualityCheck } from './hooks';

function getSchema(blocks) {
  const schema = {
    document: {
      last: { type: defaultType },
      normalize: (editor, { code, node }) => {
        switch (code) {
          case 'last_child_type_invalid': {
            const paragraph = Block.create(defaultType);
            return editor.insertNodeByKey(node.key, node.nodes.size, paragraph);
          }
        }
      },
    },
    blocks: {},
  };
  Object.keys(blocks).forEach(type => {
    if (blocks[type].schema !== undefined) {
      schema.blocks[type] = blocks[type].schema;
    }
  });
  return schema;
}

function useHasSelection() {
  let [hasSelection, setHasSelection] = useState(false);
  useLayoutEffect(() => {
    const rect = getVisibleSelectionRect();
    let newValue = rect && rect.width !== 0;
    if (newValue !== hasSelection) {
      setHasSelection(newValue);
    }
  });
  return hasSelection;
}

let stopPropagation = e => {
  e.preventDefault();
  e.stopPropagation();
};

export function useContainerQuery(ref) {
  const [height, setHeight] = useState(0);
  const [width, setWidth] = useState(0);

  // bail early without ref
  if (!ref) {
    throw new Error('You must pass a valid ref as the first argument.');
  }

  // Updates scheduled inside useLayoutEffect will be flushed synchronously,
  // before the browser has a chance to paint.
  useLayoutEffect(() => {
    // prepare the resize handler
    let resizeObserver = new ResizeObserver(([entry]) => {
      setHeight(entry.target.offsetHeight);
      setWidth(entry.target.offsetWidth);
    });

    // bind the observer to the consumer DOM node
    resizeObserver.observe(ref.current);

    // cleanup after ourselves
    return () => {
      resizeObserver.disconnect(ref.current);
    };
  });

  return { height, width };
}

// to use hooks inside of class components
let Render = ({ children }) => children();

function Stories({ value: editorState, onChange, blocks }) {
  let schema = useMemo(
    () => {
      return getSchema(blocks);
    },
    [blocks]
  );

  let plugins = useMemo(
    () => {
      let combinedPlugins = [
        ...markPlugins,
        {
          renderNode(props, editor) {
            let block = blocks[props.node.type];
            if (block) {
              return block.renderNode(props, editor);
            }
            // we don't want to define how how nodes are rendered in any other place
            throw new Error('Cannot render node of type: ' + props.node.type);
          },
        },
      ];

      Object.keys(blocks).forEach(type => {
        let blockTypePlugins = blocks[type].plugins;
        if (blockTypePlugins !== undefined) {
          combinedPlugins.push(...blockTypePlugins);
        }
      });
      return combinedPlugins;
    },
    [blocks]
  );

  let editorRef = useRef(null);
  let containerRef = useRef(null);
  return (

      <Editor
        schema={schema}
        ref={editorRef}
        plugins={plugins}
        value={editorState}
        onChange={({ value }) => {
          onChange(value);
        }}
      />
      <AddBlock editor={editorRef.current} editorState={editorState} blocks={blocks} />
      <Popper placement="top" referenceElement={selectionReference}>
        {({ style, ref, scheduleUpdate }) => {
          return (
            <Render>
              {() => {
                useLayoutEffect(scheduleUpdate, [editorState]);

                let shouldShowToolbar = useHasSelection();

                let [toolbarElement, setToolbarElement] = useStateWithEqualityCheck(null);

                let observerRef = useRef(null);

                useLayoutEffect(
                  () => {
                    if (toolbarElement !== null) {
                      let rect = toolbarElement.getBoundingClientRect();
                      let previousHeight = Math.round(rect.height);
                      let previousWidth = Math.round(rect.width);
                      observerRef.current = new ResizeObserver(entries => {
                        let entry = entries[0];
                        let { height, width } = entry.contentRect;
                        height = Math.round(height);
                        width = Math.round(width);
                        if (
                          (height !== previousHeight || width !== previousWidth) &&
                          height !== 0 &&
                          width !== 0
                        ) {
                          previousHeight = Math.round(entry.contentRect.height);
                          previousWidth = Math.round(entry.contentRect.width);
                          scheduleUpdate();
                        }
                      });
                    }
                  },
                  [scheduleUpdate, toolbarElement]
                );

                useLayoutEffect(
                  () => {
                    if (shouldShowToolbar && toolbarElement !== null) {
                      let observer = observerRef.current;
                      observer.observe(toolbarElement);
                      return () => {
                        observer.unobserve(toolbarElement);
                      };
                    }
                  },
                  [shouldShowToolbar, toolbarElement, scheduleUpdate]
                );

                return createPortal(
                  <div
                    onMouseDown={stopPropagation}
                    ref={ref}
                    style={style}
                    css={{
                      backgroundColor: 'black',
                      padding: 8,
                      borderRadius: 6,
                      width: 'auto',
                      position: 'absolute',
                      display: shouldShowToolbar ? 'flex' : 'none',
                      left: 0,
                      top: 0,
                      // this isn't as nice of a transition as i'd like since the time is fixed
                      // i think it would better if it was physics based but that would probably
                      // be a lot of work for little gain
                      // maybe base the transition time on the previous value?
                      transition: 'transform 100ms',
                    }}
                  >
                    {shouldShowToolbar && (

                        {Object.keys(blocks)
                          .map(x => blocks[x].Toolbar)
                          .filter(x => x)
                          .reduce(
                            (children, Toolbar) => {
                              return (
                                <Toolbar editor={editorRef.current} editorState={editorState}>
                                  {children}
                                </Toolbar>
                              );
                            },
                            <Fragment>
                              {Object.keys(marks).map(name => {
                                let Icon = marks[name].icon;
                                return (
                                  <ToolbarCheckbox
                                    isActive={editorState.activeMarks.some(
                                      mark => mark.type === name
                                    )}
                                    onChange={() => {
                                      editorRef.current.toggleMark(name);
                                    }}
                                    key={name}
                                  >
                                    <Icon />
                                    <A11yText>{marks[name].label}</A11yText>
                                  </ToolbarCheckbox>
                                );
                              })}
                              <ToolbarButton
                                onClick={() => {
                                  markTypes.forEach(mark => {
                                    editorRef.current.removeMark(mark);
                                  });
                                }}
                              >
                                <CircleSlashIcon title="Remove Formatting" />
                              </ToolbarButton>

                              {Object.keys(blocks).map(type => {
                                let ToolbarElement = blocks[type].ToolbarElement;
                                if (ToolbarElement === undefined) {
                                  return null;
                                }
                                return (
                                  <ToolbarElement
                                    key={type}
                                    editor={editorRef.current}
                                    editorState={editorState}
                                  />
                                );
                              })}
                            </Fragment>
                          )}

                    )}

,
                  document.body
                );
              }}
            </Render>
          );
        }}
      </Popper>

  );
}

export default Stories;
<|endoftext|>


<commit_before>'use strict';

const { parseQuery } = require('./parse');
const { getHandleQuery } = require('./query');
const {
  isIntrospectionQuery,
  getHandleIntrospection,
} = require('./introspection');

// GraphQL query handling
const executeGraphql = function (opts) {
  const { idl } = opts;
  const handleIntrospection = getHandleIntrospection(opts);
  const handleQuery = getHandleQuery({ idl });

  return async function executeGraphql(input) {
    // Parameters can be in either query variables or payload
    // (including by using application/graphql)
    const { queryVars, payload, goal, log } = input;
    const perf = log.perf.start('operation.executeGraphql', 'middleware');
    perf.ongoing = 0;

    const {
      query,
      variables,
      operationName,
    } = Object.assign({}, queryVars, payload);

    // GraphQL parsing
    const {
      queryDocument,
      graphqlMethod,
    } = parseQuery({ query, goal, operationName });

    // GraphQL execution
    let content;
    const actions = [];
    // Introspection GraphQL query
    if (isIntrospectionQuery({ query })) {
      content = await handleIntrospection({
        queryDocument,
        variables,
        operationName,
      });
    // Normal GraphQL query
    } else {
      const callback = fireNext.bind(this, input, perf, actions);
      const data = await handleQuery({
        queryDocument,
        variables,
        operationName,
        context: { graphqlMethod, callback },
        rootValue: {},
      });
      content = { data };
    }

    const type = getResponseType({ content });

    perf.stop();
    const response = { content, type, actions };
    return response;
  };
};

const fireNext = async function (request, perf, actions, actionInput) {
  const input = Object.assign({}, request, actionInput);

  // Several calls of this function are done concurrently, so we stop
  // performance recording on the first in, and restart on the last out
  if (perf.ongoing++ === 0) {
    perf.stop();
  }

  const response = await this.next(input);

  actions.push(response.action);

  if (--perf.ongoing === 0) {
    perf.start();
  }

  return response;
};

const getResponseType = function ({ content: { data } }) {
  const mainData = data[Object.keys(data)[0]];
  return mainData instanceof Array ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<commit_msg>No assignments in tests<commit_after>'use strict';

const { parseQuery } = require('./parse');
const { getHandleQuery } = require('./query');
const {
  isIntrospectionQuery,
  getHandleIntrospection,
} = require('./introspection');

// GraphQL query handling
const executeGraphql = function (opts) {
  const { idl } = opts;
  const handleIntrospection = getHandleIntrospection(opts);
  const handleQuery = getHandleQuery({ idl });

  return async function executeGraphql(input) {
    // Parameters can be in either query variables or payload
    // (including by using application/graphql)
    const { queryVars, payload, goal, log } = input;
    const perf = log.perf.start('operation.executeGraphql', 'middleware');
    perf.ongoing = 0;

    const {
      query,
      variables,
      operationName,
    } = Object.assign({}, queryVars, payload);

    // GraphQL parsing
    const {
      queryDocument,
      graphqlMethod,
    } = parseQuery({ query, goal, operationName });

    // GraphQL execution
    let content;
    const actions = [];
    // Introspection GraphQL query
    if (isIntrospectionQuery({ query })) {
      content = await handleIntrospection({
        queryDocument,
        variables,
        operationName,
      });
    // Normal GraphQL query
    } else {
      const callback = fireNext.bind(this, input, perf, actions);
      const data = await handleQuery({
        queryDocument,
        variables,
        operationName,
        context: { graphqlMethod, callback },
        rootValue: {},
      });
      content = { data };
    }

    const type = getResponseType({ content });

    perf.stop();
    const response = { content, type, actions };
    return response;
  };
};

const fireNext = async function (request, perf, actions, actionInput) {
  const input = Object.assign({}, request, actionInput);

  // Several calls of this function are done concurrently, so we stop
  // performance recording on the first in, and restart on the last out
  if (perf.ongoing === 0) {
    perf.stop();
  }
  ++perf.ongoing;

  const response = await this.next(input);

  actions.push(response.action);

  --perf.ongoing;
  if (perf.ongoing === 0) {
    perf.start();
  }

  return response;
};

const getResponseType = function ({ content: { data } }) {
  const mainData = data[Object.keys(data)[0]];
  return mainData instanceof Array ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<|endoftext|>


<commit_before>/*
 jQuery Masked Input Plugin
 Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
 Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
 Version: 1.4.1
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){var b,c=navigator.userAgent,d=/iphone/i.test(c),e=/chrome/i.test(c),f=/android/i.test(c);a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},a.fn.extend({caret:function(a,b){var c;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof a?(b="number"==typeof b?b:a,this.each(function(){this.setSelectionRange?this.setSelectionRange(a,b):this.createTextRange&&(c=this.createTextRange(),c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select())})):(this[0].setSelectionRange?(a=this[0].selectionStart,b=this[0].selectionEnd):document.selection&&document.selection.createRange&&(c=document.selection.createRange(),a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length),{begin:a,end:b})},unmask:function(){return this.trigger("unmask")},mask:function(c,g){var h,i,j,k,l,m,n,o;if(!c&&this.length>0){h=a(this[0]);var p=h.data(a.mask.dataName);return p?p():void 0}return g=a.extend({autoclear:a.mask.autoclear,placeholder:a.mask.placeholder,completed:null},g),i=a.mask.definitions,j=[],k=n=c.length,l=null,a.each(c.split(""),function(a,b){"?"==b?(n--,k=a):i[b]?(j.push(new RegExp(i[b])),null===l&&(l=j.length-1),k>a&&(m=j.length-1)):j.push(null)}),this.trigger("unmask").each(function(){function h(){if(g.completed){for(var a=l;m>=a;a++)if(j[a]&&C[a]===p(a))return;g.completed.call(B)}}function p(a){return g.placeholder.charAt(a<g.placeholder.length?a:0)}function q(a){for(;++a<n&&!j[a];);return a}function r(a){for(;--a>=0&&!j[a];);return a}function s(a,b){var c,d;if(!(0>a)){for(c=a,d=q(b);n>c;c++)if(j[c]){if(!(n>d&&j[c].test(C[d])))break;C[c]=C[d],C[d]=p(d),d=q(d)}z(),B.caret(Math.max(l,a))}}function t(a){var b,c,d,e;for(b=a,c=p(a);n>b;b++)if(j[b]){if(d=q(b),e=C[b],C[b]=c,!(n>d&&j[d].test(e)))break;c=e}}function u(){var a=B.val(),b=B.caret();if(o&&o.length&&o.length>a.length){for(A(!0);b.begin>0&&!j[b.begin-1];)b.begin--;if(0===b.begin)for(;b.begin<l&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}else{for(A(!0);b.begin<n&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}h()}function v(){A(),B.val()!=E&&B.change()}function w(a){if(!B.prop("readonly")){var b,c,e,f=a.which||a.keyCode;o=B.val(),8===f||46===f||d&&127===f?(b=B.caret(),c=b.begin,e=b.end,e-c===0&&(c=46!==f?r(c):e=q(c-1),e=46===f?q(e):e),y(c,e),s(c,e-1),a.preventDefault()):13===f?v.call(this,a):27===f&&(B.val(E),B.caret(0,A()),a.preventDefault())}}function x(b){if(!B.prop("readonly")){var c,d,e,g=b.which||b.keyCode,i=B.caret();if(!(b.ctrlKey||b.altKey||b.metaKey||32>g)&&g&&13!==g){if(i.end-i.begin!==0&&(y(i.begin,i.end),s(i.begin,i.end-1)),c=q(i.begin-1),n>c&&(d=String.fromCharCode(g),j[c].test(d))){if(t(c),C[c]=d,z(),e=q(c),f){var k=function(){a.proxy(a.fn.caret,B,e)()};setTimeout(k,0)}else B.caret(e);i.begin<=m&&h()}b.preventDefault()}}}function y(a,b){var c;for(c=a;b>c&&n>c;c++)j[c]&&(C[c]=p(c))}function z(){B.val(C.join(""))}function A(a){var b,c,d,e=B.val(),f=-1;for(b=0,d=0;n>b;b++)if(j[b]){for(C[b]=p(b);d++<e.length;)if(c=e.charAt(d-1),j[b].test(c)){C[b]=c,f=b;break}if(d>e.length){y(b+1,n);break}}else C[b]===e.charAt(d)&&d++,k>b&&(f=b);return a?z():k>f+1?g.autoclear||C.join("")===D?(B.val()&&B.val(""),y(0,n)):z():(z(),B.val(B.val().substring(0,f+1))),k?b:l}var B=a(this),C=a.map(c.split(""),function(a,b){return"?"!=a?i[a]?p(b):a:void 0}),D=C.join(""),E=B.val();B.data(a.mask.dataName,function(){return a.map(C,function(a,b){return j[b]&&a!=p(b)?a:null}).join("")}),B.one("unmask",function(){B.off(".mask").removeData(a.mask.dataName)}).on("focus.mask",function(){if(!B.prop("readonly")){clearTimeout(b);var a;E=B.val(),a=A(),b=setTimeout(function(){B.get(0)===document.activeElement&&(z(),a==c.replace("?","").length?B.caret(0,a):B.caret(a))},10)}}).on("blur.mask",v).on("keydown.mask",w).on("keypress.mask",x).on("input.mask paste.mask",function(){B.prop("readonly")||setTimeout(function(){var a=A(!0);B.caret(a),h()},0)}),e&&f&&B.off("input.mask").on("input.mask",u),A()})}})});

jQuery(document).ready(function() {

	// Functions
	function addMaskJs(attrName, attrValue, maskFormat) {
		attrValue = jQuery( "["+attrName+"~=" + attrValue + "]" );
		attrValue.each (
			function () {
				jQuery(this).attr("data-mask" , maskFormat);
			});}

	// Adiciona Mascaras com (Nome do atributo, valor do atributo, mascara)
	addMaskJs("title","Celular", "(99)99999-999?9");
	addMaskJs("title","Telefone", "(99)99999-999?9");
	addMaskJs("title","Cep", "99999-999");
	addMaskJs("title","CEP", "99999-999");
	addMaskJs("id","postcode", "99999-999");
	//jQuery(".ie input" ).attr("data-mask", "99.999.999-9");

	jQuery('input').each(function(index) {
		var me = jQuery(this);
		var dataMask = me.data('mask');
		if (dataMask) {
			me.mask(dataMask);
		}
	});
	jQuery('input[data-mask="(99) 99999-999?9"]')
		.focusout(function(){
			          var mePhone = jQuery(this);
			          var dataMask = mePhone.data('mask');
			          var phone = mePhone.val().replace(/\D/g, '');
		              mePhone.unmask();
			          if(phone.length > 10){
				          mePhone.mask("(99) 99999-999?9");
			          }else{
				          mePhone.mask("(99) 9999-9999?9");
			          }
		          })
		.trigger('focusout');
	jQuery('input[data-mask="(99)99999-999?9"]')
		.focusout(function(){
			          var mePhone = jQuery(this);
			          var dataMask = mePhone.data('mask');
			          var phone = mePhone.val().replace(/\D/g, '');
		              mePhone.unmask();
			          if(phone.length > 10){
				          mePhone.mask("(99)99999-999?9");
			          }else{
				          mePhone.mask("(99)9999-9999?9");
			          }
		          })
		.trigger('focusout');
	jQuery('input[data-mask="999.999.999-99"]')
		.focusout(function(){
			          var meCPF = jQuery(this);
			          var dataMask = meCPF.data('mask');
			          var cpf = meCPF.val().replace(/\D/g, '');

		                  meCPF.unmask();
			          if(cpf.length > 15){
				          meCPF.mask("999.999.999-99");
			          }else{
				          meCPF.mask("99.999.999/9999-99");
			          }
		          })
		.trigger('focusout');

});
<commit_msg>Mask CNPJ/CPF<commit_after>/*
 jQuery Masked Input Plugin
 Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
 Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
 Version: 1.4.1
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){var b,c=navigator.userAgent,d=/iphone/i.test(c),e=/chrome/i.test(c),f=/android/i.test(c);a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"},a.fn.extend({caret:function(a,b){var c;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof a?(b="number"==typeof b?b:a,this.each(function(){this.setSelectionRange?this.setSelectionRange(a,b):this.createTextRange&&(c=this.createTextRange(),c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select())})):(this[0].setSelectionRange?(a=this[0].selectionStart,b=this[0].selectionEnd):document.selection&&document.selection.createRange&&(c=document.selection.createRange(),a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length),{begin:a,end:b})},unmask:function(){return this.trigger("unmask")},mask:function(c,g){var h,i,j,k,l,m,n,o;if(!c&&this.length>0){h=a(this[0]);var p=h.data(a.mask.dataName);return p?p():void 0}return g=a.extend({autoclear:a.mask.autoclear,placeholder:a.mask.placeholder,completed:null},g),i=a.mask.definitions,j=[],k=n=c.length,l=null,a.each(c.split(""),function(a,b){"?"==b?(n--,k=a):i[b]?(j.push(new RegExp(i[b])),null===l&&(l=j.length-1),k>a&&(m=j.length-1)):j.push(null)}),this.trigger("unmask").each(function(){function h(){if(g.completed){for(var a=l;m>=a;a++)if(j[a]&&C[a]===p(a))return;g.completed.call(B)}}function p(a){return g.placeholder.charAt(a<g.placeholder.length?a:0)}function q(a){for(;++a<n&&!j[a];);return a}function r(a){for(;--a>=0&&!j[a];);return a}function s(a,b){var c,d;if(!(0>a)){for(c=a,d=q(b);n>c;c++)if(j[c]){if(!(n>d&&j[c].test(C[d])))break;C[c]=C[d],C[d]=p(d),d=q(d)}z(),B.caret(Math.max(l,a))}}function t(a){var b,c,d,e;for(b=a,c=p(a);n>b;b++)if(j[b]){if(d=q(b),e=C[b],C[b]=c,!(n>d&&j[d].test(e)))break;c=e}}function u(){var a=B.val(),b=B.caret();if(o&&o.length&&o.length>a.length){for(A(!0);b.begin>0&&!j[b.begin-1];)b.begin--;if(0===b.begin)for(;b.begin<l&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}else{for(A(!0);b.begin<n&&!j[b.begin];)b.begin++;B.caret(b.begin,b.begin)}h()}function v(){A(),B.val()!=E&&B.change()}function w(a){if(!B.prop("readonly")){var b,c,e,f=a.which||a.keyCode;o=B.val(),8===f||46===f||d&&127===f?(b=B.caret(),c=b.begin,e=b.end,e-c===0&&(c=46!==f?r(c):e=q(c-1),e=46===f?q(e):e),y(c,e),s(c,e-1),a.preventDefault()):13===f?v.call(this,a):27===f&&(B.val(E),B.caret(0,A()),a.preventDefault())}}function x(b){if(!B.prop("readonly")){var c,d,e,g=b.which||b.keyCode,i=B.caret();if(!(b.ctrlKey||b.altKey||b.metaKey||32>g)&&g&&13!==g){if(i.end-i.begin!==0&&(y(i.begin,i.end),s(i.begin,i.end-1)),c=q(i.begin-1),n>c&&(d=String.fromCharCode(g),j[c].test(d))){if(t(c),C[c]=d,z(),e=q(c),f){var k=function(){a.proxy(a.fn.caret,B,e)()};setTimeout(k,0)}else B.caret(e);i.begin<=m&&h()}b.preventDefault()}}}function y(a,b){var c;for(c=a;b>c&&n>c;c++)j[c]&&(C[c]=p(c))}function z(){B.val(C.join(""))}function A(a){var b,c,d,e=B.val(),f=-1;for(b=0,d=0;n>b;b++)if(j[b]){for(C[b]=p(b);d++<e.length;)if(c=e.charAt(d-1),j[b].test(c)){C[b]=c,f=b;break}if(d>e.length){y(b+1,n);break}}else C[b]===e.charAt(d)&&d++,k>b&&(f=b);return a?z():k>f+1?g.autoclear||C.join("")===D?(B.val()&&B.val(""),y(0,n)):z():(z(),B.val(B.val().substring(0,f+1))),k?b:l}var B=a(this),C=a.map(c.split(""),function(a,b){return"?"!=a?i[a]?p(b):a:void 0}),D=C.join(""),E=B.val();B.data(a.mask.dataName,function(){return a.map(C,function(a,b){return j[b]&&a!=p(b)?a:null}).join("")}),B.one("unmask",function(){B.off(".mask").removeData(a.mask.dataName)}).on("focus.mask",function(){if(!B.prop("readonly")){clearTimeout(b);var a;E=B.val(),a=A(),b=setTimeout(function(){B.get(0)===document.activeElement&&(z(),a==c.replace("?","").length?B.caret(0,a):B.caret(a))},10)}}).on("blur.mask",v).on("keydown.mask",w).on("keypress.mask",x).on("input.mask paste.mask",function(){B.prop("readonly")||setTimeout(function(){var a=A(!0);B.caret(a),h()},0)}),e&&f&&B.off("input.mask").on("input.mask",u),A()})}})});

jQuery(document).ready(function() {

	// Functions
	function addMaskJs(attrName, attrValue, maskFormat) {
		attrValue = jQuery( "["+attrName+"~=" + attrValue + "]" );
		attrValue.each (
			function () {
				jQuery(this).attr("data-mask" , maskFormat);
			});}

	// Adiciona Mascaras com (Nome do atributo, valor do atributo, mascara)
	addMaskJs("title","Celular", "(99)99999-999?9");
	addMaskJs("title","Telefone", "(99)99999-999?9");
	addMaskJs("title","Cep", "99999-999");
	addMaskJs("title","CEP", "99999-999");
	addMaskJs("id","postcode", "99999-999");
	//jQuery(".ie input" ).attr("data-mask", "99.999.999-9");

	jQuery('input').each(function(index) {
		var me = jQuery(this);
		var dataMask = me.data('mask');
		if (dataMask) {
			me.mask(dataMask);
		}
	});
	jQuery('input[data-mask="(99) 99999-999?9"]')
		.focusout(function(){
			          var mePhone = jQuery(this);
			          var dataMask = mePhone.data('mask');
			          var phone = mePhone.val().replace(/\D/g, '');
		              mePhone.unmask();
			          if(phone.length > 10){
				          mePhone.mask("(99) 99999-999?9");
			          }else{
				          mePhone.mask("(99) 9999-9999?9");
			          }
		          })
		.trigger('focusout');
	jQuery('input[data-mask="(99)99999-999?9"]')
		.focusout(function(){
			          var mePhone = jQuery(this);
			          var dataMask = mePhone.data('mask');
			          var phone = mePhone.val().replace(/\D/g, '');
		              mePhone.unmask();
			          if(phone.length > 10){
				          mePhone.mask("(99)99999-999?9");
			          }else{
				          mePhone.mask("(99)9999-9999?9");
			          }
		          })
		.trigger('focusout');
	jQuery('input[data-mask="999.999.999-99"]')
		.focusout(function(){
			          var meCPF = jQuery(this);
			          var dataMask = meCPF.data('mask');
			          var cpf = meCPF.val().replace(/\D/g, '');

		                  meCPF.unmask();
			          if(cpf.length > 15){
				          meCPF.mask("999.999.999-99");
			          }else{
				          meCPF.mask("99.999.999/9999-99");
			          }
		          })
		.trigger('focusout');

});

// Add onkeypress="mascaraMutuario(this,cpfCnpj)" in input
function mascaraMutuario(o,f){
    v_obj=o
    v_fun=f
    setTimeout('execmascara()',1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function cpfCnpj(v){

    //Remove tudo o que não é dígito
    v=v.replace(/\D/g,"")

    if (v.length <= 14) { //CPF

        //Coloca um ponto entre o terceiro e o quarto dígitos
        v=v.replace(/(\d{3})(\d)/,"$1.$2")

        //Coloca um ponto entre o terceiro e o quarto dígitos
        //de novo (para o segundo bloco de números)
        v=v.replace(/(\d{3})(\d)/,"$1.$2")

        //Coloca um hífen entre o terceiro e o quarto dígitos
        v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2")

    } else { //CNPJ

        //Coloca ponto entre o segundo e o terceiro dígitos
        v=v.replace(/^(\d{2})(\d)/,"$1.$2")

        //Coloca ponto entre o quinto e o sexto dígitos
        v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")

        //Coloca uma barra entre o oitavo e o nono dígitos
        v=v.replace(/\.(\d{3})(\d)/,".$1/$2")

        //Coloca um hífen depois do bloco de quatro dígitos
        v=v.replace(/(\d{4})(\d)/,"$1-$2")

    }

    return v

}
<|endoftext|>


<commit_before>var Landing = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        CommonLoading.render_init();
        Landing.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var landing_source = $("#landing").html();
        var template = Handlebars.compile(landing_source);

        $("#main-content").html(template());

        NoticeBanner.render_init($("#notice_banner_location"));

        Landing.load_cards_for_viewport();
        // Set initial display state
        Landing.is_desktop = Landing.get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Landing.is_desktop !== Landing.get_is_desktop()){
                Landing.load_cards_for_viewport();
                Landing.is_desktop = Landing.get_is_desktop();
            }
        });
    },

    get_is_desktop: function() {
        var mobile_cutoff_width = 992;
        var viewport_width = $(window).width();
        if (viewport_width >= mobile_cutoff_width) {
            return true;
        } else {
            return false;
        }

    },

    load_cards_for_viewport: function() {
        if (Landing.get_is_desktop()) {
            Landing._load_desktop_cards();
        } else {
            Landing._load_mobile_cards();
        }
    },
    _load_desktop_cards: function() {
        Landing._reset_content_divs();
        var desktop_body_cards = [
            FinalExamCard,
            GradeCard,
            FutureQuarterCardA,
            ThankYouCard,
            ToRegisterCard,
            RegStatusCard,
            SummerEFSCard,
            SummerRegStatusCardA,
            CriticalInfoCard,
            InternationalStuCard,
            VisualScheduleCard,
            TextbookCard,
            CourseCard,
            FutureQuarterCard1,
            SummerRegStatusCard1
        ];
        var desktop_sidebar_cards = [
            EmpFacStudentCard,
            HfsCard,
            TuitionCard,
            LibraryCard,
            EventsCard
        ];
        Cards.load_cards_in_order(desktop_body_cards, $("#landing_content_cards"));
        Cards.load_cards_in_order(desktop_sidebar_cards, $("#landing_accounts_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_desktop"));
    },

    _load_mobile_cards: function() {
        Landing._reset_content_divs();
        var mobile_cards = [
            EmpFacStudentCard,
            FinalExamCard,
            GradeCard,
            FutureQuarterCardA,
            ThankYouCard,
            ToRegisterCard,
            RegStatusCard,
            SummerEFSCard,
            SummerRegStatusCardA,
            CriticalInfoCard,
            InternationalStuCard,
            VisualScheduleCard,
            TextbookCard,
            CourseCard,
            HfsCard,
            TuitionCard,
            LibraryCard,
            EventsCard,
            FutureQuarterCard1,
            SummerRegStatusCard1
        ];
        Cards.load_cards_in_order(mobile_cards, $("#landing_content_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_mobile"));
    },

    _reset_content_divs: function() {
        $("#landing_content_cards").html('');
        $("#landing_accounts_cards").html('');
        $("#calendar_banner_location_desktop").html('');
        $("#calendar_banner_location_mobile").html('');
    }

};
<commit_msg>moves empfac card above hsf on mobile<commit_after>var Landing = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        CommonLoading.render_init();
        Landing.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var landing_source = $("#landing").html();
        var template = Handlebars.compile(landing_source);

        $("#main-content").html(template());

        NoticeBanner.render_init($("#notice_banner_location"));

        Landing.load_cards_for_viewport();
        // Set initial display state
        Landing.is_desktop = Landing.get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Landing.is_desktop !== Landing.get_is_desktop()){
                Landing.load_cards_for_viewport();
                Landing.is_desktop = Landing.get_is_desktop();
            }
        });
    },

    get_is_desktop: function() {
        var mobile_cutoff_width = 992;
        var viewport_width = $(window).width();
        if (viewport_width >= mobile_cutoff_width) {
            return true;
        } else {
            return false;
        }

    },

    load_cards_for_viewport: function() {
        if (Landing.get_is_desktop()) {
            Landing._load_desktop_cards();
        } else {
            Landing._load_mobile_cards();
        }
    },
    _load_desktop_cards: function() {
        Landing._reset_content_divs();
        var desktop_body_cards = [
            FinalExamCard,
            GradeCard,
            FutureQuarterCardA,
            ThankYouCard,
            ToRegisterCard,
            RegStatusCard,
            SummerEFSCard,
            SummerRegStatusCardA,
            CriticalInfoCard,
            InternationalStuCard,
            VisualScheduleCard,
            TextbookCard,
            CourseCard,
            FutureQuarterCard1,
            SummerRegStatusCard1
        ];
        var desktop_sidebar_cards = [
            EmpFacStudentCard,
            HfsCard,
            TuitionCard,
            LibraryCard,
            EventsCard
        ];
        Cards.load_cards_in_order(desktop_body_cards, $("#landing_content_cards"));
        Cards.load_cards_in_order(desktop_sidebar_cards, $("#landing_accounts_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_desktop"));
    },

    _load_mobile_cards: function() {
        Landing._reset_content_divs();
        var mobile_cards = [
            FinalExamCard,
            GradeCard,
            FutureQuarterCardA,
            ThankYouCard,
            ToRegisterCard,
            RegStatusCard,
            SummerEFSCard,
            SummerRegStatusCardA,
            CriticalInfoCard,
            InternationalStuCard,
            VisualScheduleCard,
            TextbookCard,
            CourseCard,
			EmpFacStudentCard,
            HfsCard,
            TuitionCard,
            LibraryCard,
            EventsCard,
            FutureQuarterCard1,
            SummerRegStatusCard1
        ];
        Cards.load_cards_in_order(mobile_cards, $("#landing_content_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_mobile"));
    },

    _reset_content_divs: function() {
        $("#landing_content_cards").html('');
        $("#landing_accounts_cards").html('');
        $("#calendar_banner_location_desktop").html('');
        $("#calendar_banner_location_mobile").html('');
    }

};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var http = require("q-io/http")
  , request = require("sync-request")
  , collections = require('gramene-mongodb-config');

var genesURL = process.argv[2];

function getTaxa(query) {
  var url = genesURL + '/query?q='+query+'&rows=0&facet=true&facet.field=taxon_id&facet.limit=-1&facet.mincount=1&json.nl=map';
  var res = request('GET',url);
  var taxa = { ids:[], counts:[]};
  var taxTally = JSON.parse(res.getBody()).facet_counts.facet_fields.taxon_id;
  for (var t in taxTally) {
    taxa.ids.push(+t);
    taxa.counts.push(taxTally[t]);
  }
  return taxa;
}

// read all of the unique ids from the genes collection
// to avoid suggesting them as non-unique terms when they are mentioned as an xref or something in another gene
collections.genes.mongoCollection().then(function(collection) {
  collection.find({},{_id:1, taxon_id:1}).toArray(function(err,docs) {
    if (err) throw err;
    var uniqueId = {};
    var uniqueTaxa = {};
    docs.forEach(function(d) {
      uniqueTaxa[d.taxon_id] = 1;
      uniqueId[d._id.toUpperCase()] = d.taxon_id;
    });

    collections.genetrees.mongoCollection().then(function(collection) {
      collection.find({},{_id:1,taxon_id:1}).toArray(function(err,docs) {
        if (err) throw err;
        collections.closeMongoDatabase();
        var treeRootNodeTaxonId = {};
        docs.forEach(function(d) {
          treeRootNodeTaxonId[d._id] = d.taxon_id;
        });

        // non-unique terms get their own doc with a relevant fq field
        // build a lookup table with the non-unique ids from these
        var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.pivot.mincount=2&facet.pivot=_terms,taxon_id';
        console.error(url);
        http.read(url).then(function(data) {
          var term_freq = {};
          var taxa_lut = {};
          JSON.parse(data).facet_counts.facet_pivot['_terms,taxon_id'].forEach(function(d) {
            var term = d.value.toUpperCase();
            if (!uniqueId.hasOwnProperty(term)) {
              if (term_freq.hasOwnProperty(term)) {
                term_freq[term] += d.count;
              }
              else {
                term_freq[term] = d.count;
                taxa_lut[term] = {}; // term may appear only once in some species, but we don't know which ones yet
              }

              if (d.pivot) { // term appears at least 2 times in some species
                d.pivot.forEach(function(p) {
                  if (taxa_lut[term].hasOwnProperty(p.value)) {
                    taxa_lut[term][p.value] += p.count;
                  }
                  else {
                    taxa_lut[term][p.value] = p.count;
                  }
                });
              }
            }
          });
          console.error("WAXY",term_freq.WAXY,taxa_lut.WAXY);
          // find all the terms in each species
          Object.keys(uniqueTaxa).forEach(function(taxon_id) {
            var url = genesURL + '/query?rows=0&facet=true&facet.field=_terms&facet.limit=-1&json.nl=map&facet.mincount=1&q=taxon_id:'+taxon_id;
            console.error(url);
            var res = request('GET',url);
            var term_tally = JSON.parse(res.getBody()).facet_counts.facet_fields._terms;
            for (var t in term_tally) {
              var term = t.toUpperCase();
              if (term_freq.hasOwnProperty(term)) {
                if (taxa_lut[term].hasOwnProperty(taxon_id)) {
                  taxa_lut[term][taxon_id] += term_tally[t];
                }
                else {
                  taxa_lut[term][taxon_id] = term_tally[t];
                }
              }
            }
            console.error("WAXY",term_freq.WAXY,taxa_lut.WAXY);
          });

          console.error("finished building taxa_lut");
          var n=0;
          for (var term in term_freq) {
            var tf = term_freq[term];
            var taxa = {ids:[],counts:[]};
            for(var taxon_id in taxa_lut[term]) {
              taxa.ids.push(+taxon_id);
              taxa.counts.push(taxa_lut[term][taxon_id]);
            }
            var solr = {
              category    : 'Gene',
              id          : '_term_'+ ++n,
              display_name: term,
              name        : term,
              fq_field    : '_terms',
              fq_value    : term,
              taxon_id    : taxa.ids,
              taxon_freq  : taxa.counts,
              num_genes   : tf,
              relevance   : tf < 10 ? 1.1 : 1
            };
            if (n===1) console.log('[');
            else console.log(',');
            console.log(JSON.stringify(solr));
          }

          // gene tree suggestion
          var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.mincount=1&facet.field=gene_tree';
          console.error(url);
          http.read(url).then(function(data) {
            var tree_size = JSON.parse(data).facet_counts.facet_fields.gene_tree;
            for (var tree in tree_size) {
              var solr = {
                category    : 'Gene tree',
                id          : '_term_'+ ++n,
                taxon_id    : [1, treeRootNodeTaxonId[tree]],
                taxon_freq  : [tree_size[tree],tree_size[tree]],
                display_name: tree,
                name        : tree,
                fq_field    : 'gene_tree',
                fq_value    : tree,
                num_genes   : tree_size[tree],
                relevance   : 1
              };
              console.log(',');
              console.log(JSON.stringify(solr));
            }

            // biotype suggestion
            var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.mincount=1&facet.field=biotype';
            console.error(url);
            http.read(url).then(function(data) {
              var biotype_count = JSON.parse(data).facet_counts.facet_fields.biotype;
              for (var biotype in biotype_count) {
                var taxa = getTaxa('biotype:'+biotype);
                var solr = {
                  category    : 'Biotype',
                  id          : '_term_'+ ++n,
                  display_name: biotype,
                  name        : biotype,
                  fq_field    : 'biotype',
                  fq_value    : biotype,
                  taxon_id    : taxa.ids,
                  taxon_freq  : taxa.counts,
                  num_genes   : biotype_count[biotype],
                  relevance   : 1
                };
                console.log(',');
                console.log(JSON.stringify(solr));
              }

              // read the mongo genes docs and generate suggestions with unique values only
              require('readline').createInterface(
                {
                  input: process.stdin,
                  terminal: false
                }
              ).on('line', function(line) { // one JSON object per line
                var mongo = JSON.parse(line);

                console.log(',');
                console.log(JSON.stringify({
                  category : 'Gene',
                  fq_field : 'id',
                  fq_value : mongo._id,
                  id       : mongo._id,
                  display_name : mongo._id,
                  num_genes : 1,
                  relevance : 1.2,
                  taxon_id : [mongo.taxon_id],
                  taxon_freq : [1]
                }));

                // add uniquely identifying xrefs
                if (mongo.xrefs) {
                  var xref_h = {};
                  mongo.xrefs.forEach(function(xref) {
                    xref.ids.forEach(function(id) {
                      xref_h[id]=xref.db;
                    });
                  });
                  Object.keys(xref_h).filter(function(xr) {
                    return !term_freq[xr.toUpperCase()];
                  }).forEach(function(xr) {
                    console.log(',');
                    console.log(JSON.stringify({
                      category : 'Gene',
                      fq_field : 'id',
                      fq_value : mongo._id,
                      id       : '_term_'+ ++n,
                      xref     : xr,
                      display_name : xr,
                      num_genes : 1,
                      relevance : 1.2,
                      taxon_id : [mongo.taxon_id],
                      taxon_freq : [1]
                    }));
                  });
                }

                // add uniquely identifying synonyms
                if (mongo.hasOwnProperty('synonyms')) {
                  mongo.synonyms.filter(function(syn) {
                    return !term_freq[syn.toUpperCase()];
                  }).forEach(function(syn) {
                    console.log(',');
                    console.log(JSON.stringify({
                      category : 'Gene',
                      fq_field : 'id',
                      fq_value : mongo._id,
                      id       : '_term_'+ ++n,
                      synonym  : syn,
                      display_name : syn,
                      num_genes : 1,
                      relevance : 1.1,
                      taxon_id : [mongo.taxon_id],
                      taxon_freq : [1]
                    }));
                  });
                }

              }).on('close', function() {
                console.log(']');
              });
            });
          });
        });
      });
    });
  });
});

<commit_msg>don't merge terms from facets any more. fixes #7<commit_after>#!/usr/bin/env node
var http = require("q-io/http")
  , request = require("sync-request")
  , collections = require('gramene-mongodb-config');

var genesURL = process.argv[2];

function getTaxa(query) {
  var url = genesURL + '/query?q='+query+'&rows=0&facet=true&facet.field=taxon_id&facet.limit=-1&facet.mincount=1&json.nl=map';
  var res = request('GET',url);
  var taxa = { ids:[], counts:[]};
  var taxTally = JSON.parse(res.getBody()).facet_counts.facet_fields.taxon_id;
  for (var t in taxTally) {
    taxa.ids.push(+t);
    taxa.counts.push(taxTally[t]);
  }
  return taxa;
}

// read all of the unique ids from the genes collection
// to avoid suggesting them as non-unique terms when they are mentioned as an xref or something in another gene
collections.genes.mongoCollection().then(function(collection) {
  collection.find({},{_id:1, taxon_id:1}).toArray(function(err,docs) {
    if (err) throw err;
    var uniqueId = {};
    var uniqueTaxa = {};
    docs.forEach(function(d) {
      uniqueTaxa[d.taxon_id] = 1;
      uniqueId[d._id.toUpperCase()] = d.taxon_id;
    });

    collections.genetrees.mongoCollection().then(function(collection) {
      collection.find({},{_id:1,taxon_id:1}).toArray(function(err,docs) {
        if (err) throw err;
        collections.closeMongoDatabase();
        var treeRootNodeTaxonId = {};
        docs.forEach(function(d) {
          treeRootNodeTaxonId[d._id] = d.taxon_id;
        });

        // non-unique terms get their own doc with a relevant fq field
        // build a lookup table with the non-unique ids from these
        var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.pivot.mincount=2&facet.pivot=_terms,taxon_id';
        console.error(url);
        http.read(url).then(function(data) {
          var term_freq = {};
          var taxa_lut = {};
          JSON.parse(data).facet_counts.facet_pivot['_terms,taxon_id'].forEach(function(d) {
            var term = d.value; // .toUpperCase(); // don't do this it leads to problems
            if (!uniqueId.hasOwnProperty(term)) {
              if (term_freq.hasOwnProperty(term)) {
                term_freq[term] += d.count;
              }
              else {
                term_freq[term] = d.count;
                taxa_lut[term] = {}; // term may appear only once in some species, but we don't know which ones yet
              }

              if (d.pivot) { // term appears at least 2 times in some species
                d.pivot.forEach(function(p) {
                  if (taxa_lut[term].hasOwnProperty(p.value)) {
                    taxa_lut[term][p.value] += p.count;
                  }
                  else {
                    taxa_lut[term][p.value] = p.count;
                  }
                });
              }
            }
          });
          console.error("WAXY",term_freq.WAXY,taxa_lut.WAXY);
          // find all the terms in each species
          Object.keys(uniqueTaxa).forEach(function(taxon_id) {
            var url = genesURL + '/query?rows=0&facet=true&facet.field=_terms&facet.limit=-1&json.nl=map&facet.mincount=1&q=taxon_id:'+taxon_id;
            console.error(url);
            var res = request('GET',url);
            var term_tally = JSON.parse(res.getBody()).facet_counts.facet_fields._terms;
            for (var t in term_tally) {
              var term = t; // .toUpperCase(); // don't do this it leads to problems
              if (term_freq.hasOwnProperty(term)) {
                if (taxa_lut[term].hasOwnProperty(taxon_id)) {
                  taxa_lut[term][taxon_id] += term_tally[t];
                }
                else {
                  taxa_lut[term][taxon_id] = term_tally[t];
                }
              }
            }
            console.error("WAXY",term_freq.WAXY,taxa_lut.WAXY);
          });

          console.error("finished building taxa_lut");
          var n=0;
          for (var term in term_freq) {
            var tf = term_freq[term];
            var taxa = {ids:[],counts:[]};
            for(var taxon_id in taxa_lut[term]) {
              taxa.ids.push(+taxon_id);
              taxa.counts.push(taxa_lut[term][taxon_id]);
            }
            var solr = {
              category    : 'Gene',
              subcategory : 'term',
              id          : '_term_'+ ++n,
              display_name: term,
              name        : term,
              fq_field    : '_terms',
              fq_value    : term,
              taxon_id    : taxa.ids,
              taxon_freq  : taxa.counts,
              num_genes   : tf,
              relevance   : tf < 10 ? 1.1 : 1
            };
            if (n===1) console.log('[');
            else console.log(',');
            console.log(JSON.stringify(solr));
          }

          // gene tree suggestion
          var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.mincount=1&facet.field=gene_tree';
          console.error(url);
          http.read(url).then(function(data) {
            var tree_size = JSON.parse(data).facet_counts.facet_fields.gene_tree;
            for (var tree in tree_size) {
              var solr = {
                category    : 'Gene tree',
                id          : '_term_'+ ++n,
                taxon_id    : [1, treeRootNodeTaxonId[tree]],
                taxon_freq  : [tree_size[tree],tree_size[tree]],
                display_name: tree,
                name        : tree,
                fq_field    : 'gene_tree',
                fq_value    : tree,
                num_genes   : tree_size[tree],
                relevance   : 1
              };
              console.log(',');
              console.log(JSON.stringify(solr));
            }

            // biotype suggestion
            var url = genesURL + '/query?rows=0&facet=true&facet.limit=-1&json.nl=map&facet.mincount=1&facet.field=biotype';
            console.error(url);
            http.read(url).then(function(data) {
              var biotype_count = JSON.parse(data).facet_counts.facet_fields.biotype;
              for (var biotype in biotype_count) {
                var taxa = getTaxa('biotype:'+biotype);
                var solr = {
                  category    : 'Biotype',
                  id          : '_term_'+ ++n,
                  display_name: biotype,
                  name        : biotype,
                  fq_field    : 'biotype',
                  fq_value    : biotype,
                  taxon_id    : taxa.ids,
                  taxon_freq  : taxa.counts,
                  num_genes   : biotype_count[biotype],
                  relevance   : 1
                };
                console.log(',');
                console.log(JSON.stringify(solr));
              }

              // read the mongo genes docs and generate suggestions with unique values only
              require('readline').createInterface(
                {
                  input: process.stdin,
                  terminal: false
                }
              ).on('line', function(line) { // one JSON object per line
                var mongo = JSON.parse(line);

                console.log(',');
                console.log(JSON.stringify({
                  category : 'Gene',
                  subcategory : 'id',
                  fq_field : 'id',
                  fq_value : mongo._id,
                  id       : mongo._id,
                  display_name : mongo._id,
                  num_genes : 1,
                  relevance : 1.2,
                  taxon_id : [mongo.taxon_id],
                  taxon_freq : [1]
                }));

                // add uniquely identifying xrefs
                if (mongo.xrefs) {
                  var xref_h = {};
                  mongo.xrefs.forEach(function(xref) {
                    xref.ids.forEach(function(id) {
                      xref_h[id]=xref.db;
                    });
                  });
                  Object.keys(xref_h).filter(function(xr) {
                    return !term_freq[xr];
                  }).forEach(function(xr) {
                    console.log(',');
                    console.log(JSON.stringify({
                      category : 'Gene',
                      subcategory : 'xref',
                      fq_field : 'id',
                      fq_value : mongo._id,
                      id       : '_term_'+ ++n,
                      xref     : xr,
                      display_name : xr,
                      num_genes : 1,
                      relevance : 1.2,
                      taxon_id : [mongo.taxon_id],
                      taxon_freq : [1]
                    }));
                  });
                }

                // add uniquely identifying synonyms
                if (mongo.hasOwnProperty('synonyms')) {
                  mongo.synonyms.filter(function(syn) {
                    return !term_freq[syn];
                  }).forEach(function(syn) {
                    console.log(',');
                    console.log(JSON.stringify({
                      category : 'Gene',
                      subcategory : 'synonym',
                      fq_field : 'id',
                      fq_value : mongo._id,
                      id       : '_term_'+ ++n,
                      synonym  : syn,
                      display_name : syn,
                      num_genes : 1,
                      relevance : 1.1,
                      taxon_id : [mongo.taxon_id],
                      taxon_freq : [1]
                    }));
                  });
                }

              }).on('close', function() {
                console.log(']');
              });
            });
          });
        });
      });
    });
  });
});

<|endoftext|>


<commit_before>
function renderGaugeRowItems () {
  updateDataForGauageItems();
  if ($("#gauge-row").children().length) {
    renderGaugeRowItemsWithUpdates();
  }
  else {
    renderGaugeRowItemsFromScratch();
  }
}

function updateDataForGauageItems () {
  $.each(gauge_data, function (index, item) {
    item['time'] = new Date();
    item['value'] *= 1 + (Math.random() - 0.5) * 0.1;
  });
}

function renderGaugeRowItemsWithUpdates () {
  $("#gauge-row").children().each(function (index, div) {
    $(div).find("h3").contents().first()[0].textContent = _formatValueForGauge(gauge_data[index].value);
    $(div).find(".small-box-footer").contents().first()[0].textContent = _formatTimestampForGauge(gauge_data[index].time);
  });
}

function renderGaugeRowItemsFromScratch () {
  var guage_row = $('<div/>', { class: "row", id: "gauge-row"});
  $.each(gauge_data, function (index, item) {
    guage_row.append(createGaugeBox(item));
  });
  $("#gauge-row").replaceWith(guage_row);
}

function createGaugeBox (item_data) {
  var _div = $("<div/>", { class: "col-lg-2 col-xs-6"});
  var _div_color = $("<div/>", { class: "small-box " + item_data.color });
  var _div_text = $("<div/>", { class: "inner"});

  var _div_value = $("<h3/>", { text: _formatValueForGauge(item_data.value) });
  if (item_data.unit) {
    $("<sup/>", { style: "font-size: 20px", text: item_data.unit }).appendTo(_div_value);
  }
  _div_value.appendTo(_div_text);
  $("<p/>", { text: item_data.name }).appendTo(_div_text);
  _div_text.appendTo(_div_color);

  var _div_icon = $("<div/>", { class: "icon"}).append($("<i/>", { class: item_data.icon}));
  _div_icon.appendTo(_div_color);

  var _div_time = $("<div/>", { class: "small-box-footer", href: "#", text: _formatTimestampForGauge(item_data.time) });
  _div_time.append($("<i/>", { class: "fa fa-arrow-circle-right"}));
  _div_time.appendTo(_div_color);

  _div_color.appendTo(_div);

  return _div;
}

function _formatValueForGauge (value) {
  return value.toFixed(3);
}

function _formatTimestampForGauge (timestamp) {
  return "Updated at " + $.format.date(timestamp, 'HH:mm:ss.SSS') + " ";
}
<commit_msg>Shorten time stamp string in gauge<commit_after>
function renderGaugeRowItems () {
  updateDataForGauageItems();
  if ($("#gauge-row").children().length) {
    renderGaugeRowItemsWithUpdates();
  }
  else {
    renderGaugeRowItemsFromScratch();
  }
}

function updateDataForGauageItems () {
  $.each(gauge_data, function (index, item) {
    item['time'] = new Date();
    item['value'] *= 1 + (Math.random() - 0.5) * 0.1;
  });
}

function renderGaugeRowItemsWithUpdates () {
  $("#gauge-row").children().each(function (index, div) {
    $(div).find("h3").contents().first()[0].textContent = _formatValueForGauge(gauge_data[index].value);
    $(div).find(".small-box-footer").contents().first()[0].textContent = _formatTimestampForGauge(gauge_data[index].time);
  });
}

function renderGaugeRowItemsFromScratch () {
  var guage_row = $('<div/>', { class: "row", id: "gauge-row"});
  $.each(gauge_data, function (index, item) {
    guage_row.append(createGaugeBox(item));
  });
  $("#gauge-row").replaceWith(guage_row);
}

function createGaugeBox (item_data) {
  var _div = $("<div/>", { class: "col-lg-2 col-xs-6"});
  var _div_color = $("<div/>", { class: "small-box " + item_data.color });
  var _div_text = $("<div/>", { class: "inner"});

  var _div_value = $("<h3/>", { text: _formatValueForGauge(item_data.value) });
  if (item_data.unit) {
    $("<sup/>", { style: "font-size: 20px", text: item_data.unit }).appendTo(_div_value);
  }
  _div_value.appendTo(_div_text);
  $("<p/>", { text: item_data.name }).appendTo(_div_text);
  _div_text.appendTo(_div_color);

  var _div_icon = $("<div/>", { class: "icon"}).append($("<i/>", { class: item_data.icon}));
  _div_icon.appendTo(_div_color);

  var _div_time = $("<div/>", { class: "small-box-footer", href: "#", text: _formatTimestampForGauge(item_data.time) });
  _div_time.append($("<i/>", { class: "fa fa-arrow-circle-right"}));
  _div_time.appendTo(_div_color);

  _div_color.appendTo(_div);

  return _div;
}

function _formatValueForGauge (value) {
  return value.toFixed(3);
}

function _formatTimestampForGauge (timestamp) {
  return $.format.date(timestamp, 'HH:mm:ss.SSS') + " ";
}
<|endoftext|>