<commit_before>import PropTypes from 'prop-types'
import React, {useState} from 'react'

import FormNavigationButtons from './form-navigation-buttons'
import { PageHeading, StackedPaneContainer } from './styled'

/**
 * This component handles the flow between screens for new OTP user accounts.
 */
const StackedPaneDisplay = ({ onCancel, paneSequence, title }) => {
  // Create indicator of if cancel button was clicked so that child components can know
  const [isBeingCanceled, updateBeingCanceled] = useState(false)

  return (
    <>
      {title && <PageHeading>{title}</PageHeading>}
      {
        paneSequence.map(({ pane: Pane, props, title }, index) => (
          <StackedPaneContainer key={index}>

{title}

<Pane canceled={isBeingCanceled} {...props} />

          </StackedPaneContainer>
        ))
      }

      <FormNavigationButtons
        backButton={{
          onClick: () => { updateBeingCanceled(true); onCancel() },
          text: 'Cancel'
        }}
        okayButton={{
          text: 'Save Preferences',
          type: 'submit'
        }}
      />
    </>)
}

StackedPaneDisplay.propTypes = {
  onCancel: PropTypes.func.isRequired,
  paneSequence: PropTypes.array.isRequired
}

export default StackedPaneDisplay
<commit_msg>style(stacked-pane-display.js): remove semicolons<commit_after>import PropTypes from 'prop-types'
import React, {useState} from 'react'

import FormNavigationButtons from './form-navigation-buttons'
import { PageHeading, StackedPaneContainer } from './styled'

/**
 * This component handles the flow between screens for new OTP user accounts.
 */
const StackedPaneDisplay = ({ onCancel, paneSequence, title }) => {
  // Create indicator of if cancel button was clicked so that child components can know
  const [isBeingCanceled, updateBeingCanceled] = useState(false)

  return (
    <>
      {title && <PageHeading>{title}</PageHeading>}
      {paneSequence.map(({ pane: Pane, props, title }, index) => (
        <StackedPaneContainer key={index}>

{title}

            <Pane canceled={isBeingCanceled} {...props} />

        </StackedPaneContainer>
      ))}

      <FormNavigationButtons
        backButton={{
          onClick: () => {
            updateBeingCanceled(true)
            onCancel()
          },
          text: 'Cancel'
        }}
        okayButton={{
          text: 'Save Preferences',
          type: 'submit'
        }}
      />
    </>
  )
}

StackedPaneDisplay.propTypes = {
  onCancel: PropTypes.func.isRequired,
  paneSequence: PropTypes.array.isRequired
}

export default StackedPaneDisplay
<|endoftext|>


<commit_before>/**
 * Functions to run a tool from the tools page.
 */

function cea_run(script) {
    if(!$('#cea-tool-parameters').parsley().isValid()) return false;
    $('.cea-modal-close').attr('disabled', 'disabled').removeClass('btn-danger').removeClass('btn-success');
    $('#cea-console-output-body').text('');
    $('#cea-console-output').modal({'show': true, 'backdrop': 'static'});

    let new_job_info = {"script": script, "parameters": get_parameter_values()};
    console.log("new_job_info", new_job_info);
    $.post('/server/jobs/new', new_job_info, function(job_info) {
        console.log("About to run job_info", job_info);
        $.post(`start/${job_info.id}`, function() {
            let socket = io.connect(`http://${document.domain}:${location.port}`);
            let $cea_modal_close = $(".cea-modal-close");
            let message_appender = function(data){
                $('#cea-console-output-body').append(data.message);
            };
            socket.on("cea-worker-message", message_appender);
            socket.on('cea-worker-success', function() {
                $cea_modal_close.addClass("btn-success");
                socket.removeListener("cea-worker-message", message_appender);
            });
            socket.on('cea-worker-error', function() {
                $cea_modal_close.removeAttr("disabled");
                $(".cea-modal-close").addClass("btn-danger");
                socket.removeListener("cea-worker-message", message_appender);
            });
        });
    }, "json");
}

function cea_save_config(script) {
    if(!$('#cea-tool-parameters').parsley().isValid()) return false;
    $('#cea-save-config-modal').modal({'show': true, 'backdrop': 'static'});
    $.post('save-config/' + script, get_parameter_values(), null, 'json');
    $('#cea-save-config-modal').modal('hide');
}

/**
 * Read the values of all the parameters.
 */
function get_parameter_values() {
    var result = {};
    $('.cea-parameter').not('bootstrap-select').each((index, element) => {
        console.log('Reading parameter: ' + element.id);
        result[element.id] = read_value(element);
    });
    console.log(result);
    return result;
}

/**
 * Update the div#cea-console-output-body with the output of the script until it is done.
 * @param script
 */
function update_output(script) {
    $.getJSON('read/' + script, {}, function(msg) {
       if (msg === null) {
           $.getJSON('is-alive/' + script, {}, function(msg) {
               if (msg) {
                   setTimeout(update_output, 1000, script);
               } else {
                   $('.cea-modal-close').removeAttr('disabled');
                   $.getJSON('exitcode/' + script, {}, function(msg){
                      if (msg === 0) {
                          $('.cea-modal-close').addClass('btn-success');
                      } else {
                          $('.cea-modal-close').addClass('btn-danger');
                      }
                   });
               }
           });

       }
       else {
           $('#cea-console-output-body').append(msg.message);
           setTimeout(update_output, 1000, script);
       }
    });
}

/**
 * Read out the value of the parameter as defined by the form input - this depends on the parameter_type.
 *
 * @param script
 * @param parameter_name
 * @param parameter_type
 */
function read_value(element) {
    let value = null;
    switch (element.dataset.ceaParameterTypename) {
        case "ChoiceParameter":
        case "ScenarioNameParameter":
            value = $(element)[0].value;
            break;
        case "WeatherPathParameter":
            value = $(element)[0].value;
            break;
        case "BooleanParameter":
            value = $(element)[0].checked;
            break;
        case "PathParameter":
            value = $(element)[0].value;
            break;
        case "MultiChoiceParameter":
        case "BuildingsParameter":
            value = $(element).val();
            if (value) {
                value = value.join();
            }
            else {
                value = [];
            }
            break;
        case "SubfoldersParameter":
            value = $(element).val();
            break;
        case "JsonParameter":
            value = JSON.parse($(element).val());
            break;
        default:
            // handle the default case
            value = $(element)[0].value;
    }
    return value;
}

/**
 * Show an open file dialog for a cea FileParameter and update the contents of the
 * input field.
 *
 * @param parameter_name
 */
function show_open_file_dialog(parameter_fqname,) {
    $.get('open-file-dialog/' + parameter_fqname, {}, function(html) {
        $('#cea-file-dialog .modal-content').html(html);
        $('#cea-file-dialog').modal({'show': true, 'backdrop': 'static'});
    });
}

/**
 * Navigate the open file dialog to a new folder.
 * @param parameter_fqname
 */
function file_dialog_navigate_to(parameter_fqname, current_folder, folder) {
    $.get('open-file-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) {
        $('#cea-file-dialog .modal-content').html(html);
    });
}

/**
 * User selected a file, highlight it.
 * @param link
 * @param file
 */
function select_file(link) {
    $('.cea-file-listing a').removeClass('bg-primary');
    $(link).addClass('bg-primary');
    $('#cea-file-dialog-select-button').prop('disabled', false);
}

/**
 * Save the selected file name (full path) to the input[type=text] with the id <target_id>.
 * @param target_id
 */
function save_file_name(target_id) {
    // figure out file path
    var file_path = $('.cea-file-listing a.bg-primary').data('save-file-path');
    $('#' + target_id).val(file_path);
}

/**
 * Show an open folder dialog for a cea PathParameter and update the contents of the
 * input field.
 *
 * @param parameter_name
 */
function show_open_folder_dialog(parameter_fqname,) {
    $.get('open-folder-dialog/' + parameter_fqname, {}, function(html) {
        $('#cea-folder-dialog .modal-content').html(html);
        $('#cea-folder-dialog').modal({'show': true, 'backdrop': 'static'});
    });
}

/**
 * Navigate the open file dialog to a new folder.
 * @param parameter_fqname
 * @param current_folder
 * @param folder
 */
function folder_dialog_navigate_to(parameter_fqname, current_folder, folder) {
    $.get('open-folder-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) {
        $('#cea-folder-dialog .modal-content').html(html);
    });
}

/**
 * Save the selected folder name (full path) to the input[type=text] with the id <target_id>.
 * @param target_id
 * @param folder_path
 */
