<commit_before>'use strict';

// Simulate a test service provider that submits usage for a resource and
// verifies the submission by retrieving a usage report.

const _ = require('underscore');

const request = require('abacus-request');
const util = require('util');
const commander = require('commander');

const map = _.map;
const omit = _.omit;
const clone = _.clone;

// Parse command line options
const argv = clone(process.argv);
argv.splice(1, 1, 'demo');
commander
  .option('-c, --collector <uri>',
    'usage collector URL or domain name [http://localhost:9080]',
    'http://localhost:9080')
  .option('-r, --reporting <uri>',
    'usage reporting URL or domain name [http://localhost:9088]',
    'http://localhost:9088')
  .option(
    '-d, --delta <d>', 'usage time window shift in milli-seconds', parseInt)
  .allowUnknownOption(true)
  .parse(argv);

// Collector service URL
const collector = /:/.test(commander.collector) ? commander.collector :
  'https://abacus-usage-collector.' + commander.collector;

// Reporting service URL
const reporting = /:/.test(commander.reporting) ? commander.reporting :
  'https://abacus-usage-reporting.' + commander.reporting;

// Usage time window shift in milli-seconds
const delta = commander.delta || 0;

describe('abacus-demo-client', () => {
  it('submits usage for a sample resource and retrieves an aggregated ' +
    'usage report', function(done) {
      // Configure the test timeout
      const timeout = 20000;
      this.timeout(timeout + 2000);

      // Test usage to be submitted by the client
      const start = 1435629365220 + delta;
      const end = 1435629465220 + delta;
      const usage = [
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start,
              end: end,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        },
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start + 1,
              end: end + 1,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        },
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start + 2,
              end: end + 2,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        }];

      // Expected usage report for the test organization
      const report = {
        organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
        charge: 46.09,
        resources: [{
          resource_id: 'object-storage',
          charge: 46.09,
          aggregated_usage: [{
            metric: 'storage',
            quantity: 1,
            summary: 1,
            charge: 1
          }, {
            metric: 'thousand_light_api_calls',
            quantity: 3,
            summary: 3,
            charge: 0.09
          }, {
            metric: 'heavy_api_calls',
            quantity: 300,
            summary: 300,
            charge: 45
          }],
          plans: [{
            plan_id: 'basic',
            charge: 46.09,
            aggregated_usage: [{
              metric: 'storage',
              quantity: 1,
              summary: 1,
              cost: 1,
              charge: 1
            }, {
              metric: 'thousand_light_api_calls',
              quantity: 3,
              summary: 3,
              cost: 0.09,
              charge: 0.09
            }, {
              metric: 'heavy_api_calls',
              quantity: 300,
              summary: 300,
              cost: 45,
              charge: 45
            }]
          }]
        }],
        spaces: [{
          space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
          charge: 46.09,
          resources: [{
            resource_id: 'object-storage',
            charge: 46.09,
            aggregated_usage: [{
              metric: 'storage',
              quantity: 1,
              summary: 1,
              charge: 1
            }, {
              metric: 'thousand_light_api_calls',
              quantity: 3,
              summary: 3,
              charge: 0.09
            }, {
              metric: 'heavy_api_calls',
              quantity: 300,
              summary: 300,
              charge: 45
            }],
            plans: [{
              plan_id: 'basic',
              charge: 46.09,
              aggregated_usage: [{
                metric: 'storage',
                quantity: 1,
                summary: 1,
                cost: 1,
                charge: 1
              }, {
                metric: 'thousand_light_api_calls',
                quantity: 3,
                summary: 3,
                cost: 0.09,
                charge: 0.09
              }, {
                metric: 'heavy_api_calls',
                quantity: 300,
                summary: 300,
                cost: 45,
                charge: 45
              }]
            }]
          }],
          consumers: [{
            consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab',
            charge: 46.09,
            resources: [{
              resource_id: 'object-storage',
              charge: 46.09,
              aggregated_usage: [{
                metric: 'storage',
                quantity: 1,
                summary: 1,
                charge: 1
              }, {
                metric: 'thousand_light_api_calls',
                quantity: 3,
                summary: 3,
                charge: 0.09
              }, {
                metric: 'heavy_api_calls',
                quantity: 300,
                summary: 300,
                charge: 45
              }],
              plans: [{
                plan_id: 'basic',
                charge: 46.09,
                aggregated_usage: [{
                  metric: 'storage',
                  quantity: 1,
                  summary: 1,
                  cost: 1,
                  charge: 1
                }, {
                  metric: 'thousand_light_api_calls',
                  quantity: 3,
                  summary: 3,
                  cost: 0.09,
                  charge: 0.09
                }, {
                  metric: 'heavy_api_calls',
                  quantity: 300,
                  summary: 300,
                  cost: 45,
                  charge: 45
                }]
              }]
            }]
          }]
        }]
      };

      // Submit usage for sample resource with 10 GB, 1000 light API calls,
      // and 100 heavy API calls
      let posts = 0;
      const post = (u, done) => {
        console.log(u.message);

        const cb = () => {
          if(++posts === usage.length) done();
        };

        request.post(collector + '/v1/metering/resource/usage', {
          body: u.usage
        }, (err, val) => {
          expect(err).to.equal(undefined);

          // Expect a 201 with the location of the accumulated usage
          expect(val.statusCode).to.equal(201);
          expect(val.headers.location).to.not.equal(undefined);
          cb();
        });
      };

      // Print the number of usage docs already processed given a get report
      // response, determined from the aggregated usage quantity found in the
      // report for our test resource
      const processed = (val) => {
        try {
          return val.body.resources[0].aggregated_usage[1].summary;
        }
        catch (e) {
          // The response doesn't contain a valid report
          return 0;
        }
      };

      // Return the reporting day for the given time
      const day = (t) => {
        const d = new Date(t);
        return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
      };

      // Get a usage report for the test organization
      let gets = 0;
      const get = (done) => {
        request.get(reporting +
          '/v1/organizations/a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27/usage/:time',
          {
            time: day(start)
          }, (err, val) => {
            expect(err).to.equal(undefined);
            expect(val.statusCode).to.equal(200);

            // Compare the usage report we got with the expected report
            console.log('Processed %d usage docs', processed(val));
            try {
              expect(omit(val.body,
                ['id', 'start', 'end'])).to.deep.equal(report);
              console.log('\n', util.inspect(val.body, {
                depth: 10
              }), '\n');
              done();
            }
            catch (e) {
              // If the comparison fails we'll be called again to retry
              // after 1 second, give up after the configured timeout
              // still not getting the expected report then something
              // must have failed in the processing of that usage
              if(++gets === timeout / 250) {
                console.log('All submitted usage still not processed\n');
                throw e;
              }
            }
          });
      };

      // Wait for the expected usage report, get a report every 250 msec until
      // we get the expected values indicating that all submitted usage has
      // been processed
      const wait = (done) => {
        console.log('\nRetrieving usage report');
        const i = setInterval(() => get(() => done(clearInterval(i))), 250);
      };

      // Run the above steps
      map(usage, (u) => post(u, () => wait(done)));
    });
});

<commit_msg>Wait for usage reporter to start before submitting demo usage<commit_after>'use strict';

// Simulate a test service provider that submits usage for a resource and
// verifies the submission by retrieving a usage report.

const _ = require('underscore');

const request = require('abacus-request');
const util = require('util');
const commander = require('commander');

const map = _.map;
const omit = _.omit;
const clone = _.clone;

// Parse command line options
const argv = clone(process.argv);
argv.splice(1, 1, 'demo');
commander
  .option('-c, --collector <uri>',
    'usage collector URL or domain name [http://localhost:9080]',
    'http://localhost:9080')
  .option('-r, --reporting <uri>',
    'usage reporting URL or domain name [http://localhost:9088]',
    'http://localhost:9088')
  .option(
    '-d, --delta <d>', 'usage time window shift in milli-seconds', parseInt)
  .allowUnknownOption(true)
  .parse(argv);

// Collector service URL
const collector = /:/.test(commander.collector) ? commander.collector :
  'https://abacus-usage-collector.' + commander.collector;

// Reporting service URL
const reporting = /:/.test(commander.reporting) ? commander.reporting :
  'https://abacus-usage-reporting.' + commander.reporting;

// Usage time window shift in milli-seconds
const delta = commander.delta || 0;

