<commit_before>
var fs = require('fs')
var path = require('path')
var express = require('express')
var static = require('serve-static')
var parser = require('body-parser')
var git = require('./git')

module.exports = (config, location) => {
  var prefix = config.path || ''
  var app = express()

  app.use(parser.json())
  app.use(`${prefix}/api`, git(config))

  app.use(`${prefix}/css`, static(path.join(config.server.assets, '/css')))
  app.use(`${prefix}/js`, static(path.join(config.server.assets, '/js')))
  app.use(`${prefix}/images`, static(path.join(config.server.assets, '/images')))

  app.use(`${prefix}/about`, static(location, {index: 'about.html'}))
  app.use(`${prefix}/events`, static(location, {index: 'events.html'}))
  app.use(`${prefix}/blogs`, static(location, {index: 'articles.html'}))
  app.use(`${prefix}/members`, static(location, {index: 'members.html'}))
  app.use(`${prefix}/links`, static(location, {index: 'links.html'}))
  app.use(`${prefix}/contacts`, static(location, {index: 'contacts.html'}))
  app.use(`${prefix}/finance`, static(location, {index: 'finance.html'}))
  app.use(`${prefix}/donate`, static(location, {index: 'donate.html'}))

  app.use(`${prefix}/events/:page`, (req, res) => {
    fs.readFile(
      path.join(location, '/events', `${req.params.page}.html`),
      'utf8',
      (err, html) => {
        if (err) {
          res.end()
        }
        else {
          res.set('content-type', 'text/html')
          res.end(html)
        }
      }
    )
  })

  app.use(`${prefix}/blogs/:y/:m/:d/:slug`, (req, res) => {
    fs.readFile(
      path.join(location, '/articles', `${req.params.slug}.html`),
      'utf8',
      (err, html) => {
        if (err) {
          res.end()
        }
        else {
          res.set('content-type', 'text/html')
          res.end(html)
        }
      }
    )
  })

  app.use(`${prefix}/`, static(location, {index: 'about.html'}))

  return app
}
<commit_msg>Add mailjet site verification.<commit_after>
var fs = require('fs')
var path = require('path')
var express = require('express')
var static = require('serve-static')
var parser = require('body-parser')
var git = require('./git')

module.exports = (config, location) => {
  var prefix = config.path || ''
  var app = express()

  app.use(parser.json())
  app.use(`${prefix}/api`, git(config))

  app.use(`${prefix}/css`, static(path.join(config.server.assets, '/css')))
  app.use(`${prefix}/js`, static(path.join(config.server.assets, '/js')))
  app.use(`${prefix}/images`, static(path.join(config.server.assets, '/images')))

  app.use(`${prefix}/about`, static(location, {index: 'about.html'}))
  app.use(`${prefix}/events`, static(location, {index: 'events.html'}))
  app.use(`${prefix}/blogs`, static(location, {index: 'articles.html'}))
  app.use(`${prefix}/members`, static(location, {index: 'members.html'}))
  app.use(`${prefix}/links`, static(location, {index: 'links.html'}))
  app.use(`${prefix}/contacts`, static(location, {index: 'contacts.html'}))
  app.use(`${prefix}/finance`, static(location, {index: 'finance.html'}))
  app.use(`${prefix}/donate`, static(location, {index: 'donate.html'}))

  app.use(`${prefix}/events/:page`, (req, res) => {
    fs.readFile(
      path.join(location, '/events', `${req.params.page}.html`),
      'utf8',
      (err, html) => {
        if (err) {
          res.end()
        }
        else {
          res.set('content-type', 'text/html')
          res.end(html)
        }
      }
    )
  })

  app.use(`${prefix}/blogs/:y/:m/:d/:slug`, (req, res) => {
    fs.readFile(
      path.join(location, '/articles', `${req.params.slug}.html`),
      'utf8',
      (err, html) => {
        if (err) {
          res.end()
        }
        else {
          res.set('content-type', 'text/html')
          res.end(html)
        }
      }
    )
  })

  app.use(`${prefix}/`, static(location, {index: 'about.html'}))

  app.use(`${prefix}/89fd43a2409b6e74768e5e5a66dcda43.txt`, (req, res) => {
    res.set('content-type', 'text/plain')
    res.send('')
  })

  return app
}
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var ElementExplorerClient = require('./elementExplorerClient');

var startServer = function() {
  var exClient;

  var app = express();
  app.use(bodyParser.json());

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    console.log('Got', query);
    res.send('Hello World!');
  });

  function handlePopupRequest(input, res) {
    console.log('popup input', input);

    exClient.runCommand(input).then(function(response) {
      res.send(response);
    });
  }

  function handleDevToolsRequest(input, res) {
    console.log('Dev tools input', input);

    res.send('dev tool');
  }

// Open a server.
  var server = app.listen(13000, function() {

    console.log('Starting client');
    exClient = new ElementExplorerClient();

    console.log('Elementor is listening at http://localhost:%s',
        server.address().port);
  });
};

module.exports = {
  startServer: startServer
};
<commit_msg>Start protractor and then elementor server<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var ElementExplorerClient = require('./elementExplorerClient');
var cliHelper = require('./cliHelper');

var startExpress = function() {
  var exClient;

  var app = express();
  app.use(bodyParser.json());

  app.get('/testSelector', function(req, res) {
    var query = req.query;

    if (query.popupInput) {
      return handlePopupRequest(query.popupInput, res);
    }

    console.log('Got', query);
    res.send('Hello World!');
  });

  function handlePopupRequest(input, res) {
    console.log('popup input', input);

    exClient.runCommand(input).then(function(response) {
      res.send(response);
    });
  }

  var server = app.listen(13000, function() {
    console.log('Starting client');
    exClient = new ElementExplorerClient();

    console.log('Elementor is listening at http://localhost:%s',
        server.address().port);
  });
};

var startProtractor = function() {
  console.log('Starting protractor');

  var protractorPromise = cliHelper.startProtractor();

  protractorPromise.then(function() {
    console.log('Protractor started');
    console.log('Starting elementor server');
  });

  protractorPromise.catch(function(error) {
    console.log('Error starting protractor', e);
  });

  return protractorPromise;
};

var startServer = function() {
  startProtractor().then(function() {
    startExpress();
  });
};

module.exports = {
  start: startServer
};
<|endoftext|>