function save_folder_name(target_id, folder_path) {
    // figure out folder path
    $('#' + target_id).val(folder_path).trigger("input").trigger("change");
    console.log(target_id)
}
<commit_msg>allow closing of modal dialog on success<commit_after>/**
 * Functions to run a tool from the tools page.
 */

function cea_run(script) {
    if(!$('#cea-tool-parameters').parsley().isValid()) return false;
    $('.cea-modal-close').attr('disabled', 'disabled').removeClass('btn-danger').removeClass('btn-success');
    $('#cea-console-output-body').text('');
    $('#cea-console-output').modal({'show': true, 'backdrop': 'static'});

    let new_job_info = {"script": script, "parameters": get_parameter_values()};
    console.log("new_job_info", new_job_info);
    $.post('/server/jobs/new', new_job_info, function(job_info) {
        console.log("About to run job_info", job_info);
        $.post(`start/${job_info.id}`, function() {
            let socket = io.connect(`http://${document.domain}:${location.port}`);
            let $cea_modal_close = $(".cea-modal-close");
            let message_appender = function(data){
                $('#cea-console-output-body').append(data.message);
            };
            socket.on("cea-worker-message", message_appender);
            socket.on('cea-worker-success', function() {
                $cea_modal_close.removeAttr("disabled");
                $cea_modal_close.addClass("btn-success");
                socket.removeListener("cea-worker-message", message_appender);
            });
            socket.on('cea-worker-error', function() {
                $cea_modal_close.removeAttr("disabled");
                $(".cea-modal-close").addClass("btn-danger");
                socket.removeListener("cea-worker-message", message_appender);
            });
        });
    }, "json");
}

function cea_save_config(script) {
    if(!$('#cea-tool-parameters').parsley().isValid()) return false;
    $('#cea-save-config-modal').modal({'show': true, 'backdrop': 'static'});
    $.post('save-config/' + script, get_parameter_values(), null, 'json');
    $('#cea-save-config-modal').modal('hide');
}

/**
 * Read the values of all the parameters.
 */
function get_parameter_values() {
    var result = {};
    $('.cea-parameter').not('bootstrap-select').each((index, element) => {
        console.log('Reading parameter: ' + element.id);
        result[element.id] = read_value(element);
    });
    console.log(result);
    return result;
}

/**
 * Update the div#cea-console-output-body with the output of the script until it is done.
 * @param script
 */
function update_output(script) {
    $.getJSON('read/' + script, {}, function(msg) {
       if (msg === null) {
           $.getJSON('is-alive/' + script, {}, function(msg) {
               if (msg) {
                   setTimeout(update_output, 1000, script);
               } else {
                   $('.cea-modal-close').removeAttr('disabled');
                   $.getJSON('exitcode/' + script, {}, function(msg){
                      if (msg === 0) {
                          $('.cea-modal-close').addClass('btn-success');
                      } else {
                          $('.cea-modal-close').addClass('btn-danger');
                      }
                   });
               }
           });

       }
       else {
           $('#cea-console-output-body').append(msg.message);
           setTimeout(update_output, 1000, script);
       }
    });
}

/**
 * Read out the value of the parameter as defined by the form input - this depends on the parameter_type.
 *
 * @param script
 * @param parameter_name
 * @param parameter_type
 */
function read_value(element) {
    let value = null;
    switch (element.dataset.ceaParameterTypename) {
        case "ChoiceParameter":
        case "ScenarioNameParameter":
            value = $(element)[0].value;
            break;
        case "WeatherPathParameter":
            value = $(element)[0].value;
            break;
        case "BooleanParameter":
            value = $(element)[0].checked;
            break;
        case "PathParameter":
            value = $(element)[0].value;
            break;
        case "MultiChoiceParameter":
        case "BuildingsParameter":
            value = $(element).val();
            if (value) {
                value = value.join();
            }
            else {
                value = [];
            }
            break;
        case "SubfoldersParameter":
            value = $(element).val();
            break;
        case "JsonParameter":
            value = JSON.parse($(element).val());
            break;
        default:
            // handle the default case
            value = $(element)[0].value;
    }
    return value;
}

/**
 * Show an open file dialog for a cea FileParameter and update the contents of the
 * input field.
 *
 * @param parameter_name
 */
function show_open_file_dialog(parameter_fqname,) {
    $.get('open-file-dialog/' + parameter_fqname, {}, function(html) {
        $('#cea-file-dialog .modal-content').html(html);
        $('#cea-file-dialog').modal({'show': true, 'backdrop': 'static'});
    });
}

/**
 * Navigate the open file dialog to a new folder.
 * @param parameter_fqname
 */
function file_dialog_navigate_to(parameter_fqname, current_folder, folder) {
    $.get('open-file-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) {
        $('#cea-file-dialog .modal-content').html(html);
    });
}

/**
 * User selected a file, highlight it.
 * @param link
 * @param file
 */
function select_file(link) {
    $('.cea-file-listing a').removeClass('bg-primary');
    $(link).addClass('bg-primary');
    $('#cea-file-dialog-select-button').prop('disabled', false);
}

/**
 * Save the selected file name (full path) to the input[type=text] with the id <target_id>.
 * @param target_id
 */
function save_file_name(target_id) {
    // figure out file path
    var file_path = $('.cea-file-listing a.bg-primary').data('save-file-path');
    $('#' + target_id).val(file_path);
}

/**
 * Show an open folder dialog for a cea PathParameter and update the contents of the
 * input field.
 *
 * @param parameter_name
 */
function show_open_folder_dialog(parameter_fqname,) {
    $.get('open-folder-dialog/' + parameter_fqname, {}, function(html) {
        $('#cea-folder-dialog .modal-content').html(html);
        $('#cea-folder-dialog').modal({'show': true, 'backdrop': 'static'});
    });
}

/**
 * Navigate the open file dialog to a new folder.
 * @param parameter_fqname
 * @param current_folder
 * @param folder
 */
function folder_dialog_navigate_to(parameter_fqname, current_folder, folder) {
    $.get('open-folder-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) {
        $('#cea-folder-dialog .modal-content').html(html);
    });
}

/**
 * Save the selected folder name (full path) to the input[type=text] with the id <target_id>.
 * @param target_id
 * @param folder_path
 */