describe('abacus-demo-client', () => {
  it('submits usage for a sample resource and retrieves an aggregated ' +
    'usage report', function(done) {
      // Configure the test timeout
      const timeout = 20000;
      this.timeout(timeout + 2000);

      // Test usage to be submitted by the client
      const start = 1435629365220 + delta;
      const end = 1435629465220 + delta;
      const usage = [
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start,
              end: end,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        },
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start + 1,
              end: end + 1,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        },
        {
          message:
            'Submitting 10 GB, 1000 light API calls, 100 heavy API calls',
          usage: {
            usage: [{
              start: start + 2,
              end: end + 2,
              region: 'us',
              organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
              space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
              consumer: {
                type: 'EXTERNAL',
                consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab'
              },
              resource_id: 'object-storage',
              plan_id: 'basic',
              resource_instance_id: '0b39fa70-a65f-4183-bae8-385633ca5c87',
              measured_usage: [{
                measure: 'storage',
                quantity: 1073741824
              }, {
                measure: 'light_api_calls',
                quantity: 1000
              }, {
                measure: 'heavy_api_calls',
                quantity: 100
              }]
            }]
          }
        }];

      // Expected usage report for the test organization
      const report = {
        organization_id: 'a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27',
        charge: 46.09,
        resources: [{
          resource_id: 'object-storage',
          charge: 46.09,
          aggregated_usage: [{
            metric: 'storage',
            quantity: 1,
            summary: 1,
            charge: 1
          }, {
            metric: 'thousand_light_api_calls',
            quantity: 3,
            summary: 3,
            charge: 0.09
          }, {
            metric: 'heavy_api_calls',
            quantity: 300,
            summary: 300,
            charge: 45
          }],
          plans: [{
            plan_id: 'basic',
            charge: 46.09,
            aggregated_usage: [{
              metric: 'storage',
              quantity: 1,
              summary: 1,
              cost: 1,
              charge: 1
            }, {
              metric: 'thousand_light_api_calls',
              quantity: 3,
              summary: 3,
              cost: 0.09,
              charge: 0.09
            }, {
              metric: 'heavy_api_calls',
              quantity: 300,
              summary: 300,
              cost: 45,
              charge: 45
            }]
          }]
        }],
        spaces: [{
          space_id: 'aaeae239-f3f8-483c-9dd0-de5d41c38b6a',
          charge: 46.09,
          resources: [{
            resource_id: 'object-storage',
            charge: 46.09,
            aggregated_usage: [{
              metric: 'storage',
              quantity: 1,
              summary: 1,
              charge: 1
            }, {
              metric: 'thousand_light_api_calls',
              quantity: 3,
              summary: 3,
              charge: 0.09
            }, {
              metric: 'heavy_api_calls',
              quantity: 300,
              summary: 300,
              charge: 45
            }],
            plans: [{
              plan_id: 'basic',
              charge: 46.09,
              aggregated_usage: [{
                metric: 'storage',
                quantity: 1,
                summary: 1,
                cost: 1,
                charge: 1
              }, {
                metric: 'thousand_light_api_calls',
                quantity: 3,
                summary: 3,
                cost: 0.09,
                charge: 0.09
              }, {
                metric: 'heavy_api_calls',
                quantity: 300,
                summary: 300,
                cost: 45,
                charge: 45
              }]
            }]
          }],
          consumers: [{
            consumer_id: 'bbeae239-f3f8-483c-9dd0-de6781c38bab',
            charge: 46.09,
            resources: [{
              resource_id: 'object-storage',
              charge: 46.09,
              aggregated_usage: [{
                metric: 'storage',
                quantity: 1,
                summary: 1,
                charge: 1
              }, {
                metric: 'thousand_light_api_calls',
                quantity: 3,
                summary: 3,
                charge: 0.09
              }, {
                metric: 'heavy_api_calls',
                quantity: 300,
                summary: 300,
                charge: 45
              }],
              plans: [{
                plan_id: 'basic',
                charge: 46.09,
                aggregated_usage: [{
                  metric: 'storage',
                  quantity: 1,
                  summary: 1,
                  cost: 1,
                  charge: 1
                }, {
                  metric: 'thousand_light_api_calls',
                  quantity: 3,
                  summary: 3,
                  cost: 0.09,
                  charge: 0.09
                }, {
                  metric: 'heavy_api_calls',
                  quantity: 300,
                  summary: 300,
                  cost: 45,
                  charge: 45
                }]
              }]
            }]
          }]
        }]
      };

      // Submit usage for sample resource with 10 GB, 1000 light API calls,
      // and 100 heavy API calls
      let posts = 0;
      const post = (u, done) => {
        console.log(u.message);

        const cb = () => {
          if(++posts === usage.length) done();
        };

        request.post(collector + '/v1/metering/resource/usage', {
          body: u.usage
        }, (err, val) => {
          expect(err).to.equal(undefined);

          // Expect a 201 with the location of the accumulated usage
          expect(val.statusCode).to.equal(201);
          expect(val.headers.location).to.not.equal(undefined);
          cb();
        });
      };

      // Print the number of usage docs already processed given a get report
      // response, determined from the aggregated usage quantity found in the
      // report for our test resource
      const processed = (val) => {
        try {
          return val.body.resources[0].aggregated_usage[1].summary;
        }
        catch (e) {
          // The response doesn't contain a valid report
          return 0;
        }
      };

      // Return the reporting day for the given time
      const day = (t) => {
        const d = new Date(t);
        return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
      };

      // Get a usage report for the test organization
      let gets = 0;
      const get = (done) => {
        request.get(reporting +
          '/v1/organizations/a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27/usage/:time',
          {
            time: day(start)
          }, (err, val) => {
            expect(err).to.equal(undefined);
            expect(val.statusCode).to.equal(200);

            // Compare the usage report we got with the expected report
            console.log('Processed %d usage docs', processed(val));
            try {
              expect(omit(val.body,
                ['id', 'start', 'end'])).to.deep.equal(report);
              console.log('\n', util.inspect(val.body, {
                depth: 10
              }), '\n');
              done();
            }
            catch (e) {
              // If the comparison fails we'll be called again to retry
              // after 1 second, give up after the configured timeout
              // still not getting the expected report then something
              // must have failed in the processing of that usage
              if(++gets === timeout / 250) {
                console.log('All submitted usage still not processed\n');
                throw e;
              }
            }
          });
      };

      // Wait for the expected usage report, get a report every 250 msec until
      // we get the expected values indicating that all submitted usage has
      // been processed
      const wait = (done) => {
        console.log('\nRetrieving usage report');
        const i = setInterval(() => get(() => done(clearInterval(i))), 250);
      };

      // Wait for usage reporter to start
      request.waitFor(reporting + '/batch', {}, (err, value) => {
        // Failed to ping usage reporter before timing out
        if (err) throw err;

        // Run the above steps
        map(usage, (u) => post(u, () => wait(done)));
      });
    });
});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
import { faLock } from '@fortawesome/fontawesome-free-solid'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom';
import { connect } from 'react-redux'
import {
  Collapse,
  Navbar,
  NavbarToggler,
  Nav,
  NavItem,
 } from 'reactstrap';
 import SearchBar from '../../SearchBar/SearchBar';