<commit_before>(function() {
  slUnits = new function() {
    var slUnits = this;

    /**
     * The container that saves the user unit settings
     * @type {Object}
     */
    var settings = {
      distance: 'm',
      speed: 'km/h',
      lift: 'm/s',
      altitude: 'm'
    };

    /**
     * A static dictionary of the supported units with its
     * conversion factors and formatting functions
     * @const
     * @type {Object}
     */
    var UNITS = {
      // Length
      'm': [1, function(value) {
        return slUnits.format_decimal(value);
      }],
      'ft': [3.28084, function(value) {
        return slUnits.format_decimal(value);
      }],
      'km': [1 / 1000., function(value) {
        return slUnits.format_decimal(value);
      }],
      'NM': [1 / 1852., function(value) {
        return slUnits.format_decimal(value);
      }],
      'mi': [1 / 1609.34, function(value) {
        return slUnits.format_decimal(value);
      }],

      // Speed
      'm/s': [1, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'km/h': [3.6, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'kt': [1.94384449, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'mph': [2.23693629, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'ft/min': [196.850394, function(value) {
        return slUnits.format_decimal(value);
      }]
    };

    /**
     * Initialises the slUnits module with the user settings
     *
     * @param {String} distance The distance unit (e.g. 'km').
     * @param {String} speed The speed unit (e.g. 'km/h').
     * @param {String} lift The vertical speed unit (e.g. 'm/s').
     * @param {String} altitude The altitude unit (e.g. 'm').
     */
    slUnits.init = function(distance, speed, lift, altitude) {
      if (UNITS[distance]) settings.distance = distance;
      if (UNITS[speed]) settings.speed = speed;
      if (UNITS[lift]) settings.lift = lift;
      if (UNITS[altitude]) settings.altitude = altitude;
    };

    /**
     * Formats a number to a string with a given number of decimal places
     *
     * @param  {number} value A number that should be formatted.
     * @param  {[type]} decimals
     *   The number of decimal places that should be kept.
     * @return {String} The formatted value as a string.
     */
    slUnits.format_decimal = function(value, decimals) {
      return value.toFixed(decimals);
    };

    // unit formatter functions
    slUnits.format_distance = function(value) {
      return slUnits.add_distance_unit(slUnits.convert_distance(value));
    };

    slUnits.format_speed = function(value) {
      return slUnits.add_speed_unit(slUnits.convert_speed(value));
    };

    slUnits.format_lift = function(value) {
      return slUnits.add_lift_unit(slUnits.convert_lift(value));
    };

    slUnits.format_altitude = function(value) {
      return slUnits.add_altitude_unit(slUnits.convert_altitude(value));
    };

    // unit conversion functions
    slUnits.convert_distance = function(value) {
      return value * UNITS[settings.distance][0];
    };

    slUnits.convert_speed = function(value) {
      return value * UNITS[settings.speed][0];
    };

    slUnits.convert_lift = function(value) {
      return value * UNITS[settings.lift][0];
    };

    slUnits.convert_altitude = function(value) {
      return value * UNITS[settings.altitude][0];
    };

    // unit name functions
    slUnits.add_distance_unit = function(value) {
      value = UNITS[settings.distance][1](value);
      return value + ' ' + settings.distance;
    };

    slUnits.add_speed_unit = function(value) {
      value = UNITS[settings.speed][1](value);
      return value + ' ' + settings.speed;
    };

    slUnits.add_lift_unit = function(value) {
      value = UNITS[settings.lift][1](value);
      return value + ' ' + settings.lift;
    };

    slUnits.add_altitude_unit = function(value) {
      value = UNITS[settings.altitude][1](value);
      return value + ' ' + settings.altitude;
    };
  };
})();
<commit_msg>units.js: Generate unit-based functions dynamically<commit_after>(function() {
  slUnits = new function() {
    var slUnits = this;

    var UNIT_TYPES = ['distance', 'speed', 'lift', 'altitude'];
    var UNIT_TYPES_LENGTH = UNIT_TYPES.length;

    /**
     * The container that saves the user unit settings
     * @type {Object}
     */
    var settings = {
      distance: 'm',
      speed: 'km/h',
      lift: 'm/s',
      altitude: 'm'
    };

    /**
     * A static dictionary of the supported units with its
     * conversion factors and formatting functions
     * @const
     * @type {Object}
     */
    var UNITS = {
      // Length
      'm': [1, function(value) {
        return slUnits.format_decimal(value);
      }],
      'ft': [3.28084, function(value) {
        return slUnits.format_decimal(value);
      }],
      'km': [1 / 1000., function(value) {
        return slUnits.format_decimal(value);
      }],
      'NM': [1 / 1852., function(value) {
        return slUnits.format_decimal(value);
      }],
      'mi': [1 / 1609.34, function(value) {
        return slUnits.format_decimal(value);
      }],

      // Speed
      'm/s': [1, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'km/h': [3.6, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'kt': [1.94384449, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'mph': [2.23693629, function(value) {
        return slUnits.format_decimal(value, 1);
      }],
      'ft/min': [196.850394, function(value) {
        return slUnits.format_decimal(value);
      }]
    };

    /**
     * Initialises the slUnits module with the user settings
     *
     * @param {String} distance The distance unit (e.g. 'km').
     * @param {String} speed The speed unit (e.g. 'km/h').
     * @param {String} lift The vertical speed unit (e.g. 'm/s').
     * @param {String} altitude The altitude unit (e.g. 'm').
     */
    slUnits.init = function(distance, speed, lift, altitude) {
      if (UNITS[distance]) settings.distance = distance;
      if (UNITS[speed]) settings.speed = speed;
      if (UNITS[lift]) settings.lift = lift;
      if (UNITS[altitude]) settings.altitude = altitude;
    };

    /**
     * Formats a number to a string with a given number of decimal places
     *
     * @param  {number} value A number that should be formatted.
     * @param  {[type]} decimals
     *   The number of decimal places that should be kept.
     * @return {String} The formatted value as a string.
     */
    slUnits.format_decimal = function(value, decimals) {
      return value.toFixed(decimals);
    };

    function generateFunctions(unit_type) {
      // Generate e.g. format_distance(value) functions
      slUnits['format_' + unit_type] = function(value) {
        value = slUnits['convert_' + unit_type](value);
        return slUnits['add_' + unit_type + '_unit'](value);
      };

      // Generate e.g. convert_distance(value) functions
      slUnits['convert_' + unit_type] = function(value) {
        return value * UNITS[settings[unit_type]][0];
      };

      // Generate e.g. add_distance_unit(value) functions
      slUnits['add_' + unit_type + '_unit'] = function(value) {
        value = UNITS[settings[unit_type]][1](value);
        return value + ' ' + settings[unit_type];
      };
    }

    for (var i = 0; i < UNIT_TYPES_LENGTH; ++i) {
      generateFunctions(UNIT_TYPES[i]);
    }
  };
})();
<|endoftext|>


<commit_before>var chalk = require('chalk')
var es = require('event-stream')
var fs = require('fs')
var gh = require('github-url-to-object')
var json = require('JSONStream')
var padLeft = require('pad-left')
var path = require('path')

var freqs = {}

// search some modules specifically
var modules = [
  'standard', 'snazzy'
]

var allFreqs = {}

fs.createReadStream(path.join(__dirname, '..', 'alldata.json'))
  .pipe(json.parse('rows.*.value'))
  .pipe(es.mapSync(function (data) {
    var repo = data.repository && data.repository.url
    if (repo) repo = gh(repo)
    if (repo) repo = repo.https_url
    if (repo === '') repo = null

    var description = data.description
    if (description === '') description = null

    var name = data.name
    var deps = []
    if (data.dependencies) deps = deps.concat(Object.keys(data.dependencies))
    if (data.devDependencies) deps = deps.concat(Object.keys(data.devDependencies))
    deps.forEach(function (key) {
      if (modules.indexOf(key) >= 0) {
        if (!(key in freqs)) {
          freqs[key] = { count: 1, deps: [] }
        } else {
          freqs[key].count++
        }
        if (name && repo) freqs[key].deps.push([ name, repo, description ])
      }

      if (!(key in allFreqs)) {
        allFreqs[key] = 1
      } else {
        allFreqs[key]++
      }
    })
    return deps
  }))
  .on('end', function (ev) {
    var values = Object.keys(allFreqs)
      .map(function (k) {
        return { value: k, frequency: allFreqs[k] }
      })
      .sort(function (a, b) {
        return (b.frequency || 0) - (a.frequency || 0)
      })

    values = values.slice(0, 200)

    var longest = values.reduce(function (prev, a) {
      return Math.max(prev, a.value.length)
    }, 0)

    console.log('\n--------')
    console.log('SPECIFIC MODULES')
    console.log('--------\n')

    var arr = []
    modules.forEach(function (key) {
      var padding = longest - key.length
      console.log(key, padLeft(freqs[key].count || 0, padding + 1))
      freqs[key].deps
        .forEach(function (dep) {
          arr.push({ name: dep[0], repo: dep[1], description: dep[2], dependents: allFreqs[dep[0]] })
        })
    })
    arr = arr.sort(function (a, b) {
      return (b.dependents || 0) - (a.dependents || 0)
    })
    fs.writeFileSync(path.join(__dirname, '..', 'standard.json'), JSON.stringify(arr, undefined, 2))

    console.log('\n--------')
    console.log('TOP ' + values.length)
    console.log('--------\n')

    values.forEach(function (x, i) {
      var key = x.value
      var count = x.frequency
      var padding = longest - key.length

      // highlight standard style packages
      modules.forEach(function (module) {
        freqs[module].deps.some(function (val) {
          if (key === val[0]) {
            key = chalk.green(key + ' (using standard)')
            return true
          }
          return false
        })
      })

      console.log((i + 1) + '. ' + key, padLeft(count || 0, padding + 1))
    })
  })
<commit_msg>Special case -- add `standard` to the list<commit_after>var chalk = require('chalk')
var es = require('event-stream')
var fs = require('fs')
var gh = require('github-url-to-object')
var json = require('JSONStream')
var padLeft = require('pad-left')
var path = require('path')

var freqs = {}

// search some modules specifically
var modules = [
  'standard', 'snazzy'
]

var allFreqs = {}

fs.createReadStream(path.join(__dirname, '..', 'alldata.json'))
  .pipe(json.parse('rows.*.value'))
  .pipe(es.mapSync(function (data) {
    var repo = data.repository && data.repository.url
    if (repo) repo = gh(repo)
    if (repo) repo = repo.https_url
    if (repo === '') repo = null

    var description = data.description
    if (description === '') description = null

    var name = data.name
    var deps = []
    if (data.dependencies) deps = deps.concat(Object.keys(data.dependencies))
    if (data.devDependencies) deps = deps.concat(Object.keys(data.devDependencies))
    deps.forEach(function (key) {
      if (modules.indexOf(key) >= 0) {
        if (!(key in freqs)) {
          freqs[key] = { count: 1, deps: [] }
        } else {
          freqs[key].count++
        }
        if (name && repo) freqs[key].deps.push([ name, repo, description ])
      }

      if (!(key in allFreqs)) {
        allFreqs[key] = 1
      } else {
        allFreqs[key]++
      }
    })
    return deps
  }))
  .on('end', function (ev) {
    var values = Object.keys(allFreqs)
      .map(function (k) {
        return { value: k, frequency: allFreqs[k] }
      })
      .sort(function (a, b) {
        return (b.frequency || 0) - (a.frequency || 0)
      })

    values = values.slice(0, 200)

    var longest = values.reduce(function (prev, a) {
      return Math.max(prev, a.value.length)
    }, 0)

    console.log('\n--------')
    console.log('SPECIFIC MODULES')
    console.log('--------\n')

    var arr = []
    modules.forEach(function (key) {
      var padding = longest - key.length
      console.log(key, padLeft(freqs[key].count || 0, padding + 1))
      freqs[key].deps
        .forEach(function (dep) {
          arr.push({ name: dep[0], repo: dep[1], description: dep[2], dependents: allFreqs[dep[0]] })
        })
    })

    // Special case -- add `standard` to the list
    arr.push({
      name: 'standard',
      repo: 'https://github.com/feross/standard',
      description: 'JavaScript Standard Style — One Style to Rule Them All',
      dependents: arr.length
    })

    arr = arr.sort(function (a, b) {
      return (b.dependents || 0) - (a.dependents || 0)
    })
    fs.writeFileSync(path.join(__dirname, '..', 'standard.json'), JSON.stringify(arr, undefined, 2))

    console.log('\n--------')
    console.log('TOP ' + values.length)
    console.log('--------\n')

    values.forEach(function (x, i) {
      var key = x.value
      var count = x.frequency
      var padding = longest - key.length

      // highlight standard style packages
      modules.forEach(function (module) {
        freqs[module].deps.some(function (val) {
          if (key === val[0] || key === 'standard') {
            key = chalk.green(key + ' (using standard)')
            return true
          }
          return false
        })
      })

      console.log((i + 1) + '. ' + key, padLeft(count || 0, padding + 1))
    })
  })
<|endoftext|>


<commit_before>import '!style-loader!css-loader!react-datepicker/dist/react-datepicker.css'
import {getHours, getMinutes, startOfDay} from 'date-fns'
import PropTypes from 'prop-types'
import {useRef, useState} from 'react'
import ReactDatePicker from 'react-datepicker'
import {injectIntl} from 'react-intl'
import {withTheme} from 'styled-components'
import {date as dateUtil} from 'tocco-util'

import Ball from '../../Ball'
import Button from '../../Button'
import {loadLocales, parseISOValue} from '../../DatePicker/utils'
import {StyledDatePickerWrapper, StyledDatePickerOuterWrapper, StyledTimeInput} from './StyledDatePicker'

loadLocales()

const ReactDatepickerTimeInputClassName = 'react-datepicker-time__input'
const ReactDatepickerDayClassName = 'react-datepicker__day'
const ReactDatepickerInputClassName = 'react-datepicker-ignore-onclickoutside'

const CustomTodayButton = ({onChange, label}) => (
  <Button
    onMouseDown={e => {
      // this keeps the focus from changing, allowing handleConfirmKey on datepicker to keep working
      e.preventDefault()
      // this is a workaround for the previous date still being selected, see https://github.com/Hacker0x01/react-datepicker/issues/2206
      onChange(null)
    }}
  >
    {label}
  </Button>
)

CustomTodayButton.propTypes = {
  onChange: PropTypes.func.isRequired,
  label: PropTypes.string.isRequired
}

const TimeInput = ({value, onChange, onKeyDown}) => (
  <StyledTimeInput
    type="time"
    className={ReactDatepickerTimeInputClassName}
    required
    value={value}
    onKeyDown={onKeyDown}
    onChange={ev => {
      if (onChange) {
        onChange(ev.target.value)
      }
    }}
    onClick={e => {
      /**
       * Workaround
       * When a day is selected it's not possible to set focus with mouse by clicking inside time input.
       */
      e.target.focus()
    }}
  />
)

TimeInput.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  onKeyDown: PropTypes.func
}

const focusTimeInput = wrapper => {
  const inputElement = wrapper.querySelector(`input.${ReactDatepickerTimeInputClassName}`)
  if (inputElement) {
    inputElement.focus()
  }
}

const isDay = element => element.classList.contains(ReactDatepickerDayClassName)
const isTimeInput = element => element.classList.contains(ReactDatepickerTimeInputClassName)
const isInput = element => element.classList.contains(ReactDatepickerInputClassName)

const DatePicker = ({immutable, id, value, minDate, maxDate, onChange, intl, placeholder, hasTime, dateFormat}) => {
  const locale = intl.locale
  const msg = msgId => intl.formatMessage({id: msgId})

  const wrapper = useRef(null)
  const datePickerRef = useRef(null)
  const [open, setOpen] = useState(false)

  const hasValue = Boolean(value)
  const selectedDate = parseISOValue(value)
  const minDateVal = minDate ? parseISOValue(minDate) : undefined
  const maxDateVal = maxDate ? parseISOValue(maxDate) : undefined

  const handleOnChange = val => {
    if (val) {
      const changedInitially = !value && val

      const startOfSelectedDay = startOfDay(val)
      const hasTimeChanged =
        getHours(val) !== getHours(startOfSelectedDay) || getMinutes(val) !== getMinutes(startOfSelectedDay)

      // set time to now when time has not set explicitly yet
      if (changedInitially && hasTime && !hasTimeChanged) {
        val = dateUtil.setCurrentTime(val)
      }
      onChange(val.toISOString())
    }
  }

  const handleOpen = val => {
    setOpen(val)
    if (datePickerRef.current?.setPreSelection) {
      datePickerRef.current?.setPreSelection(selectedDate)
    }
  }

  const handleConfirmKey = e => {
    if (e.key === 'Tab' && !e.shiftKey) {
      if (isDay(e.target)) {
        if (hasTime) {
          // tab to time-input when tabbing on a day
          focusTimeInput(wrapper.current)
        } else {
          handleOpen(false)
        }
      } else if (isTimeInput(e.target)) {
        // Close Datepicker and tab to next input in time-input
        handleOpen(false)
      }
    }

    if (isInput(e.target) && e.key === 'Tab' && e.shiftKey) {
      // Close Datepicker and tab to prev input in datepicker-input
      handleOpen(false)
    }

    if (e.key === 'Enter') {
      // Close Datepicker and do not submit form
      handleOpen(false)
      e.preventDefault()
      e.stopPropagation()
    }
  }

  return (
    <StyledDatePickerOuterWrapper immutable={immutable} id={id} tabIndex="-1">
      <StyledDatePickerWrapper immutable={immutable} ref={wrapper} hasTime={hasTime}>
        <ReactDatePicker
          ref={datePickerRef}
          selected={selectedDate}
          onChange={handleOnChange}
          disabled={immutable}
          showTimeInput={hasTime}
          dateFormat={dateFormat}
          placeholderText={placeholder}
          showMonthDropdown
          showYearDropdown
          scrollableYearDropdown
          fixedHeight
          showPopperArrow={false}
          open={open}
          onFocus={() => {
            handleOpen(true)
          }}
          onClickOutside={() => {
            handleOpen(false)
          }}
          locale={locale}
          onKeyDown={handleConfirmKey}
          customTimeInput={<TimeInput onKeyDown={handleConfirmKey} />}
          enableTabLoop={false}
          timeInputLabel=""
          minDate={minDateVal}
          maxDate={maxDateVal}
          todayButton={<CustomTodayButton onChange={onChange} label={msg('client.component.datePicker.todayLabel')} />}
        />

        {!immutable && hasValue && (
          <Ball
            icon="times"
            tabIndex={-1}
            aria-label={msg('client.component.datePicker.clearDateLabel')}
            onMouseDown={e => {
              e.preventDefault()
              onChange(null)
            }}
          />
        )}
      </StyledDatePickerWrapper>
    </StyledDatePickerOuterWrapper>
  )
}

DatePicker.propTypes = {
  id: PropTypes.string,
  intl: PropTypes.object.isRequired,
  onChange: PropTypes.func.isRequired,
  value: PropTypes.string,
  hasTime: PropTypes.bool,
  dateFormat: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  placeholder: PropTypes.string,
  immutable: PropTypes.bool,
  initialized: PropTypes.func,
  minDate: PropTypes.string,
  maxDate: PropTypes.string,
  events: PropTypes.shape({
    onFocus: PropTypes.func
  })
}

export default withTheme(injectIntl(DatePicker))
<commit_msg>refactor(tocco-ui): close datepicker on scroll<commit_after>import '!style-loader!css-loader!react-datepicker/dist/react-datepicker.css'
import {getHours, getMinutes, startOfDay} from 'date-fns'
import PropTypes from 'prop-types'
import {useRef, useState} from 'react'
import ReactDatePicker from 'react-datepicker'
import {injectIntl} from 'react-intl'
import {withTheme} from 'styled-components'
import {date as dateUtil} from 'tocco-util'

import Ball from '../../Ball'
import Button from '../../Button'
import {loadLocales, parseISOValue} from '../../DatePicker/utils'
import {StyledDatePickerWrapper, StyledDatePickerOuterWrapper, StyledTimeInput} from './StyledDatePicker'

loadLocales()

const ReactDatepickerTimeInputClassName = 'react-datepicker-time__input'
const ReactDatepickerDayClassName = 'react-datepicker__day'
const ReactDatepickerInputClassName = 'react-datepicker-ignore-onclickoutside'

const CustomTodayButton = ({onChange, label}) => {
  const handleOnMouseDown = e => {
    // this keeps the focus from changing, allowing handleConfirmKey on datepicker to keep working
    e.preventDefault()
    // this is a workaround for the previous date still being selected, see https://github.com/Hacker0x01/react-datepicker/issues/2206
    onChange(null)
  }

  return <Button onMouseDown={handleOnMouseDown}>{label}</Button>
}

CustomTodayButton.propTypes = {
  onChange: PropTypes.func.isRequired,
  label: PropTypes.string.isRequired
}

const TimeInput = ({value, onChange, onKeyDown}) => {
  const handleOnChange = ev => {
    if (onChange) {
      onChange(ev.target.value)
    }
  }

  const handleOnClick = e => {
    /**
     * Workaround
     * When a day is selected it's not possible to set focus with mouse by clicking inside time input.
     */
    e.target.focus()
  }

  return (
    <StyledTimeInput
      type="time"
      className={ReactDatepickerTimeInputClassName}
      required
      value={value}
      onKeyDown={onKeyDown}
      onChange={handleOnChange}
      onClick={handleOnClick}
    />
  )
}

TimeInput.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  onKeyDown: PropTypes.func
}

const focusTimeInput = wrapper => {
  const inputElement = wrapper.querySelector(`input.${ReactDatepickerTimeInputClassName}`)
  if (inputElement) {
    inputElement.focus()
  }
}

const isDay = element => element.classList.contains(ReactDatepickerDayClassName)
const isTimeInput = element => element.classList.contains(ReactDatepickerTimeInputClassName)
const isInput = element => element.classList.contains(ReactDatepickerInputClassName)

const DatePicker = ({immutable, id, value, minDate, maxDate, onChange, intl, placeholder, hasTime, dateFormat}) => {
  const locale = intl.locale
  const msg = msgId => intl.formatMessage({id: msgId})

  const wrapper = useRef(null)
  const datePickerRef = useRef(null)
  const [isOpen, setIsOpen] = useState(false)

  const hasValue = Boolean(value)
  const selectedDate = parseISOValue(value)
  const minDateVal = minDate ? parseISOValue(minDate) : undefined
  const maxDateVal = maxDate ? parseISOValue(maxDate) : undefined

  const handleOnChange = val => {
    if (val) {
      const changedInitially = !value && val

      const startOfSelectedDay = startOfDay(val)
      const hasTimeChanged =
        getHours(val) !== getHours(startOfSelectedDay) || getMinutes(val) !== getMinutes(startOfSelectedDay)

      // set time to now when time has not set explicitly yet
      if (changedInitially && hasTime && !hasTimeChanged) {
        val = dateUtil.setCurrentTime(val)
      }
      onChange(val.toISOString())
    }
  }

  const handleOpen = val => {
    setIsOpen(val)
    if (datePickerRef.current?.setPreSelection) {
      datePickerRef.current?.setPreSelection(selectedDate)
    }
  }

  const handleConfirmKey = e => {
    if (e.key === 'Tab' && !e.shiftKey) {
      if (isDay(e.target)) {
        if (hasTime) {
          // tab to time-input when tabbing on a day
          focusTimeInput(wrapper.current)
        } else {
          handleOpen(false)
        }
      } else if (isTimeInput(e.target)) {
        // Close Datepicker and tab to next input in time-input
        handleOpen(false)
      }
    }

    if (isInput(e.target) && e.key === 'Tab' && e.shiftKey) {
      // Close Datepicker and tab to prev input in datepicker-input
      handleOpen(false)
    }

    if (e.key === 'Enter') {
      // Close Datepicker and do not submit form
      handleOpen(false)
      e.preventDefault()
      e.stopPropagation()
    }
  }

  const handleFocus = () => {
    handleOpen(true)
  }

  const handleClickOutside = () => {
    handleOpen(false)
  }

  const showClearButton = !immutable && hasValue

  const handleOnMouseDown = e => {
    e.preventDefault()
    onChange(null)
  }

  const handleCloseOnScroll = () => {
    handleOpen(false)
    return true
  }

  return (
    <StyledDatePickerOuterWrapper immutable={immutable} id={id} tabIndex="-1">
      <StyledDatePickerWrapper immutable={immutable} ref={wrapper} hasTime={hasTime}>
        <ReactDatePicker
          ref={datePickerRef}
          selected={selectedDate}
          onChange={handleOnChange}
          disabled={immutable}
          showTimeInput={hasTime}
          dateFormat={dateFormat}
          placeholderText={placeholder}
          showMonthDropdown
          showYearDropdown
          scrollableYearDropdown
          fixedHeight
          showPopperArrow={false}
          closeOnScroll={handleCloseOnScroll}
          open={isOpen}
          onFocus={handleFocus}
          onClickOutside={handleClickOutside}
          locale={locale}
          onKeyDown={handleConfirmKey}
          customTimeInput={<TimeInput onKeyDown={handleConfirmKey} />}
          enableTabLoop={false}
          timeInputLabel=""
          minDate={minDateVal}
          maxDate={maxDateVal}
          popperProps={{strategy: 'fixed'}}
          todayButton={<CustomTodayButton onChange={onChange} label={msg('client.component.datePicker.todayLabel')} />}
        />
        {showClearButton && (
          <Ball
            icon="times"
            tabIndex={-1}
            aria-label={msg('client.component.datePicker.clearDateLabel')}
            onMouseDown={handleOnMouseDown}
          />
        )}
      </StyledDatePickerWrapper>
    </StyledDatePickerOuterWrapper>
  )
}

DatePicker.propTypes = {
  id: PropTypes.string,
  intl: PropTypes.object.isRequired,
  onChange: PropTypes.func.isRequired,
  value: PropTypes.string,
  hasTime: PropTypes.bool,
  dateFormat: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  placeholder: PropTypes.string,
  immutable: PropTypes.bool,
  initialized: PropTypes.func,
  minDate: PropTypes.string,
  maxDate: PropTypes.string,
  events: PropTypes.shape({
    onFocus: PropTypes.func
  })
}

export default withTheme(injectIntl(DatePicker))
<|endoftext|>


<commit_before>import toastr from 'toastr';
Template.redlinkInlineResult._copyReplySuggestion = function (event, instance) {
	if (instance.data.result.replySuggestion) {
		$('#chat-window-' + instance.data.roomId + ' .input-message').val(instance.data.result.replySuggestion);
	}
};

Template.redlinkInlineResult.helpers({
	templateName(){
		const instance = Template.instance();

		let templateSuffix = "generic";
		switch (instance.data.creator) {
			case 'bahn.de':
				templateSuffix = "bahn_de";
				break;
			case 'community.bahn.de':
				templateSuffix = "VKL_community";
				break;
			case 'VKL':
				templateSuffix = "VKL_community";
				break;
			case 'Hasso-MLT':
				templateSuffix = "Hasso";
				break;
			case 'Hasso-Search':
				templateSuffix = "Hasso";
				break;
			default:
				if (!!Template['redlinkInlineResult_' + instance.data.creator]) {
					templateSuffix = instance.data.creator;
				} else {
					templateSuffix = "generic";
				}
				break;
		}
		return 'redlinkInlineResult_' + templateSuffix;
	},
	templateData(){
		const instance = Template.instance();
		return {
			result: instance.data.result,
			roomId: instance.data.roomId
		}
	}
});

Template.redlinkInlineResult.events({
	'click .js-copy-reply-suggestion': function (event, instance) {
		return Template.redlinkInlineResult._copyReplySuggestion(event, instance)
	}
});

//----------------------------------- Generic helper as fallback ------------------------------

Template.redlinkInlineResult_generic.helpers({
	relevantKeyValues(){
		const instance = Template.instance();

		let keyValuePairs = [];
		for (key in instance.data.result) {
			keyValuePairs.push({key: key, value: instance.data.result[key]});
		}

		return keyValuePairs;
	}
});

//------------------------------------- Bahn.de -----------------------------------------------

Template.redlinkInlineResult_bahn_de.events({
	'click .js-copy-reply-suggestion': function (event, instance) {
		return Template.redlinkInlineResult._copyReplySuggestion(event, instance)
	}
});

Template.redlinkInlineResult_bahn_de.helpers({
	durationformat(val){
		return new _dbs.Duration(val * 60 * 1000).toHHMMSS();
	}
});

//----------------------------------- VKL and community ---------------------------------------
Template.redlinkInlineResult_VKL_community.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	}
});

Template.redlinkInlineResult_VKL_community.events({
	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);
	},
});