function save_folder_name(target_id, folder_path) {
    // figure out folder path
    $('#' + target_id).val(folder_path).trigger("input").trigger("change");
    console.log(target_id)
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {graphql, createFragmentContainer} from 'react-relay';

import {SearchPropType, RemotePropType, BranchSetPropType} from '../prop-types';
import IssueishListView from '../views/issueish-list-view';
import Issueish from '../models/issueish';

export class BareIssueishListController extends React.Component {
  static propTypes = {
    results: PropTypes.shape({
      issueCount: PropTypes.number.isRequired,
      nodes: PropTypes.arrayOf(
        PropTypes.shape({
          number: PropTypes.number.isRequired,
          title: PropTypes.string.isRequired,
          url: PropTypes.string.isRequired,
          author: PropTypes.shape({
            login: PropTypes.string.isRequired,
            avatarUrl: PropTypes.string.isRequired,
          }).isRequired,
          createdAt: PropTypes.string.isRequired,
          headRefName: PropTypes.string.isRequired,
          headRepository: PropTypes.shape({
            nameWithOwner: PropTypes.string.isRequired,
          }).isRequired,
        }),
      ),
    }),
    repository: PropTypes.shape({
      defaultBranchRef: PropTypes.string,
    }),

    search: SearchPropType.isRequired,
    remote: RemotePropType.isRequired,
    branches: BranchSetPropType.isRequired,
    aheadCount: PropTypes.number.isRequired,
    pushInProgress: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,

    onCreatePr: PropTypes.func.isRequired,
  };

  static defaultProps = {
    results: {
      issueCount: 0,
      nodes: [],
    },
  }

  constructor(props) {
    super(props);

    this.state = {};
  }

  static getDerivedStateFromProps(props, state) {
    if (props.results === null) {
      return {
        isLoading: true,
        total: 0,
        issueishes: [],
      };
    }

    return {
      isLoading: false,
      total: props.results.issueCount,
      issueishes: props.results.nodes.map(node => new Issueish(node)),
    };
  }

  render() {
    return (
      <IssueishListView
        search={this.props.search}
        isLoading={this.state.isLoading}
        total={this.state.total}
        issueishes={this.state.issueishes}

        repository={this.props.repository}

        remote={this.props.remote}
        branches={this.props.branches}
        aheadCount={this.props.aheadCount}
        pushInProgress={this.props.pushInProgress}

        onCreatePr={this.props.onCreatePr}
      />
    );
  }
}

export default createFragmentContainer(BareIssueishListController, {
  results: graphql`
    fragment issueishListController_results on SearchResultItemConnection {
      issueCount
      nodes {
        ... on PullRequest {
          number
          title
          url
          author {
            login
            avatarUrl
          }
          createdAt
          headRefName
          headRepository {
            nameWithOwner
          }
        }
      }
    }
  `,
});
<commit_msg>Accept isLoading from props instead of state<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {graphql, createFragmentContainer} from 'react-relay';

import {SearchPropType, RemotePropType, BranchSetPropType} from '../prop-types';
import IssueishListView from '../views/issueish-list-view';
import Issueish from '../models/issueish';

export class BareIssueishListController extends React.Component {
  static propTypes = {
    results: PropTypes.shape({
      issueCount: PropTypes.number.isRequired,
      nodes: PropTypes.arrayOf(
        PropTypes.shape({
          number: PropTypes.number.isRequired,
          title: PropTypes.string.isRequired,
          url: PropTypes.string.isRequired,
          author: PropTypes.shape({
            login: PropTypes.string.isRequired,
            avatarUrl: PropTypes.string.isRequired,
          }).isRequired,
          createdAt: PropTypes.string.isRequired,
          headRefName: PropTypes.string.isRequired,
          headRepository: PropTypes.shape({
            nameWithOwner: PropTypes.string.isRequired,
          }).isRequired,
        }),
      ),
    }),
    repository: PropTypes.shape({
      defaultBranchRef: PropTypes.string,
    }),

    search: SearchPropType.isRequired,
    remote: RemotePropType.isRequired,
    branches: BranchSetPropType.isRequired,
    aheadCount: PropTypes.number.isRequired,
    pushInProgress: PropTypes.bool.isRequired,
    isLoading: PropTypes.bool.isRequired,

    onCreatePr: PropTypes.func.isRequired,
  };

  static defaultProps = {
    results: {
      issueCount: 0,
      nodes: [],
    },
  }

  constructor(props) {
    super(props);

    this.state = {};
  }

  static getDerivedStateFromProps(props, state) {
    if (props.results === null) {
      return {
        total: 0,
        issueishes: [],
      };
    }

    return {
      total: props.results.issueCount,
      issueishes: props.results.nodes.map(node => new Issueish(node)),
    };
  }

  render() {
    return (
      <IssueishListView
        search={this.props.search}
        isLoading={this.props.isLoading}
        total={this.state.total}
        issueishes={this.state.issueishes}

        repository={this.props.repository}

        remote={this.props.remote}
        branches={this.props.branches}
        aheadCount={this.props.aheadCount}
        pushInProgress={this.props.pushInProgress}

        onCreatePr={this.props.onCreatePr}
      />
    );
  }
}

export default createFragmentContainer(BareIssueishListController, {
  results: graphql`
    fragment issueishListController_results on SearchResultItemConnection {
      issueCount
      nodes {
        ... on PullRequest {
          number
          title
          url
          author {
            login
            avatarUrl
          }
          createdAt
          headRefName
          headRepository {
            nameWithOwner
          }
        }
      }
    }
  `,
});
<|endoftext|>


<commit_before>goog.provide('recoil.ui.widgets.table.TableWidgetTest');

goog.require('goog.testing.jsunit');
goog.require('recoil.ui.widgets.table.TableWidget');
goog.require('recoil.util');
goog.require('recoil.frp.Frp');
goog.require('recoil.ui.widgets.table.TableWidget');
goog.require('recoil.ui.widgets.TableMetaData');
goog.require('recoil.ui.widgets.ButtonWidget');
goog.require('recoil.ui.BoolWithExplanation');
goog.require('recoil.ui.WidgetScope');
goog.require('recoil.ui.widgets.table.StringColumn');
goog.require('recoil.ui.widgets.table.NumberColumn');
goog.require('recoil.ui.widgets.table.BooleanColumn');
goog.require('recoil.ui.widgets.CheckboxWidget');
goog.require('recoil.ui.widgets.table.SelectColumn');
goog.require('goog.testing.AsyncTestCase');

var typeFactories = {"int": function(meta) {
    return new recoil.ui.widgets.table.NumberColumn(meta);
}, "string": function (meta) {
    return new recoil.ui.widgets.table.StringColumn(meta);
}, "boolean": function (meta) {
    return new recoil.ui.widgets.table.BooleanColumn(meta);
}, "select": function (meta) {
    return new recoil.ui.widgets.table.SelectColumn(meta);
}};

var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
asyncTestCase.stepTimeout = 5000;
var shared = {};

function testOrderChange01() {
    shared = {
        container : goog.dom.createDom('div', {id: 'foo'}),
        scope : new recoil.ui.WidgetScope()
    };
    var frp = shared.scope.getFrp();

    var tblKeys = {
        id : new recoil.structs.table.ColumnKey("id_"),
        value : new recoil.structs.table.ColumnKey("value_")
    };

    var rawTableMeta = {
        value : { type : "string", length : 20, key : tblKeys.value},
        id : { type : "int", primary : 0, key : tblKeys.id}
    };

   var rawTable = [];

    for (var i = 4; i >= 0; i--) {
	rawTable.push({id: i, value: "row " + i});
    }

    var columns = new recoil.ui.widgets.TableMetaData();
    columns.add(tblKeys.id, "ID");
    columns.add(tblKeys.value, "Value");

    shared.tableB = frp.createB(recoil.structs.table.Table.create(typeFactories, rawTableMeta, rawTable, true));
    var tableWidget = new recoil.ui.widgets.table.TableWidget(shared.scope);

    shared.tableB.refListen(function (b) {
        console.log("referenced", b);
        asyncTestCase.continueTesting();
    });
    tableWidget.getComponent().render(shared.container);
    tableWidget.attach(shared.tableB,columns);

    assertEquals(0,frp.tm().watching());
    document.body.appendChild(shared.container);

    asyncTestCase.waitForAsync('test show table');
}

function findInput(val) {
    return goog.dom.findNode(shared.container, function (n) {

        return n.nodeName === 'INPUT' && n.value === val  && n.type === 'text';
    }) ;
}

function findVal(val) {
    return goog.dom.findNode(shared.container, function (n) {
        return n.nodeName === '#text' && n.nodeValue === val;
    }) ;
}

function getAncestor (node, type) {
    var parent = goog.dom.getParentElement(node);

    while (parent.nodeName !== type) {
        parent = goog.dom.getParentElement(parent);
    }
    return parent;
}
function testOrderChange02() {
    var frp = shared.scope.getFrp();
    var watching = frp.tm().watching();
    assertNotEquals(0,watching);

    shared.input = findInput('row 1');

    var row0 = findInput('row 0');
    assertNotUndefined(shared.input);

    var  tr1 = getAncestor(shared.input,'TR');
    var  tr0 = getAncestor(row0,'TR');

    assertTrue("init order correct",goog.dom.getNextElementSibling(tr1) === tr0);

    frp.accessTrans(function () {
        var tbl = shared.tableB.get().unfreeze();
        var row = tbl.getRow([1]).unfreeze();
        row.setPos(10);
        tbl.removeRow([1]);
        tbl.addRow(row);
        shared.tableB.set(tbl.freeze());
    },shared.tableB);

    assertTrue(findInput('row 0') === row0);
    assertTrue(findInput('row 1') === shared.input);
    assertTrue("final order correct",goog.dom.getNextElementSibling(tr0) === tr1);

    // no more behaviours should be added or removed
    assertEquals(watching,frp.tm().watching());

    document.body.removeChild(shared.container);
    asyncTestCase.waitForAsync('test remove table');
}

function testOrderChange03() {
    var frp = shared.scope.getFrp();
    assertEquals(0,frp.tm().watching());
    shared = {};
}

function testColumnChange01() {
    shared = {
        container : goog.dom.createDom('div', {id: 'foo'}),
        scope : new recoil.ui.WidgetScope()
    };
    var frp = shared.scope.getFrp();

    shared.tblKeys = {
        id : new recoil.structs.table.ColumnKey("id_"),
        v1 : new recoil.structs.table.ColumnKey("value1_"),
        v2 : new recoil.structs.table.ColumnKey("value2_"),
        v3 : new recoil.structs.table.ColumnKey("value3_"),
        v4 : new recoil.structs.table.ColumnKey("value4_"),
        v5 : new recoil.structs.table.ColumnKey("value5_")
    };
    var tblKeys = shared.tblKeys;

    var rawTableMeta = {
        v1 : { type : "string", length : 20, key : tblKeys.v1},
        v2 : { type : "string", length : 20, key : tblKeys.v2},
        v3 : { type : "string", length : 20, key : tblKeys.v3},
        v4 : { type : "string", length : 20, key : tblKeys.v4},
        v5 : { type : "string", length : 20, key : tblKeys.v5},
        id : { type : "int", primary : 0, key : tblKeys.id}
    };

   var rawTable = [];

    for (var i = 4; i >= 0; i--) {
	rawTable.push({id: i, v1: "c1 " + i, v2:"c2 " + i,v3:"c3 " + i, v4:"c4 " + i, v5:"c5 " + i});
    }

    var columns = new recoil.ui.widgets.TableMetaData();
    columns.add(tblKeys.id, "ID");
    columns.add(tblKeys.v1, "V1");
    columns.add(tblKeys.v2, "V2");
    columns.add(tblKeys.v3, "V3");
    columns.add(tblKeys.v4, "V4");

    shared.tableB = frp.createB(recoil.structs.table.Table.create(typeFactories, rawTableMeta, rawTable, true));
    var tableWidget = new recoil.ui.widgets.table.TableWidget(shared.scope);

    shared.columnsB = frp.createB(columns);
    shared.tableB.refListen(function (b) {
        asyncTestCase.continueTesting();
    });
    tableWidget.getComponent().render(shared.container);
    tableWidget.attach(shared.tableB,shared.columnsB);

    assertEquals(0,frp.tm().watching());
    document.body.appendChild(shared.container);

    asyncTestCase.waitForAsync('test show table');
}

function testColumnChange02() {
    var frp = shared.scope.getFrp();
    var watching = frp.tm().watching();
    assertNotEquals(0,watching);

    shared.id = findVal('ID');
    shared.v1 = findVal('V1');
    shared.v2 = findVal('V2');
    shared.v3 = findVal('V3');
    shared.v4 = findVal('V4');

    assertNotUndefined(shared.id);
    assertNotUndefined(shared.v1);
    assertNotUndefined(shared.v2);
    assertNotUndefined(shared.v3);
    assertNotUndefined(shared.v4);

    var  id = getAncestor(shared.id,'TH');
    var  v1 = getAncestor(shared.v1,'TH');
    var  v2 = getAncestor(shared.v2,'TH');
    var  v3 = getAncestor(shared.v3,'TH');
    var  v4 = getAncestor(shared.v4,'TH');

    assertTrue("init order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("init order correct 2",goog.dom.getNextElementSibling(v1) === v2);
    assertTrue("init order correct 3",goog.dom.getNextElementSibling(v2) === v3);
    assertTrue("init order correct 4",goog.dom.getNextElementSibling(v3) === v4);

    // swaping v1 and v3
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v4, "V4");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));
    assertEquals(shared.v4 , findVal('V4'));

    assertEquals(id,getAncestor(shared.id,'TH'));
    assertEquals(v1,getAncestor(shared.v1,'TH'));
    assertEquals(v2,getAncestor(shared.v2,'TH'));
    assertEquals(v3,getAncestor(shared.v3,'TH'));
    assertEquals(v4,getAncestor(shared.v4,'TH'));

    assertTrue("move order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("move order correct 2",goog.dom.getNextElementSibling(v1) === v3);
    assertTrue("move order correct 3",goog.dom.getNextElementSibling(v3) === v4);
    assertTrue("move order correct 4",goog.dom.getNextElementSibling(v4) === v2);

    // no more behaviours should be added or removed
    assertEquals(watching,frp.tm().watching());

    // remove v4
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));
    assertUndefined(findVal('V4'));

    assertEquals(id,getAncestor(shared.id,'TH'));
    assertEquals(v1,getAncestor(shared.v1,'TH'));
    assertEquals(v2,getAncestor(shared.v2,'TH'));
    assertEquals(v3,getAncestor(shared.v3,'TH'));

    assertTrue("remove order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("remove order correct 2",goog.dom.getNextElementSibling(v1) === v3);
    assertTrue("remove order correct 3",goog.dom.getNextElementSibling(v3) === v2);

    // add v5
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v5, "V5");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    shared.v5 = findVal('V5');
    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));

    assertEquals(id,getAncestor(shared.id,'TH'));
    assertEquals(v1,getAncestor(shared.v1,'TH'));
    assertEquals(v2,getAncestor(shared.v2,'TH'));
    assertEquals(v3,getAncestor(shared.v3,'TH'));
    var v5 = getAncestor(shared.v5,'TH');

    assertTrue("add order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("add order correct 2",goog.dom.getNextElementSibling(v1) === v3);
    assertTrue("add order correct 3",goog.dom.getNextElementSibling(v3) === v5);
    assertTrue("add order correct 3",goog.dom.getNextElementSibling(v5) === v2);

    document.body.removeChild(shared.container);
    asyncTestCase.waitForAsync('test remove table');
}

