<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Fuse from 'fuse.js';
import classnames from 'classnames';

import TableActions from 'components/admin/table/TableActions';
import Toolbar from 'components/admin/table/Toolbar';
import TableFooter from 'components/admin/table/TableFooter';

import { Modal } from 'components';

const fuseOptions = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1
};

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

    const cols = props.columns || Object.keys(props.data[0]);

    this.state = {
      q: '',
      sort: {
        /**
         * Sort order
         * 1 for ASC, -1 for DESC
         * @type {1|-1} order
         */
        order: 1,
        /**
         * Column index used to sort the tbale
         * @type {number} columnIndex
         */
        columnIndex: 0
      },
      modalOpen: false,
      datasetInfo: null,
      columns: cols,
      // when / if we get dynamic pagination, use that information instead
      pagination: {
        limit: props.limit,
        page: 1,
        offset: 0,
        pages: Math.ceil(props.data.length / props.limit)
      }
    };

    this.fuse = new Fuse(props.data, { keys: cols.map(col => `${col.toLowerCase()}.value`), ...fuseOptions });
  }

  /**
   * Event handler executed when the user
   * sorts a column
   * @param {string} column Column
   */
  onSort(column) {
    const columnIndex = this.state.columns.indexOf(column);
    if (columnIndex !== -1) {
      if (columnIndex === this.state.sort.columnIndex) {
        this.setState({ sort: { ...this.state.sort, order: this.state.sort.order * -1 } });
      } else {
        this.setState({ sort: {
          ...this.state.sort,
          columnIndex,
          order: 1
        } });
      }

      this.setState({ pagination: { ...this.state.pagination, page: 1, offset: 0 } });
    }
  }

  onSearch(e) {
    this.setState({ q: e.target.value });
  }

  onCloseModal() {
    this.setState({ modalOpen: false, datasetInfo: null });
  }

  setRowsPerPage(e) {
    const pagination = {
      ...this.state.pagination,
      limit: parseInt(e.target.value),
      pages: Math.ceil(this.props.data.length / parseInt(e.target.value)),
      page: 1,
      offset: 0
    };

    this.setState({ pagination });
  }

  offsetPage(p) {
    const { offset, limit, page } = this.state.pagination;

    const newOffset = p > page ? offset + limit : offset - limit;
    const pagination = { ...this.state.pagination, page: p, offset: newOffset };

    this.setState({ pagination });
  }

  showRowInfo(data) {
    this.setState({ modalOpen: true, datasetInfo: data });
  }

  formatRow(d, k) {
    const { actions } = this.props;
    return (

        {this.formatCols(d)}
        {actions && <TableActions actions={actions} data={d} showRowInfo={i => this.showRowInfo(i)} />}

    );
  }

  // verify pagination, if we should render item
  verifyPagination(k) {
    const { pagination } = this.state;
    const { limit, offset } = pagination;

    const shouldShow = k < (limit + offset) && k >= offset;

    return shouldShow;
  }

  formatCols(d) {
    const { columns } = this.state;
    const re = new RegExp(columns.join('|').toLowerCase());

    return Object.keys(d).map((key) => {

      const value = d[key].value && d[key].value.length > 0 ? d[key].value : '-';
      const cls = classnames({
        isLong: value.length > 15,
        isList: Array.isArray(value)
      });

      if (re.test(key)) {
        if (typeof d[key] !== 'object') {
          return (

                {d[key]}

            	);
        }

        if ('link' in d[key]) {
          return (

                {value}

          );
        }
        return (

              {Array.isArray(value) ? value.join(' ') : value}

          	);
      }
      return null;
    });
  }

  /**
   * Return the sorted rows
   * @param {Row[]} rows Rows
   * @returns {Row[]}
   */
  sortResults(rows) {
    return rows.sort((a, b) => {
      const column = this.state.columns[this.state.sort.columnIndex].toLowerCase();

      const cellA = a[column];
      const cellB = b[column];

      const valA = Array.isArray(cellA.value) ? cellA.value[0] : cellA.value;
      const valB = Array.isArray(cellB.value) ? cellB.value[0] : cellB.value;

      if ((valA === undefined || valA === null) && (valB === undefined || valB === null)) {
        return 0;
      } else if ((valA === undefined || valB === null) && valB) {
        return -1 * this.state.sort.order;
      } else if (valA && (valB === undefined || valB === null)) {
        return this.state.sort.order;
      }

      if (typeof valA === 'number' && typeof valB === 'number') {
        if (valA < valB) return -1 * this.state.sort.order;
        if (valA > valB) return this.state.sort.order;
        return 0;
      } else if (typeof valA === 'number' && typeof valB !== 'number') {
        return -1 * this.state.sort.order;
      } else if (typeof valA !== 'number' && typeof valB === 'number') {
        return this.state.sort.order;
      }

      return valA.localeCompare(valB, [], { sensitivity: 'base' }) * this.state.sort.order;
    });
  }

  render() {
    const { data, actions, modal, searchable } = this.props;
    const { q, sort, columns, pagination, modalOpen, datasetInfo } = this.state;

    const filteredResults = this.sortResults(q.length > 0 && searchable
      ? this.fuse.search(q)
      : data);

    const sortName = sort.order === 1 ? 'ascending' : 'descending';
    const isSortable = (column) => {
      if (data.length && data[0][column.toLowerCase()]) {
        return !!data[0][column.toLowerCase()].sortable;
      }

      return false;
    };

    return (

        {searchable && <Toolbar q={q} onSearch={query => this.onSearch(query)} />}

            {this.props.name}, sorted by {columns[sort.columnIndex]}: {sortName}

            {filteredResults.length > 0 &&

                {columns.map((col, k) => (
                  <th
                    key={col}
                    aria-sort={k === sort.columnIndex ? sortName : 'none'}
                    tabIndex={k === sort.columnIndex ? '0' : '-1'}
                    className={k === sort.columnIndex ? `-order-${sortName}` : ''}
                    role="columnheader"
                    onClick={() => isSortable(col) && this.onSort(col)}
                  >{col}
                  	))}
                {/* Render empty rows for each action */}
                {actions && actions.map((a, k) => ())}

            }

            {filteredResults &&
              filteredResults.map((d, k) => (this.verifyPagination(k) ? this.formatRow(d, k) : null))}

            {filteredResults.length === 0 &&

              {q.length > 0 ? No results found for {q}	 :
              No items to display	}

}

        <TableFooter
          pagination={pagination}
          offsetPage={p => this.offsetPage(p)}
          setRowsPerPage={e => this.setRowsPerPage(e)}
        />

        <Modal show={modalOpen} onClose={() => this.onCloseModal()}>
          {modal && typeof modal === 'function' ? React.createElement(modal, datasetInfo) : null}
        </Modal>

    );
  }
}

/* eslint-disable max-len */
/**
 * Definition of a row
 * @typedef {{ [column: string]: { value?: any, searchable?: boolean, sortable?: boolean, link?: { url: string, external: boolean }, method?: string } }}  Row
 */
/* eslint-enable max-len */

Table.propTypes = {
  /**
   * Name of the table (for screen readers)
   */
  name: PropTypes.string.isRequired,
  /**
   * Number of results per page
   */
  limit: PropTypes.number,
  /**
   * Data to display in the table
   * Each row contains several columns with their value,
   * an attribute to tell if the column can be searchable and another to tell if it's sortable
   * NOTE: The name of the columns must be in lowercase
   * NOTE: the data will always be sorted ASC by the first column
   * The value attribute can have an array of strings
   * An optional link attribute can be present, it contains its url and an attribute to tell
   * if the link is external or not (this is not built for multi-value cells)
   * An example of the format can be:
   * [
   *   {
   *     name: { value: '$3', searchable: true },
   *     description: { value: ['Spain', 'France'], searchable: true, sortable: false },
   *     price: { value: 'iPhone 6', link: { url: 'https://www.apple.com', external: true }, searchable: false }
   *   }
   * ]
   * @type {Row[]} data
   */
  data: PropTypes.arrayOf(PropTypes.object).isRequired,
  /**
   * Name of the columns
   * Make sure the name matches one attribute of the
   * rows (case insensitive)
   */
  columns: PropTypes.arrayOf(PropTypes.string).isRequired,
  // TODO: document
  actions: PropTypes.array.isRequired
};

Table.defaultProps = {
  limit: 10
};

export default Table;
<commit_msg>Fix the searching feature<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Fuse from 'fuse.js';
import classnames from 'classnames';

import TableActions from 'components/admin/table/TableActions';
import Toolbar from 'components/admin/table/Toolbar';
import TableFooter from 'components/admin/table/TableFooter';

import { Modal } from 'components';