Template.redlinkInlineResult_VKL_community.onCreated(function () {
	const instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false
	});
});

//-------------------------------------- Assistify --------------------------------
Template.inlineResultMessage.helpers({
	getOriginatorClass(message){
		switch (message.origin) {
			case 'User':
				return 'seeker';
			case 'Agent':
				return 'provider';
			default:
				return 'unknown';
		}
	},
	getSelectedClass(){
		const instance = Template.instance();

		if (instance.selected.get()) {
			return 'selected';
		}
	}
});

Template.inlineResultMessage.events({
	'click .conversationMessage': function (event, instance) {
		const current = instance.selected.get();

		instance.selected.set(!current);

		if (instance.selected.get()) {
			Template.redlinkQueries.utilities.addCleanupActivity(() => {
				instance.selected.set(false)
			});

		}
	}
});

Template.inlineResultMessage.onCreated(function () {
	const instance = this;

	instance.selected = new ReactiveVar(false);
});

Template.redlinkInlineResult_Hasso.events({
	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);

		if (!instance.state.get('expanded')) {
			Template.redlinkQueries.utilities.resultsInteractionCleanup();
		}
	},
	'click .js-send-message': function (event, instance) {

		/* buffer metadata of messages which are _about to be sent_
		 * This is necessary as the results or queries displayed may be entered into the message-area,
		 * but only one the message is actually sent, the metadata becomes effective for this new message
		 * - and only by then we know the message-id for which this metadata is actually valid
		 */
		Session.set('messageMetadata', {
			user: Meteor.user(),
			room: instance.data.roomId,
			metadata: {
				origin: "historicConversation",
				conversationId: instance.data.result.conversationId
			}
		});

		//create a text-response
		let textToInsert = "";
		const selectedMessages = instance.findAll('.selected');
		if (selectedMessages.length > 0) {
			textToInsert = selectedMessages.reduce(function (concat, elem) {
					return concat + " " + elem.textContent;
				},
				'');
		} else {
			//translate GUID of the conversation provided into a link
			const originRoom = RocketChat.models.Rooms.findOne({_id: instance.data.result.conversationId});
			if (originRoom) {
				const routeLink = RocketChat.roomTypes.getRouteLink(originRoom.t, originRoom);
				const roomLink = Meteor.absoluteUrl() + routeLink.slice(1, routeLink.length);
				textToInsert = TAPi18n.__('Link_provided') + " " + roomLink;
			} else {
				return toastr.info(TAPi18n.__('No_room_link_possible'));
			}
		}

		$('#chat-window-' + instance.data.roomId + ' .input-message').val(textToInsert).focus();
	}
});