class Header extends Component {
  constructor(props) {
    super(props)

    this.state = {
      open: false,
      navbar: false,
      dropdownOpen: false,
      isOpen: false,
      search: false,
      showMenu: false,
      community: false,
      js_scrolled: false,
    }

    this.handleScroll = this.handleScroll.bind(this);
    this.toggleDrop = this.toggleDrop.bind(this)
    this.closeMenu = this.closeMenu.bind(this)
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  };

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  };

  handleScroll(event) {
    if(window.scrollY > 80){
      this.setState({
        js_scrolled: true
      })
    }
    else{
      this.setState({
        js_scrolled: false
      })
    }
  };

  openDrop(event){
    event.preventDefault();

    this.setState({
      open:!this.state.open
    }, () => {
      document.addEventListener('click', this.closeMenu);
    })
  }

  toggleDrop(){
    this.setState({
      dropdownOpen:!this.state.open
    })
  }

  openSearch(){
    this.setState({
      search: !this.state.search
    })
  }

  toggle() {
    this.setState({
      navbar: !this.state.navbar
    });
  }

  showMenu(event) {
    event.preventDefault();

    this.setState({ showMenu: !this.state.showMenu }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  community(event) {
    event.preventDefault();

    this.setState({ community: !this.state.community }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  closeMenu() {
    this.setState({ showMenu: false, community: false, open: false }, () => {
      document.removeEventListener('click', this.closeMenu);
    });
  }

  render(){
    const { properties } = this.props
    var jsscrolled = this.state.js_scrolled ? 'js-scrolled': ''
    var show = this.state.open?" show":""

    return(

Agid + Team Digitale

              <Link to={'/'}>

                {properties.domain!=='dataportal' && properties.domain!=='dataportal-private' && }
              </Link>

                <Link className="text-white" to={'/'}>

{/* props.styleProps.headerSiglaTool */}DAF {properties.headerSiglaTool}

                </Link>
                versione alpha 1.0

{/* props.styleProps.headerDescTool */}{"Data & Analytics Framework"} {properties.headerDescTool}

Seguici su

                {/*  */}

                  <button className={(this.state.search ? "btn-accento":"btn-header")+" h-100 btn"} style={{width: '56px'}} onClick={this.openSearch.bind(this)}></button>
                    {localStorage.getItem('token')?

                    <button className="h-100 btn btn-accento px-4" style={{marginLeft: '1px'}} id="dropdown" data-toggle="dropdown"  aria-haspopup="true" aria-expanded="false" onClick={this.openDrop.bind(this)}>
Area Pubblica
 </button>

VAI A

                        <button className="dropdown-item bg-light b-l-pvt border-primary pr-5" onClick={()=>{this.props.history.push('/private/home')}}>

<FontAwesomeIcon icon={faLock} className="mx-2"/>

Area privata e strumenti

Piattaforma di gestione
e analisi dati del DAF

                        </button>

                    :<button className="h-100 btn btn-header btn-accedi" onClick={()=>{this.props.history.push('/login')}}>
Accedi
</button>}

          {this.state.search && <SearchBar history={this.props.history} open={this.state.search}/>}

          <Navbar color="primary" light  className="py-1 h-100">
          <NavbarToggler className="d-md-none text-white border-0" onClick={this.toggle.bind(this)} children={}/>

              <NavItem>

                Il progetto

                  <Link to={'/missione'} className="dropdown-item text-primary font-lg">Missione</Link>
                  <Link to={'/team'} className="dropdown-item text-primary font-lg">Chi siamo</Link>
                  <Link to={'/lineeguida'} className="dropdown-item text-primary font-lg">Linee guida</Link>

              </NavItem>
              <NavItem>

                Community

                  <Link to={'/userstory/list'} className="dropdown-item text-primary font-lg">Storie</Link>
                  <Link to={'/notizie'} className="dropdown-item text-primary font-lg">Notizie</Link>
                  Forum

              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/partecipa'}>Partecipa</Link>
              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/data-applications'}>Data Application</Link>
              </NavItem>

          <Collapse isOpen={this.state.navbar} navbar>

              <NavItem>

                Il progetto

                  <Link to={'/missione'} className="dropdown-item">Missione</Link>
                  <Link to={'/team'} className="dropdown-item">Chi siamo</Link>
                  <Link to={'/lineeguida'} className="dropdown-item">Linee guida</Link>

              </NavItem>
              <NavItem>

                Community

                  <Link to={'/userstory/list'} className="dropdown-item">Storie</Link>
                  <Link to={'/notizie'} className="dropdown-item">Notizie</Link>
                  Forum

              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/partecipa'}>Partecipa</Link>
              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/data-applications'}>Data Application</Link>
              </NavItem>

          </Collapse>
        </Navbar>

    )
  }
}

Header.propTypes = {
  loggedUser: PropTypes.object,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { loggedUser, authed } = state.userReducer['obj'] || {}
  const { properties } = state.propertiesReducer['prop'] || {}

  return { loggedUser, authed, properties }
}

export default connect(mapStateToProps)(Header);<commit_msg>Add 'Faqs' entry in Header's 'Community' menu<commit_after>import React, { Component } from 'react';
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
import { faLock } from '@fortawesome/fontawesome-free-solid'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom';
import { connect } from 'react-redux'
import {
  Collapse,
  Navbar,
  NavbarToggler,
  Nav,
  NavItem,
 } from 'reactstrap';
 import SearchBar from '../../SearchBar/SearchBar';

class Header extends Component {
  constructor(props) {
    super(props)

    this.state = {
      open: false,
      navbar: false,
      dropdownOpen: false,
      isOpen: false,
      search: false,
      showMenu: false,
      community: false,
      js_scrolled: false,
    }

    this.handleScroll = this.handleScroll.bind(this);
    this.toggleDrop = this.toggleDrop.bind(this)
    this.closeMenu = this.closeMenu.bind(this)
  }

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  };

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  };

  handleScroll(event) {
    if(window.scrollY > 80){
      this.setState({
        js_scrolled: true
      })
    }
    else{
      this.setState({
        js_scrolled: false
      })
    }
  };

  openDrop(event){
    event.preventDefault();

    this.setState({
      open:!this.state.open
    }, () => {
      document.addEventListener('click', this.closeMenu);
    })
  }

  toggleDrop(){
    this.setState({
      dropdownOpen:!this.state.open
    })
  }

  openSearch(){
    this.setState({
      search: !this.state.search
    })
  }

  toggle() {
    this.setState({
      navbar: !this.state.navbar
    });
  }

  showMenu(event) {
    event.preventDefault();

    this.setState({ showMenu: !this.state.showMenu }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  community(event) {
    event.preventDefault();

    this.setState({ community: !this.state.community }, () => {
      document.addEventListener('click', this.closeMenu);
    });
  }

  closeMenu() {
    this.setState({ showMenu: false, community: false, open: false }, () => {
      document.removeEventListener('click', this.closeMenu);
    });
  }

  render(){
    const { properties } = this.props
    var jsscrolled = this.state.js_scrolled ? 'js-scrolled': ''
    var show = this.state.open?" show":""

    return(

Agid + Team Digitale

              <Link to={'/'}>

                {properties.domain!=='dataportal' && properties.domain!=='dataportal-private' && }
              </Link>

                <Link className="text-white" to={'/'}>

{/* props.styleProps.headerSiglaTool */}DAF {properties.headerSiglaTool}

                </Link>
                versione alpha 1.0

{/* props.styleProps.headerDescTool */}{"Data & Analytics Framework"} {properties.headerDescTool}

Seguici su

                {/*  */}

                  <button className={(this.state.search ? "btn-accento":"btn-header")+" h-100 btn"} style={{width: '56px'}} onClick={this.openSearch.bind(this)}></button>
                    {localStorage.getItem('token')?

                    <button className="h-100 btn btn-accento px-4" style={{marginLeft: '1px'}} id="dropdown" data-toggle="dropdown"  aria-haspopup="true" aria-expanded="false" onClick={this.openDrop.bind(this)}>
Area Pubblica
 </button>

VAI A

                        <button className="dropdown-item bg-light b-l-pvt border-primary pr-5" onClick={()=>{this.props.history.push('/private/home')}}>

<FontAwesomeIcon icon={faLock} className="mx-2"/>

Area privata e strumenti

Piattaforma di gestione
e analisi dati del DAF

                        </button>

                    :<button className="h-100 btn btn-header btn-accedi" onClick={()=>{this.props.history.push('/login')}}>
Accedi
</button>}

          {this.state.search && <SearchBar history={this.props.history} open={this.state.search}/>}

          <Navbar color="primary" light  className="py-1 h-100">
          <NavbarToggler className="d-md-none text-white border-0" onClick={this.toggle.bind(this)} children={}/>

              <NavItem>

                Il progetto

                  <Link to={'/missione'} className="dropdown-item text-primary font-lg">Missione</Link>
                  <Link to={'/team'} className="dropdown-item text-primary font-lg">Chi siamo</Link>
                  <Link to={'/lineeguida'} className="dropdown-item text-primary font-lg">Linee guida</Link>

              </NavItem>
              <NavItem>

                Community

                  <Link to={'/userstory/list'} className="dropdown-item text-primary font-lg">Storie</Link>
                  <Link to={'/notizie'} className="dropdown-item text-primary font-lg">Notizie</Link>
                  <Link to={'/faqs'} className="dropdown-item text-primary font-lg">Faqs</Link>
                  Forum

              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/partecipa'}>Partecipa</Link>
              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/data-applications'}>Data Application</Link>
              </NavItem>

          <Collapse isOpen={this.state.navbar} navbar>

              <NavItem>

                Il progetto

                  <Link to={'/missione'} className="dropdown-item">Missione</Link>
                  <Link to={'/team'} className="dropdown-item">Chi siamo</Link>
                  <Link to={'/lineeguida'} className="dropdown-item">Linee guida</Link>

              </NavItem>
              <NavItem>

                Community

                  <Link to={'/userstory/list'} className="dropdown-item">Storie</Link>
                  <Link to={'/notizie'} className="dropdown-item">Notizie</Link>
                  Forum

              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/partecipa'}>Partecipa</Link>
              </NavItem>
              <NavItem>
                <Link className="nav-link font-weight-bold lead text-white" to={'/data-applications'}>Data Application</Link>
              </NavItem>

          </Collapse>
        </Navbar>

    )
  }
}

Header.propTypes = {
  loggedUser: PropTypes.object,
  dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
  const { loggedUser, authed } = state.userReducer['obj'] || {}
  const { properties } = state.propertiesReducer['prop'] || {}

  return { loggedUser, authed, properties }
}

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


<commit_before>import React from "react";
import PropTypes from 'prop-types';
import Radium from "radium";

import Knob from "components/knob";
import Guides from "components/guides";
import SelectorKnobInner from "components/selectorKnobInner";

import { grey } from "theme/variables";
import { labelGreySmall, labelGreyLarge, ring } from "theme/mixins";

const labelHeight = 33;

const guideValues = [

MANUAL
,
  16,
  12,
  8,
  4,
  2
];
guideValues.push();

class AutoFillInKnob extends React.Component {
  render() {
    const { value, onChange, size = 200 } = this.props;

    const knobSize = size - 75;

    const styles = {
      wrapper: {
        display: "flex",
        flexDirection: "column",
        alignItems: "stretch",
        justifyContent: "space-between",
        width: size,
        height: size
      },

      controlWrapper: {
        position: "relative",
        width: size,
        height: size,
        minWidth: size,
        minHeight: size
      },

      labelGuide: labelGreySmall,

      dotGuide: {
        width: 5,
        height: 5,
        backgroundColor: grey,
        borderRadius: "50%"
      },

      knobWrapper: ring(knobSize),

      labelWrapper: {
        position: "relative",
        top: -30,
        width: size,
        height: labelHeight,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "space-between"
      },

      measuresLabel: labelGreySmall,

      autoLabel: {
        position: "relative",
        top: -2,
        ...labelGreyLarge
      }
    };

    return (

          <Guides
            num={6}
            distance={size * 0.29}
            hideCount={6}
            guideStyle={styles.dotGuide}
          />
          <Guides
            distance={size * 0.37}
            hideCount={5.5}
            values={guideValues}
            rotate={false}
            guideStyle={styles.labelGuide}
          />

            <Knob
              value={value}
              onChange={onChange}
              size={knobSize}
              bufferSize={150}
              min={0}
              max={5}
              step={1}
            >
              <SelectorKnobInner size={knobSize} />
            </Knob>

MEASURES

AUTO FILL IN

    );
  }
}

AutoFillInKnob.propTypes = {
  onChange: PropTypes.func.isRequired,
  value: PropTypes.number.isRequired
};

export default Radium(AutoFillInKnob);
<commit_msg>migrate autoFillInKnob to hooks<commit_after>import React from "react";

import Knob from "components/knob";
import Guides from "components/guides";
import SelectorKnobInner from "components/selectorKnobInner";

import { grey } from "theme/variables";
import { labelGreySmall, labelGreyLarge, ring } from "theme/mixins";

const labelHeight = 33;

const styles = {
  wrapper: {
    display: "flex",
    flexDirection: "column",
    alignItems: "stretch",
    justifyContent: "space-between"
  },
  controlWrapper: {
    position: "relative"
  },
  labelGuide: labelGreySmall,
  dotGuide: {
    width: 5,
    height: 5,
    backgroundColor: grey,
    borderRadius: "50%"
  },
  labelWrapper: {
    position: "relative",
    top: -30,
    height: labelHeight,
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "space-between"
  },
  measuresLabel: labelGreySmall,
  autoLabel: {
    position: "relative",
    top: -2,
    ...labelGreyLarge
  }
};

const guideValues = [

MANUAL
,
  16,
  12,
  8,
  4,
  2
];

const AutoFillInKnob = props => {
  const { value, onChange, size = 200 } = props;
  const knobSize = size - 75;
  return (

        <Guides
          num={6}
          distance={size * 0.29}
          hideCount={6}
          guideStyle={styles.dotGuide}
        />
        <Guides
          distance={size * 0.37}
          hideCount={5.5}
          values={guideValues}
          rotate={false}
          guideStyle={styles.labelGuide}
        />

          <Knob
            value={value}
            onChange={onChange}
            size={knobSize}
            bufferSize={150}
            min={0}
            max={5}
            step={1}
          >
            <SelectorKnobInner size={knobSize} />
          </Knob>

MEASURES

AUTO FILL IN

  );
};

export default AutoFillInKnob;
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow

import React, { PureComponent } from 'react';
import classNames from 'classnames';
import {
  changeRightClickedTrack,
  changeLocalTrackOrder,
  selectTrack,
} from '../../actions/profile-view';
import ContextMenuTrigger from '../shared/ContextMenuTrigger';
import {
  getSelectedThreadIndex,
  getHiddenGlobalTracks,
  getLocalTrackOrder,
  getSelectedTab,
} from '../../selectors/url-state';
import explicitConnect from '../../utils/connect';
import {
  getGlobalTracks,
  getLocalTracks,
  getGlobalTrackName,
  getProcessesWithMemoryTrack,
} from '../../selectors/profile';
import { getThreadSelectors } from '../../selectors/per-thread';
import './Track.css';
import TimelineTrackThread from './TrackThread';
import TimelineTrackScreenshots from './TrackScreenshots';
import TimelineLocalTrack from './LocalTrack';
import Reorderable from '../shared/Reorderable';
import type { TabSlug } from '../../app-logic/tabs-handling';
import type { GlobalTrackReference } from '../../types/actions';
import type { Pid } from '../../types/profile';
import type {
  TrackIndex,
  GlobalTrack,
  LocalTrack,
} from '../../types/profile-derived';
import type {
  ExplicitConnectOptions,
  ConnectedProps,
} from '../../utils/connect';

type OwnProps = {|
  +trackReference: GlobalTrackReference,
  +trackIndex: TrackIndex,
  +style?: Object /* This is used by Reorderable */,
|};

type StateProps = {|
  +trackName: string,
  +globalTrack: GlobalTrack,
  +isSelected: boolean,
  +isHidden: boolean,
  +titleText: string | null,
  +localTrackOrder: TrackIndex[],
  +localTracks: LocalTrack[],
  +pid: Pid | null,
  +selectedTab: TabSlug,
  +processesWithMemoryTrack: Set<Pid>,
|};

type DispatchProps = {|
  +changeRightClickedTrack: typeof changeRightClickedTrack,
  +changeLocalTrackOrder: typeof changeLocalTrackOrder,
  +selectTrack: typeof selectTrack,
|};

type Props = ConnectedProps<OwnProps, StateProps, DispatchProps>;

class GlobalTrackComponent extends PureComponent<Props> {
  _onLabelMouseDown = (event: MouseEvent) => {
    const { changeRightClickedTrack, trackReference } = this.props;

    if (event.button === 0) {
      // Don't allow clicks on the threads list to steal focus from the tree view.
      event.preventDefault();
      this._selectCurrentTrack();
    } else if (event.button === 2) {
      // This is needed to allow the context menu to know what was right clicked without
      // actually changing the current selection.
      changeRightClickedTrack(trackReference);
    }
  };

  _selectCurrentTrack = () => {
    const { selectTrack, trackReference } = this.props;
    selectTrack(trackReference);
  };

  renderTrack() {
    const { globalTrack, processesWithMemoryTrack } = this.props;
    switch (globalTrack.type) {
      case 'process': {
        const { mainThreadIndex } = globalTrack;
        if (mainThreadIndex === null) {
          return
;
        }
        return (
          <TimelineTrackThread
            threadIndex={mainThreadIndex}
            showMemoryMarkers={!processesWithMemoryTrack.has(globalTrack.pid)}
          />
        );
      }
      case 'screenshots': {
        const { threadIndex, id } = globalTrack;
        return (
          <TimelineTrackScreenshots threadIndex={threadIndex} windowId={id} />
        );
      }
      default:
        console.error('Unhandled globalTrack type', (globalTrack: empty));
        return null;
    }
  }

  _changeLocalTrackOrder = (trackOrder: TrackIndex[]) => {
    const { globalTrack, changeLocalTrackOrder } = this.props;
    if (globalTrack.type === 'process') {
      // Only process tracks have local tracks.
      changeLocalTrackOrder(globalTrack.pid, trackOrder);
    }
  };

  renderLocalTracks(pid: Pid) {
    const { localTracks, localTrackOrder } = this.props;
    return (
      <Reorderable
        tagName="ol"
        className="timelineTrackLocalTracks"
        order={localTrackOrder}
        orient="vertical"
        grippyClassName="timelineTrackLocalGrippy"
        onChangeOrder={this._changeLocalTrackOrder}
      >
        {localTracks.map((localTrack, trackIndex) => (
          <TimelineLocalTrack
            key={trackIndex}
            pid={pid}
            localTrack={localTrack}
            trackIndex={trackIndex}
          />
        ))}
      </Reorderable>
    );
  }

  render() {
    const {
      isSelected,
      isHidden,
      titleText,
      trackName,
      style,
      localTracks,
      pid,
    } = this.props;

    if (isHidden) {
      // If this global track is hidden, render out a stub element so that the
      // Reorderable Component still works across all the tracks.
      return
;
    }

    return (

          <ContextMenuTrigger
            id="TimelineTrackContextMenu"
            renderTag="div"
            attributes={{
              title: titleText,
              className: 'timelineTrackLabel timelineTrackGlobalGrippy',
              onMouseDown: this._onLabelMouseDown,
            }}
          >
            <button type="button" className="timelineTrackNameButton">
              {trackName}

                PID: {pid}

            </button>
          </ContextMenuTrigger>

{this.renderTrack()}

        {localTracks.length > 0 && pid !== null
          ? this.renderLocalTracks(pid)
          : null}

    );
  }
}

// Provide some empty lists, so that strict equality checks work for component updates.
const EMPTY_TRACK_ORDER = [];
const EMPTY_LOCAL_TRACKS = [];

const options: ExplicitConnectOptions<OwnProps, StateProps, DispatchProps> = {
  mapStateToProps: (state, { trackIndex }) => {
    const globalTracks = getGlobalTracks(state);
    const globalTrack = globalTracks[trackIndex];
    const selectedTab = getSelectedTab(state);

    // These get assigned based on the track type.
    let threadIndex = null;
    let isSelected = false;
    let titleText = null;

    let localTrackOrder = EMPTY_TRACK_ORDER;
    let localTracks = EMPTY_LOCAL_TRACKS;
    let pid = null;

    // Run different selectors based on the track type.
    switch (globalTrack.type) {
      case 'process': {
        // Look up the thread information for the process if it exists.
        if (globalTrack.mainThreadIndex !== null) {
          threadIndex = globalTrack.mainThreadIndex;
          const selectors = getThreadSelectors(threadIndex);
          isSelected =
            threadIndex === getSelectedThreadIndex(state) &&
            selectedTab !== 'network-chart';
          titleText = selectors.getThreadProcessDetails(state);
        }
        pid = globalTrack.pid;
        localTrackOrder = getLocalTrackOrder(state, pid);
        localTracks = getLocalTracks(state, pid);
        break;
      }
      case 'screenshots':
        break;
      default:
        throw new Error(`Unhandled GlobalTrack type ${(globalTrack: empty)}`);
    }

    return {
      trackName: getGlobalTrackName(state, trackIndex),
      titleText,
      globalTrack,
      isSelected,
      localTrackOrder,
      localTracks,
      pid,
      isHidden: getHiddenGlobalTracks(state).has(trackIndex),
      selectedTab,
      processesWithMemoryTrack: getProcessesWithMemoryTrack(state),
    };
  },
  mapDispatchToProps: {
    changeRightClickedTrack,
    changeLocalTrackOrder,
    selectTrack,
  },
  component: GlobalTrackComponent,
};

export default explicitConnect(options);
<commit_msg>Only show the PID if it is a number (PR #1898)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// @flow

import React, { PureComponent } from 'react';
import classNames from 'classnames';
import {
  changeRightClickedTrack,
  changeLocalTrackOrder,
  selectTrack,
} from '../../actions/profile-view';
import ContextMenuTrigger from '../shared/ContextMenuTrigger';
import {
  getSelectedThreadIndex,
  getHiddenGlobalTracks,
  getLocalTrackOrder,
  getSelectedTab,
} from '../../selectors/url-state';
import explicitConnect from '../../utils/connect';
import {
  getGlobalTracks,
  getLocalTracks,
  getGlobalTrackName,
  getProcessesWithMemoryTrack,
} from '../../selectors/profile';
import { getThreadSelectors } from '../../selectors/per-thread';
import './Track.css';
import TimelineTrackThread from './TrackThread';
import TimelineTrackScreenshots from './TrackScreenshots';
import TimelineLocalTrack from './LocalTrack';
import Reorderable from '../shared/Reorderable';
import type { TabSlug } from '../../app-logic/tabs-handling';
import type { GlobalTrackReference } from '../../types/actions';
import type { Pid } from '../../types/profile';
import type {
  TrackIndex,
  GlobalTrack,
  LocalTrack,
} from '../../types/profile-derived';
import type {
  ExplicitConnectOptions,
  ConnectedProps,
} from '../../utils/connect';

type OwnProps = {|
  +trackReference: GlobalTrackReference,
  +trackIndex: TrackIndex,
  +style?: Object /* This is used by Reorderable */,
|};

type StateProps = {|
  +trackName: string,
  +globalTrack: GlobalTrack,
  +isSelected: boolean,
  +isHidden: boolean,
  +titleText: string | null,
  +localTrackOrder: TrackIndex[],
  +localTracks: LocalTrack[],
  +pid: Pid | null,
  +selectedTab: TabSlug,
  +processesWithMemoryTrack: Set<Pid>,
|};

type DispatchProps = {|
  +changeRightClickedTrack: typeof changeRightClickedTrack,
  +changeLocalTrackOrder: typeof changeLocalTrackOrder,
  +selectTrack: typeof selectTrack,
|};

type Props = ConnectedProps<OwnProps, StateProps, DispatchProps>;

class GlobalTrackComponent extends PureComponent<Props> {
  _onLabelMouseDown = (event: MouseEvent) => {
    const { changeRightClickedTrack, trackReference } = this.props;

    if (event.button === 0) {
      // Don't allow clicks on the threads list to steal focus from the tree view.
      event.preventDefault();
      this._selectCurrentTrack();
    } else if (event.button === 2) {
      // This is needed to allow the context menu to know what was right clicked without
      // actually changing the current selection.
      changeRightClickedTrack(trackReference);
    }
  };

  _selectCurrentTrack = () => {
    const { selectTrack, trackReference } = this.props;
    selectTrack(trackReference);
  };

  renderTrack() {
    const { globalTrack, processesWithMemoryTrack } = this.props;
    switch (globalTrack.type) {
      case 'process': {
        const { mainThreadIndex } = globalTrack;
        if (mainThreadIndex === null) {
          return
;
        }
        return (
          <TimelineTrackThread
            threadIndex={mainThreadIndex}
            showMemoryMarkers={!processesWithMemoryTrack.has(globalTrack.pid)}
          />
        );
      }
      case 'screenshots': {
        const { threadIndex, id } = globalTrack;
        return (
          <TimelineTrackScreenshots threadIndex={threadIndex} windowId={id} />
        );
      }
      default:
        console.error('Unhandled globalTrack type', (globalTrack: empty));
        return null;
    }
  }

  _changeLocalTrackOrder = (trackOrder: TrackIndex[]) => {
    const { globalTrack, changeLocalTrackOrder } = this.props;
    if (globalTrack.type === 'process') {
      // Only process tracks have local tracks.
      changeLocalTrackOrder(globalTrack.pid, trackOrder);
    }
  };

  renderLocalTracks(pid: Pid) {
    const { localTracks, localTrackOrder } = this.props;
    return (
      <Reorderable
        tagName="ol"
        className="timelineTrackLocalTracks"
        order={localTrackOrder}
        orient="vertical"
        grippyClassName="timelineTrackLocalGrippy"
        onChangeOrder={this._changeLocalTrackOrder}
      >
        {localTracks.map((localTrack, trackIndex) => (
          <TimelineLocalTrack
            key={trackIndex}
            pid={pid}
            localTrack={localTrack}
            trackIndex={trackIndex}
          />
        ))}
      </Reorderable>
    );
  }

  render() {
    const {
      isSelected,
      isHidden,
      titleText,
      trackName,
      style,
      localTracks,
      pid,
    } = this.props;

    if (isHidden) {
      // If this global track is hidden, render out a stub element so that the
      // Reorderable Component still works across all the tracks.
      return
;
    }

    return (

          <ContextMenuTrigger
            id="TimelineTrackContextMenu"
            renderTag="div"
            attributes={{
              title: titleText,
              className: 'timelineTrackLabel timelineTrackGlobalGrippy',
              onMouseDown: this._onLabelMouseDown,
            }}
          >
            <button type="button" className="timelineTrackNameButton">
              {trackName}
              {/* Only show the PID if it is a real number. A string PID is an
                * artificially generated value that is not useful, and a null
                * value does not exist. */}
              {typeof pid === 'number' ? (

                  PID: {pid}

              ) : null}
            </button>
          </ContextMenuTrigger>

{this.renderTrack()}

        {localTracks.length > 0 && pid !== null
          ? this.renderLocalTracks(pid)
          : null}

    );
  }
}

// Provide some empty lists, so that strict equality checks work for component updates.
const EMPTY_TRACK_ORDER = [];
const EMPTY_LOCAL_TRACKS = [];

const options: ExplicitConnectOptions<OwnProps, StateProps, DispatchProps> = {
  mapStateToProps: (state, { trackIndex }) => {
    const globalTracks = getGlobalTracks(state);
    const globalTrack = globalTracks[trackIndex];
    const selectedTab = getSelectedTab(state);

    // These get assigned based on the track type.
    let threadIndex = null;
    let isSelected = false;
    let titleText = null;

    let localTrackOrder = EMPTY_TRACK_ORDER;
    let localTracks = EMPTY_LOCAL_TRACKS;
    let pid = null;

    // Run different selectors based on the track type.
    switch (globalTrack.type) {
      case 'process': {
        // Look up the thread information for the process if it exists.
        if (globalTrack.mainThreadIndex !== null) {
          threadIndex = globalTrack.mainThreadIndex;
          const selectors = getThreadSelectors(threadIndex);
          isSelected =
            threadIndex === getSelectedThreadIndex(state) &&
            selectedTab !== 'network-chart';
          titleText = selectors.getThreadProcessDetails(state);
        }
        pid = globalTrack.pid;
        localTrackOrder = getLocalTrackOrder(state, pid);
        localTracks = getLocalTracks(state, pid);
        break;
      }
      case 'screenshots':
        break;
      default:
        throw new Error(`Unhandled GlobalTrack type ${(globalTrack: empty)}`);
    }

    return {
      trackName: getGlobalTrackName(state, trackIndex),
      titleText,
      globalTrack,
      isSelected,
      localTrackOrder,
      localTracks,
      pid,
      isHidden: getHiddenGlobalTracks(state).has(trackIndex),
      selectedTab,
      processesWithMemoryTrack: getProcessesWithMemoryTrack(state),
    };
  },
  mapDispatchToProps: {
    changeRightClickedTrack,
    changeLocalTrackOrder,
    selectTrack,
  },
  component: GlobalTrackComponent,
};

export default explicitConnect(options);
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

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

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

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

'use strict';
var React = require("react");
var ReactDOM = require("react-dom");
var GeminiScrollbar = require('react-gemini-scrollbar');
var MatrixClientPeg = require("../../../MatrixClientPeg");
var CallHandler = require('../../../CallHandler');
var RoomListSorter = require("../../../RoomListSorter");
var Unread = require('../../../Unread');
var dis = require("../../../dispatcher");
var sdk = require('../../../index');

var HIDE_CONFERENCE_CHANS = true;

module.exports = React.createClass({
    displayName: 'RoomList',

    propTypes: {
        ConferenceHandler: React.PropTypes.any,
        collapsed: React.PropTypes.bool,
        currentRoom: React.PropTypes.string
    },

    getInitialState: function() {
        return {
            isLoadingLeftRooms: false,
            lists: {},
            incomingCall: null,
        }
    },

    componentWillMount: function() {
        var cli = MatrixClientPeg.get();
        cli.on("Room", this.onRoom);
        cli.on("deleteRoom", this.onDeleteRoom);
        cli.on("Room.timeline", this.onRoomTimeline);
        cli.on("Room.name", this.onRoomName);
        cli.on("Room.tags", this.onRoomTags);
        cli.on("Room.receipt", this.onRoomReceipt);
        cli.on("RoomState.events", this.onRoomStateEvents);
        cli.on("RoomMember.name", this.onRoomMemberName);

        var s = this.getRoomLists();
        this.setState(s);
    },

    componentDidMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
    },

    onAction: function(payload) {
        switch (payload.action) {
            case 'view_tooltip':
                this.tooltip = payload.tooltip;
                this._repositionTooltip();
                if (this.tooltip) this.tooltip.style.display = 'block';
                break;
            case 'call_state':
                var call = CallHandler.getCall(payload.room_id);
                if (call && call.call_state === 'ringing') {
                    this.setState({
                        incomingCall: call
                    });
                    this._repositionIncomingCallBox(undefined, true);
                }
                else {
                    this.setState({
                        incomingCall: null
                    });
                }
                break;
        }
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("Room", this.onRoom);
            MatrixClientPeg.get().removeListener("Room.timeline", this.onRoomTimeline);
            MatrixClientPeg.get().removeListener("Room.receipt", this.onRoomReceipt);
            MatrixClientPeg.get().removeListener("Room.name", this.onRoomName);
            MatrixClientPeg.get().removeListener("RoomState.events", this.onRoomStateEvents);
        }
    },

    onRoom: function(room) {
        this._delayedRefreshRoomList();
    },

    onDeleteRoom: function(roomId) {
        this._delayedRefreshRoomList();
    },

    onArchivedHeaderClick: function(isHidden) {
        if (!isHidden) {
            var self = this;
            this.setState({ isLoadingLeftRooms: true });
            // we don't care about the response since it comes down via "Room"
            // events.
            MatrixClientPeg.get().syncLeftRooms().catch(function(err) {
                console.error("Failed to sync left rooms: %s", err);
                console.error(err);
            }).finally(function() {
                self.setState({ isLoadingLeftRooms: false });
            });
        }
    },

    onRoomTimeline: function(ev, room, toStartOfTimeline) {
        if (toStartOfTimeline) return;
        this.refreshRoomList();
    },

    onRoomReceipt: function(receiptEvent, room) {
        // because if we read a notification, it will affect notification count
        // only bother updating if there's a receipt from us
        var receiptKeys = Object.keys(receiptEvent.getContent());
        for (var i = 0; i < receiptKeys.length; ++i) {
            var rcpt = receiptEvent.getContent()[receiptKeys[i]];
            if (rcpt['m.read'] && rcpt['m.read'][MatrixClientPeg.get().credentials.userId]) {
                this.refreshRoomList();
                break;
            }
        }
    },

    onRoomName: function(room) {
        this._delayedRefreshRoomList();
    },

    onRoomTags: function(event, room) {
        this._delayedRefreshRoomList();
    },

    onRoomStateEvents: function(ev, state) {
        this._delayedRefreshRoomList();
    },

    onRoomMemberName: function(ev, member) {
        this._delayedRefreshRoomList();
    },

    _delayedRefreshRoomList: function() {
        // There can be 1000s of JS SDK events when rooms are initially synced;
        // we don't want to do lots of work rendering until things have settled.
        // Therefore, keep a 1s refresh buffer which will refresh the room list
        // at MOST once every 1s to prevent thrashing.
        var MAX_REFRESH_INTERVAL_MS = 1000;
        var self = this;

        if (!self._lastRefreshRoomListTs) {
            self.refreshRoomList(); // first refresh evar
        }
        else {
            var timeWaitedMs = Date.now() - self._lastRefreshRoomListTs;
            if (timeWaitedMs > MAX_REFRESH_INTERVAL_MS) {
                clearTimeout(self._refreshRoomListTimerId);
                self._refreshRoomListTimerId = null;
                self.refreshRoomList(); // refreshed more than MAX_REFRESH_INTERVAL_MS ago
            }
            else {
                // refreshed less than MAX_REFRESH_INTERVAL_MS ago, wait the difference
                // if we aren't already waiting. If we are waiting then NOP, it will
                // fire soon, promise!
                if (!self._refreshRoomListTimerId) {
                    self._refreshRoomListTimerId = setTimeout(function() {
                        self.refreshRoomList();
                    }, 10 + MAX_REFRESH_INTERVAL_MS - timeWaitedMs); // 10 is a buffer amount
                }
            }
        }
    },

    refreshRoomList: function() {
        // console.log("DEBUG: Refresh room list delta=%s ms",
        //     (!this._lastRefreshRoomListTs ? "-" : (Date.now() - this._lastRefreshRoomListTs))
        // );

        // TODO: rather than bluntly regenerating and re-sorting everything
        // every time we see any kind of room change from the JS SDK
        // we could do incremental updates on our copy of the state
        // based on the room which has actually changed.  This would stop
        // us re-rendering all the sublists every time anything changes anywhere
        // in the state of the client.
        this.setState(this.getRoomLists());
        this._lastRefreshRoomListTs = Date.now();
    },

    getRoomLists: function() {
        var self = this;
        var s = { lists: {} };

        s.lists["im.vector.fake.invite"] = [];
        s.lists["m.favourite"] = [];
        s.lists["im.vector.fake.recent"] = [];
        s.lists["m.lowpriority"] = [];
        s.lists["im.vector.fake.archived"] = [];

        MatrixClientPeg.get().getRooms().forEach(function(room) {
            var me = room.getMember(MatrixClientPeg.get().credentials.userId);

            if (me && me.membership == "invite") {
                s.lists["im.vector.fake.invite"].push(room);
            }
            else if (me && me.membership === "leave") {
                s.lists["im.vector.fake.archived"].push(room);
            }
            else {
                var shouldShowRoom =  (
                    me && (me.membership == "join" || me.membership === "ban")
                );

                // hiding conf rooms only ever toggles shouldShowRoom to false
                if (shouldShowRoom && HIDE_CONFERENCE_CHANS) {
                    // we want to hide the 1:1 conf<->user room and not the group chat
                    var joinedMembers = room.getJoinedMembers();
                    if (joinedMembers.length === 2) {
                        var otherMember = joinedMembers.filter(function(m) {
                            return m.userId !== me.userId
                        })[0];
                        var ConfHandler = self.props.ConferenceHandler;
                        if (ConfHandler && ConfHandler.isConferenceUser(otherMember.userId)) {
                            // console.log("Hiding conference 1:1 room %s", room.roomId);
                            shouldShowRoom = false;
                        }
                    }
                }

                if (shouldShowRoom) {
                    var tagNames = Object.keys(room.tags);
                    if (tagNames.length) {
                        for (var i = 0; i < tagNames.length; i++) {
                            var tagName = tagNames[i];
                            s.lists[tagName] = s.lists[tagName] || [];
                            s.lists[tagNames[i]].push(room);
                        }
                    }
                    else {
                        s.lists["im.vector.fake.recent"].push(room);
                    }
                }
            }
        });

        //console.log("calculated new roomLists; im.vector.fake.recent = " + s.lists["im.vector.fake.recent"]);

        // we actually apply the sorting to this when receiving the prop in RoomSubLists.

        return s;
    },

    _getScrollNode: function() {
        var panel = ReactDOM.findDOMNode(this);
        if (!panel) return null;

        if (panel.classList.contains('gm-prevented')) {
            return panel;
        } else {
            return panel.children[2]; // XXX: Fragile!
        }
    },

    _repositionTooltips: function(e) {
        this._repositionTooltip(e);
        this._repositionIncomingCallBox(e, false);
    },

    _repositionTooltip: function(e) {
        if (this.tooltip && this.tooltip.parentElement) {
            var scroll = ReactDOM.findDOMNode(this);
            this.tooltip.style.top = (scroll.parentElement.offsetTop + this.tooltip.parentElement.offsetTop - this._getScrollNode().scrollTop) + "px";
        }
    },

    _repositionIncomingCallBox: function(e, firstTime) {
        var incomingCallBox = document.getElementById("incomingCallBox");
        if (incomingCallBox && incomingCallBox.parentElement) {
            var scroll = this._getScrollNode();
            var top = (scroll.offsetTop + incomingCallBox.parentElement.offsetTop - scroll.scrollTop);

            if (firstTime) {
                // scroll to make sure the callbox is on the screen...
                if (top < 10) { // 10px of vertical margin at top of screen
                    scroll.scrollTop = incomingCallBox.parentElement.offsetTop - 10;
                }
                else if (top > scroll.clientHeight - incomingCallBox.offsetHeight + 50) {
                    scroll.scrollTop = incomingCallBox.parentElement.offsetTop - scroll.offsetHeight + incomingCallBox.offsetHeight - 50;
                }
                // recalculate top in case we clipped it.
                top = (scroll.offsetTop + incomingCallBox.parentElement.offsetTop - scroll.scrollTop);
            }
            else {
                // stop the box from scrolling off the screen
                if (top < 10) {
                    top = 10;
                }
                else if (top > scroll.clientHeight - incomingCallBox.offsetHeight + 50) {
                    top = scroll.clientHeight - incomingCallBox.offsetHeight + 50;
                }
            }

            incomingCallBox.style.top = top + "px";
            incomingCallBox.style.left = scroll.offsetLeft + scroll.offsetWidth + "px";
        }
    },

    onShowClick: function() {
        dis.dispatch({
            action: 'show_left_panel',
        });
    },

    render: function() {
        var expandButton = this.props.collapsed ?
                           "/> :
                           null;

        var RoomSubList = sdk.getComponent('structures.RoomSubList');
        var self = this;

        return (
            <GeminiScrollbar className="mx_RoomList_scrollbar" autoshow={true} onScroll={ self._repositionTooltips }>

                { expandButton }

                <RoomSubList list={ self.state.lists['im.vector.fake.invite'] }
                             label="Invites"
                             editable={ false }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed } />

                <RoomSubList list={ self.state.lists['m.favourite'] }
                             label="Favourites"
                             tagName="m.favourite"
                             verb="favourite"
                             editable={ true }
                             order="manual"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed } />

                <RoomSubList list={ self.state.lists['im.vector.fake.recent'] }
                             label="Rooms"
                             editable={ true }
                             verb="restore"
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed } />

                { Object.keys(self.state.lists).map(function(tagName) {
                    if (!tagName.match(/^(m\.(favourite|lowpriority)|im\.vector\.fake\.(invite|recent|archived))$/)) {
                        return <RoomSubList list={ self.state.lists[tagName] }
                             key={ tagName }
                             label={ tagName }
                             tagName={ tagName }
                             verb={ "tag as " + tagName }
                             editable={ true }
                             order="manual"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed } />

                    }
                }) }

                <RoomSubList list={ self.state.lists['m.lowpriority'] }
                             label="Low priority"
                             tagName="m.lowpriority"
                             verb="demote"
                             editable={ true }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed } />

                <RoomSubList list={ self.state.lists['im.vector.fake.archived'] }
                             label="Historical"
                             editable={ false }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             collapsed={ self.props.collapsed }
                             alwaysShowHeader={ true }
                             startAsHidden={ true }
                             showSpinner={ self.state.isLoadingLeftRooms }
                             onHeaderClick= { self.onArchivedHeaderClick }
                             incomingCall={ self.state.incomingCall } />

            </GeminiScrollbar>
        );
    }
});
<commit_msg>Add onShowMoreRooms prop for kicking gemini<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

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

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

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