const fuseOptions = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1
};

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

    const cols = props.columns || Object.keys(props.data[0]);

    this.state = {
      q: '',
      sort: {
        /**
         * Sort order
         * 1 for ASC, -1 for DESC
         * @type {1|-1} order
         */
        order: 1,
        /**
         * Column index used to sort the tbale
         * @type {number} columnIndex
         */
        columnIndex: 0
      },
      modalOpen: false,
      datasetInfo: null,
      columns: cols,
      // when / if we get dynamic pagination, use that information instead
      pagination: {
        limit: props.limit,
        page: 1,
        offset: 0,
        pages: Math.ceil(props.data.length / props.limit)
      }
    };

    this.fuse = new Fuse(props.data, { keys: cols.map(col => `${col.toLowerCase()}.value`), ...fuseOptions });
  }

  /**
   * Event handler executed when the user
   * sorts a column
   * @param {string} column Column
   */
  onSort(column) {
    const columnIndex = this.state.columns.indexOf(column);
    if (columnIndex !== -1) {
      if (columnIndex === this.state.sort.columnIndex) {
        this.setState({ sort: { ...this.state.sort, order: this.state.sort.order * -1 } });
      } else {
        this.setState({ sort: {
          ...this.state.sort,
          columnIndex,
          order: 1
        } });
      }

      this.setState({ pagination: { ...this.state.pagination, page: 1, offset: 0 } });
    }
  }

  onSearch(e) {
    this.setState({
      q: e.target.value,
      pagination: {
        ...this.state.pagination,
        offset: 0,
        page: 1
      }
    });
  }

  onCloseModal() {
    this.setState({ modalOpen: false, datasetInfo: null });
  }

  setRowsPerPage(e) {
    const pagination = {
      ...this.state.pagination,
      limit: parseInt(e.target.value),
      pages: Math.ceil(this.props.data.length / parseInt(e.target.value)),
      page: 1,
      offset: 0
    };

    this.setState({ pagination });
  }

  offsetPage(p) {
    const { offset, limit, page } = this.state.pagination;

    const newOffset = p > page ? offset + limit : offset - limit;
    const pagination = { ...this.state.pagination, page: p, offset: newOffset };

    this.setState({ pagination });
  }

  showRowInfo(data) {
    this.setState({ modalOpen: true, datasetInfo: data });
  }

  formatRow(d, k) {
    const { actions } = this.props;
    return (

        {this.formatCols(d)}
        {actions && <TableActions actions={actions} data={d} showRowInfo={i => this.showRowInfo(i)} />}

    );
  }

  // verify pagination, if we should render item
  verifyPagination(k) {
    const { pagination } = this.state;
    const { limit, offset } = pagination;

    const shouldShow = k < (limit + offset) && k >= offset;

    return shouldShow;
  }

  formatCols(d) {
    const { columns } = this.state;
    const re = new RegExp(columns.join('|').toLowerCase());

    return Object.keys(d).map((key) => {

      const value = d[key].value && d[key].value.length > 0 ? d[key].value : '-';
      const cls = classnames({
        isLong: value.length > 15,
        isList: Array.isArray(value)
      });

      if (re.test(key)) {
        if (typeof d[key] !== 'object') {
          return (

                {d[key]}

            	);
        }

        if ('link' in d[key]) {
          return (

                {value}

          );
        }
        return (

              {Array.isArray(value) ? value.join(' ') : value}

          	);
      }
      return null;
    });
  }

  /**
   * Return the sorted rows
   * @param {Row[]} rows Rows
   * @returns {Row[]}
   */
  sortResults(rows) {
    return rows.sort((a, b) => {
      const column = this.state.columns[this.state.sort.columnIndex].toLowerCase();

      const cellA = a[column];
      const cellB = b[column];

      const valA = Array.isArray(cellA.value) ? cellA.value[0] : cellA.value;
      const valB = Array.isArray(cellB.value) ? cellB.value[0] : cellB.value;

      if ((valA === undefined || valA === null) && (valB === undefined || valB === null)) {
        return 0;
      } else if ((valA === undefined || valB === null) && valB) {
        return -1 * this.state.sort.order;
      } else if (valA && (valB === undefined || valB === null)) {
        return this.state.sort.order;
      }

      if (typeof valA === 'number' && typeof valB === 'number') {
        if (valA < valB) return -1 * this.state.sort.order;
        if (valA > valB) return this.state.sort.order;
        return 0;
      } else if (typeof valA === 'number' && typeof valB !== 'number') {
        return -1 * this.state.sort.order;
      } else if (typeof valA !== 'number' && typeof valB === 'number') {
        return this.state.sort.order;
      }

      return valA.localeCompare(valB, [], { sensitivity: 'base' }) * this.state.sort.order;
    });
  }

  render() {
    const { data, actions, modal, searchable } = this.props;
    const { q, sort, columns, pagination, modalOpen, datasetInfo } = this.state;

    const filteredResults = this.sortResults(q.length > 0 && searchable
      ? this.fuse.search(q)
      : data);

    const sortName = sort.order === 1 ? 'ascending' : 'descending';
    const isSortable = (column) => {
      if (data.length && data[0][column.toLowerCase()]) {
        return !!data[0][column.toLowerCase()].sortable;
      }

      return false;
    };

    return (

        {searchable && <Toolbar q={q} onSearch={query => this.onSearch(query)} />}

            {this.props.name}, sorted by {columns[sort.columnIndex]}: {sortName}

            {filteredResults.length > 0 &&

                {columns.map((col, k) => (
                  <th
                    key={col}
                    aria-sort={k === sort.columnIndex ? sortName : 'none'}
                    tabIndex={k === sort.columnIndex ? '0' : '-1'}
                    className={k === sort.columnIndex ? `-order-${sortName}` : ''}
                    role="columnheader"
                    onClick={() => isSortable(col) && this.onSort(col)}
                  >{col}
                  	))}
                {/* Render empty rows for each action */}
                {actions && actions.map((a, k) => ())}

            }

            {filteredResults &&
              filteredResults.map((d, k) => (this.verifyPagination(k) ? this.formatRow(d, k) : null))}

            {filteredResults.length === 0 &&

              {q.length > 0 ? No results found for {q}	 :
              No items to display	}

}

        <TableFooter
          pagination={{
            ...pagination,
            pages: filteredResults
              ? Math.ceil(filteredResults.length / pagination.limit)
              : pagination.pages
          }}
          offsetPage={p => this.offsetPage(p)}
          setRowsPerPage={e => this.setRowsPerPage(e)}
        />

        <Modal show={modalOpen} onClose={() => this.onCloseModal()}>
          {modal && typeof modal === 'function' ? React.createElement(modal, datasetInfo) : null}
        </Modal>

    );
  }
}

/* eslint-disable max-len */
/**
 * Definition of a row
 * @typedef {{ [column: string]: { value?: any, searchable?: boolean, sortable?: boolean, link?: { url: string, external: boolean }, method?: string } }}  Row
 */
/* eslint-enable max-len */

Table.propTypes = {
  /**
   * Name of the table (for screen readers)
   */
  name: PropTypes.string.isRequired,
  /**
   * Number of results per page
   */
  limit: PropTypes.number,
  /**
   * Whether the user can search text in the table
   */
  searchable: PropTypes.bool,
  /**
   * Data to display in the table
   * Each row contains several columns with their value and
   * an attribute to tell if the column can be sortable
   * NOTE: The name of the columns must be in lowercase
   * NOTE: the data will always be sorted ASC by the first column
   * The value attribute can have an array of strings
   * An optional link attribute can be present, it contains its url and an attribute to tell
   * if the link is external or not (this is not built for multi-value cells)
   * An example of the format can be:
   * [
   *   {
   *     name: { value: '$3' },
   *     description: { value: ['Spain', 'France'], sortable: false },
   *     price: { value: 'iPhone 6', link: { url: 'https://www.apple.com', external: true }, searchable: false }
   *   }
   * ]
   * @type {Row[]} data
   */
  data: PropTypes.arrayOf(PropTypes.object).isRequired,
  /**
   * Name of the columns
   * Make sure the name matches one attribute of the
   * rows (case insensitive)
   */
  columns: PropTypes.arrayOf(PropTypes.string).isRequired,
  // TODO: document
  actions: PropTypes.array.isRequired
};

Table.defaultProps = {
  limit: 10,
  searchable: false
};

export default Table;
<|endoftext|>


<commit_before>window.MyApp = new Backbone.Marionette.Application();

window.MyApp.addRegions({
  mainRegion: '#content'
});

var AngryCat = Backbone.Model.extend({});

var AngryCats = Backbone.Collection.extend({
  model: AngryCat
});<commit_msg>Implemented cat item view skeleton<commit_after>window.MyApp = new Backbone.Marionette.Application();

window.MyApp.addRegions({
  mainRegion: '#content'
});

var AngryCat = Backbone.Model.extend({});

var AngryCats = Backbone.Collection.extend({
  model: AngryCat
});

var AngryCatView = Backbone.Marionette.ItemView.extend({
  template: '#angry_cat-template',
  tagName: 'tr',
  className: 'angry_cat'
});<|endoftext|>


<commit_before>function initMap() {
		var element = document.createElement('div');
        var mapDiv = document.getElementById('map-hider').appendChild(element);
		mapDiv.id = 'map';
		mapDiv.style.cssText = 'width:1000px; height:700px; margin: auto';
        var map = new google.maps.Map(mapDiv, {
            center: {lat: 44.540, lng: -78.546},
            zoom: 8
        });

		window.alert("Loaded Google Map, adding WanderlustSA markers...");
}

window.onload = initMap;

<commit_msg>Nice for 1920x1080 screen (resize)<commit_after>function initMap() {
		var element = document.createElement('div');
        var mapDiv = document.getElementById('map-hider').appendChild(element);
		mapDiv.id = 'map';
		mapDiv.style.cssText = 'width:1400px; height:750px; margin: auto';
        var map = new google.maps.Map(mapDiv, {
            center: {lat: 44.540, lng: -78.546},
            zoom: 8
        });

		window.alert("Loaded Google Map, adding WanderlustSA markers...");
}

window.onload = initMap;