Template.redlinkInlineResult_Hasso.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	},
	getResultTitle(){
		const instance = Template.instance();
		if (instance.state.get('expanded') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages[0].content;
		} else {
			return instance.data.result.content
		}
	},
	originQuestion(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages[0].content;
		}
	},
	latestResponse(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages.filter((message) => message.user && message.user.displayName === 'Provider').pop().text;
		}
	},

	subsequentCommunication(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages.slice(1);
		}
	}
});

Template.redlinkInlineResult_Hasso.onCreated(function () {
	let instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false,
		conversation: {},
		conversationLoaded: false
	});

	instance.autorun(() => {

		if (instance.state.get('expanded')) {
			Meteor.call('redlink:getStoredConversation', instance.data.result.conversationId,
				(err, conversation) => {
					if (!err) {
						instance.state.set('conversation', conversation);
						instance.state.set('conversationLoaded', true);
					} else {
						console.error(err);
					}
				}
			);
		}

	});
});

Template.redlinkInlineResult_dbsearch.onCreated(function () {

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false,
	});
});

Template.redlinkInlineResult_dbsearch.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	}
});

Template.redlinkInlineResult_dbsearch.events({

	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);

		if (!instance.state.get('expanded')) {
			Template.redlinkQueries.utilities.resultsInteractionCleanup();
		}
	},
	'click .js-send-message': function (event, instance) {

		/* buffer metadata of messages which are _about to be sent_
		 * This is necessary as the results or queries displayed may be entered into the message-area,
		 * but only one the message is actually sent, the metadata becomes effective for this new message
		 * - and only by then we know the message-id for which this metadata is actually valid
		 */
		Session.set('messageMetadata', {
			user: Meteor.user(),
			room: instance.data.roomId,
			metadata: {
				origin: "historicConversation",
				searchLink: instance.data.result.dbsearch_link_s
			}
		});

		//create a text-response
		let textToInsert = "";
		const selectedMessages = instance.findAll('.selected');
		if (selectedMessages.length > 0) {
			textToInsert = selectedMessages.reduce(function (concat, elem) {
					return concat + " " + elem.textContent;
				},
				'');
		} else {
			textToInsert = instance.data.result.dbsearch_link_s;
		}

		$('#chat-window-' + instance.data.roomId + ' .input-message').val(textToInsert).focus();
	}

});
<commit_msg>Trim inserted result message<commit_after>import toastr from 'toastr';
Template.redlinkInlineResult._copyReplySuggestion = function (event, instance) {
	if (instance.data.result.replySuggestion) {
		$('#chat-window-' + instance.data.roomId + ' .input-message').val(instance.data.result.replySuggestion);
	}
};