function testColumnChange03() {
    var frp = shared.scope.getFrp();
    assertEquals(0,frp.tm().watching());
    shared = {};
}
<commit_msg>finish doing testColumnChange<commit_after>goog.provide('recoil.ui.widgets.table.TableWidgetTest');

goog.require('goog.testing.jsunit');
goog.require('recoil.ui.widgets.table.TableWidget');
goog.require('recoil.util');
goog.require('recoil.frp.Frp');
goog.require('recoil.ui.widgets.table.TableWidget');
goog.require('recoil.ui.widgets.TableMetaData');
goog.require('recoil.ui.widgets.ButtonWidget');
goog.require('recoil.ui.BoolWithExplanation');
goog.require('recoil.ui.WidgetScope');
goog.require('recoil.ui.widgets.table.StringColumn');
goog.require('recoil.ui.widgets.table.NumberColumn');
goog.require('recoil.ui.widgets.table.BooleanColumn');
goog.require('recoil.ui.widgets.CheckboxWidget');
goog.require('recoil.ui.widgets.table.SelectColumn');
goog.require('goog.testing.AsyncTestCase');

var typeFactories = {"int": function(meta) {
    return new recoil.ui.widgets.table.NumberColumn(meta);
}, "string": function (meta) {
    return new recoil.ui.widgets.table.StringColumn(meta);
}, "boolean": function (meta) {
    return new recoil.ui.widgets.table.BooleanColumn(meta);
}, "select": function (meta) {
    return new recoil.ui.widgets.table.SelectColumn(meta);
}};

var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
asyncTestCase.stepTimeout = 5000;
var shared = {};

function waitFor(test, start) {
    start = start || new Date().getTime();
    setTimeout(function () {
        if (test()) {
            asyncTestCase.continueTesting();
        }
        else {
            if (new Date().getTime() < start + asyncTestCase.stepTimeout) {
                waitFor(test);
            }
        }
    }, 10);
}
function testOrderChange01() {
    shared = {
        container : goog.dom.createDom('div', {id: 'foo'}),
        scope : new recoil.ui.WidgetScope()
    };
    var frp = shared.scope.getFrp();

    var tblKeys = {
        id : new recoil.structs.table.ColumnKey("id_"),
        value : new recoil.structs.table.ColumnKey("value_")
    };

    var rawTableMeta = {
        value : { type : "string", length : 20, key : tblKeys.value},
        id : { type : "int", primary : 0, key : tblKeys.id}
    };

   var rawTable = [];

    for (var i = 4; i >= 0; i--) {
	rawTable.push({id: i, value: "row " + i});
    }

    var columns = new recoil.ui.widgets.TableMetaData();
    columns.add(tblKeys.id, "ID");
    columns.add(tblKeys.value, "Value");

    shared.tableB = frp.createB(recoil.structs.table.Table.create(typeFactories, rawTableMeta, rawTable, true));
    var tableWidget = new recoil.ui.widgets.table.TableWidget(shared.scope);

    shared.tableB.refListen(function (b) {
        console.log("referenced", b);
        asyncTestCase.continueTesting();
    });
    tableWidget.getComponent().render(shared.container);
    tableWidget.attach(shared.tableB,columns);

    assertEquals(0,frp.tm().watching());
    document.body.appendChild(shared.container);

    asyncTestCase.waitForAsync('test show table');
}

function findInput(val) {
    return goog.dom.findNode(shared.container, function (n) {

        return n.nodeName === 'INPUT' && n.value === val  && n.type === 'text';
    }) ;
}