<|endoftext|>


<commit_before>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Controlled as CodeMirror } from 'react-codemirror2';
import {
  FormGroup,
  ControlLabel,
  Radio,
  HelpBlock,
} from 'patternfly-react';

// editor modes
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/yaml/yaml';
// editor help
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';

import { useFieldApi } from '@@ddf';

import RequiredLabel from '../../forms/required-label';

const getMode = mode => ({
  json: { name: 'javascript', json: true },
})[mode] || mode;

const CodeEditor = ({
  mode,
  modes,
  hasError,
  onChange,
  ...props
}) => {
  const [codeMode, setCodeMode] = useState(mode);
  const [editor, setEditor] = useState();
  useEffect(() => {
    if (editor) {
      editor.refresh();
    }
  }, [editor]);
  return (

      {modes.length > 0 && (
        <FormGroup controlId="radioGroup" disabled={false}>

            {modes.map(mode => <Radio checked={codeMode === mode} onChange={() => setCodeMode(mode)} inline key={mode} name={mode}>{mode}</Radio>)}

        </FormGroup>
      )}
      <CodeMirror
        className={`miq-codemirror ${hasError ? 'has-error' : ''}`}
        options={{
          mode: getMode(codeMode),
          theme: 'eclipse',
          lint: true,
          lineNumbers: true,
          lineWrapping: true,
          autoCloseBrackets: true,
          styleActiveLine: true,
          gutters: ['CodeMirror-lint-markers'],
        }}
        style={{ height: 'auto' }}
        onBeforeChange={(editor, _data, value) => {
          onChange(editor, _data, value);
        }}
        onChange={(editor, _data, value) => {
          onChange(editor, _data, value);
        }}
        editorDidMount={(editor) => {
          setEditor(editor);
        }}
        {...props}
      />

  );
};

CodeEditor.propTypes = {
  mode: PropTypes.oneOf(['json', 'yaml']),
  modes: PropTypes.arrayOf(PropTypes.string),
  onChange: PropTypes.func.isRequired,
};

CodeEditor.defaultProps = {
  mode: 'yaml',
  modes: [],
};

const CodeGroup = ({
  input: { value, onChange, name },
  meta: { error },
  label,
  isRequired,
  ...props
}) => (
  <FormGroup name={name} validationState={error && 'error'}>
    <ControlLabel>
      {isRequired ? <RequiredLabel label={label} /> : label }
    </ControlLabel>
    <CodeEditor
      onChange={(_editor, _data, value) => onChange(value)}
      value={value}
      hasError={!!error}
      {...props}
    />
    {error && <HelpBlock>{error}</HelpBlock>}
  </FormGroup>
);

export const DataDrivenFormCodeEditor = (props) => {
  const { input, meta, ...rest } = useFieldApi(props);
  return <CodeGroup input={input} meta={meta} {...rest} />;
};

export default CodeEditor;
<commit_msg>Introduce a helperText on the code-editor component<commit_after>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Controlled as CodeMirror } from 'react-codemirror2';
import {
  FormGroup,
  ControlLabel,
  Radio,
  HelpBlock,
  FieldLevelHelp,
} from 'patternfly-react';

// editor modes
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/yaml/yaml';
// editor help
import 'codemirror/addon/edit/matchbrackets';
import 'codemirror/addon/edit/closebrackets';

import { useFieldApi } from '@@ddf';

import RequiredLabel from '../../forms/required-label';

const getMode = mode => ({
  json: { name: 'javascript', json: true },
})[mode] || mode;

const CodeEditor = ({
  mode,
  modes,
  hasError,
  onChange,
  ...props
}) => {
  const [codeMode, setCodeMode] = useState(mode);
  const [editor, setEditor] = useState();
  useEffect(() => {
    if (editor) {
      editor.refresh();
    }
  }, [editor]);
  return (

      {modes.length > 0 && (
        <FormGroup controlId="radioGroup" disabled={false}>

            {modes.map(mode => <Radio checked={codeMode === mode} onChange={() => setCodeMode(mode)} inline key={mode} name={mode}>{mode}</Radio>)}

        </FormGroup>
      )}
      <CodeMirror
        className={`miq-codemirror ${hasError ? 'has-error' : ''}`}
        options={{
          mode: getMode(codeMode),
          theme: 'eclipse',
          lint: true,
          lineNumbers: true,
          lineWrapping: true,
          autoCloseBrackets: true,
          styleActiveLine: true,
          gutters: ['CodeMirror-lint-markers'],
        }}
        style={{ height: 'auto' }}
        onBeforeChange={(editor, _data, value) => {
          onChange(editor, _data, value);
        }}
        onChange={(editor, _data, value) => {
          onChange(editor, _data, value);
        }}
        editorDidMount={(editor) => {
          setEditor(editor);
        }}
        {...props}
      />

  );
};

CodeEditor.propTypes = {
  mode: PropTypes.oneOf(['json', 'yaml']),
  modes: PropTypes.arrayOf(PropTypes.string),
  onChange: PropTypes.func.isRequired,
};

CodeEditor.defaultProps = {
  mode: 'yaml',
  modes: [],
};

const CodeGroup = ({
  input: { value, onChange, name },
  meta: { error },
  label,
  isRequired,
  helperText,
  ...props
}) => (
  <FormGroup name={name} validationState={error && 'error'}>
    <ControlLabel>
      {isRequired ? <RequiredLabel label={label} /> : label }
      {helperText && <FieldLevelHelp content={helperText} />}
    </ControlLabel>
    <CodeEditor
      onChange={(_editor, _data, value) => onChange(value)}
      value={value}
      hasError={!!error}
      {...props}
    />
    {error && <HelpBlock>{error}</HelpBlock>}
  </FormGroup>
);

export const DataDrivenFormCodeEditor = (props) => {
  const { input, meta, ...rest } = useFieldApi(props);
  return <CodeGroup input={input} meta={meta} {...rest} />;
};

export default CodeEditor;
<|endoftext|>