Template.redlinkInlineResult.helpers({
	templateName(){
		const instance = Template.instance();

		let templateSuffix = "generic";
		switch (instance.data.creator) {
			case 'bahn.de':
				templateSuffix = "bahn_de";
				break;
			case 'community.bahn.de':
				templateSuffix = "VKL_community";
				break;
			case 'VKL':
				templateSuffix = "VKL_community";
				break;
			case 'Hasso-MLT':
				templateSuffix = "Hasso";
				break;
			case 'Hasso-Search':
				templateSuffix = "Hasso";
				break;
			default:
				if (!!Template['redlinkInlineResult_' + instance.data.creator]) {
					templateSuffix = instance.data.creator;
				} else {
					templateSuffix = "generic";
				}
				break;
		}
		return 'redlinkInlineResult_' + templateSuffix;
	},
	templateData(){
		const instance = Template.instance();
		return {
			result: instance.data.result,
			roomId: instance.data.roomId
		}
	}
});

Template.redlinkInlineResult.events({
	'click .js-copy-reply-suggestion': function (event, instance) {
		return Template.redlinkInlineResult._copyReplySuggestion(event, instance)
	}
});

//----------------------------------- Generic helper as fallback ------------------------------

Template.redlinkInlineResult_generic.helpers({
	relevantKeyValues(){
		const instance = Template.instance();

		let keyValuePairs = [];
		for (key in instance.data.result) {
			keyValuePairs.push({key: key, value: instance.data.result[key]});
		}

		return keyValuePairs;
	}
});