function findVal(val) {
    return goog.dom.findNode(shared.container, function (n) {
        return n.nodeName === '#text' && n.nodeValue === val;
    }) ;
}

function getAncestor (node, type) {
    var parent = goog.dom.getParentElement(node);

    while (parent.nodeName !== type) {
        parent = goog.dom.getParentElement(parent);
    }
    return parent;
}
function testOrderChange02() {
    var frp = shared.scope.getFrp();
    var watching = frp.tm().watching();
    assertNotEquals(0,watching);

    shared.input = findInput('row 1');

    var row0 = findInput('row 0');
    assertNotUndefined(shared.input);

    var  tr1 = getAncestor(shared.input,'TR');
    var  tr0 = getAncestor(row0,'TR');

    assertTrue("init order correct",goog.dom.getNextElementSibling(tr1) === tr0);

    frp.accessTrans(function () {
        var tbl = shared.tableB.get().unfreeze();
        var row = tbl.getRow([1]).unfreeze();
        row.setPos(10);
        tbl.removeRow([1]);
        tbl.addRow(row);
        shared.tableB.set(tbl.freeze());
    },shared.tableB);

    assertTrue(findInput('row 0') === row0);
    assertTrue(findInput('row 1') === shared.input);
    assertTrue("final order correct",goog.dom.getNextElementSibling(tr0) === tr1);

    // no more behaviours should be added or removed
    assertEquals(watching,frp.tm().watching());

    document.body.removeChild(shared.container);
    asyncTestCase.waitForAsync('test remove table');
}

function testOrderChange03() {
    var frp = shared.scope.getFrp();
    assertEquals(0,frp.tm().watching());
    shared = {};
}

function testColumnChange01() {
    shared = {
        container : goog.dom.createDom('div', {id: 'foo'}),
        scope : new recoil.ui.WidgetScope()
    };
    var frp = shared.scope.getFrp();

    shared.tblKeys = {
        id : new recoil.structs.table.ColumnKey("id_"),
        v1 : new recoil.structs.table.ColumnKey("value1_"),
        v2 : new recoil.structs.table.ColumnKey("value2_"),
        v3 : new recoil.structs.table.ColumnKey("value3_"),
        v4 : new recoil.structs.table.ColumnKey("value4_"),
        v5 : new recoil.structs.table.ColumnKey("value5_")
    };
    var tblKeys = shared.tblKeys;

    var rawTableMeta = {
        v1 : { type : "string", length : 20, key : tblKeys.v1},
        v2 : { type : "string", length : 20, key : tblKeys.v2},
        v3 : { type : "string", length : 20, key : tblKeys.v3},
        v4 : { type : "string", length : 20, key : tblKeys.v4},
        v5 : { type : "string", length : 20, key : tblKeys.v5},
        id : { type : "int", primary : 0, key : tblKeys.id}
    };

   var rawTable = [];

    for (var i = 4; i >= 0; i--) {
	rawTable.push({id: i, v1: "c1 " + i, v2:"c2 " + i,v3:"c3 " + i, v4:"c4 " + i, v5:"c5 " + i});
    }

    var columns = new recoil.ui.widgets.TableMetaData();
    columns.add(tblKeys.id, "ID");
    columns.add(tblKeys.v1, "V1");
    columns.add(tblKeys.v2, "V2");
    columns.add(tblKeys.v3, "V3");
    columns.add(tblKeys.v4, "V4");

    shared.tableB = frp.createB(recoil.structs.table.Table.create(typeFactories, rawTableMeta, rawTable, true));
    var tableWidget = new recoil.ui.widgets.table.TableWidget(shared.scope);

    shared.columnsB = frp.createB(columns);
    shared.tableB.refListen(function (b) {
        asyncTestCase.continueTesting();
    });
    tableWidget.getComponent().render(shared.container);
    tableWidget.attach(shared.tableB,shared.columnsB);

    assertEquals(0,frp.tm().watching());
    document.body.appendChild(shared.container);

    asyncTestCase.waitForAsync('test show table');
}

function testColumnChange02() {
    var frp = shared.scope.getFrp();
    var watching = frp.tm().watching();
    assertNotEquals(0,watching);

    shared.id = findVal('ID');
    shared.v1 = findVal('V1');
    shared.v2 = findVal('V2');
    shared.v3 = findVal('V3');
    shared.v4 = findVal('V4');

    assertNotUndefined(shared.id);
    assertNotUndefined(shared.v1);
    assertNotUndefined(shared.v2);
    assertNotUndefined(shared.v3);
    assertNotUndefined(shared.v4);

    var  id = getAncestor(shared.id,'TH');
    var  v1 = getAncestor(shared.v1,'TH');
    var  v2 = getAncestor(shared.v2,'TH');
    var  v3 = getAncestor(shared.v3,'TH');
    var  v4 = getAncestor(shared.v4,'TH');

    assertTrue("init order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("init order correct 2",goog.dom.getNextElementSibling(v1) === v2);
    assertTrue("init order correct 3",goog.dom.getNextElementSibling(v2) === v3);
    assertTrue("init order correct 4",goog.dom.getNextElementSibling(v3) === v4);

    // swaping v1 and v3
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v4, "V4");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));
    assertEquals(shared.v4 , findVal('V4'));

    assertEquals(id,getAncestor(shared.id,'TH'));
    assertEquals(v1,getAncestor(shared.v1,'TH'));
    assertEquals(v2,getAncestor(shared.v2,'TH'));
    assertEquals(v3,getAncestor(shared.v3,'TH'));
    assertEquals(v4,getAncestor(shared.v4,'TH'));

    assertTrue("move order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("move order correct 2",goog.dom.getNextElementSibling(v1) === v3);
    assertTrue("move order correct 3",goog.dom.getNextElementSibling(v3) === v4);
    assertTrue("move order correct 4",goog.dom.getNextElementSibling(v4) === v2);

    // no more behaviours should be added or removed
    assertEquals(watching,frp.tm().watching());

    // remove v4
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));
    assertUndefined(findVal('V4'));

    assertEquals(id,getAncestor(shared.id,'TH'));
    assertEquals(v1,getAncestor(shared.v1,'TH'));
    assertEquals(v2,getAncestor(shared.v2,'TH'));
    assertEquals(v3,getAncestor(shared.v3,'TH'));

    assertTrue("remove order correct 1",goog.dom.getNextElementSibling(id) === v1);
    assertTrue("remove order correct 2",goog.dom.getNextElementSibling(v1) === v3);
    assertTrue("remove order correct 3",goog.dom.getNextElementSibling(v3) === v2);

    // add v5
    frp.accessTrans(function () {
        var columns = new recoil.ui.widgets.TableMetaData();
        columns.add(shared.tblKeys.id, "ID");
        columns.add(shared.tblKeys.v1, "V1");
        columns.add(shared.tblKeys.v3, "V3");
        columns.add(shared.tblKeys.v5, "V5");
        columns.add(shared.tblKeys.v2, "V2");
        shared.columnsB.set(columns);

    },shared.columnsB);

    waitFor(function () {
        return findVal('V5');
    });
    shared.th = {
        id : id,
        v1 : v1,
        v2 : v2,
        v3 : v3
    };
    asyncTestCase.waitForAsync('check column added');
}

function testColumnChange03() {
    shared.v5 = findVal('V5');
    assertEquals(shared.id , findVal('ID'));
    assertEquals(shared.v1 , findVal('V1'));
    assertEquals(shared.v2 , findVal('V2'));
    assertEquals(shared.v3 , findVal('V3'));

    assertEquals(shared.th.id,getAncestor(shared.id,'TH'));
    assertEquals(shared.th.v1,getAncestor(shared.v1,'TH'));
    assertEquals(shared.th.v2,getAncestor(shared.v2,'TH'));
    assertEquals(shared.th.v3,getAncestor(shared.v3,'TH'));
    var v5 = getAncestor(shared.v5,'TH');

    assertTrue("add order correct 1",goog.dom.getNextElementSibling(shared.th.id) === shared.th.v1);
    assertTrue("add order correct 2",goog.dom.getNextElementSibling(shared.th.v1) === shared.th.v3);
    assertTrue("add order correct 3",goog.dom.getNextElementSibling(shared.th.v3) === v5);
    assertTrue("add order correct 3",goog.dom.getNextElementSibling(v5) === shared.th.v2);

    document.body.removeChild(shared.container);
    asyncTestCase.waitForAsync('test remove table');
}