<commit_before>(function() {
function url_to_item(item_url){
	$('#Main').stop();
	$('#Main').fadeOut(function(){
		$('#Main').empty();
	});

	var url = item_url;
	var item = url.split('[item=');
	console.log(item);
	var item = item[1].split(']');
	console.log(item);
	var url = item[0];
	console.log(item);
	$.ajax({
		   url: "get_content.php",
		   type: "POST",
		   data: {url: url},
		   success: function(reponse){
		   		reponse = jQuery.parseJSON(reponse);
			   	console.log(reponse);
			   	reponse = reponse.split('
');
			   	reponse = reponse[1].split('
');
			   	reponse = reponse[0];
			   	urlImage = reponse.split('	');
			   	console.log(urlImage);
			   	urlImageFinal = urlImage[0];
			   	console.log(urlImageFinal);
			   	$('#Main').append(reponse);
			   	$('td.icon_cell').empty().append('');
			   	$('#Main').fadeIn();
			}
	});
}
/*(function() {
  function replaceItemLink (text) {
    while (text != (text = text.replace(/\[item=([^\]]+)\]((?:(?!\[item=[^\]]+\]|\[\/item\])[\S\s])*)\[\/item\]/ig, function (match, p1, p2, offset, string) {
      return "" + p2 + "";
    })));
    return text;
  }

  Discourse.Dialect.addPreProcessor(replaceItemLink);
  Discourse.Markdown.whiteListTag('a', 'href', 'onmouseenter', 'class');

})();*/

	Discourse.BBCode.replaceBBCodeParamsRaw('item', function(param, contents) {
	  var url = param.replace(/(^")|("$)/g, '');
	  return ['a', {'href': '#', 'onmouseenter': 'javascript:url_to_item('+url+')', 'class': 'item-bdo'}].concat(this.processInline(contents));
	});

})();<commit_msg>Added files via upload<commit_after>(function() {
function url_to_item(item_url){
	$('#Main').stop();
	$('#Main').fadeOut(function(){
		$('#Main').empty();
	});

	var url = item_url;
	var item = url.split('[item=');
	console.log(item);
	var item = item[1].split(']');
	console.log(item);
	var url = item[0];
	console.log(item);
	$.ajax({
		   url: "get_content.php",
		   type: "POST",
		   data: {url: url},
		   success: function(reponse){
		   		reponse = jQuery.parseJSON(reponse);
			   	console.log(reponse);
			   	reponse = reponse.split('
');
			   	reponse = reponse[1].split('
');
			   	reponse = reponse[0];
			   	urlImage = reponse.split('	');
			   	console.log(urlImage);
			   	urlImageFinal = urlImage[0];
			   	console.log(urlImageFinal);
			   	$('#Main').append(reponse);
			   	$('td.icon_cell').empty().append('');
			   	$('#Main').fadeIn();
			}
	});
}
/*(function() {
  function replaceItemLink (text) {
    while (text != (text = text.replace(/\[item=([^\]]+)\]((?:(?!\[item=[^\]]+\]|\[\/item\])[\S\s])*)\[\/item\]/ig, function (match, p1, p2, offset, string) {
      return "" + p2 + "";
    })));
    return text;
  }

  Discourse.Dialect.addPreProcessor(replaceItemLink);
  Discourse.Markdown.whiteListTag('a', 'href', 'onmouseenter', 'class');

})();*/

	Discourse.BBCode.rawBBCode('item', function(contents) { return ['a', {href: contents, 'class' : 'item-bbcode', 'data-bbcode': true}, contents]; });

})();<|endoftext|>


<commit_before>var glob = require('glob'),
    fs = require('fs'),
    mark = require('marked'),
    cheerio = require('cheerio'),
    argv = require('minimist')(process.argv.slice(2)),
    postsPerPage = argv.n || 5;

function parseFiles(files, cb) {
  var out = [];

  files.forEach(function(file){
    var data = '';
    fs.createReadStream(file)
      .on('error', cb)
      .on('data', function(chunk){
        data += chunk;
      })
      .on('end', function(){
        var o = {
          html: mark(data),
          ts: fs.statSync(file).mtime.getTime()
        };
        out.push(o);

        if (out.length === files.length) {
          cb(null, out);
        }
      });
  });
}

function sortAndStrip(collection) {
  return collection
    .sort(function(a, b){
      return b.ts - a.ts;
    })
    .map(function(o){
      return o.html;
    });
}

function buildPage(html, i) {
  var posts = html.join(''),
      base = '';

  // ideally -> reader.pipe(applyPosts).pipe(writer)
  fs.createReadStream('./lib/base.html')
    .on('data', function(chunk){
      base += chunk;
    })
    .on('end', function(){
      var $ = cheerio.load(base);
      $('.content').append(posts);

      var outFile = (i > 0)? './public/page' + i + '.html': 'index.html';

      fs.createWriteStream(outFile)
        .end($.html(), 'utf8'); // cb
    });
}

function groupFiles(collection, n) {
  var i = 0,
      len = collection.length,
      chunk,
      out = [];

  for (i; i < len; i += n) {
    chunk = collection.slice(i, (i+n));
    out.push(chunk);
  }
  return out;
}

function done() {
  console.log('done');
}

function clean(cb) {
  glob('public/*', function (err, files) {
    files.forEach(function(file){
      fs.unlinkSync(file);
    });
    cb();
  });
}

function main() {
  glob('posts/*', function (err, files) { // get file names
    if (err) throw err;

    parseFiles(files, function(err, html){ // parse text to html + ts
      if (err) throw err;

      html = sortAndStrip(html);

      if (html.length > postsPerPage) { // group
        var group = groupFiles(html, postsPerPage);
        group.forEach(function(arr, i){
          buildPage(arr, i);
        });
      } else { // only build index
        buildPage(arr, 0);
      }
      done();
    });
  })
}

clean(main);
<commit_msg>added buildtime<commit_after>var glob = require('glob'),
    fs = require('fs'),
    mark = require('marked'),
    cheerio = require('cheerio'),
    argv = require('minimist')(process.argv.slice(2)),
    postsPerPage = argv.n || 5;

function parseFiles(files, cb) {
  var out = [];

  files.forEach(function(file){
    var data = '';
    fs.createReadStream(file)
      .on('error', cb)
      .on('data', function(chunk){
        data += chunk;
      })
      .on('end', function(){
        var o = {
          html: mark(data),
          ts: fs.statSync(file).mtime.getTime()
        };
        out.push(o);

        if (out.length === files.length) {
          cb(null, out);
        }
      });
  });
}

function sortAndStrip(collection) {
  return collection
    .sort(function(a, b){
      return b.ts - a.ts;
    })
    .map(function(o){
      return o.html;
    });
}

function buildPage(html, i) {
  var posts = html.join(''),
      base = '';

  // ideally -> reader.pipe(applyPosts).pipe(writer)
  fs.createReadStream('./lib/base.html')
    .on('data', function(chunk){
      base += chunk;
    })
    .on('end', function(){
      var $ = cheerio.load(base);
      $('.content').append(posts);

      var outFile = (i > 0)? './public/page' + i + '.html': 'index.html';

      fs.createWriteStream(outFile)
        .end($.html(), 'utf8'); // cb
    });
}

function groupFiles(collection, n) {
  var i = 0,
      len = collection.length,
      chunk,
      out = [];

  for (i; i < len; i += n) {
    chunk = collection.slice(i, (i+n));
    out.push(chunk);
  }
  return out;
}

function done() {
  console.timeEnd('buildtime');
  console.log('done');
}

function clean(cb) {
  console.time('buildtime');

  glob('public/*', function (err, files) {
    files.forEach(function(file){
      fs.unlinkSync(file);
    });
    cb();
  });
}

function main() {
  glob('posts/*', function (err, files) { // get file names
    if (err) throw err;

    parseFiles(files, function(err, html){ // parse text to html + ts
      if (err) throw err;

      html = sortAndStrip(html);

      if (html.length > postsPerPage) { // group
        var group = groupFiles(html, postsPerPage);
        group.forEach(function(arr, i){
          buildPage(arr, i);
        });
      } else { // only build index
        buildPage(arr, 0);
      }
      done();
    });
  })
}

clean(main);
<|endoftext|>


<commit_before>import styled, { css } from 'styled-components'
import { animated } from 'react-spring/dist/react-spring.umd'
import { spacing } from '@ui/common/constants'
import { Buttons } from '@components/ui/components/button'

const Loading = styled(animated.div)`
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  z-index: 99;
  width: calc(100% + 60px);
  left: -30px;
  height: calc(100% + 53px);
  top: -30px;
`

const Header = styled.div``
const Title = styled.div`
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
  margin-bottom: ${spacing.gutter};
  display: flex;
`
const TitleSection = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  &:not(:first-of-type):last-of-type {
    padding-left: ${spacing.base};
  }
`
const AnimatedTitle = styled(animated.div)``
const Content = styled(animated.div)`
  flex-grow: ${({ grow }) => (grow ? 1 : 0)};
  display: flex;
  flex-direction: column;
}
`
const Actions = styled(animated.div)`
  @media (max-width: 599px) {
    padding-bottom: 30px;
  }
`

const Main = styled(animated.div)`
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  flex-shrink: 0;
  width: 100%;
`
const Wrapper = styled(animated.div)`
  position: absolute;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  width: 100%;
  flex-direction: column;
  flex-grow: 1;
  &:first-of-type {
    z-index: 20;
  }
`

const Sidebar = styled.div`
  position: relative;
  width: 342px;
  min-width: 342px;
  display: flex;
  flex-direction: column;
  justify-content: center;

  color: white;
  padding: ${spacing.gutter};
  background-image: linear-gradient(97.35deg, #382c68 0%, #7858a2 173.24%);
  @media (max-width: 900px) {
    display: none;
  }
`

const SidebarLogo = styled.div`
  position: absolute;
  top: 30px;
  left: 30px;
`

const SidebarContent = styled.div`
  min-height: 400px;
  h1 {
    margin-bottom: ${spacing.gutter};
  }
`

const ContentContainer = styled.div`
  display: flex;
  width: 100%;
  padding: ${spacing.gutter};
  background: white;
  border-radius: 8px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
  position: relative;

  @media (max-width: 599px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    min-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    min-width: 100vw;
    overflow-y: auto;
    padding-bottom: 0;
  }
  @media (min-width: 600px) {
    max-width: 450px;
    flex-direction: column;
    flex-grow: 1;
    justify-content: center;
    align-items: center;
  }
`
const ContentWrapper = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  ${Wrapper} {
    position: relative;
    @media (min-width: 900px) {
    }
  }
`

const StyledShell = styled.div`
  position: fixed;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  min-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
  top: 0;
  left: 0;
  width: 100%;
  z-index: 900000;
  background-color: rgba(240, 240, 240, 0.8);

  ${({ maxHeight }) =>
    maxHeight &&
    css`
      ${ContentContainer} {
        @media (min-width: 600px) {
          max-height: calc(100vh - 120px) !important;
        }
      }
    `};

  ${({ invert }) =>
    invert
      ? css`
          @media (max-width: 599px) {
            background: linear-gradient(97.35deg, #382c68 0%, #7858a2 173.24%);
            overflow-y: auto !important;

            ${Actions} {
              margin-bottom: 0;
              ${Buttons} {
                margin-top: 0 !important;
              }
            }
            ${ContentContainer} {
              padding: 30px;
              background: transparent;
              border-radius: 0;
              box-shadow: none;
              max-height: none;
            }

            ${Wrapper} {
              background: white;
              border-radius: 8px;
            }
            ${Title}, ${Actions} {
              padding: ${spacing.gutter};
            }

            ${Content} {
              padding: 0 ${spacing.gutter};
            }

            ${Title} {
              border-bottom: 1px solid rgba(39, 15, 52, 0.1);
            }
          }
        `
      : css``};

  @media (min-width: 600px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    overflow-y: auto;
    overflow-x: hidden;
    padding: 60px;
  }

  @media (max-height: 700px) {
    align-items: flex-start;
  }

  @media (max-width: 600px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    overflow: hidden;
  }
  * {
    font-family: -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI',
      Roboto, sans-serif;
  }
  * {
    box-sizing: border-box;
  }
`

StyledShell.Header = Header
StyledShell.Title = Title
StyledShell.Title.Section = TitleSection
StyledShell.Title.Animated = AnimatedTitle
StyledShell.Content = Content
StyledShell.Actions = Actions
StyledShell.Main = Main
StyledShell.Wrapper = Wrapper
StyledShell.Loading = Loading
StyledShell.Sidebar = Sidebar
StyledShell.Sidebar.Logo = SidebarLogo
StyledShell.Sidebar.Content = SidebarContent
StyledShell.Content.Container = ContentContainer
StyledShell.Content.Wrapper = ContentWrapper

export { StyledShell }
<commit_msg>add in more nuanced settings for when to overflow<commit_after>import styled, { css } from 'styled-components'
import { animated } from 'react-spring/dist/react-spring.umd'
import { spacing } from '@ui/common/constants'
import { Buttons } from '@components/ui/components/button'

const Loading = styled(animated.div)`
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  z-index: 99;
  width: calc(100% + 60px);
  left: -30px;
  height: calc(100% + 53px);
  top: -30px;
`

const Header = styled.div``
const Title = styled.div`
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
  margin-bottom: ${spacing.gutter};
  display: flex;
`
const TitleSection = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  &:not(:first-of-type):last-of-type {
    padding-left: ${spacing.base};
  }
`
const AnimatedTitle = styled(animated.div)``
const Content = styled(animated.div)`
  flex-grow: ${({ grow }) => (grow ? 1 : 0)};
  display: flex;
  flex-direction: column;
}
`
const Actions = styled(animated.div)`
  @media (max-width: 599px) {
    padding-bottom: 30px;
  }
`

const Main = styled(animated.div)`
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  position: relative;

  width: 100%;
  @media (max-height: 700px) and (max-width: 599px) {
    flex-shrink: 0;
  }
`
const Wrapper = styled(animated.div)`
  position: absolute;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  width: 100%;
  flex-direction: column;
  flex-grow: 1;
  &:first-of-type {
    z-index: 20;
  }
`

const Sidebar = styled.div`
  position: relative;
  width: 342px;
  min-width: 342px;
  display: flex;
  flex-direction: column;
  justify-content: center;

  color: white;
  padding: ${spacing.gutter};
  background-image: linear-gradient(97.35deg, #382c68 0%, #7858a2 173.24%);
  @media (max-width: 900px) {
    display: none;
  }
`

const SidebarLogo = styled.div`
  position: absolute;
  top: 30px;
  left: 30px;
`

const SidebarContent = styled.div`
  min-height: 400px;
  h1 {
    margin-bottom: ${spacing.gutter};
  }
`

const ContentContainer = styled.div`
  display: flex;
  width: 100%;
  padding: ${spacing.gutter};
  background: white;
  border-radius: 8px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
  position: relative;

  @media (max-width: 599px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    min-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    min-width: 100vw;
    overflow-y: auto;
    padding-bottom: 0;
  }
  @media (min-width: 600px) {
    max-width: 450px;
    flex-direction: column;
    flex-grow: 1;
    justify-content: center;
    align-items: center;
  }
`
const ContentWrapper = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  ${Wrapper} {
    position: relative;
    @media (min-width: 900px) {
    }
  }
`

const StyledShell = styled.div`
  position: fixed;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
  min-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
  top: 0;
  left: 0;
  width: 100%;
  z-index: 900000;
  background-color: rgba(240, 240, 240, 0.8);

  ${({ maxHeight }) =>
    maxHeight &&
    css`
      ${ContentContainer} {
        @media (min-width: 600px) {
          max-height: calc(100vh - 120px) !important;
        }
      }
    `};

  ${({ invert }) =>
    invert
      ? css`
          @media (max-width: 599px) {
            background: linear-gradient(97.35deg, #382c68 0%, #7858a2 173.24%);
            overflow-y: auto !important;

            ${Actions} {
              margin-bottom: 0;
              ${Buttons} {
                margin-top: 0 !important;
              }
            }
            ${ContentContainer} {
              padding: 30px;
              background: transparent;
              border-radius: 0;
              box-shadow: none;
              max-height: none;
            }

            ${Wrapper} {
              background: white;
              border-radius: 8px;
            }
            ${Title}, ${Actions} {
              padding: ${spacing.gutter};
            }

            ${Content} {
              padding: 0 ${spacing.gutter};
            }

            ${Title} {
              border-bottom: 1px solid rgba(39, 15, 52, 0.1);
            }
          }
        `
      : css``};

  @media (min-width: 600px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    overflow-y: auto;
    overflow-x: hidden;
    padding: 60px;
  }

  @media (max-height: 700px) {
    align-items: flex-start;
  }

  @media (max-width: 600px) {
    max-height: ${({ height }) => (height > 0 ? `${height}px` : '100vh')};
    overflow: hidden;
  }
  * {
    font-family: -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI',
      Roboto, sans-serif;
  }
  * {
    box-sizing: border-box;
  }
`

StyledShell.Header = Header
StyledShell.Title = Title
StyledShell.Title.Section = TitleSection
StyledShell.Title.Animated = AnimatedTitle
StyledShell.Content = Content
StyledShell.Actions = Actions
StyledShell.Main = Main
StyledShell.Wrapper = Wrapper
StyledShell.Loading = Loading
StyledShell.Sidebar = Sidebar
StyledShell.Sidebar.Logo = SidebarLogo
StyledShell.Sidebar.Content = SidebarContent
StyledShell.Content.Container = ContentContainer
StyledShell.Content.Wrapper = ContentWrapper

export { StyledShell }
<|endoftext|>


<commit_before>/**
 * Sparkline component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import GoogleChartV2 from './GoogleChartV2';

function Sparkline( {
	change,
	data,
	invertChangeColor,
	loadingHeight,
} ) {
	if ( ! data ) {
		return null;
	}

	const positiveColor = ! invertChangeColor ? 'green' : 'red';
	const negativeColor = ! invertChangeColor ? 'red' : 'green';

	const chartOptions = {
		title: '',
		backgroundColor: 'transparent',
		curveType: 'line',
		width: '100%',
		height: '50',
		enableInteractivity: false,
		chartArea: {
			height: '100%',
			width: '100%',
		},
		legend: { position: 'none' },
		axisFontSize: 0,
		hAxis: {
			baselineColor: 'none',
			ticks: [],
		},
		vAxis: {
			baselineColor: 'none',
			ticks: [],
		},
		axes: [],
		colors: [
			0 <= ( parseFloat( change ) || 0 ) ? positiveColor : negativeColor,
		],
	};

	return (

			<GoogleChartV2
				chartType="LineChart"
				data={ data }
				loadingHeight={ loadingHeight }
				options={ chartOptions }
			/>

	);
}

Sparkline.propTypes = {
	invertChangeColor: PropTypes.bool,
	loadingHeight: PropTypes.string,
};

Sparkline.defaultProps = {
	invertChangeColor: false,
	loadingHeight: '46px',
};

export default Sparkline;
<commit_msg>Sparkline with zero goals renders level with the baseline of the other dashboard graphs.<commit_after>/**
 * Sparkline component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import GoogleChartV2 from './GoogleChartV2';

function Sparkline( {
	change,
	data,
	invertChangeColor,
	loadingHeight,
} ) {
	if ( ! data ) {
		return null;
	}

	const positiveColor = ! invertChangeColor ? 'green' : 'red';
	const negativeColor = ! invertChangeColor ? 'red' : 'green';

	const chartOptions = {
		title: '',
		backgroundColor: 'transparent',
		curveType: 'line',
		width: '100%',
		height: '50',
		enableInteractivity: false,
		chartArea: {
			height: '100%',
			width: '100%',
		},
		legend: { position: 'none' },
		axisFontSize: 0,
		hAxis: {
			baselineColor: 'none',
			ticks: [],
		},
		vAxis: {
			baselineColor: 'none',
			ticks: [],
		},
		axes: [],
		colors: [
			0 <= ( parseFloat( change ) || 0 ) ? positiveColor : negativeColor,
		],
	};

	if ( ! data.slice( 1 ).some( ( row ) => row[ 1 ] > 0 ) ) {
		chartOptions.vAxis.minValue = 0;
		chartOptions.vAxis.maxValue = 1;
	}

	return (

			<GoogleChartV2
				chartType="LineChart"
				data={ data }
				loadingHeight={ loadingHeight }
				options={ chartOptions }
			/>

	);
}

Sparkline.propTypes = {
	invertChangeColor: PropTypes.bool,
	loadingHeight: PropTypes.string,
};

Sparkline.defaultProps = {
	invertChangeColor: false,
	loadingHeight: '46px',
};

export default Sparkline;
<|endoftext|>


<commit_before>require('json-schema-ref-parser').bundle(
  require('./schema.json'),
  function(error, schema) {
    if (error) {
      console.error(error)
      process.exit(1) }
    else {
      console.log('%j', schema) } })
<commit_msg>Format bundled schema with lispy-json<commit_after>require('json-schema-ref-parser').bundle(
  require('./schema.json'),
  function(error, schema) {
    if (error) {
      console.error(error)
      process.exit(1) }
    else {
      console.log(require('lispy-json')(schema)) } })
<|endoftext|>


<commit_before>/**
 * `useQueryString` hook.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import qs from 'query-string';

/**
 * WordPress dependencies
 */
import { useState, useCallback } from '@wordpress/element';

/**
 * Uses a location query param as a state.
 *
 * @since n.e.x.t
 *
 * @param {string}      key          The query param key to be used.
 * @param {string|null} initialValue The initial value for the query param to be used.
 * @return {Array} The getter and setter for the query param state.
 */
function useQueryString( key, initialValue = null ) {
	const [ value, setValue ] = useState( getQueryStringValue( key ) || initialValue );
	const onSetValue = useCallback(
		( newValue ) => {
			setValue( newValue );
			setQueryStringValue( key, newValue );
		},
		[ key ]
	);

	return [ value, onSetValue ];
}

const setQueryStringWithoutPageReload = ( qsValue ) => {
	const newURL = `${ global.location.pathname }${ qsValue }`;
	global.history.pushState( { path: newURL }, '', newURL );
};

const getQueryStringValue = (
	key,
	queryString = global.location.search
) => {
	const values = qs.parse( queryString );
	return values[ key ];
};

const setQueryStringValue = (
	key,
	value,
	queryString = global.location.search
) => {
	const values = qs.parse( queryString );
	const newQsValue = qs.stringify( {
		...values,
		[ key ]: value,
	} );
	setQueryStringWithoutPageReload( `?${ newQsValue }` );
};

export default useQueryString;
<commit_msg>Possible fix to failing builds.<commit_after>/**
 * `useQueryString` hook.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import qs from 'query-string';

/**
 * WordPress dependencies
 */
import { useState, useCallback } from '@wordpress/element';

/**
 * Uses a location query param as a state.
 *
 * @since n.e.x.t
 *
 * @param {string}        key          The query param key to be used.
 * @param {(string|null)} initialValue The initial value for the query param to be used.
 * @return {Array} The getter and setter for the query param state.
 */
function useQueryString( key, initialValue = null ) {
	const [ value, setValue ] = useState( getQueryStringValue( key ) || initialValue );
	const onSetValue = useCallback(
		( newValue ) => {
			setValue( newValue );
			setQueryStringValue( key, newValue );
		},
		[ key ]
	);

	return [ value, onSetValue ];
}

const setQueryStringWithoutPageReload = ( qsValue ) => {
	const newURL = `${ global.location.pathname }${ qsValue }`;
	global.history.pushState( { path: newURL }, '', newURL );
};

const getQueryStringValue = (
	key,
	queryString = global.location.search
) => {
	const values = qs.parse( queryString );
	return values[ key ];
};

const setQueryStringValue = (
	key,
	value,
	queryString = global.location.search
) => {
	const values = qs.parse( queryString );
	const newQsValue = qs.stringify( {
		...values,
		[ key ]: value,
	} );
	setQueryStringWithoutPageReload( `?${ newQsValue }` );
};

export default useQueryString;
<|endoftext|>


<commit_before>const fse = require('fs-extra');
const os = require('os');
const inquirer = require('inquirer');
const crypto = require('crypto')
const zlib = require('zlib');
const fs = require('fs');
const shell = require('shelljs');
const figlet = require('figlet');
const path = require("path");
const replace = require("replace");
const Datauri = require('datauri').sync;
const absolutePath = path.resolve(".");
const algorithm = 'sha1';

function startBuild() {
    console.log(' Preparing for building Jste Framework ');
    shell.rm('-rf', 'tmp');
    shell.mkdir('tmp');
    shell.ln('-sf', absolutePath + '/src', 'tmp/src');
    shell.cd('build');
    shell.rm('-rf', '*');
    shell.mkdir('minified', 'compressed');
    fse.copySync(absolutePath + '/src/JS/Core/analyzeCommand-CompilationTemplate.js', absolutePath + '/tmp/analyzeCommand-Compiled.js');
    fse.copySync(absolutePath + '/src/JS/Core/wordsTranslationsInit-CompilationTemplate.js', absolutePath + '/tmp/wordsTranslationsInit-Compiled.js');
    fse.copySync(absolutePath + '/src/Res.html', absolutePath + '/tmp/Res.html');
    fse.copySync(absolutePath + '/src/Res-LiveVersion.html', absolutePath + '/tmp/Res-LiveVersion.html');
    var langCodes = ['en', 'fr', 'ar', 'arz'];
    for (var i = 0; i < langCodes.length; i++) {
        replace({
            regex: langCodes[i].toUpperCase() + "_RIVESCRIPT",
            replacement: Datauri(absolutePath + '/src/JS/Translations/RiveScript/' + langCodes[i] + '.rive'),
            paths: [absolutePath + '/tmp/analyzeCommand-Compiled.js'],
            recursive: true,
            silent: true,
        });
    }
    replace({
        regex: "DICTIONARY_URL",
        replacement: Datauri(absolutePath + '/src/JS/Translations/words.json'),
        paths: [absolutePath + '/tmp/wordsTranslationsInit-Compiled.js'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src="(?!http)',
        replacement: 'src="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'href="(?!http)',
        replacement: 'href="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/wordsTranslationsInit\.js',
        replacement: 'wordsTranslationsInit-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/analyzeCommand\.js',
        replacement: 'analyzeCommand-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    console.log(' ');
    console.log(' Starting building Jste Framework ');
    var frameworkMinifiedFileInfo = {};
    var frameworkCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework.min.html');
    frameworkMinifiedFileInfo.size = fs.statSync('minified/framework.min.html').size;
    frameworkCompressedFileInfo.size = frameworkMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework.min.html', 'utf8'));
    frameworkMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework.info.json', JSON.stringify(frameworkMinifiedFileInfo));
    shell.rm('-rf', 'framework.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework.min.html');
    var out = fs.createWriteStream('compressed/framework.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework.min.html.gz', 'utf8'));
    frameworkCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework.info.json', JSON.stringify(frameworkCompressedFileInfo));
    console.log(' Jste Framework has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building Jste Framework Live Version ');
    var frameworkLiveVersionMinifiedFileInfo = {};
    var frameworkLiveVersionCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res-LiveVersion.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework-LiveVersion.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework-LiveVersion.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework-LiveVersion.min.html');
    frameworkLiveVersionMinifiedFileInfo.size = fs.statSync('minified/framework-LiveVersion.min.html').size;
    frameworkLiveVersionCompressedFileInfo.size = frameworkLiveVersionMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework-LiveVersion.min.html', 'utf8'));
    frameworkLiveVersionMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionMinifiedFileInfo));
    shell.rm('-rf', 'framework-LiveVersion.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework-LiveVersion.min.html');
    var out = fs.createWriteStream('compressed/framework-LiveVersion.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework-LiveVersion.min.html.gz', 'utf8'));
    frameworkLiveVersionCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionCompressedFileInfo));
    console.log(' Jste Framework Live Version has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building the BLOB DB Manager for Jste Framework Live Version ');
    var dbManagerMinifiedFileInfo = {};
    var dbManagerCompressedFileInfo = {};
    console.log(' Minifying the BLOB DB Manager file ');
    shell.exec('html-minifier ../utils/db-manager.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/db-manager.min.html');
    dbManagerMinifiedFileInfo.size = fs.statSync('minified/db-manager.min.html').size;
    dbManagerCompressedFileInfo.size = dbManagerMinifiedFileInfo.size;
    console.log(' Hashing the BLOB DB Manager minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/db-manager.min.html', 'utf8'));
    dbManagerMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/db-manager.info.json', JSON.stringify(dbManagerMinifiedFileInfo));
    shell.rm('-rf', 'db-manager.html');
    console.log(' Compresssing the BLOB DB Manager minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/db-manager.min.html');
    var out = fs.createWriteStream('compressed/db-manager.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the BLOB DB Manager compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/db-manager.min.html.gz', 'utf8'));
    dbManagerCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/db-manager.info.json', JSON.stringify(dbManagerCompressedFileInfo));
    console.log(' The BLOB DB Manager for Jste Framework Live Version has been built properly ;) ');
    shell.cd('../');
    shell.rm('-rf', 'tmp');
    if (global.gitURLPrefix) {
        console.log(' ');
        console.log(' Updating the index ');
        shell.exec('git add .');
        console.log(' ');
        console.log(' Recording the change to the local repo ');
        shell.exec('git commit -m "' + global.commitMessage + '"');
        console.log(' ');
        console.log(' Pushing the updates to GitHub ');
        shell.exec('git push ' + gitURLPrefix + 'framework.git master');
    }
    if (shell.test('-d', '../manager')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager ');
        shell.cd('../manager');
        console.log(' ');
        console.log(' Updating framework file ');
        fse.copySync('../framework/build/compressed/framework.min.html.gz', 'src/assets/framework.min.html');
        console.log(' ');
        console.log(' Starting building Jste Manager ');
        shell.exec('node build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager.git master');
        }
    }
    if (shell.test('-d', '../manager-heroku')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager Heroku version ');
        shell.cd('../manager-heroku');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp(['../framework/build/compressed/framework-LiveVersion.min.html.gz', '../framework/build/compressed/db-manager.min.html.gz'], 'assets');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-heroku.git master');
            console.log(' ');
            console.log(' Pushing the updates to Heroku ');
            shell.exec('git push heroku master');
        }
    }
    if (shell.test('-d', '../manager-phone')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager phone version ');
        shell.cd('../manager-phone/src');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('../../framework/build/minified/framework.min.html', 'www/jxcore/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager phone version ');
        shell.exec('cordova build');
        shell.cd('../');
        shell.cp('src/platforms/android/build/outputs/apk/debug/android-debug.apk', 'build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-phone.git master');
        }
    }
}