//------------------------------------- Bahn.de -----------------------------------------------

Template.redlinkInlineResult_bahn_de.events({
	'click .js-copy-reply-suggestion': function (event, instance) {
		return Template.redlinkInlineResult._copyReplySuggestion(event, instance)
	}
});

Template.redlinkInlineResult_bahn_de.helpers({
	durationformat(val){
		return new _dbs.Duration(val * 60 * 1000).toHHMMSS();
	}
});

//----------------------------------- VKL and community ---------------------------------------
Template.redlinkInlineResult_VKL_community.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	}
});

Template.redlinkInlineResult_VKL_community.events({
	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);
	},
});

Template.redlinkInlineResult_VKL_community.onCreated(function () {
	const instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false
	});
});

//-------------------------------------- Assistify --------------------------------
Template.inlineResultMessage.helpers({
	getOriginatorClass(message){
		switch (message.origin) {
			case 'User':
				return 'seeker';
			case 'Agent':
				return 'provider';
			default:
				return 'unknown';
		}
	},
	getSelectedClass(){
		const instance = Template.instance();

		if (instance.selected.get()) {
			return 'selected';
		}
	}
});

Template.inlineResultMessage.events({
	'click .conversationMessage': function (event, instance) {
		const current = instance.selected.get();

		instance.selected.set(!current);

		if (instance.selected.get()) {
			Template.redlinkQueries.utilities.addCleanupActivity(() => {
				instance.selected.set(false)
			});

		}
	}
});

Template.inlineResultMessage.onCreated(function () {
	const instance = this;

	instance.selected = new ReactiveVar(false);
});

Template.redlinkInlineResult_Hasso.events({
	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);

		if (!instance.state.get('expanded')) {
			Template.redlinkQueries.utilities.resultsInteractionCleanup();
		}
	},
	'click .js-send-message': function (event, instance) {

		/* buffer metadata of messages which are _about to be sent_
		 * This is necessary as the results or queries displayed may be entered into the message-area,
		 * but only one the message is actually sent, the metadata becomes effective for this new message
		 * - and only by then we know the message-id for which this metadata is actually valid
		 */
		Session.set('messageMetadata', {
			user: Meteor.user(),
			room: instance.data.roomId,
			metadata: {
				origin: "historicConversation",
				conversationId: instance.data.result.conversationId
			}
		});

		//create a text-response
		let textToInsert = "";
		const selectedMessages = instance.findAll('.selected');
		if (selectedMessages.length > 0) {
			textToInsert = selectedMessages.reduce(function (concat, elem) {
					return concat + " " + elem.textContent;
				},
				'');
		} else {
			//translate GUID of the conversation provided into a link
			const originRoom = RocketChat.models.Rooms.findOne({_id: instance.data.result.conversationId});
			if (originRoom) {
				const routeLink = RocketChat.roomTypes.getRouteLink(originRoom.t, originRoom);
				const roomLink = Meteor.absoluteUrl() + routeLink.slice(1, routeLink.length);
				textToInsert = TAPi18n.__('Link_provided') + " " + roomLink;
			} else {
				return toastr.info(TAPi18n.__('No_room_link_possible'));
			}
		}

		$('#chat-window-' + instance.data.roomId + ' .input-message').val(textToInsert.trim()).focus();
	}
});

Template.redlinkInlineResult_Hasso.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	},
	getResultTitle(){
		const instance = Template.instance();
		if (instance.state.get('expanded') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages[0].content;
		} else {
			return instance.data.result.content
		}
	},
	originQuestion(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages[0].content;
		}
	},
	latestResponse(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages.filter((message) => message.user && message.user.displayName === 'Provider').pop().text;
		}
	},

	subsequentCommunication(){
		const instance = Template.instance();
		if (instance.state.get('conversation') && instance.state.get('conversationLoaded')) {
			return instance.state.get('conversation').messages.slice(1);
		}
	}
});

Template.redlinkInlineResult_Hasso.onCreated(function () {
	let instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false,
		conversation: {},
		conversationLoaded: false
	});

	instance.autorun(() => {

		if (instance.state.get('expanded')) {
			Meteor.call('redlink:getStoredConversation', instance.data.result.conversationId,
				(err, conversation) => {
					if (!err) {
						instance.state.set('conversation', conversation);
						instance.state.set('conversationLoaded', true);
					} else {
						console.error(err);
					}
				}
			);
		}

	});
});

Template.redlinkInlineResult_dbsearch.onCreated(function () {

	this.state = new ReactiveDict();
	this.state.setDefault({
		expanded: false,
	});
});

Template.redlinkInlineResult_dbsearch.helpers({
	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('expanded') ? 'expanded' : 'collapsed';
	}
});

Template.redlinkInlineResult_dbsearch.events({

	'click .result-item-wrapper .js-toggle-result-preview-expanded': function (event, instance) {
		const current = instance.state.get('expanded');
		instance.state.set('expanded', !current);

		if (!instance.state.get('expanded')) {
			Template.redlinkQueries.utilities.resultsInteractionCleanup();
		}
	},
	'click .js-send-message': function (event, instance) {

		/* buffer metadata of messages which are _about to be sent_
		 * This is necessary as the results or queries displayed may be entered into the message-area,
		 * but only one the message is actually sent, the metadata becomes effective for this new message
		 * - and only by then we know the message-id for which this metadata is actually valid
		 */
		Session.set('messageMetadata', {
			user: Meteor.user(),
			room: instance.data.roomId,
			metadata: {
				origin: "historicConversation",
				searchLink: instance.data.result.dbsearch_link_s
			}
		});

		//create a text-response
		let textToInsert = "";
		const selectedMessages = instance.findAll('.selected');
		if (selectedMessages.length > 0) {
			textToInsert = selectedMessages.reduce(function (concat, elem) {
					return concat + " " + elem.textContent;
				},
				'');
		} else {
			textToInsert = instance.data.result.dbsearch_link_s;
		}

		$('#chat-window-' + instance.data.roomId + ' .input-message').val(textToInsert).focus();
	}

});
<|endoftext|>