function testColumnChange04() {
    var frp = shared.scope.getFrp();
    assertEquals(0,frp.tm().watching());
    shared = {};
}
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-08-16');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-08-17');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// Redirect between plain HTTP and encrypted HTTPS by following rules:
// - If user is logged in - force HTTPS.
// - If user is visiting "users.auth.*" page - force HTTPS.
// - Otherwise force HTTP.

'use strict';

var isEncryptionAllowed = require('nodeca.core/lib/system/utils/is_encryption_allowed');

module.exports = function (N) {
  N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env) {
    var shouldBeEncrypted = Boolean(env.session.user_id) ||
                            'users.auth' === env.method.slice(0, 'users.auth'.length);

    if (env.request.isEncrypted === shouldBeEncrypted) {
      return; // Redirection is not needed. Continue.
    }

    if (!isEncryptionAllowed(N, env.method)) {
      return; // It is not possible to encrypt current connection.
    }

    var redirectUrl = env.url_to(env.method, env.params, {
      protocol: shouldBeEncrypted ? 'https' : 'http'
    });

    return { code: N.io.REDIRECT, head: { Location: redirectUrl } };
  });
};
<commit_msg>Return 'Bad Request' on plain HTTP/RPC when encryption is required.<commit_after>// Redirect between plain HTTP and encrypted HTTPS by following rules:
// - If user is logged in - force HTTPS.
// - If user is visiting "users.auth.*" page - force HTTPS.
// - Otherwise force HTTP.

'use strict';

var isEncryptionAllowed = require('nodeca.core/lib/system/utils/is_encryption_allowed');

module.exports = function (N) {
  N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env) {
    var shouldBeEncrypted = Boolean(env.session.user_id) ||
                            'users.auth' === env.method.slice(0, 'users.auth'.length);

    if (env.request.isEncrypted === shouldBeEncrypted) {
      return; // Redirection is not needed. Continue.
    }

    if (!isEncryptionAllowed(N, env.method)) {
      return; // It is not possible to encrypt current connection.
    }

    var redirectUrl = env.url_to(env.method, env.params, {
      protocol: shouldBeEncrypted ? 'https' : 'http'
    });

    if (!redirectUrl) {
      // Can't build URL - usually RPC-only method.
      return { code: N.io.BAD_REQUEST, message: 'Encrypted connection is required' };
    }

    return { code: N.io.REDIRECT, head: { Location: redirectUrl } };
  });
};
<|endoftext|>


<commit_before>(function() {

d3.hexbin = {
  mesh: function(width, height, radius) {
    var path = [],
        dx = radius * 1.5,
        dy = radius * 2 * Math.sin(Math.PI / 3),
        mesh = hexagon(radius).slice(3).join("l");

    for (var y = 0, i = 0; y < height + radius; y += dx, ++i) {
      for (var x = i & 1 ? -dy / 2 : 0; x < width + dy / 2; x += dy) {
        path.push("M", x, ",", y, "m", mesh);
      }
    }

    return path.join("");
  }
};

function hexagon(radius) {
  return d3.range(0, 2 * Math.PI, Math.PI / 3).map(function(angle) {
    return [Math.sin(angle) * radius, -Math.cos(angle) * radius];
  });
}

})();
<commit_msg>Rewrite d3.hexbin.<commit_after>(function() {

d3.hexbin = function() {
  var width = 1,
      height = 1,
      r,
      x = d3_hexbinX,
      y = d3_hexbinY,
      dx,
      dy,
      hexagon;

  function hexbin(points) {
    var binsById = {};

    points.forEach(function(point, i) {
      var py = y.call(hexbin, point, i) / dy, pj = Math.round(py),
          px = x.call(hexbin, point, i) / dx - (pj & 1 ? .5 : 0), pi = Math.round(px),
          py1 = py - pj;

      if (Math.abs(py1) * 3 > 1) {
        var px1 = px - pi,
            pi2 = pi + (px < pi ? -1 : 1) / 2,
            pj2 = pj + (py < pj ? -1 : 1),
            px2 = px - pi2,
            py2 = py - pj2;
        if (px1 * px1 + py1 * py1 > px2 * px2 + py2 * py2) pi = pi2 + (pj & 1 ? 1 : -1) / 2, pj = pj2;
      }

      var id = pi + "-" + pj,
          bin = binsById[id] || (binsById[id] = {i: pi, j: pj, points: []});
      bin.points.push(point);
    });

    return d3.values(binsById);
  }

  hexbin.x = function(_) {
    if (!arguments.length) return x;
    x = _;
    return hexbin;
  };

  hexbin.y = function(_) {
    if (!arguments.length) return y;
    y = _;
    return hexbin;
  };

  hexbin.point = function(d) {
    return [(d.i + (d.j & 1 ? 1 / 2 : 0)) * dx, d.j * dy];
  };

  hexbin.hexagon = function(d) {
    return (arguments.length ? "M" + hexbin.point(d) + "m" : "M") + hexagon.join("l") + "Z";
  };

  hexbin.mesh = function() {
    var path = [], mesh = hexagon.slice(0, 4).join("l");
    for (var y = 0, odd = false; y < height + r; y += dy, odd = !odd) {
      for (var x = odd ? dx / 2 : 0; x < width; x += dx) {
        path.push("M", x, ",", y, "m", mesh);
      }
    }
    return path.join("");
  };

  hexbin.size = function(_) {
    if (!arguments.length) return [width, height];
    width = +_[0], height = +_[1];
    return hexbin;
  };

  hexbin.radius = function(_) {
    if (!arguments.length) return r;
    r = +_;
    dx = r * 2 * Math.sin(Math.PI / 3);
    dy = r * 1.5;
    var x0 = 0, y0 = 0;
    hexagon = d3_hexbinAngles.map(function(angle) {
      var x1 = Math.sin(angle) * r,
          y1 = -Math.cos(angle) * r,
          dx = x1 - x0, dy = y1 - y0;
      x0 = x1, y0 = y1;
      return [dx, dy];
    });
    return hexbin;
  };

  return hexbin.radius(1);
};

var d3_hexbinAngles = d3.range(0, 2 * Math.PI, Math.PI / 3),
    d3_hexbinX = function(d) { return d[0]; },
    d3_hexbinY = function(d) { return d[1]; };

})();
<|endoftext|>


<commit_before>import { ALL, EACH } from '../util'

describe('The Extension page should', () => {
  beforeAll(ALL)
  afterAll(ALL)
  beforeEach(EACH)
  afterEach(EACH)

  it('execute the injected script after page loaded', async () => {
    await page.evaluate(() => {
      const editor = window.ace.edit('ace-editor')
      editor.session.setValue(`
console.log('abc')
document.querySelector('body').style.background = 'red'`)
    })
    await page.evaluate(() => {
      document.querySelectorAll('button')[6].click()
    })
    await page.waitForTimeout(100)
    const input = await page.$$('textarea')
    await input[1].evaluate((node) => (node.value = ''))
    await input[1].type(
      'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.11.0/underscore-min.js',
      { delay: 2 }
    )
    await page.waitForTimeout(100)
    const allButtons = await page.$$('button')
    await allButtons[allButtons.length - 1].click()
    await page.waitForTimeout(100)
    await page.$eval('button', (x) => x.click())

    const newPage = await browser.newPage()
    await newPage.goto('https://google.com')
    await newPage.bringToFront()
    const background = await newPage.$eval(
      'body',
      (node) => node.style.background
    )
    expect(background).toBe('red')
    expect(await newPage.$eval('body', (node) => window._.VERSION)).toBe(
      '1.11.0'
    )

    page.bringToFront()
    const buttons = await page.$$('button')
    await buttons[1].click()
    await page.waitForTimeout(100)
    const dialogButtons = await page.$$('.MuiDialogActions-root > button')
    expect(dialogButtons).toHaveLength(3)
    await dialogButtons[1].click()
    await page.waitForTimeout(500)
  })
})
<commit_msg>Optimize integration test on CI<commit_after>import { ALL, EACH } from '../util'