'use strict';
var React = require("react");
var ReactDOM = require("react-dom");
var GeminiScrollbar = require('react-gemini-scrollbar');
var MatrixClientPeg = require("../../../MatrixClientPeg");
var CallHandler = require('../../../CallHandler');
var RoomListSorter = require("../../../RoomListSorter");
var Unread = require('../../../Unread');
var dis = require("../../../dispatcher");
var sdk = require('../../../index');

var HIDE_CONFERENCE_CHANS = true;

module.exports = React.createClass({
    displayName: 'RoomList',

    propTypes: {
        ConferenceHandler: React.PropTypes.any,
        collapsed: React.PropTypes.bool,
        currentRoom: React.PropTypes.string
    },

    getInitialState: function() {
        return {
            isLoadingLeftRooms: false,
            lists: {},
            incomingCall: null,
        }
    },

    componentWillMount: function() {
        var cli = MatrixClientPeg.get();
        cli.on("Room", this.onRoom);
        cli.on("deleteRoom", this.onDeleteRoom);
        cli.on("Room.timeline", this.onRoomTimeline);
        cli.on("Room.name", this.onRoomName);
        cli.on("Room.tags", this.onRoomTags);
        cli.on("Room.receipt", this.onRoomReceipt);
        cli.on("RoomState.events", this.onRoomStateEvents);
        cli.on("RoomMember.name", this.onRoomMemberName);

        var s = this.getRoomLists();
        this.setState(s);
    },

    componentDidMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
    },

    onAction: function(payload) {
        switch (payload.action) {
            case 'view_tooltip':
                this.tooltip = payload.tooltip;
                this._repositionTooltip();
                if (this.tooltip) this.tooltip.style.display = 'block';
                break;
            case 'call_state':
                var call = CallHandler.getCall(payload.room_id);
                if (call && call.call_state === 'ringing') {
                    this.setState({
                        incomingCall: call
                    });
                    this._repositionIncomingCallBox(undefined, true);
                }
                else {
                    this.setState({
                        incomingCall: null
                    });
                }
                break;
        }
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("Room", this.onRoom);
            MatrixClientPeg.get().removeListener("Room.timeline", this.onRoomTimeline);
            MatrixClientPeg.get().removeListener("Room.receipt", this.onRoomReceipt);
            MatrixClientPeg.get().removeListener("Room.name", this.onRoomName);
            MatrixClientPeg.get().removeListener("RoomState.events", this.onRoomStateEvents);
        }
    },

    onRoom: function(room) {
        this._delayedRefreshRoomList();
    },

    onDeleteRoom: function(roomId) {
        this._delayedRefreshRoomList();
    },

    onArchivedHeaderClick: function(isHidden) {
        if (!isHidden) {
            var self = this;
            this.setState({ isLoadingLeftRooms: true });
            // we don't care about the response since it comes down via "Room"
            // events.
            MatrixClientPeg.get().syncLeftRooms().catch(function(err) {
                console.error("Failed to sync left rooms: %s", err);
                console.error(err);
            }).finally(function() {
                self.setState({ isLoadingLeftRooms: false });
            });
        }
    },

    onRoomTimeline: function(ev, room, toStartOfTimeline) {
        if (toStartOfTimeline) return;
        this.refreshRoomList();
    },

    onRoomReceipt: function(receiptEvent, room) {
        // because if we read a notification, it will affect notification count
        // only bother updating if there's a receipt from us
        var receiptKeys = Object.keys(receiptEvent.getContent());
        for (var i = 0; i < receiptKeys.length; ++i) {
            var rcpt = receiptEvent.getContent()[receiptKeys[i]];
            if (rcpt['m.read'] && rcpt['m.read'][MatrixClientPeg.get().credentials.userId]) {
                this.refreshRoomList();
                break;
            }
        }
    },

    onRoomName: function(room) {
        this._delayedRefreshRoomList();
    },

    onRoomTags: function(event, room) {
        this._delayedRefreshRoomList();
    },

    onRoomStateEvents: function(ev, state) {
        this._delayedRefreshRoomList();
    },

    onRoomMemberName: function(ev, member) {
        this._delayedRefreshRoomList();
    },

    _delayedRefreshRoomList: function() {
        // There can be 1000s of JS SDK events when rooms are initially synced;
        // we don't want to do lots of work rendering until things have settled.
        // Therefore, keep a 1s refresh buffer which will refresh the room list
        // at MOST once every 1s to prevent thrashing.
        var MAX_REFRESH_INTERVAL_MS = 1000;
        var self = this;

        if (!self._lastRefreshRoomListTs) {
            self.refreshRoomList(); // first refresh evar
        }
        else {
            var timeWaitedMs = Date.now() - self._lastRefreshRoomListTs;
            if (timeWaitedMs > MAX_REFRESH_INTERVAL_MS) {
                clearTimeout(self._refreshRoomListTimerId);
                self._refreshRoomListTimerId = null;
                self.refreshRoomList(); // refreshed more than MAX_REFRESH_INTERVAL_MS ago
            }
            else {
                // refreshed less than MAX_REFRESH_INTERVAL_MS ago, wait the difference
                // if we aren't already waiting. If we are waiting then NOP, it will
                // fire soon, promise!
                if (!self._refreshRoomListTimerId) {
                    self._refreshRoomListTimerId = setTimeout(function() {
                        self.refreshRoomList();
                    }, 10 + MAX_REFRESH_INTERVAL_MS - timeWaitedMs); // 10 is a buffer amount
                }
            }
        }
    },

    refreshRoomList: function() {
        // console.log("DEBUG: Refresh room list delta=%s ms",
        //     (!this._lastRefreshRoomListTs ? "-" : (Date.now() - this._lastRefreshRoomListTs))
        // );

        // TODO: rather than bluntly regenerating and re-sorting everything
        // every time we see any kind of room change from the JS SDK
        // we could do incremental updates on our copy of the state
        // based on the room which has actually changed.  This would stop
        // us re-rendering all the sublists every time anything changes anywhere
        // in the state of the client.
        this.setState(this.getRoomLists());
        this._lastRefreshRoomListTs = Date.now();
    },

    getRoomLists: function() {
        var self = this;
        var s = { lists: {} };

        s.lists["im.vector.fake.invite"] = [];
        s.lists["m.favourite"] = [];
        s.lists["im.vector.fake.recent"] = [];
        s.lists["m.lowpriority"] = [];
        s.lists["im.vector.fake.archived"] = [];

        MatrixClientPeg.get().getRooms().forEach(function(room) {
            var me = room.getMember(MatrixClientPeg.get().credentials.userId);

            if (me && me.membership == "invite") {
                s.lists["im.vector.fake.invite"].push(room);
            }
            else if (me && me.membership === "leave") {
                s.lists["im.vector.fake.archived"].push(room);
            }
            else {
                var shouldShowRoom =  (
                    me && (me.membership == "join" || me.membership === "ban")
                );

                // hiding conf rooms only ever toggles shouldShowRoom to false
                if (shouldShowRoom && HIDE_CONFERENCE_CHANS) {
                    // we want to hide the 1:1 conf<->user room and not the group chat
                    var joinedMembers = room.getJoinedMembers();
                    if (joinedMembers.length === 2) {
                        var otherMember = joinedMembers.filter(function(m) {
                            return m.userId !== me.userId
                        })[0];
                        var ConfHandler = self.props.ConferenceHandler;
                        if (ConfHandler && ConfHandler.isConferenceUser(otherMember.userId)) {
                            // console.log("Hiding conference 1:1 room %s", room.roomId);
                            shouldShowRoom = false;
                        }
                    }
                }

                if (shouldShowRoom) {
                    var tagNames = Object.keys(room.tags);
                    if (tagNames.length) {
                        for (var i = 0; i < tagNames.length; i++) {
                            var tagName = tagNames[i];
                            s.lists[tagName] = s.lists[tagName] || [];
                            s.lists[tagNames[i]].push(room);
                        }
                    }
                    else {
                        s.lists["im.vector.fake.recent"].push(room);
                    }
                }
            }
        });

        //console.log("calculated new roomLists; im.vector.fake.recent = " + s.lists["im.vector.fake.recent"]);

        // we actually apply the sorting to this when receiving the prop in RoomSubLists.

        return s;
    },

    _getScrollNode: function() {
        var panel = ReactDOM.findDOMNode(this);
        if (!panel) return null;

        if (panel.classList.contains('gm-prevented')) {
            return panel;
        } else {
            return panel.children[2]; // XXX: Fragile!
        }
    },

    _repositionTooltips: function(e) {
        this._repositionTooltip(e);
        this._repositionIncomingCallBox(e, false);
    },

    _repositionTooltip: function(e) {
        if (this.tooltip && this.tooltip.parentElement) {
            var scroll = ReactDOM.findDOMNode(this);
            this.tooltip.style.top = (scroll.parentElement.offsetTop + this.tooltip.parentElement.offsetTop - this._getScrollNode().scrollTop) + "px";
        }
    },

    _repositionIncomingCallBox: function(e, firstTime) {
        var incomingCallBox = document.getElementById("incomingCallBox");
        if (incomingCallBox && incomingCallBox.parentElement) {
            var scroll = this._getScrollNode();
            var top = (scroll.offsetTop + incomingCallBox.parentElement.offsetTop - scroll.scrollTop);

            if (firstTime) {
                // scroll to make sure the callbox is on the screen...
                if (top < 10) { // 10px of vertical margin at top of screen
                    scroll.scrollTop = incomingCallBox.parentElement.offsetTop - 10;
                }
                else if (top > scroll.clientHeight - incomingCallBox.offsetHeight + 50) {
                    scroll.scrollTop = incomingCallBox.parentElement.offsetTop - scroll.offsetHeight + incomingCallBox.offsetHeight - 50;
                }
                // recalculate top in case we clipped it.
                top = (scroll.offsetTop + incomingCallBox.parentElement.offsetTop - scroll.scrollTop);
            }
            else {
                // stop the box from scrolling off the screen
                if (top < 10) {
                    top = 10;
                }
                else if (top > scroll.clientHeight - incomingCallBox.offsetHeight + 50) {
                    top = scroll.clientHeight - incomingCallBox.offsetHeight + 50;
                }
            }

            incomingCallBox.style.top = top + "px";
            incomingCallBox.style.left = scroll.offsetLeft + scroll.offsetWidth + "px";
        }
    },

    onShowClick: function() {
        dis.dispatch({
            action: 'show_left_panel',
        });
    },

    onShowMoreRooms: function() {
        // kick gemini in the balls to get it to wake up
        // XXX: uuuuuuugh.
        this.refs.gemscroll.forceUpdate();
    },

    render: function() {
        var expandButton = this.props.collapsed ?
                           "/> :
                           null;

        var RoomSubList = sdk.getComponent('structures.RoomSubList');
        var self = this;

        return (
            <GeminiScrollbar className="mx_RoomList_scrollbar" autoshow={true} onScroll={ self._repositionTooltips } ref="gemscroll">

                { expandButton }

                <RoomSubList list={ self.state.lists['im.vector.fake.invite'] }
                             label="Invites"
                             editable={ false }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed }
                             onShowMoreRooms={ this.onShowMoreRooms } />

                <RoomSubList list={ self.state.lists['m.favourite'] }
                             label="Favourites"
                             tagName="m.favourite"
                             verb="favourite"
                             editable={ true }
                             order="manual"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed }
                             onShowMoreRooms={ this.onShowMoreRooms } />

                <RoomSubList list={ self.state.lists['im.vector.fake.recent'] }
                             label="Rooms"
                             editable={ true }
                             verb="restore"
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed }
                             onShowMoreRooms={ this.onShowMoreRooms } />

                { Object.keys(self.state.lists).map(function(tagName) {
                    if (!tagName.match(/^(m\.(favourite|lowpriority)|im\.vector\.fake\.(invite|recent|archived))$/)) {
                        return <RoomSubList list={ self.state.lists[tagName] }
                             key={ tagName }
                             label={ tagName }
                             tagName={ tagName }
                             verb={ "tag as " + tagName }
                             editable={ true }
                             order="manual"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed }
                             onShowMoreRooms={ this.onShowMoreRooms } />

                    }
                }) }

                <RoomSubList list={ self.state.lists['m.lowpriority'] }
                             label="Low priority"
                             tagName="m.lowpriority"
                             verb="demote"
                             editable={ true }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             incomingCall={ self.state.incomingCall }
                             collapsed={ self.props.collapsed }
                             onShowMoreRooms={ this.onShowMoreRooms } />

                <RoomSubList list={ self.state.lists['im.vector.fake.archived'] }
                             label="Historical"
                             editable={ false }
                             order="recent"
                             selectedRoom={ self.props.selectedRoom }
                             collapsed={ self.props.collapsed }
                             alwaysShowHeader={ true }
                             startAsHidden={ true }
                             showSpinner={ self.state.isLoadingLeftRooms }
                             onHeaderClick= { self.onArchivedHeaderClick }
                             incomingCall={ self.state.incomingCall }
                             onShowMoreRooms={ this.onShowMoreRooms } />

            </GeminiScrollbar>
        );
    }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