<commit_before>it("should import a changed chunk (dynamic import)", function(done) {
	function load(name) {
		return System.import("./chunk" + name);
	}
	load(1).then(function(chunk) {
		chunk.value.should.be.eql(1);
		NEXT(require("../../update")(done));
		setTimeout(function() {
			chunk.value.should.be.eql(2);
			load(2).then(function(chunk2) {
				chunk2.value.should.be.eql(2);
				done();
			}).catch(done);
		}, 100);
	}).catch(done);
});
<commit_msg>increase timeout for test<commit_after>it("should import a changed chunk (dynamic import)", function(done) {
	function load(name) {
		return System.import("./chunk" + name);
	}
	load(1).then(function(chunk) {
		chunk.value.should.be.eql(1);
		NEXT(require("../../update")(done));
		setTimeout(function() {
			chunk.value.should.be.eql(2);
			load(2).then(function(chunk2) {
				chunk2.value.should.be.eql(2);
				done();
			}).catch(done);
		}, 300);
	}).catch(done);
});
<|endoftext|>


<commit_before>module.exports = {
  files: [
    ['love.html', 'http://dict.cnki.net/dict_result.aspx?searchword=love']
  ]
}
<commit_msg>fix(:fixtures): cnki url<commit_after>module.exports = {
  files: [
    ['love.html', 'http://dict.cnki.net/old/dict_result.aspx?scw=love']
  ]
}
<|endoftext|>


<commit_before>var OPCUAClient = require("../lib/opcua-client").OPCUAClient;
var OPCUASession = require("../lib/opcua-client").OPCUASession;
var ClientSubscription = require("../lib/client/client_subscription").ClientSubscription;
var assert = require('better-assert');
var async = require("async");
var should = require('should');
var build_server_with_temperature_device = require("./utils/build_server_with_temperature_device").build_server_with_temperature_device;
var sinon = require("sinon");

describe("testing Client-Server subscription use case, on a fake server exposing the temperature device",function() {

    var server , client,temperatureVariableId,endpointUrl ;

    var port = 2001;
    before(function(done){
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        port+=1;
        server = build_server_with_temperature_device({ port:port},function() {
            endpointUrl = server.endpoints[0].endpointDescription().endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done();
        });
    });

    beforeEach(function(done){
        client = new OPCUAClient();
        done();
    });

    afterEach(function(done){
        client = null;
        done();
    });

    after(function(done){
        server.shutdown(done);
    });

    /**
     * simple wrapper that operates on a freshly created opcua session.
     * The wrapper:
     *   - connects to the server,
     *   - creates a session
     *   -     calls your callback method wit the session object
     *   - closes the session
     *   - disconnects the client
     *
     * @param func
     * @param done_func
     */
    function perform_operation_on_client_session(func,done_func) {

        assert(_.isFunction(done_func));
        var the_session;

        async.series([

            // connect
            function(callback) { client.connect(endpointUrl,callback); },

            // create session
            function(callback) {
                client.createSession(function (err,session){
                    if (!err) {
                        the_session = session;
                    }
                    callback(err);
                });
            },

            // call the user provided func
            function(callback) { func(the_session,callback); },

            // closing session
            function(callback) { the_session.close(function(err){ callback(err); }); },

            // disconnect
            function(callback) { client.disconnect(function() {  callback(); }); }
        ],done_func);
    }

    it("should create a ClientSubscription to manage a subscription",function(done){

        perform_operation_on_client_session(function(session,done){

            assert(session instanceof OPCUASession);

            var subscription = new ClientSubscription(session,{
                requestedPublishingInterval: 100,
                requestedLifetimeCount:      100 * 60 * 10 ,
                requestedMaxKeepAliveCount:  5,
                maxNotificationsPerPublish:  5,
                publishingEnabled:           true,
                priority:                    6
            });
            subscription.on("started",function(){
                setTimeout(function() { subscription.terminate(); },1000 );
            });
            subscription.on("terminated",function(){
                done();
            });
        },done);
    });
    it("a ClientSubscription should receive keep-alive events from the server",function(done){

        perform_operation_on_client_session(function(session,done){

            assert(session instanceof OPCUASession);

            var nb_keep_alive_received = 0;

            var subscription = new ClientSubscription(session,{
                requestedPublishingInterval: 10,
                requestedLifetimeCount:      10 * 60 * 10 ,
                requestedMaxKeepAliveCount:  2,
                maxNotificationsPerPublish:  2,
                publishingEnabled:           true,
                priority:                    6
            });
            subscription.on("started",function(){
                setTimeout(function() { subscription.terminate(); },1000 );
            });
            subscription.on("keepalive",function(){
                nb_keep_alive_received +=1;
            });
            subscription.on("terminated",function(){
                nb_keep_alive_received.should.be.greaterThan(0);
                done();
            });
        },done);
    });
    it("a ClientSubscription should survive longer than the life time",function(done){
        done();
    });
    it("client should be able to create subscription to monitor the temperature variable and received notification of change",function(done){
        done();
    });
});
<commit_msg>fix activateSession statusResult issue<commit_after>var OPCUAClient = require("../lib/opcua-client").OPCUAClient;
var OPCUASession = require("../lib/opcua-client").OPCUASession;
var ClientSubscription = require("../lib/client/client_subscription").ClientSubscription;
var assert = require('better-assert');
var async = require("async");
var should = require('should');
var build_server_with_temperature_device = require("./utils/build_server_with_temperature_device").build_server_with_temperature_device;
var sinon = require("sinon");

describe("testing Client-Server subscription use case, on a fake server exposing the temperature device",function() {

    var server , client,temperatureVariableId,endpointUrl ;

    var port = 2001;
    before(function(done){
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        port+=1;
        server = build_server_with_temperature_device({ port:port},function() {
            endpointUrl = server.endpoints[0].endpointDescription().endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done();
        });
    });

    beforeEach(function(done){
        client = new OPCUAClient();
        done();
    });

    afterEach(function(done){
        client = null;
        done();
    });

    after(function(done){
        server.shutdown(done);
    });

    /**
     * simple wrapper that operates on a freshly created opcua session.
     * The wrapper:
     *   - connects to the server,
     *   - creates a session
     *   -     calls your callback method wit the session object
     *   - closes the session
     *   - disconnects the client
     *
     * @param func
     * @param done_func
     */
    function perform_operation_on_client_session(func,done_func) {

        assert(_.isFunction(done_func));
        var the_session;

        async.series([

            // connect
            function(callback) { client.connect(endpointUrl,callback); },

            // create session
            function(callback) {
                client.createSession(function (err,session){
                    if (!err) {
                        the_session = session;
                    }
                    callback(err);
                });
            },

            // call the user provided func
            function(callback) { func(the_session,callback); },

            // closing session
            function(callback) { the_session.close(function(err){ callback(err); }); },

            // disconnect
            function(callback) { client.disconnect(function() {  callback(); }); }
        ],done_func);
    }

    it("should create a ClientSubscription to manage a subscription",function(done){

        perform_operation_on_client_session(function(session,done){

            assert(session instanceof OPCUASession);

            var subscription = new ClientSubscription(session,{
                requestedPublishingInterval: 100,
                requestedLifetimeCount:      100 * 60 * 10 ,
                requestedMaxKeepAliveCount:  5,
                maxNotificationsPerPublish:  5,
                publishingEnabled:           true,
                priority:                    6
            });
            subscription.on("started",function(){
                setTimeout(function() { subscription.terminate(); },1000 );
            });
            subscription.on("terminated",function(){
                done();
            });
        },done);
    });
    it("a ClientSubscription should receive keep-alive events from the server",function(done){

        perform_operation_on_client_session(function(session,done){

            assert(session instanceof OPCUASession);

            var nb_keep_alive_received = 0;

            var subscription = new ClientSubscription(session,{
                requestedPublishingInterval: 100,
                requestedLifetimeCount:      10 * 60 * 10 ,
                requestedMaxKeepAliveCount:  2,
                maxNotificationsPerPublish:  2,
                publishingEnabled:           true,
                priority:                    6
            });
            subscription.on("started",function(){
                setTimeout(function() {
                    subscription.terminate(); }
                , 500 );
            });
            subscription.on("keepalive",function(){
                nb_keep_alive_received +=1;
            });
            subscription.on("terminated",function(){
                nb_keep_alive_received.should.be.greaterThan(0);
                done();
            });
        },done);
    });
    it("a ClientSubscription should survive longer than the life time",function(done){
        done();
    });
    it("client should be able to create subscription to monitor the temperature variable and received notification of change",function(done){
        done();
    });
});
<|endoftext|>