describe('The Extension page should', () => {
  beforeAll(ALL)
  afterAll(ALL)
  beforeEach(EACH)
  afterEach(EACH)

  it('execute the injected script after page loaded', async () => {
    await page.evaluate(() => {
      const editor = window.ace.edit('ace-editor')
      editor.session.setValue(`
console.log('abc')
document.querySelector('body').style.background = 'red'`)
    })
    await page.evaluate(() => {
      document.querySelectorAll('button')[6].click()
    })
    await page.waitForTimeout(100)
    const input = await page.$$('textarea')
    await input[1].evaluate((node) => (node.value = ''))
    await input[1].type(
      'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.11.0/underscore-min.js',
      { delay: 2 }
    )
    await page.waitForTimeout(100)
    const allButtons = await page.$$('button')
    await allButtons[allButtons.length - 1].click()
    await page.waitForTimeout(100)
    await page.$eval('button', (x) => x.click())

    const newPage = await browser.newPage()
    await newPage.goto('https://google.com')
    await newPage.bringToFront()
    const background = await newPage.$eval(
      'body',
      (node) => node.style.background
    )
    expect(background).toBe('red')
    expect(await newPage.$eval('body', (node) => window._.VERSION)).toBe(
      '1.11.0'
    )

    page.bringToFront()
    const buttons = await page.$$('button')
    await buttons[1].click()
    await page.waitForTimeout(500)
    const dialogButtons = await page.$$('.MuiDialogActions-root > button')
    expect(dialogButtons).toHaveLength(3)
    await dialogButtons[1].click()
    await page.waitForTimeout(500)
  })
})
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name base
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/array/base}
*/
setReadOnly( ns, 'base', require( '@stdlib/array/base' ) );

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name DataView
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/dataview}
*/
setReadOnly( ns, 'DataView', require( '@stdlib/array/dataview' ) );