// deploy itch to itch.io

const fs = require("fs");
const $ = require("./common");

async function ciDeploy() {
  const dirs = fs.readdirSync("./packages");
  const packages = [];
  for (const dir of dirs) {
    const [os, arch] = dir.split("-")
    packages.push({path: dir, os, arch});
    $.say(`Queuing ${os}-${arch} build`);
  }

  $.say("Grabbing butler");
  const butlerName = `butler`;
  const butlerArch = process.arch === "x64" ? "amd64" : "386";
  const butlerUrl = `https://broth.itch.ovh/butler/linux-amd64/LATEST/.zip`;
  $(await $.sh(`curl -L ${butlerUrl} -o butler.zip`));
  $(await $.sh(`unzip butler.zip`));
  $(await $.sh(`./butler --version`));

  let wd = process.cwd();
  for (const pkg of packages) {
    const {os, arch, path} = pkg;
    let butlerChannel = os;
    let artifactPath = ospath.join(wd, "packages", path);
    if (os === "darwin") {
      butlerChannel = "mac";
      artifactPath = `${buildPath}/${$.appName()}.app`;
    }

    butlerChannel = `${butlerChannel}-${arch === "386" ? "32" : "64"}`;
    const butlerTarget = `fasterthanlime/${$.appName()}`;
    $.say(`Pushing ${os}-${arch} to itch.io...`);
    let butlerCmd = `./butler push ${artifactPath} ${butlerTarget}:${butlerChannel} --userversion=${$.buildVersion()}`;
    $(await $.sh(butlerCmd));
  }
}