figlet('JSTE FRAMEWORK', function (err, data) {
    console.log(data);
    console.log('');
    console.log(' Welcome to Jste Framework builder :) ')
    inquirer
        .prompt([{
            type: 'confirm',
            name: 'deploy',
            message: 'Do you want to deploy this build ?'
        }])
        .then(options => {
            if (options.deploy == true) {
                inquirer
                    .prompt([{
                        type: 'input',
                        name: 'commit_message',
                        message: 'Please enter the commit message '
                    },{
                            type: 'input',
                            name: 'git_username',
                            message: 'Please enter your GitHub username '
                        },
                        {
                            type: 'password',
                            name: 'git_password',
                            mask: '*',
                            message: 'Please enter your GitHub password '
                        }
                    ]).then(git_info => {
                        global.gitURLPrefix = 'https://' + git_info.git_username + ':' + git_info.git_password + '@github.com/project-jste/';
                        global.commitMessage = git_info.commit_message;
                        startBuild();
                    })
            } else {
                startBuild();
            }
        });
});<commit_msg>Bug Fixes<commit_after>const fse = require('fs-extra');
const os = require('os');
const inquirer = require('inquirer');
const crypto = require('crypto')
const zlib = require('zlib');
const fs = require('fs');
const shell = require('shelljs');
const figlet = require('figlet');
const path = require("path");
const replace = require("replace");
const Datauri = require('datauri').sync;
const absolutePath = path.resolve(".");
const algorithm = 'sha1';