<commit_before>/* jshint camelcase: false, quotmark: false, unused: false */
/* global inject: false */
'use strict';

describe('pascalprecht.translate', function () {

  describe('$translateProvider', function () {

    describe('#determinePreferredLanguage()', function () {

      describe('without locale negotiation', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en_US', {FOO : 'bar'})
            .translations('de_DE', {FOO : 'foo'})
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'], {
              'en_US' : 'en',
              'de_DE' : 'de'
            })
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation and lower-case navigation language', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'], {
              'en_US' : 'en',
              'de_DE' : 'de'
            })
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_us'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation w/o aliases', function () {

        var translateProvider;

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'])
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });

          translateProvider = $translateProvider;
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });

        it('should be chainable', function () {
          inject(function () {
            var ret = translateProvider.determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });

            expect(ret).toEqual(translateProvider);
          });
        });
      });

      describe('using resolver "default"', function () {
        describe('should resolve to en-US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en_US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en-us to en_us', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_us');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "java"', function () {
        describe('should resolve to en-US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en_US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en-us to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "bcp47"', function () {
        describe('should resolve to en-US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en_US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en-us to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "iso639-1"', function () {
        describe('should resolve to en-US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en_US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en-us to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

    });
  });
});
<commit_msg>test(service): test for language strings matching only if ignoring case<commit_after>/* jshint camelcase: false, quotmark: false, unused: false */
/* global inject: false */
'use strict';

describe('pascalprecht.translate', function () {

  describe('$translateProvider', function () {

    describe('#determinePreferredLanguage()', function () {

      describe('without locale negotiation', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en_US', {FOO : 'bar'})
            .translations('de_DE', {FOO : 'foo'})
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'], {
              'en_US' : 'en',
              'de_DE' : 'de'
            })
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation and lower-case navigation language', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'], {
              'en_US' : 'en',
              'de_DE' : 'de'
            })
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_us'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });
      });

      describe('with locale negotiation and lower-case preferred language and canonical form avaliable language', function () {

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en_UK', {FOO : 'bar'})
            .registerAvailableLanguageKeys(['en_UK'])
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_uk'`
              var nav = {
                language : 'en_uk'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });
        }));

        it('should respect casing in language map', function () {
          inject(function ($translate, $q, $rootScope) {
            var lang = $translate.use();
            expect(lang).toEqual('en_UK');
          });
        });
      });

      describe('with locale negotiation w/o aliases', function () {

        var translateProvider;

        beforeEach(module('pascalprecht.translate', function ($translateProvider) {
          $translateProvider
            .translations('en', {FOO : 'bar'})
            .translations('de', {FOO : 'foo'})
            .registerAvailableLanguageKeys(['en', 'de'])
            .determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });

          translateProvider = $translateProvider;
        }));

        it('should determine browser language', function () {
          inject(function ($translate, $q, $rootScope) {
            var deferred = $q.defer(),
              promise = deferred.promise,
              value;

            promise.then(function (foo) {
              value = foo;
            });
            $translate('FOO').then(function (translation) {
              deferred.resolve(translation);
            });
            $rootScope.$digest();
            expect(value).toEqual('bar');
          });
        });

        it('should be chainable', function () {
          inject(function () {
            var ret = translateProvider.determinePreferredLanguage(function () {
              // mocking
              // Work's like `window.navigator.lang = 'en_US'`
              var nav = {
                language : 'en_US'
              };
              return ((
                nav.language ||
                nav.browserLanguage ||
                nav.systemLanguage ||
                nav.userLanguage
              ) || '').split('-').join('_');
            });

            expect(ret).toEqual(translateProvider);
          });
        });
      });

      describe('using resolver "default"', function () {
        describe('should resolve to en-US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en_US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en-us to en_us', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_us');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider.determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "java"', function () {
        describe('should resolve to en-US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en_US to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en-us to en_US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en_US');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('java')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "bcp47"', function () {
        describe('should resolve to en-US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en_US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en-us to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en-US');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('bcp47')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

      describe('using resolver "iso639-1"', function () {
        describe('should resolve to en-US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-US';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en_US to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en_US';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en-us to en-US', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en-us';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });

        describe('should resolve to en to en using', function () {
          beforeEach(module('pascalprecht.translate', function ($translateProvider, $provide, pascalprechtTranslateOverrider) {
            pascalprechtTranslateOverrider.getLocale = function () {
              return 'en';
            };
            $translateProvider
              .uniformLanguageTag('iso639-1')
              .determinePreferredLanguage();
          }));
          it('test', inject(function ($window, $translate) {
            expect($translate.use()).toEqual('en');
          }));
        });
      });

    });
  });
});
<|endoftext|>


<commit_before>
function TryJobResult()
{
    this.tests = [];
    this.slave = "";
    this.url = "";
    this.timestamp = ""; // Date
    this.builder = "";
    this.clobber = false;
    this.project = "";
    this.reason = "";
    this.result = "";
    // this.key = ""; // What is this for?
    this.requester = null; // User
    this.buildnumber = 0;
    this.revision = ""; // Number or HEAD
}

TryJobResult.URL = "http://build.chromium.org/p/tryserver.chromium/builders/{1}/builds/{2}";

TryJobResult.RESULT = {
    "-1": "pending",
    "0": "success",
    "1": "warnings",
    "2": "failure",
    "3": "skipped",
    "4": "exception",
    "5": "retry",
    // It's not clear from the Rietveld code if pending is -1 or 6, the server seems to reply with -1?
    "6": "pending",
};

TryJobResult.prototype.getDetailUrl = function()
{
    return this.url;
};

TryJobResult.prototype.parseData = function(data)
{
    var result = this;
    this.tests = (data.tests || []).map(function(name) {
        return new TryJobResultStep(result, name);
    });
    this.slave = data.slave || "";
    this.timestamp = Date.utc.create(data.timestamp);
    this.builder = data.builder || "";
    this.clobber = data.clobber || false;
    this.project = data.project || "";
    this.reason = data.reason || "";
    this.result = TryJobResult.RESULT[data.result] || "";
    this.requester = new User(data.requester);
    this.buildnumber = parseInt(data.buildnumber, 10) || 0;
    this.revision = data.revision || "";
    this.url = TryJobResult.URL.assign(this.builder, this.buildnumber);
};
<commit_msg>Fix try server links now that we have tryserver.blink<commit_after>
function TryJobResult()
{
    this.tests = [];
    this.slave = "";
    this.url = "";
    this.timestamp = ""; // Date
    this.builder = "";
    this.clobber = false;
    this.project = "";
    this.reason = "";
    this.result = "";
    // this.key = ""; // What is this for?
    this.requester = null; // User
    this.buildnumber = 0;
    this.revision = ""; // Number or HEAD
}

TryJobResult.URL = "http://build.chromium.org/p/tryserver.blink/builders/{1}/builds/{2}";

TryJobResult.RESULT = {
    "-1": "pending",
    "0": "success",
    "1": "warnings",
    "2": "failure",
    "3": "skipped",
    "4": "exception",
    "5": "retry",
    // It's not clear from the Rietveld code if pending is -1 or 6, the server seems to reply with -1?
    "6": "pending",
};

TryJobResult.prototype.getDetailUrl = function()
{
    return this.url;
};

TryJobResult.prototype.parseData = function(data)
{
    var result = this;
    this.tests = (data.tests || []).map(function(name) {
        return new TryJobResultStep(result, name);
    });
    this.slave = data.slave || "";
    this.timestamp = Date.utc.create(data.timestamp);
    this.builder = data.builder || "";
    this.clobber = data.clobber || false;
    this.project = data.project || "";
    this.reason = data.reason || "";
    this.result = TryJobResult.RESULT[data.result] || "";
    this.requester = new User(data.requester);
    this.buildnumber = parseInt(data.buildnumber, 10) || 0;
    this.revision = data.revision || "";
    this.url = TryJobResult.URL.assign(this.builder, this.buildnumber);
};
<|endoftext|>