ciDeploy();
<commit_msg>Use go-style channels for deployment<commit_after>#!/usr/bin/env node

// deploy itch to itch.io

const fs = require("fs");
const $ = require("./common");

async function ciDeploy() {
  const dirs = fs.readdirSync("./packages");
  const packages = [];
  for (const dir of dirs) {
    const [os, arch] = dir.split("-")
    packages.push({path: dir, os, arch});
    $.say(`Queuing ${os}-${arch} build`);
  }

  $.say("Grabbing butler");
  const butlerName = `butler`;
  const butlerArch = process.arch === "x64" ? "amd64" : "386";
  const butlerUrl = `https://broth.itch.ovh/butler/linux-amd64/LATEST/.zip`;
  $(await $.sh(`curl -L ${butlerUrl} -o butler.zip`));
  $(await $.sh(`unzip butler.zip`));
  $(await $.sh(`./butler --version`));

  let wd = process.cwd();
  for (const pkg of packages) {
    const {os, arch, path} = pkg;
    let artifactPath = ospath.join(wd, "packages", path);
    if (os === "darwin") {
      artifactPath = `${buildPath}/${$.appName()}.app`;
    }

    butlerChannel = `${os}-${arch}`;
    const butlerTarget = `fasterthanlime/${$.appName()}`;
    $.say(`Pushing ${os}-${arch} to itch.io...`);
    let butlerCmd = `./butler push ${artifactPath} ${butlerTarget}:${butlerChannel} --userversion=${$.buildVersion()}`;
    $(await $.sh(butlerCmd));
  }
}

ciDeploy();
<|endoftext|>