function startBuild() {
    console.log(' Preparing for building Jste Framework ');
    shell.rm('-rf', 'tmp');
    shell.mkdir('tmp');
    shell.ln('-sf', absolutePath + '/src', 'tmp/src');
    shell.cd('build');
    shell.rm('-rf', '*');
    shell.mkdir('minified', 'compressed');
    fse.copySync(absolutePath + '/src/JS/Core/analyzeCommand-CompilationTemplate.js', absolutePath + '/tmp/analyzeCommand-Compiled.js');
    fse.copySync(absolutePath + '/src/JS/Core/wordsTranslationsInit-CompilationTemplate.js', absolutePath + '/tmp/wordsTranslationsInit-Compiled.js');
    fse.copySync(absolutePath + '/src/Res.html', absolutePath + '/tmp/Res.html');
    fse.copySync(absolutePath + '/src/Res-LiveVersion.html', absolutePath + '/tmp/Res-LiveVersion.html');
    var langCodes = ['en', 'fr', 'ar', 'arz'];
    for (var i = 0; i < langCodes.length; i++) {
        replace({
            regex: langCodes[i].toUpperCase() + "_RIVESCRIPT",
            replacement: Datauri(absolutePath + '/src/JS/Translations/RiveScript/' + langCodes[i] + '.rive'),
            paths: [absolutePath + '/tmp/analyzeCommand-Compiled.js'],
            recursive: true,
            silent: true,
        });
    }
    replace({
        regex: "DICTIONARY_URL",
        replacement: Datauri(absolutePath + '/src/JS/Translations/words.json'),
        paths: [absolutePath + '/tmp/wordsTranslationsInit-Compiled.js'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src="(?!http)',
        replacement: 'src="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'href="(?!http)',
        replacement: 'href="src/',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/wordsTranslationsInit\.js',
        replacement: 'wordsTranslationsInit-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    replace({
        regex: 'src/JS/Core/analyzeCommand\.js',
        replacement: 'analyzeCommand-Compiled.js',
        paths: [absolutePath + '/tmp/Res.html', absolutePath + '/tmp/Res-LiveVersion.html'],
        recursive: true,
        silent: true
    });
    console.log(' ');
    console.log(' Starting building Jste Framework ');
    var frameworkMinifiedFileInfo = {};
    var frameworkCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework.min.html');
    frameworkMinifiedFileInfo.size = fs.statSync('minified/framework.min.html').size;
    frameworkCompressedFileInfo.size = frameworkMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework.min.html', 'utf8'));
    frameworkMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework.info.json', JSON.stringify(frameworkMinifiedFileInfo));
    shell.rm('-rf', 'framework.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework.min.html');
    var out = fs.createWriteStream('compressed/framework.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework.min.html.gz', 'utf8'));
    frameworkCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework.info.json', JSON.stringify(frameworkCompressedFileInfo));
    console.log(' Jste Framework has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building Jste Framework Live Version ');
    var frameworkLiveVersionMinifiedFileInfo = {};
    var frameworkLiveVersionCompressedFileInfo = {};
    console.log(' Bundling the framework files into one HTML file ');
    shell.exec('polymer-bundler -r ' + absolutePath + '/tmp Res-LiveVersion.html  --strip-comments --inline-scripts --inline-css --rewrite-urls-in-templates > framework-LiveVersion.html');
    console.log(' Minifying the framework bundled file ');
    shell.exec('html-minifier framework-LiveVersion.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/framework-LiveVersion.min.html');
    frameworkLiveVersionMinifiedFileInfo.size = fs.statSync('minified/framework-LiveVersion.min.html').size;
    frameworkLiveVersionCompressedFileInfo.size = frameworkLiveVersionMinifiedFileInfo.size;
    console.log(' Hashing the framework minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/framework-LiveVersion.min.html', 'utf8'));
    frameworkLiveVersionMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionMinifiedFileInfo));
    shell.rm('-rf', 'framework-LiveVersion.html');
    console.log(' Compresssing the framework minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/framework-LiveVersion.min.html');
    var out = fs.createWriteStream('compressed/framework-LiveVersion.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the framework compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/framework-LiveVersion.min.html.gz', 'utf8'));
    frameworkLiveVersionCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/framework-LiveVersion.info.json', JSON.stringify(frameworkLiveVersionCompressedFileInfo));
    console.log(' Jste Framework Live Version has been built properly ;) ');
    console.log(' ');
    console.log(' Starting building the BLOB DB Manager for Jste Framework Live Version ');
    var dbManagerMinifiedFileInfo = {};
    var dbManagerCompressedFileInfo = {};
    console.log(' Minifying the BLOB DB Manager file ');
    shell.exec('html-minifier ../utils/db-manager.html --remove-comments --minify-css --minify-js --remove-comments --use-short-doctype > minified/db-manager.min.html');
    dbManagerMinifiedFileInfo.size = fs.statSync('minified/db-manager.min.html').size;
    dbManagerCompressedFileInfo.size = dbManagerMinifiedFileInfo.size;
    console.log(' Hashing the BLOB DB Manager minified file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('minified/db-manager.min.html', 'utf8'));
    dbManagerMinifiedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('minified/db-manager.info.json', JSON.stringify(dbManagerMinifiedFileInfo));
    shell.rm('-rf', 'db-manager.html');
    console.log(' Compresssing the BLOB DB Manager minified file ');
    var gzip = zlib.createGzip();
    var inp = fs.createReadStream('minified/db-manager.min.html');
    var out = fs.createWriteStream('compressed/db-manager.min.html.gz');
    inp.pipe(gzip).pipe(out);
    console.log(' Hashing the BLOB DB Manager compressed file ');
    var shasum = crypto.createHash(algorithm);
    shasum.update(fs.readFileSync('compressed/db-manager.min.html.gz', 'utf8'));
    dbManagerCompressedFileInfo.sha1 = shasum.digest('hex');
    fs.writeFileSync('compressed/db-manager.info.json', JSON.stringify(dbManagerCompressedFileInfo));
    console.log(' The BLOB DB Manager for Jste Framework Live Version has been built properly ;) ');
    shell.cd('../');
    shell.rm('-rf', 'tmp');
    if (global.gitURLPrefix) {
        console.log(' ');
        console.log(' Updating the index ');
        shell.exec('git add .');
        console.log(' ');
        console.log(' Recording the change to the local repo ');
        shell.exec('git commit -m "' + global.commitMessage + '"');
        console.log(' ');
        console.log(' Pushing the updates to GitHub ');
        shell.exec('git push ' + gitURLPrefix + 'framework.git master');
    }
    if (shell.test('-d', '../manager')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager ');
        shell.cd('../manager');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('../framework/build/minified/framework.min.html', 'src/assets');
        var gzip = zlib.createGzip();
        var inp = fs.createReadStream('src/assets/framework.min.html');
        var out = fs.createWriteStream('src/assets/framework.min.html.gz');
        inp.pipe(gzip).pipe(out);
        shell.rm('-rf', 'src/assets/framework.min.html');
        console.log(' ');
        console.log(' Starting building Jste Manager ');
        shell.exec('node build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager.git master');
        }
    }
    if (shell.test('-d', '../manager-heroku')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager Heroku version ');
        shell.cd('../manager-heroku');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp(['../framework/build/compressed/framework-LiveVersion.min.html.gz', '../framework/build/compressed/db-manager.min.html.gz'], 'assets');
        var gzip = zlib.createGzip();
        var inp = fs.createReadStream('assets/framework-LiveVersion.min.html');
        var out = fs.createWriteStream('assets/framework-LiveVersion.min.html.gz');
        inp.pipe(gzip).pipe(out);
        shell.rm('-rf', 'assets/framework-LiveVersion.min.html');
        var gzip = zlib.createGzip();
        var inp = fs.createReadStream('assets/db-manager.min.html');
        var out = fs.createWriteStream('assets/db-manager.min.html.gz');
        inp.pipe(gzip).pipe(out);
        shell.rm('-rf', 'assets/db-manager.min.html');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-heroku.git master');
            console.log(' ');
            console.log(' Pushing the updates to Heroku ');
            shell.exec('git push heroku master');
        }
    }
    if (shell.test('-d', '../manager-phone')) {
        console.log(' ');
        console.log(' Preparing for building Jste Manager phone version ');
        shell.cd('../manager-phone/src');
        console.log(' ');
        console.log(' Updating framework file ');
        shell.cp('../../framework/build/minified/framework.min.html', 'www/jxcore/assets');
        console.log(' ');
        console.log(' Starting building Jste Manager phone version ');
        shell.exec('cordova build');
        shell.cd('../');
        shell.cp('src/platforms/android/build/outputs/apk/debug/android-debug.apk', 'build');
        if (global.gitURLPrefix) {
            console.log(' ');
            console.log(' Updating the index ');
            shell.exec('git add .');
            console.log(' ');
            console.log(' Recording the change to the local repo ');
            shell.exec('git commit -m "Updating Framework Files"');
            console.log(' ');
            console.log(' Pushing the updates to GitHub ');
            shell.exec('git push ' + gitURLPrefix + 'manager-phone.git master');
        }
    }
}