/**
* @name datespace
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/datespace}
*/
setReadOnly( ns, 'datespace', require( '@stdlib/array/datespace' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name filledarray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled}
*/
setReadOnly( ns, 'filledarray', require( '@stdlib/array/filled' ) );

/**
* @name filledarrayBy
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled-by}
*/
setReadOnly( ns, 'filledarrayBy', require( '@stdlib/array/filled-by' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name incrspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/incrspace}
*/
setReadOnly( ns, 'incrspace', require( '@stdlib/array/incrspace' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name linspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/linspace}
*/
setReadOnly( ns, 'linspace', require( '@stdlib/array/linspace' ) );

/**
* @name logspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/logspace}
*/
setReadOnly( ns, 'logspace', require( '@stdlib/array/logspace' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name arrayview2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator}
*/
setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) );

/**
* @name arrayview2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator-right}
*/
setReadOnly( ns, 'arrayview2iteratorRight', require( '@stdlib/array/to-view-iterator-right' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name complexarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex}
*/
setReadOnly( ns, 'complexarray', require( '@stdlib/array/typed-complex' ) );

/**
* @name complexarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'complexarrayCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name complexarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'complexarrayDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name realarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real}
*/
setReadOnly( ns, 'realarray', require( '@stdlib/array/typed-real' ) );

/**
* @name realarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real-ctors}
*/
setReadOnly( ns, 'realarrayCtors', require( '@stdlib/array/typed-real-ctors' ) );

/**
* @name realarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real-dtypes}
*/
setReadOnly( ns, 'realarrayDataTypes', require( '@stdlib/array/typed-real-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name base
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/array/base}
*/
setReadOnly( ns, 'base', require( '@stdlib/array/base' ) );

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name DataView
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/dataview}
*/
setReadOnly( ns, 'DataView', require( '@stdlib/array/dataview' ) );

/**
* @name datespace
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/datespace}
*/
setReadOnly( ns, 'datespace', require( '@stdlib/array/datespace' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name filledarray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled}
*/
setReadOnly( ns, 'filledarray', require( '@stdlib/array/filled' ) );

/**
* @name filledarrayBy
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled-by}
*/
setReadOnly( ns, 'filledarrayBy', require( '@stdlib/array/filled-by' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name incrspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/incrspace}
*/
setReadOnly( ns, 'incrspace', require( '@stdlib/array/incrspace' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name linspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/linspace}
*/
setReadOnly( ns, 'linspace', require( '@stdlib/array/linspace' ) );

/**
* @name logspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/logspace}
*/
setReadOnly( ns, 'logspace', require( '@stdlib/array/logspace' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name arrayview2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator}
*/
setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) );

/**
* @name arrayview2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator-right}
*/
setReadOnly( ns, 'arrayview2iteratorRight', require( '@stdlib/array/to-view-iterator-right' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name complexarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex}
*/
setReadOnly( ns, 'complexarray', require( '@stdlib/array/typed-complex' ) );

/**
* @name complexarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'complexarrayCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name complexarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'complexarrayDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name realarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real}
*/
setReadOnly( ns, 'realarray', require( '@stdlib/array/typed-real' ) );

/**
* @name realarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real-ctors}
*/
setReadOnly( ns, 'realarrayCtors', require( '@stdlib/array/typed-real-ctors' ) );

/**
* @name realarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-real-dtypes}
*/
setReadOnly( ns, 'realarrayDataTypes', require( '@stdlib/array/typed-real-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name arrayZeros
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/zeros}
*/
setReadOnly( ns, 'arrayZeros', require( '@stdlib/array/zeros' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Page switcher
 * This is the class for the left and right navigation arrows that switch
 * between pages.
 */
cr.define('ntp4', function() {

  function PageSwitcher() {
  }

  PageSwitcher.template = {
    __proto__: HTMLButtonElement.prototype,

    decorate: function(el) {
      el.__proto__ = PageSwitcher.template;

      el.addEventListener('click', el.activate_);
      el.addEventListener('mousewheel', el.onMouseWheel_);

      el.direction_ = el.id == 'page-switcher-start' ? -1 : 1;

      el.dragWrapper_ = new DragWrapper(el, el);
    },

    /**
     * Activate the switcher (go to the next card).
     * @private
     */
    activate_: function() {
      var cardSlider = ntp4.getCardSlider();
      cardSlider.selectCard(cardSlider.currentCard + this.direction_, true);
    },

    /**
     * Handler for the mousewheel event on a pager. We pass through the scroll
     * to the page. This is necssary because the page is our sibling in the DOM
     * hierarchy, so the event won't naturally pass through to it.
     * @param {Event} e The mousewheel event.
     * @private
     */
    onMouseWheel_: function(e) {
      var page = ntp4.getCardSlider().currentCardValue;
      page.handleMouseWheel(e);
    },

    shouldAcceptDrag: function(e) {
      return true;
    },

    doDragEnter: function(e) {
      this.scheduleDelayedSwitch_();
    },

    doDragLeave: function(e) {
      this.cancelDelayedSwitch_();
    },

    doDragOver: function(e) {},

    doDrop: function(e) {
      e.stopPropagation();
      this.cancelDelayedSwitch_();

      var tile = ntp4.getCurrentlyDraggingTile();
      if (!tile)
        return;

      var sourcePage = tile.tilePage;
      var targetPage = ntp4.getCardSlider().currentCardValue;
      if (targetPage == sourcePage)
        return;

      targetPage.appendDraggingTile();
    },

    /**
     * Starts a timer to activate the switcher. The timer repeats until
     * cancelled by cancelDelayedSwitch_.
     * @private
     */
    scheduleDelayedSwitch_: function() {
      var self = this;
      function navPageClearTimeout() {
        self.activate_();
        self.dragNavTimeout_ = null;
        self.scheduleDelayedSwitch_();
      }
      this.dragNavTimeout_ = window.setTimeout(navPageClearTimeout, 500);
    },

    /**
     * Cancels the timer that activates the switcher while dragging.
     * @private
     */
    cancelDelayedSwitch_: function() {
      if (this.dragNavTimeout_) {
        window.clearTimeout(this.dragNavTimeout_);
        this.dragNavTimeout_ = null;
      }
    },

  };

  return {
    initializePageSwitcher: PageSwitcher.template.decorate
  }
});
<commit_msg>ntp4: dragging onto page switcher fix<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Page switcher
 * This is the class for the left and right navigation arrows that switch
 * between pages.
 */
cr.define('ntp4', function() {

  function PageSwitcher() {
  }

  PageSwitcher.template = {
    __proto__: HTMLButtonElement.prototype,

    decorate: function(el) {
      el.__proto__ = PageSwitcher.template;

      el.addEventListener('click', el.activate_);
      el.addEventListener('mousewheel', el.onMouseWheel_);

      el.direction_ = el.id == 'page-switcher-start' ? -1 : 1;

      el.dragWrapper_ = new DragWrapper(el, el);
    },

    /**
     * Activate the switcher (go to the next card).
     * @private
     */
    activate_: function() {
      var cardSlider = ntp4.getCardSlider();
      cardSlider.selectCard(cardSlider.currentCard + this.direction_, true);
    },

    /**
     * Handler for the mousewheel event on a pager. We pass through the scroll
     * to the page. This is necssary because the page is our sibling in the DOM
     * hierarchy, so the event won't naturally pass through to it.
     * @param {Event} e The mousewheel event.
     * @private
     */
    onMouseWheel_: function(e) {
      var page = ntp4.getCardSlider().currentCardValue;
      page.handleMouseWheel(e);
    },

    shouldAcceptDrag: function(e) {
      return true;
    },

    doDragEnter: function(e) {
      this.scheduleDelayedSwitch_();
      this.doDragOver(e);
    },

    doDragLeave: function(e) {
      this.cancelDelayedSwitch_();
    },

    doDragOver: function(e) {
      e.preventDefault();
      var targetPage = ntp4.getCardSlider().currentCardValue;
      targetPage.setDropEffect(e.dataTransfer);
    },

    doDrop: function(e) {
      e.stopPropagation();
      this.cancelDelayedSwitch_();

      var tile = ntp4.getCurrentlyDraggingTile();
      if (!tile)
        return;

      var sourcePage = tile.tilePage;
      var targetPage = ntp4.getCardSlider().currentCardValue;
      if (targetPage == sourcePage)
        return;

      targetPage.appendDraggingTile();
    },

    /**
     * Starts a timer to activate the switcher. The timer repeats until
     * cancelled by cancelDelayedSwitch_.
     * @private
     */
    scheduleDelayedSwitch_: function() {
      var self = this;
      function navPageClearTimeout() {
        self.activate_();
        self.dragNavTimeout_ = null;
        self.scheduleDelayedSwitch_();
      }
      this.dragNavTimeout_ = window.setTimeout(navPageClearTimeout, 500);
    },

    /**
     * Cancels the timer that activates the switcher while dragging.
     * @private
     */
    cancelDelayedSwitch_: function() {
      if (this.dragNavTimeout_) {
        window.clearTimeout(this.dragNavTimeout_);
        this.dragNavTimeout_ = null;
      }
    },

  };

  return {
    initializePageSwitcher: PageSwitcher.template.decorate
  }
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Query } from '@apollo/client/react/components'

import searchContentsQuery from 'v2/components/SearchContents/queries/searchContents'

import SearchEmptyMessage from 'v2/components/SearchEmptyMessage'
import ErrorAlert from 'v2/components/UI/ErrorAlert'
import BlocksLoadingIndicator from 'v2/components/UI/BlocksLoadingIndicator'
import Grid from 'v2/components/UI/Grid'
import Cell from 'v2/components/Cell'

export default class SearchContents extends PureComponent {
  static propTypes = {
    type: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string),
    ]),
    q: PropTypes.string.isRequired,
    fetchPolicy: PropTypes.oneOf(['cache-first', 'network-only']).isRequired,
    block_filter: PropTypes.oneOf([
      'IMAGE',
      'EMBED',
      'TEXT',
      'ATTACHMENT',
      'LINK',
    ]),
  }

  static defaultProps = {
    type: null,
    block_filter: null,
  }

  state = {
    page: 1,
    per: 12,
    hasMore: true,
  }

  loadMore = fetchMore => () => {
    const { page, per } = this.state

    fetchMore({
      variables: { page: page + 1, per },
      updateQuery: (prevResult, { fetchMoreResult }) => ({
        contents: [...prevResult.contents, ...fetchMoreResult.contents],
      }),
    }).then(({ errors, data }) => {
      const {
        contents: { length },
      } = data
      const hasMore = !errors && length > 0 && length >= per

      this.setState({
        page: page + 1,
        hasMore,
      })
    })
  }

  render() {
    const { per, hasMore } = this.state
    const { type, fetchPolicy, q, block_filter } = this.props

    return (
      <Query
        query={searchContentsQuery}
        variables={{
          type,
          per,
          q,
          block_filter,
        }}
        fetchPolicy={fetchPolicy}
        ssr={false}
      >
        {({ loading, error, data, fetchMore }) => {
          if (error) {
            return <ErrorAlert>{error.message}</ErrorAlert>
          }

          if (loading) {
            return <BlocksLoadingIndicator />
          }

          const { contents } = data

          return (

              {loading && <BlocksLoadingIndicator />}

              {!loading && contents.length === 0 && (
                <SearchEmptyMessage term={q} type={type} />
              )}

              {!loading && contents.length > 0 && (
                <Grid
                  pageStart={1}
                  threshold={800}
                  initialLoad={false}
                  loader={<BlocksLoadingIndicator key="loading" />}
                  hasMore={contents.length >= per && hasMore}
                  loadMore={this.loadMore(fetchMore)}
                >
                  {contents.map(cell =>
                    ({
                      Image: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      Attachment: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      Text: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      Link: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      Embed: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      Channel: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                        />
                      ),
                      User: () => (
                        <Cell.Identifiable
                          key={`${cell.__typename}_${cell.id}`}
                          identifiable={cell}
                        />
                      ),
                      Group: () => (
                        <Cell.Identifiable
                          key={`${cell.__typename}_${cell.id}`}
                          identifiable={cell}
                        />
                      ),
                    }[cell.__typename]())
                  )}
                </Grid>
              )}

          )
        }}
      </Query>
    )
  }
}
<commit_msg>Add context to Cell on Search results<commit_after>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Query } from '@apollo/client/react/components'

import searchContentsQuery from 'v2/components/SearchContents/queries/searchContents'

import SearchEmptyMessage from 'v2/components/SearchEmptyMessage'
import ErrorAlert from 'v2/components/UI/ErrorAlert'
import BlocksLoadingIndicator from 'v2/components/UI/BlocksLoadingIndicator'
import Grid from 'v2/components/UI/Grid'
import Cell from 'v2/components/Cell'

export default class SearchContents extends PureComponent {
  static propTypes = {
    type: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string),
    ]),
    q: PropTypes.string.isRequired,
    fetchPolicy: PropTypes.oneOf(['cache-first', 'network-only']).isRequired,
    block_filter: PropTypes.oneOf([
      'IMAGE',
      'EMBED',
      'TEXT',
      'ATTACHMENT',
      'LINK',
    ]),
  }

  static defaultProps = {
    type: null,
    block_filter: null,
  }

  state = {
    page: 1,
    per: 12,
    hasMore: true,
  }

  loadMore = fetchMore => () => {
    const { page, per } = this.state

    fetchMore({
      variables: { page: page + 1, per },
      updateQuery: (prevResult, { fetchMoreResult }) => ({
        contents: [...prevResult.contents, ...fetchMoreResult.contents],
      }),
    }).then(({ errors, data }) => {
      const {
        contents: { length },
      } = data
      const hasMore = !errors && length > 0 && length >= per

      this.setState({
        page: page + 1,
        hasMore,
      })
    })
  }

  render() {
    const { per, hasMore } = this.state
    const { type, fetchPolicy, q, block_filter } = this.props

    return (
      <Query
        query={searchContentsQuery}
        variables={{
          type,
          per,
          q,
          block_filter,
        }}
        fetchPolicy={fetchPolicy}
        ssr={false}
      >
        {({ loading, error, data, fetchMore }) => {
          if (error) {
            return <ErrorAlert>{error.message}</ErrorAlert>
          }

          if (loading) {
            return <BlocksLoadingIndicator />
          }

          const { contents } = data

          return (

              {loading && <BlocksLoadingIndicator />}

              {!loading && contents.length === 0 && (
                <SearchEmptyMessage term={q} type={type} />
              )}

              {!loading && contents.length > 0 && (
                <Grid
                  pageStart={1}
                  threshold={800}
                  initialLoad={false}
                  loader={<BlocksLoadingIndicator key="loading" />}
                  hasMore={contents.length >= per && hasMore}
                  loadMore={this.loadMore(fetchMore)}
                >
                  {contents.map(cell =>
                    ({
                      Image: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      Attachment: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      Text: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      Link: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      Embed: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      Channel: () => (
                        <Cell.Konnectable
                          key={`${cell.__typename}_${cell.id}`}
                          konnectable={cell}
                          context={contents}
                        />
                      ),
                      User: () => (
                        <Cell.Identifiable
                          key={`${cell.__typename}_${cell.id}`}
                          identifiable={cell}
                          context={contents}
                        />
                      ),
                      Group: () => (
                        <Cell.Identifiable
                          key={`${cell.__typename}_${cell.id}`}
                          identifiable={cell}
                          context={contents}
                        />
                      ),
                    }[cell.__typename]())
                  )}
                </Grid>
              )}

          )
        }}
      </Query>
    )
  }
}
<|endoftext|>