figlet('JSTE FRAMEWORK', function (err, data) {
    console.log(data);
    console.log('');
    console.log(' Welcome to Jste Framework builder :) ')
    inquirer
        .prompt([{
            type: 'confirm',
            name: 'deploy',
            message: 'Do you want to deploy this build ?'
        }])
        .then(options => {
            if (options.deploy == true) {
                inquirer
                    .prompt([{
                            type: 'input',
                            name: 'commit_message',
                            message: 'Please enter the commit message '
                        }, {
                            type: 'input',
                            name: 'git_username',
                            message: 'Please enter your GitHub username '
                        },
                        {
                            type: 'password',
                            name: 'git_password',
                            mask: '*',
                            message: 'Please enter your GitHub password '
                        }
                    ]).then(git_info => {
                        global.gitURLPrefix = 'https://' + git_info.git_username + ':' + git_info.git_password + '@github.com/project-jste/';
                        global.commitMessage = git_info.commit_message;
                        startBuild();
                    })
            } else {
                startBuild();
            }
        });
});<|endoftext|>


<commit_before>/**
 * @file This file contains functions and bindings for the UserFrosting project management pages.
 *
 * @author Alex Weissman
 * @license MIT
 */

/**
 * Display a modal form for updating/creating a project.
 *
 * @todo This function is highly redundant with userForm.  Can we refactor?
 */
function formGeneratorDisplay(button) {

	var box_id = $(button).data('target');
	if (box_id == undefined) {
		box_id = "formGeneratorModal";
	}

	// Delete any existing instance of the form with the same name
	if($('#' + box_id).length ) {
		$('#' + box_id).remove();
	}

	// Fetch and render the form
	$.ajax({
	  type: "GET",
	  url: $(button).data('formurl'),
	  data: {
		box_id: box_id,
		bData: $(button).data()
	  },
	  cache: false
	})
	.fail(function(result) {
        // Display errors on failure
        console.log("Error (" + result.status + "): " + result.responseText );
        //base.options.msgTarget.ufAlerts().ufAlerts('fetch').ufAlerts('render');
        //$('#userfrosting-alerts').flashAlerts().done(function() {});
	})
	.done(function(result) {

        // Append the form as a modal dialog to the body
		$( "body" ).append(result);
		$('#' + box_id).modal('show');

		// Setup the loaded form with ufForm
		$('#' + box_id).find("form").ufForm({
            validators: validators,
            msgTarget: $("#"+box_id+"_alert")
        }).on("submitSuccess.ufForm", function() {
            // Forward to settings page on success
            window.location.reload(true);
        }).on("submitError.ufForm", function() {
            $("#"+box_id+"_alert").show();
        });
	});
}

function formGeneratorConfirm(button){

	var box_id = $(button).data('target');
	if (box_id == undefined) {
		box_id = "formGeneratorModal";
	}

	// Delete any existing instance of the form with the same name
	if($('#' + box_id).length ) {
		$('#' + box_id).remove();
	}

	//Prepare the data
	var data = {
		box_id: box_id,
		box_title: $(button).data('confirmTitle') ? $(button).data('confirmTitle') : "Deleting",
		confirm_message: $(button).data('confirmMessage') ? $(button).data('confirmMessage') : "Are you sure you want to delete this?",
		confirm_button: $(button).data('confirmButton') ? $(button).data('confirmButton') : "Yes, delete",
		bData: $(button).data()
	};

	// Generate the form
	$.ajax({
	  type: "GET",
	  url: $(button).data('formurl') ? $(button).data('formurl') : site['uri']['public'] + "/forms/confirm",
	  data: data
	})
	.fail(function(result) {
        // Display errors on failure
        console.log("Error (" + result.status + "): " + result.responseText );
        base.options.msgTarget.ufAlerts().ufAlerts('fetch').ufAlerts('render');
	})
	.done(function(result) {
		// Append the form as a modal dialog to the body
		$( "body" ).append(result);
		$('#' + box_id).modal('show');
		$('#' + box_id + ' .js-confirm').click(function(){

            var url = $(button).data('postUrl');
            var data = {
                bData: $(button).data(),
                csrf_name: $('#' + box_id).find("input[name='csrf_name']").val(),
                csrf_value: $('#' + box_id).find("input[name='csrf_value']").val()
            };

            $.ajax({
              type: "POST",
              url: url,
              data: data
            }).done(function(result) {
              // Reload the page
              window.location.reload();
            }).fail(function(jqXHR) {
                if (site['debug'] == true) {
                    document.body.innerHTML = jqXHR.responseText;
                } else {
                    console.log("Error (" + jqXHR.status + "): " + jqXHR.responseText );
                }
                //base.options.msgTarget.ufAlerts().ufAlerts('fetch').ufAlerts('render');
/*
                $('#userfrosting-alerts').flashAlerts().done(function() {
                    // Close the dialog
                    $('#' + box_id).modal('hide');
                });
*/
            });
        });
	});
}<commit_msg>Temporary ufAlerts implementation<commit_after>/**
 * @file This file contains functions and bindings for the UserFrosting project management pages.
 *
 * @author Alex Weissman
 * @license MIT
 */

/**
 * Display a modal form for updating/creating a project.
 *
 * @todo This function is highly redundant with userForm.  Can we refactor?
 */
function formGeneratorDisplay(button) {

	var box_id = $(button).data('target');
	if (box_id == undefined) {
		box_id = "formGeneratorModal";
	}

	// Delete any existing instance of the form with the same name
	if($('#' + box_id).length ) {
		$('#' + box_id).remove();
	}

	// Fetch and render the form
	$.ajax({
	  type: "GET",
	  url: $(button).data('formurl'),
	  data: {
		box_id: box_id,
		bData: $(button).data()
	  },
	  cache: false
	})
	.fail(function(result) {
        // Display errors on failure
        console.log("Error (" + result.status + "): " + result.responseText );
        $("#alerts-main").ufAlerts('clear').ufAlerts('fetch').ufAlerts('render');
	})
	.done(function(result) {

        // Append the form as a modal dialog to the body
		$( "body" ).append(result);
		$('#' + box_id).modal('show');

		// Setup the loaded form with ufForm
		$('#' + box_id).find("form").ufForm({
            validators: validators,
            msgTarget: $("#"+box_id+"_alert")
        }).on("submitSuccess.ufForm", function() {
            // Forward to settings page on success
            window.location.reload(true);
        }).on("submitError.ufForm", function() {
            $("#"+box_id+"_alert").show();
        });
	});
}

function formGeneratorConfirm(button){

	var box_id = $(button).data('target');
	if (box_id == undefined) {
		box_id = "formGeneratorModal";
	}

	// Delete any existing instance of the form with the same name
	if($('#' + box_id).length ) {
		$('#' + box_id).remove();
	}

	//Prepare the data
	var data = {
		box_id: box_id,
		box_title: $(button).data('confirmTitle') ? $(button).data('confirmTitle') : "Deleting",
		confirm_message: $(button).data('confirmMessage') ? $(button).data('confirmMessage') : "Are you sure you want to delete this?",
		confirm_button: $(button).data('confirmButton') ? $(button).data('confirmButton') : "Yes, delete",
		bData: $(button).data()
	};

	// Generate the form
	$.ajax({
	  type: "GET",
	  url: $(button).data('formurl') ? $(button).data('formurl') : site['uri']['public'] + "/forms/confirm",
	  data: data
	})
	.fail(function(result) {
        // Display errors on failure
        console.log("Error (" + result.status + "): " + result.responseText );
        $("#alerts-main").ufAlerts('clear').ufAlerts('fetch').ufAlerts('render');
	})
	.done(function(result) {
		// Append the form as a modal dialog to the body
		$( "body" ).append(result);
		$('#' + box_id).modal('show');
		$('#' + box_id + ' .js-confirm').click(function(){

            var url = $(button).data('postUrl');
            var data = {
                bData: $(button).data(),
                csrf_name: $('#' + box_id).find("input[name='csrf_name']").val(),
                csrf_value: $('#' + box_id).find("input[name='csrf_value']").val()
            };

            $.ajax({
              type: "POST",
              url: url,
              data: data
            }).done(function(result) {
              // Reload the page
              window.location.reload();
            }).fail(function(jqXHR) {
                if (site['debug'] == true) {
                    document.body.innerHTML = jqXHR.responseText;
                } else {
                    console.log("Error (" + jqXHR.status + "): " + jqXHR.responseText );
                }
                //base.options.msgTarget.ufAlerts().ufAlerts('fetch').ufAlerts('render');
/*
                $('#userfrosting-alerts').flashAlerts().done(function() {
                    // Close the dialog
                    $('#' + box_id).modal('hide');
                });
*/
            });
        });
	});
}<|endoftext|>