<commit_before>function initOpenLayers() {
  OpenLayers.ImgPath = "/images/OpenLayers/"

  var map = new OpenLayers.Map("map_canvas", {
    projection: "EPSG:900913",
    controls: [],
    theme: null
  });

  map.addControl(new OpenLayers.Control.PanZoomBar());
  map.addControl(new OpenLayers.Control.Navigation());
  map.addControl(new OpenLayers.Control.KeyboardDefaults());
  map.addControl(new OpenLayers.Control.Attribution());
  map.addControl(new OpenLayers.Control.ScaleLine({geodesic: true}));

  var osmLayer = new OpenLayers.Layer.OSM("OpenStreetMap");
  osmLayer.addOptions({
    transitionEffect: "resize",
    numZoomLevels: 18
  });

  map.addLayer(osmLayer);

  var airspace = new OpenLayers.Layer.XYZ("Airspace",
    "http://www.prosoar.de/airspace/${z}/${x}/${y}.png", {
    isBaseLayer: false,
    transparent: true,
    'visibility': true,
    'displayInLayerSwitcher': true
  });
  map.addLayer(airspace);

  var flightPathLayer = new OpenLayers.Layer.Vector("Flight", {
    styleMap: new OpenLayers.StyleMap({
      'default': new OpenLayers.Style({
        strokeColor: "${color}",
        strokeWidth: 2,
        // Set the external graphic and background graphic images.
        externalGraphic: "/images/glider_symbol.png",
        // Makes sure the background graphic is placed correctly relative
        // to the external graphic.
        graphicXOffset: -(40/2),
        graphicYOffset: -8,
        graphicWidth: 40,
        graphicHeight: 24,
        rotation: "${rotation}",
        // Set the z-indexes of both graphics to make sure the background
        // graphics stay in the background (shadows on top of markers looks
        // odd; let's not do that).
        graphicZIndex: 2000
      })
    })
  });

  map.addLayer(flightPathLayer);
  map.events.register("moveend", flightPathLayer, flightPathLayer.redraw);

  map.setCenter(new OpenLayers.LonLat(30, 0).
    transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject() ),
    9);

  return map;
};

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/nearest-number [rev. #0]
function getNearestNumber(a, n){
  if((l = a.length) < 2)
    return l - 1;
  for(var l, p = Math.abs(a[--l] - n); l--;)
    if(p < (p = Math.abs(a[l] - n)))
      break;
  return l + 1;
}

// add leading zeros to a number
function pad(num, size) {
  var s = "000000000" + num;
  return s.substr(s.length-size);
}

function formatSecondsAsTime(seconds) {
  seconds %= 86400;
  var h = Math.floor(seconds/3600);
  var m = Math.floor((seconds%3600)/60);
  var s = Math.floor(seconds%3600%60);

  return pad(h,2) + ":" + pad(m,2) + ":" + pad(s,2); // Format the result into time strings
}

function render_barogram() {
  var element = document.getElementById("barogram");
  var linechart = barogram.linechart(30, 0,
                      element.clientWidth - 50, element.clientHeight - 10,
                      barogram_t,
                      [barogram_h],
                      { axis: "0 0 1 1",
                        axisxstep: 8,
                        axisxfunc: formatSecondsAsTime });

  var position = barogram.set().hide();

  var hoverLine = barogram.path().attr({
    stroke: '#c44',
    'stroke-width': 2
  }).hide();

  var text = barogram.text().hide();

  var textRect = barogram.rect().attr({
    fill: '#fff',
    opacity: .7,
    stroke: '#999',
    r: 3
  }).hide();

  var hoverCircle = barogram.circle().attr({
    stroke: '#c44',
    'stroke-width': 2,
    r: 6
  }).hide();

  position.push(hoverLine);
  position.push(hoverCircle);
  position.push(textRect.insertAfter(hoverCircle));
  position.push(text.insertAfter(textRect));

  linechart.hoverColumn(function() {
    hoverLine.attr({ path:
      "M " + this.x.toString() + " " + this.attrs.height + " " +
      "l 0 " + (-(this.attrs.height - this.y) + 6).toString() +
      "M " + this.x.toString() + " 0 " +
      "l 0 " + (this.y - 6).toString()
    });
    var vario = null;
    if (this.next && this.next.values) {
      vario = (this.next.values[0] - this.values[0]) / (this.next.axis - this.axis);
    }

    text.attr({
      x: this.x,
      y: this.attrs.height - 20,
      text: Math.round(this.values[0]) + " m" +
            ((vario !== null)?"\n" + (Math.round(vario*10)/10) + " m/s":"")
    });

    hoverCircle.attr({
      cx: this.x,
      cy: this.y,
    });

    var textBBox = text.getBBox();
    textRect.attr({
      x: textBBox.x - 2,
      y: textBBox.y - 2,
      width: textBBox.width + 4,
      height: textBBox.height + 4
    });

    position.show();

    this.index = getNearestNumber(barogram_t, this.axis);
    showPlanePosition(this.index);
  }, function() {
    hidePlanePosition(this.index);
    position && position.hide();
  });
}

function showPlanePosition(id) {
  var rotation = 0;
  if (lonlat[id+1] != 'undefined') {
    rotation = Math.atan2(lonlat[id+1].lon-lonlat[id].lon, lonlat[id+1].lat-lonlat[id].lat) * 180/Math.PI;
  } else if (lonlat[id-1] != 'undefined') {
    rotation = Math.atan2(lonlat[id].lon-lonlat[id-1].lon, lonlat[id].lat-lonlat[id-1].lat) * 180/Math.PI;
  }
  plane.attributes.rotation = rotation;
  plane.geometry = new OpenLayers.Geometry.Point(lonlat[id].lon, lonlat[id].lat).
    transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
  map.getLayersByName("Flight")[0].drawFeature(plane);
}

function hidePlanePosition(id) {
  map.getLayersByName("Flight")[0].removeFeatures(plane);
}

<commit_msg>public.js.flight: redraw flight layer every 200ms on map pan<commit_after>function initOpenLayers() {
  OpenLayers.ImgPath = "/images/OpenLayers/"

  var map = new OpenLayers.Map("map_canvas", {
    projection: "EPSG:900913",
    controls: [],
    theme: null
  });

  map.addControl(new OpenLayers.Control.PanZoomBar());
  map.addControl(new OpenLayers.Control.Navigation());
  map.addControl(new OpenLayers.Control.KeyboardDefaults());
  map.addControl(new OpenLayers.Control.Attribution());
  map.addControl(new OpenLayers.Control.ScaleLine({geodesic: true}));

  var osmLayer = new OpenLayers.Layer.OSM("OpenStreetMap");
  osmLayer.addOptions({
    transitionEffect: "resize",
    numZoomLevels: 18
  });

  map.addLayer(osmLayer);

  var airspace = new OpenLayers.Layer.XYZ("Airspace",
    "http://www.prosoar.de/airspace/${z}/${x}/${y}.png", {
    isBaseLayer: false,
    transparent: true,
    'visibility': true,
    'displayInLayerSwitcher': true
  });
  map.addLayer(airspace);

  var flightPathLayer = new OpenLayers.Layer.Vector("Flight", {
    styleMap: new OpenLayers.StyleMap({
      'default': new OpenLayers.Style({
        strokeColor: "${color}",
        strokeWidth: 2,
        // Set the external graphic and background graphic images.
        externalGraphic: "/images/glider_symbol.png",
        // Makes sure the background graphic is placed correctly relative
        // to the external graphic.
        graphicXOffset: -(40/2),
        graphicYOffset: -8,
        graphicWidth: 40,
        graphicHeight: 24,
        rotation: "${rotation}",
        // Set the z-indexes of both graphics to make sure the background
        // graphics stay in the background (shadows on top of markers looks
        // odd; let's not do that).
        graphicZIndex: 2000
      })
    })
  });

  map.addLayer(flightPathLayer);
//  map.events.register("moveend", flightPathLayer, flightPathLayer.redraw);

  map.setCenter(new OpenLayers.LonLat(30, 0).
    transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject() ),
    9);

  var initRedrawLayer = function(layer) {
    if (this.timer) return;
    this.timer = window.setTimeout(function() { this.timer = null; layer.redraw(); }.bind(this), 200);
  };
  map.events.register("move", this, function() { initRedrawLayer(flightPathLayer); });

  return map;
};

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/nearest-number [rev. #0]
function getNearestNumber(a, n){
  if((l = a.length) < 2)
    return l - 1;
  for(var l, p = Math.abs(a[--l] - n); l--;)
    if(p < (p = Math.abs(a[l] - n)))
      break;
  return l + 1;
}

// add leading zeros to a number
function pad(num, size) {
  var s = "000000000" + num;
  return s.substr(s.length-size);
}

function formatSecondsAsTime(seconds) {
  seconds %= 86400;
  var h = Math.floor(seconds/3600);
  var m = Math.floor((seconds%3600)/60);
  var s = Math.floor(seconds%3600%60);

  return pad(h,2) + ":" + pad(m,2) + ":" + pad(s,2); // Format the result into time strings
}

function render_barogram() {
  var element = document.getElementById("barogram");
  var linechart = barogram.linechart(30, 0,
                      element.clientWidth - 50, element.clientHeight - 10,
                      barogram_t,
                      [barogram_h],
                      { axis: "0 0 1 1",
                        axisxstep: 8,
                        axisxfunc: formatSecondsAsTime });

  var position = barogram.set().hide();

  var hoverLine = barogram.path().attr({
    stroke: '#c44',
    'stroke-width': 2
  }).hide();

  var text = barogram.text().hide();

  var textRect = barogram.rect().attr({
    fill: '#fff',
    opacity: .7,
    stroke: '#999',
    r: 3
  }).hide();

  var hoverCircle = barogram.circle().attr({
    stroke: '#c44',
    'stroke-width': 2,
    r: 6
  }).hide();

  position.push(hoverLine);
  position.push(hoverCircle);
  position.push(textRect.insertAfter(hoverCircle));
  position.push(text.insertAfter(textRect));

  linechart.hoverColumn(function() {
    hoverLine.attr({ path:
      "M " + this.x.toString() + " " + this.attrs.height + " " +
      "l 0 " + (-(this.attrs.height - this.y) + 6).toString() +
      "M " + this.x.toString() + " 0 " +
      "l 0 " + (this.y - 6).toString()
    });
    var vario = null;
    if (this.next && this.next.values) {
      vario = (this.next.values[0] - this.values[0]) / (this.next.axis - this.axis);
    }

    text.attr({
      x: this.x,
      y: this.attrs.height - 20,
      text: Math.round(this.values[0]) + " m" +
            ((vario !== null)?"\n" + (Math.round(vario*10)/10) + " m/s":"")
    });

    hoverCircle.attr({
      cx: this.x,
      cy: this.y,
    });

    var textBBox = text.getBBox();
    textRect.attr({
      x: textBBox.x - 2,
      y: textBBox.y - 2,
      width: textBBox.width + 4,
      height: textBBox.height + 4
    });

    position.show();

    this.index = getNearestNumber(barogram_t, this.axis);
    showPlanePosition(this.index);
  }, function() {
    hidePlanePosition(this.index);
    position && position.hide();
  });
}

function showPlanePosition(id) {
  var rotation = 0;
  if (lonlat[id+1] != 'undefined') {
    rotation = Math.atan2(lonlat[id+1].lon-lonlat[id].lon, lonlat[id+1].lat-lonlat[id].lat) * 180/Math.PI;
  } else if (lonlat[id-1] != 'undefined') {
    rotation = Math.atan2(lonlat[id].lon-lonlat[id-1].lon, lonlat[id].lat-lonlat[id-1].lat) * 180/Math.PI;
  }
  plane.attributes.rotation = rotation;
  plane.geometry = new OpenLayers.Geometry.Point(lonlat[id].lon, lonlat[id].lat).
    transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
  map.getLayersByName("Flight")[0].drawFeature(plane);
}

function hidePlanePosition(id) {
  map.getLayersByName("Flight")[0].removeFeatures(plane);
}

<|endoftext|>


<commit_before>import _ from 'lodash'
import postcss from 'postcss'

function updateSource(nodes, source) {
  return _.tap(Array.isArray(nodes) ? postcss.root({ nodes }) : nodes, (tree) => {
    tree.walk((node) => (node.source = source))
  })
}

export default function (
  _config,
  { base: pluginBase, components: pluginComponents, utilities: pluginUtilities }
) {
  return function (css) {
    css.walkAtRules('import', (atRule) => {
      if (atRule.params === '"tailwindcss/base"' || atRule.params === "'tailwindcss/base'") {
        atRule.name = 'tailwind'
        atRule.params = 'base'
      }

      if (
        atRule.params === '"tailwindcss/components"' ||
        atRule.params === "'tailwindcss/components'"
      ) {
        atRule.name = 'tailwind'
        atRule.params = 'components'
      }

      if (
        atRule.params === '"tailwindcss/utilities"' ||
        atRule.params === "'tailwindcss/utilities'"
      ) {
        atRule.name = 'tailwind'
        atRule.params = 'utilities'
      }

      if (atRule.params === '"tailwindcss/screens"' || atRule.params === "'tailwindcss/screens'") {
        atRule.name = 'tailwind'
        atRule.params = 'screens'
      }
    })

    let includesScreensExplicitly = false
    const layers = {
      base: [],
      components: [],
      utilities: [],
    }

    css.walkAtRules('layer', (atRule) => {
      if (!['base', 'components', 'utilities'].includes(atRule.params)) {
        return
      }

      layers[atRule.params].push(atRule)
    })

    css.walkAtRules('tailwind', (atRule) => {
      if (atRule.params === 'preflight') {
        // prettier-ignore
        throw atRule.error("`@tailwind preflight` is not a valid at-rule in Tailwind v1.0, use `@tailwind base` instead.", { word: 'preflight' })
      }

      if (atRule.params === 'base') {
        atRule.after(layers.base)
        atRule.after(updateSource(pluginBase, atRule.source))
      }

      if (atRule.params === 'components') {
        atRule.after(layers.components)
        atRule.after(updateSource(pluginComponents, atRule.source))
      }

      if (atRule.params === 'utilities') {
        atRule.after(layers.utilities)
        atRule.after(updateSource(pluginUtilities, atRule.source))
      }

      if (atRule.params === 'screens') {
        includesScreensExplicitly = true
      }
    })

    if (!includesScreensExplicitly) {
      css.append([postcss.atRule({ name: 'tailwind', params: 'screens' })])
    }
  }
}
<commit_msg>Version number corrected in substituteTailwindAtRules (#3237)<commit_after>import _ from 'lodash'
import postcss from 'postcss'

function updateSource(nodes, source) {
  return _.tap(Array.isArray(nodes) ? postcss.root({ nodes }) : nodes, (tree) => {
    tree.walk((node) => (node.source = source))
  })
}

export default function (
  _config,
  { base: pluginBase, components: pluginComponents, utilities: pluginUtilities }
) {
  return function (css) {
    css.walkAtRules('import', (atRule) => {
      if (atRule.params === '"tailwindcss/base"' || atRule.params === "'tailwindcss/base'") {
        atRule.name = 'tailwind'
        atRule.params = 'base'
      }

      if (
        atRule.params === '"tailwindcss/components"' ||
        atRule.params === "'tailwindcss/components'"
      ) {
        atRule.name = 'tailwind'
        atRule.params = 'components'
      }

      if (
        atRule.params === '"tailwindcss/utilities"' ||
        atRule.params === "'tailwindcss/utilities'"
      ) {
        atRule.name = 'tailwind'
        atRule.params = 'utilities'
      }

      if (atRule.params === '"tailwindcss/screens"' || atRule.params === "'tailwindcss/screens'") {
        atRule.name = 'tailwind'
        atRule.params = 'screens'
      }
    })

    let includesScreensExplicitly = false
    const layers = {
      base: [],
      components: [],
      utilities: [],
    }

    css.walkAtRules('layer', (atRule) => {
      if (!['base', 'components', 'utilities'].includes(atRule.params)) {
        return
      }

      layers[atRule.params].push(atRule)
    })

    css.walkAtRules('tailwind', (atRule) => {
      if (atRule.params === 'preflight') {
        // prettier-ignore
        throw atRule.error("`@tailwind preflight` is not a valid at-rule in Tailwind v2.0, use `@tailwind base` instead.", { word: 'preflight' })
      }

      if (atRule.params === 'base') {
        atRule.after(layers.base)
        atRule.after(updateSource(pluginBase, atRule.source))
      }

      if (atRule.params === 'components') {
        atRule.after(layers.components)
        atRule.after(updateSource(pluginComponents, atRule.source))
      }

      if (atRule.params === 'utilities') {
        atRule.after(layers.utilities)
        atRule.after(updateSource(pluginUtilities, atRule.source))
      }

      if (atRule.params === 'screens') {
        includesScreensExplicitly = true
      }
    })

    if (!includesScreensExplicitly) {
      css.append([postcss.atRule({ name: 'tailwind', params: 'screens' })])
    }
  }
}
<|endoftext|>


<commit_before>var db
var leveldown
var testCommon
var isTypedArray = require('./util').isTypedArray

module.exports.setUp = function (_leveldown, test, _testCommon) {
  test('setUp common', _testCommon.setUp)
  test('setUp db', function (t) {
    leveldown = _leveldown
    testCommon = _testCommon
    db = leveldown(testCommon.location())
    db.open(t.end.bind(t))
  })
}

module.exports.args = function (test) {
  test('test argument-less put() throws', function (t) {
    t.throws(
        db.put.bind(db)
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'no-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 1-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo')
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 1-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 2-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo', 'bar')
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 2-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 3-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo', 'bar', {})
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 3-arg put() throws'
    )
    t.end()
  })

  test('test _serialize object', function (t) {
    t.plan(3)
    var db = leveldown(testCommon.location())
    db._put = function (key, value, opts, callback) {
      t.ok(key)
      t.ok(value)
      process.nextTick(callback)
    }
    db.put({}, {}, function (err, val) {
      t.error(err)
    })
  })

  test('test custom _serialize*', function (t) {
    t.plan(4)
    var db = leveldown(testCommon.location())
    db._serializeKey = db._serializeValue = function (data) { return data }
    db._put = function (key, value, options, callback) {
      t.deepEqual(key, { foo: 'bar' })
      t.deepEqual(value, { beep: 'boop' })
      process.nextTick(callback)
    }
    db.open(function () {
      db.put({ foo: 'bar' }, { beep: 'boop' }, function (err) {
        t.error(err)
        db.close(t.error.bind(t))
      })
    })
  })
}

module.exports.put = function (test) {
  test('test simple put()', function (t) {
    db.put('foo', 'bar', function (err) {
      t.error(err)
      db.get('foo', function (err, value) {
        t.error(err)
        var result = value.toString()
        if (isTypedArray(value)) {
          result = String.fromCharCode.apply(null, new Uint16Array(value))
        }
        t.equal(result, 'bar')
        t.end()
      })
    })
  })

  if (process.browser) {
    test('test object value put()', function (t) {
      db.put('dood', {pete: 'sampras'}, function (err) {
        t.error(err)
        db.get('dood', { asBuffer: false }, function (err, value) {
          t.error(err)
          t.equal(JSON.stringify(value), JSON.stringify({pete: 'sampras'}))
          t.end()
        })
      })
    })
  }
}

module.exports.sync = function (test) {
  test('sync put', function (t) {
    db.put('foo', 'bar', { sync: true }, function (err) {
      t.error(err)
      db.get('foo', function (err, value) {
        t.error(err)
        t.equal(value.toString(), 'bar')
        t.end()
      })
    })
  })
  test('sync put just before close', function (t) {
    t.plan(2)
    db.put('foo', 'bar', { sync: true }, function (err) {
      t.error(err)
    })
    db.close(function (err) {
      t.error(err)
    })
  })
}

module.exports.tearDown = function (test, testCommon) {
  test('tearDown', function (t) {
    db.close(testCommon.tearDown.bind(null, t))
  })
}

module.exports.all = function (leveldown, test, testCommon) {
  module.exports.setUp(leveldown, test, testCommon)
  module.exports.args(test)
  module.exports.put(test)
  module.exports.tearDown(test, testCommon)
}
<commit_msg>remove object value test<commit_after>var db
var leveldown
var testCommon
var isTypedArray = require('./util').isTypedArray

module.exports.setUp = function (_leveldown, test, _testCommon) {
  test('setUp common', _testCommon.setUp)
  test('setUp db', function (t) {
    leveldown = _leveldown
    testCommon = _testCommon
    db = leveldown(testCommon.location())
    db.open(t.end.bind(t))
  })
}

module.exports.args = function (test) {
  test('test argument-less put() throws', function (t) {
    t.throws(
        db.put.bind(db)
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'no-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 1-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo')
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 1-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 2-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo', 'bar')
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 2-arg put() throws'
    )
    t.end()
  })

  test('test callback-less, 3-arg, put() throws', function (t) {
    t.throws(
        db.put.bind(db, 'foo', 'bar', {})
      , { name: 'Error', message: 'put() requires a callback argument' }
      , 'callback-less, 3-arg put() throws'
    )
    t.end()
  })

  test('test _serialize object', function (t) {
    t.plan(3)
    var db = leveldown(testCommon.location())
    db._put = function (key, value, opts, callback) {
      t.ok(key)
      t.ok(value)
      process.nextTick(callback)
    }
    db.put({}, {}, function (err, val) {
      t.error(err)
    })
  })

  test('test custom _serialize*', function (t) {
    t.plan(4)
    var db = leveldown(testCommon.location())
    db._serializeKey = db._serializeValue = function (data) { return data }
    db._put = function (key, value, options, callback) {
      t.deepEqual(key, { foo: 'bar' })
      t.deepEqual(value, { beep: 'boop' })
      process.nextTick(callback)
    }
    db.open(function () {
      db.put({ foo: 'bar' }, { beep: 'boop' }, function (err) {
        t.error(err)
        db.close(t.error.bind(t))
      })
    })
  })
}

module.exports.put = function (test) {
  test('test simple put()', function (t) {
    db.put('foo', 'bar', function (err) {
      t.error(err)
      db.get('foo', function (err, value) {
        t.error(err)
        var result = value.toString()
        if (isTypedArray(value)) {
          result = String.fromCharCode.apply(null, new Uint16Array(value))
        }
        t.equal(result, 'bar')
        t.end()
      })
    })
  })
}

module.exports.sync = function (test) {
  test('sync put', function (t) {
    db.put('foo', 'bar', { sync: true }, function (err) {
      t.error(err)
      db.get('foo', function (err, value) {
        t.error(err)
        t.equal(value.toString(), 'bar')
        t.end()
      })
    })
  })
  test('sync put just before close', function (t) {
    t.plan(2)
    db.put('foo', 'bar', { sync: true }, function (err) {
      t.error(err)
    })
    db.close(function (err) {
      t.error(err)
    })
  })
}

module.exports.tearDown = function (test, testCommon) {
  test('tearDown', function (t) {
    db.close(testCommon.tearDown.bind(null, t))
  })
}

module.exports.all = function (leveldown, test, testCommon) {
  module.exports.setUp(leveldown, test, testCommon)
  module.exports.args(test)
  module.exports.put(test)
  module.exports.tearDown(test, testCommon)
}
<|endoftext|>


<commit_before>function parseUri(str) {
    var	o   = parseUri.options,
    m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
                           if ($1) uri[o.q.name][$1] = $2;
                           });

    uri['extension'] = uri.file.substr(uri.file.lastIndexOf('.') + 1);

    return uri;
};

parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q:   {
name:   "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};

// http://www.fileinfo.com/list/x
var ext_mapper = {
    'c': 'c',
    'h': 'c',
    'm': 'c',
    'css': 'css',
    'cpp': 'cpp',
    'c++': 'cpp',
    'cc': 'cpp',
    'h': 'cpp',
    'c#': 'csharp',
    'cs': 'csharp',
    'css': 'css',
    'diff': 'diff',
    'patch': 'diff',
    'as': 'flex',
    'html': 'html',
    'htm': 'html',
    'java': 'java',
    'js': 'javascript_dom',
    'tex': 'latex',
    'log': 'log',
    'm4': 'm4',
    'pas': 'pascal',
    '~pa': 'pascal',
    'pl': 'perl',
    'php': 'html',
    'php3': 'html',
    'php4': 'html',
    'php5': 'html',
    'py': 'python',
    'rb': 'ruby',
    'scl': 'scala',
    'sh': 'sh',
    'bash': 'bash',
    'sql': 'sql',
    'tcl': 'tcl',
    'xml': 'xml',
    'xhtml': 'xml',
    'xslt': 'xml',
    'xdl': 'xml',
    'xlnk': 'xml',
    'xsd': 'xml',
    'xsl': 'xml',
    'xspf': 'xml',
    'xul': 'xml',
};

var fn_mapper = {
    'Makefile': 'makefile'
};

function gotDocument(uri, source) {
    var components = parseUri(uri);
    var extension = components.extension;
    var syntax = ext_mapper[extension];

    if ( ( syntax === null ) || ( syntax === undefined ) ) {
        if ( source[0] == '<' ) syntax = 'html';
        else syntax = '';
    }

    document.title = components.file ? components.file : uri;

    $('body').empty();
    $('

').text(source).addClass('sh_' + syntax).appendTo('body');

    if ( syntax != '' )
        sh_highlightDocument('js/lang/', '.min.js');

    $('a').click(function(){
                 return true;
                 });
}

$(function(){
  var uri = window.location.search ? unescape(window.location.search.substr(1)) : 'samples/jquery.timeago.js';
  $.get(uri, function(data){ gotDocument(uri, data); });
  });

$('a').live('click', function(){
            var uri = '' + window.location;

            if ( uri.indexOf('?') != -1 ) {
            uri = uri.substr(0, uri.indexOf('?')-1);
            }

            window.location = '?' + escape($(this).attr('href'));

            return false;
            });
<commit_msg>enable syntax highlighting for php files.<commit_after>function parseUri(str) {
    var	o   = parseUri.options,
    m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
                           if ($1) uri[o.q.name][$1] = $2;
                           });

    uri['extension'] = uri.file.substr(uri.file.lastIndexOf('.') + 1);

    return uri;
};

parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q:   {
name:   "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};

// http://www.fileinfo.com/list/x
var ext_mapper = {
    'c': 'c',
    'h': 'c',
    'm': 'c',
    'css': 'css',
    'cpp': 'cpp',
    'c++': 'cpp',
    'cc': 'cpp',
    'h': 'cpp',
    'c#': 'csharp',
    'cs': 'csharp',
    'css': 'css',
    'diff': 'diff',
    'patch': 'diff',
    'as': 'flex',
    'html': 'html',
    'htm': 'html',
    'java': 'java',
    'js': 'javascript_dom',
    'tex': 'latex',
    'log': 'log',
    'm4': 'm4',
    'pas': 'pascal',
    '~pa': 'pascal',
    'pl': 'perl',
    'php': 'php',
    'php3': 'php',
    'php4': 'php',
    'php5': 'php',
    'py': 'python',
    'rb': 'ruby',
    'scl': 'scala',
    'sh': 'sh',
    'bash': 'bash',
    'sql': 'sql',
    'tcl': 'tcl',
    'xml': 'xml',
    'xhtml': 'xml',
    'xslt': 'xml',
    'xdl': 'xml',
    'xlnk': 'xml',
    'xsd': 'xml',
    'xsl': 'xml',
    'xspf': 'xml',
    'xul': 'xml',
};

var fn_mapper = {
    'Makefile': 'makefile'
};

function gotDocument(uri, source) {
    var components = parseUri(uri);
    var extension = components.extension;
    var syntax = ext_mapper[extension];

    if ( ( syntax === null ) || ( syntax === undefined ) ) {
        if ( source[0] == '<' ) syntax = 'html';
        else syntax = '';
    }

    document.title = components.file ? components.file : uri;

    $('body').empty();
    $('

').text(source).addClass('sh_' + syntax).appendTo('body');

    if ( syntax != '' )
        sh_highlightDocument('js/lang/', '.min.js');

    $('a').click(function(){
                 return true;
                 });
}

$(function(){
  var uri = window.location.search ? unescape(window.location.search.substr(1)) : 'samples/jquery.timeago.js';
  $.get(uri, function(data){ gotDocument(uri, data); });
  });

$('a').live('click', function(){
            var uri = '' + window.location;

            if ( uri.indexOf('?') != -1 ) {
            uri = uri.substr(0, uri.indexOf('?')-1);
            }

            window.location = '?' + escape($(this).attr('href'));

            return false;
            });
<|endoftext|>


<commit_before>describe('Auto fetching', function() {
  var Person, server;

  beforeEach(function() {
    Person = Ember.Resource.define({
      url: '/people',
      schema: {
        id:       Number,
        name:     String
      }
    });

    server = sinon.fakeServer.create();
    Ember.Resource.Lifecycle.clock.tick();
  });

  afterEach(function() {
    server.restore();
  });

  describe('of models', function() {
    var person;

    beforeEach(function() {
      server.respondWith("GET", "/people/1",
                         [200, { "Content-Type": "application/json" },
                         '{ "id": 1, "name": "Mick Staugaard" }']);
      person = Person.create({id: 1});
    });

    it('getting known attributes should not schedule a fetch', function() {
      spyOn(person, 'fetch');
      runs(function() {
        expect(person.get('id')).toBe(1);
      });

      waits(100);

      runs(function() {
        expect(person.fetch).not.toHaveBeenCalled();
      });
    });

    it('getting unknown attributes should not schedule a fetch', function() {
      runs(function() {
        expect(person.get('name')).toBeUndefined();
      });

      waits(100);

      runs(function() {
        server.respond();
        expect(person.get('name')).toBe('Mick Staugaard');
      });
    });
  });

  describe('of collections', function() {
    var people;

    beforeEach(function() {
      server.respondWith("GET", "/people",
                         [200, { "Content-Type": "application/json" },
                         '[{ "id": 1, "name": "Mick Staugaard" }]']);
      people = Ember.ResourceCollection.create({type: Person});
      server.respond();
    });

    it('should not fetch on creation', function() {
      var hasFetched = false;
      var TestCollection = Ember.ResourceCollection.extend({
        fetch: function() {
          hasFetched = true;
        }
      });

      runs(function() {
        people = TestCollection.create({type: Person});
      });

      waits(100);

      runs(function() {
        expect(hasFetched).toBe(false);
      });
    });

    describe('that are fetched', function() {
      beforeEach(function() {
        people.fetch();
        server.respond();

        waitsFor(function() {
          return people.get('length') > 0;
        }, 'collection never fetched', 1000);

        runs(function() {
          server.restore();
          server = sinon.fakeServer.create();
          server.respondWith("GET", "/people",
                             [200, { "Content-Type": "application/json" },
                             '[{ "id": 1, "name": "Mick Staugaard" }, { "id": 2, "name": "Shajith Chacko" }]']);
        });
      });

      it('should not be refetched', function() {
        runs(function() {
           people.fetch();
           server.respond();
        });

        waits(1000);

        runs(function() {
          expect(people.get('length')).toBe(1);
        });
      });

      it('should return a resolved deferred', function() {
        var result = people.fetch();
        expect(result).not.toBeUndefined();
        expect(result.state()).toBe('resolved');
      });

      describe('and expired', function() {
        beforeEach(function() {
          runs(function() {
            people.expire();
          });

          waitsFor(function() {
            return people.get('isExpired');
          }, 'collection never expired', 1000);
        });

        it('should refetch', function() {
          waitsFor(function() {
            server.respond();
            return people.get('length') === 2;
          }, 'collection never refetched', 2000);
        });
      });
    });

  });

});
<commit_msg>AutoFetch spec: some cleanup, adding a test case<commit_after>describe('Auto fetching', function() {
  var Person, server;

  beforeEach(function() {
    Person = Ember.Resource.define({
      url: '/people',
      schema: {
        id:       Number,
        name:     String
      }
    });

    server = sinon.fakeServer.create();
    Ember.Resource.Lifecycle.clock.tick();
  });

  afterEach(function() {
    server.restore();
  });

  describe('of models', function() {
    var person;

    beforeEach(function() {
      server.respondWith("GET", "/people/1",
                         [200, { "Content-Type": "application/json" },
                         '{ "id": 1, "name": "Mick Staugaard" }']);
      person = Person.create({id: 1});
    });

    it('getting known attributes should not schedule a fetch', function() {
      spyOn(person, 'fetch');
      runs(function() {
        expect(person.get('id')).toBe(1);
      });

      waits(100);

      runs(function() {
        expect(person.fetch).not.toHaveBeenCalled();
      });
    });

    it('getting known attributes that are not defined should schedule a fetch', function() {
      runs(function() {
        expect(person.get('name')).toBeUndefined();
      });

      waits(100);

      runs(function() {
        server.respond();
        expect(person.get('name')).toBe('Mick Staugaard');
      });
    });

    it('getting unknown attributes should not schedule a fetch', function() {
      spyOn(person, 'fetch');
      runs(function() {
        expect(person.get('notInSchema')).toBeUndefined();
      });

      waits(100);

      runs(function() {
        expect(person.fetch).not.toHaveBeenCalled();
      });
    });
  });

  describe('of collections', function() {
    var people;

    beforeEach(function() {
      server.respondWith("GET", "/people",
                         [200, { "Content-Type": "application/json" },
                         '[{ "id": 1, "name": "Mick Staugaard" }]']);
      people = Ember.ResourceCollection.create({type: Person});
      server.respond();
    });

    it('should not fetch on creation', function() {
      var hasFetched = false;
      var TestCollection = Ember.ResourceCollection.extend({
        fetch: function() {
          hasFetched = true;
        }
      });

      runs(function() {
        people = TestCollection.create({type: Person});
      });

      waits(100);

      runs(function() {
        expect(hasFetched).toBe(false);
      });
    });

    describe('that are fetched', function() {
      beforeEach(function() {
        people.fetch();
        server.respond();

        waitsFor(function() {
          return people.get('length') > 0;
        }, 'collection never fetched', 1000);

        runs(function() {
          server.restore();
          server = sinon.fakeServer.create();
          server.respondWith("GET", "/people",
                             [200, { "Content-Type": "application/json" },
                             '[{ "id": 1, "name": "Mick Staugaard" }, { "id": 2, "name": "Shajith Chacko" }]']);
        });
      });

      it('should not be refetched', function() {
        runs(function() {
           people.fetch();
           server.respond();
        });

        waits(1000);

        runs(function() {
          expect(people.get('length')).toBe(1);
        });
      });

      it('should return a resolved deferred', function() {
        var result = people.fetch();
        expect(result).not.toBeUndefined();
        expect(result.state()).toBe('resolved');
      });

      describe('and expired', function() {
        beforeEach(function() {
          runs(function() {
            people.expire();
          });

          waitsFor(function() {
            return people.get('isExpired');
          }, 'collection never expired', 1000);
        });

        it('should refetch', function() {
          waitsFor(function() {
            server.respond();
            return people.get('length') === 2;
          }, 'collection never refetched', 2000);
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>var request = require('request');
var Q = require('q');
var config = require('konfig')().app;
var Minutedock = function (apiKey) {

    var self = this;
    this.apiKey = apiKey;

    this.api = {
        accounts:{
            all:function () {
                return self.request('accounts.json', "GET");
            },
            active:function () {
                return self.request('accounts/current.json', "GET");
            }
        },
        users:{
            all:function (accountID) {
                var data = { account_id:accountID }
                return self.request('users.json', "GET", data);
            }
        },
        entries:{
            current:function () {
                return self.request('entries/current.json', "GET");
            },
            update:function (id, data) {
                var form_data = { entry:data };
                return self.request('entries/' + id + '.json', "PUT", form_data);
            },
            start:function () {
                return self.request('entries/current/start.json', "POST");
            },
            pause:function () {
                return self.request('entries/current/pause.json', "POST");

            },
            log:function () {
                return self.request('entries/current/log.json', "POST");
            },
            new:function (accountID, data) {
                var form_data = {
                    entry:data,
                    account_id:accountID
                };
                return self.request('entries.json', "POST", form_data);
            },
            search:function (data) {
                return self.request('entries.json', "GET", data);
            },
            delete:function (entryId) {
                return self.request('entries/' + entryId + '.json', "DELETE");
            }
        },
        contacts:{
            all:function (accountID) {
                var data = { account_id:accountID };
                return self.request('contacts.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    contact:data,
                    account_id:accountID
                };
                return self.request('contacts.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { contact:data };
                return self.request('contacts/' + id + '.json', "PUT", form_data);
            }
        },
        tasks:{
            all:function (accountID) {
                var data = {account_id:accountID };
                return self.request('tasks.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    task:data,
                    account_id:accountID
                };
                return self.request('tasks.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { task:data };
                return self.request('tasks/' + id + '.json', "PUT", form_data);
            },
            delete:function (id) {
                return self.request('tasks/' + id + '.json', "DELETE");
            },
            archive:function (id) {
                return self.request('tasks/' + id + '/archive.json', "POST");
            }
        },
        projects:{
            all:function (accountID) {
                var data = { account_id:accountID };
                return self.request('projects.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    project:data,
                    account_id:accountID
                };
                return self.request('projects.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { project:data };
                return self.request('projects/' + id + '.json', "PUT", form_data);
            },
            delete:function (id) {
                return self.request('projects/' + id + '.json', "DELETE");
            },
            archive:function (id) {
                return self.request('projects/' + id + '/archive.json', "POST");
            }
        }
    };

    return this.api;
};

Minutedock.prototype.request = function (path, method, form_data) {

    var data = form_data || { };
    data["api_key"] = this.apiKey;

    var options = {
        "uri" : config["minutedock.base.uri"] + path,
        "method":method,
        "json" : data,
        "qs" : data
    };

    var deferred = Q.defer();
    request(options, function (error, res, body) {
        if(error){
            console.error('Request error: ' + error + ' ' + options.uri);
            deferred.reject({'status':res.statusCode});
            return;
        }
        if (res.statusCode != 200) {
            console.error('MinuteDock API error: ' + res.statusCode + ' ' + options.uri);
            deferred.reject({'status':res.statusCode});
            return;
        }
        deferred.resolve(body);
    });
    return deferred.promise;
};

module.exports = Minutedock;<commit_msg>Fixed #83. Sending either body or query params<commit_after>var request = require('request');
var Q = require('q');
var config = require('konfig')().app;
var Minutedock = function (apiKey) {

    var self = this;
    this.apiKey = apiKey;

    this.api = {
        accounts:{
            all:function () {
                return self.request('accounts.json', "GET");
            },
            active:function () {
                return self.request('accounts/current.json', "GET");
            }
        },
        users:{
            all:function (accountID) {
                var data = { account_id:accountID }
                return self.request('users.json', "GET", data);
            }
        },
        entries:{
            current:function () {
                return self.request('entries/current.json', "GET");
            },
            update:function (id, data) {
                var form_data = { entry:data };
                return self.request('entries/' + id + '.json', "PUT", form_data);
            },
            start:function () {
                return self.request('entries/current/start.json', "POST");
            },
            pause:function () {
                return self.request('entries/current/pause.json', "POST");

            },
            log:function () {
                return self.request('entries/current/log.json', "POST");
            },
            new:function (accountID, data) {
                var form_data = {
                    entry:data,
                    account_id:accountID
                };
                return self.request('entries.json', "POST", form_data);
            },
            search:function (data) {
                return self.request('entries.json', "GET", data);
            },
            delete:function (entryId) {
                return self.request('entries/' + entryId + '.json', "DELETE");
            }
        },
        contacts:{
            all:function (accountID) {
                var data = { account_id:accountID };
                return self.request('contacts.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    contact:data,
                    account_id:accountID
                };
                return self.request('contacts.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { contact:data };
                return self.request('contacts/' + id + '.json', "PUT", form_data);
            }
        },
        tasks:{
            all:function (accountID) {
                var data = {account_id:accountID };
                return self.request('tasks.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    task:data,
                    account_id:accountID
                };
                return self.request('tasks.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { task:data };
                return self.request('tasks/' + id + '.json', "PUT", form_data);
            },
            delete:function (id) {
                return self.request('tasks/' + id + '.json', "DELETE");
            },
            archive:function (id) {
                return self.request('tasks/' + id + '/archive.json', "POST");
            }
        },
        projects:{
            all:function (accountID) {
                var data = { account_id:accountID };
                return self.request('projects.json', "GET", data);
            },
            new:function (accountID, data) {
                var form_data = {
                    project:data,
                    account_id:accountID
                };
                return self.request('projects.json', "POST", form_data);
            },
            update:function (id, data) {
                var form_data = { project:data };
                return self.request('projects/' + id + '.json', "PUT", form_data);
            },
            delete:function (id) {
                return self.request('projects/' + id + '.json', "DELETE");
            },
            archive:function (id) {
                return self.request('projects/' + id + '/archive.json', "POST");
            }
        }
    };

    return this.api;
};

Minutedock.prototype.request = function (path, method, form_data) {

    var data = form_data || {};
    data["api_key"] = this.apiKey;

    var options = {
        "uri" : config["minutedock.base.uri"] + path,
        "method":method
    };

    if(method === "POST" || method === "PUT"){
        options.json = data;
    } else {
        options.json = {};
        options.qs = data;
    }

    var deferred = Q.defer();
    request(options, function (error, res, body) {
        if(error){
            console.error('Request error: ' + error + ' ' + options.uri);
            deferred.reject({'status':res.statusCode});
            return;
        }
        if (res.statusCode != 200) {
            console.error('MinuteDock API error: ' + res.statusCode + ' ' + options.uri);
            deferred.reject({'status':res.statusCode});
            return;
        }
        deferred.resolve(body);
    });
    return deferred.promise;
};

module.exports = Minutedock;<|endoftext|>


<commit_before><commit_msg>Update main.5859b74d.js<commit_after><|endoftext|>


<commit_before><commit_msg>Update test description<commit_after><|endoftext|>


<commit_before><commit_msg>Add mock helper index<commit_after><|endoftext|>


<commit_before><commit_msg>[QA-161] Ensure we have sdc-role output available in TAP stream<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { DatePickerAndroid, TimePickerAndroid } from 'react-native';
import moment from 'moment';

export default class CustomDatePickerAndroid extends Component {
  static propTypes = {
    date: PropTypes.instanceOf(Date),
    mode: PropTypes.oneOf(['date', 'time', 'datetime']),
    onCancel: PropTypes.func.isRequired,
    onConfirm: PropTypes.func.isRequired,
    onHideAfterConfirm: PropTypes.func,
    is24Hour: PropTypes.bool,
    isVisible: PropTypes.bool,
    datePickerModeAndroid: PropTypes.oneOf(['calendar', 'spinner', 'default']),
    minimumDate: PropTypes.instanceOf(Date),
    maximumDate: PropTypes.instanceOf(Date),
  };

  static defaultProps = {
    date: new Date(),
    mode: 'date',
    datePickerModeAndroid: 'calendar',
    is24Hour: true,
    isVisible: false,
    onHideAfterConfirm: () => {},
  };

  componentDidUpdate = prevProps => {
    if (!prevProps.isVisible && this.props.isVisible) {
      if (this.props.mode === 'date' || this.props.mode === 'datetime') {
        this._showDatePickerAndroid();
      } else {
        this._showTimePickerAndroid();
      }
    }
  };

  _showDatePickerAndroid = async () => {
    try {
      const { action, year, month, day } = await DatePickerAndroid.open({
        date: this.props.date,
        minDate: this.props.minimumDate,
        maxDate: this.props.maximumDate,
        mode: this.props.datePickerModeAndroid,
      });
      if (action !== DatePickerAndroid.dismissedAction) {
        const date = moment({ year, month, day }).toDate();

        if (this.props.mode === 'datetime') {
          // Prepopulate and show time picker
          const timeOptions = !this.props.date
            ? {}
            : { hour: this.props.date.getHours(), minute: this.props.date.getMinutes() };

          TimePickerAndroid.open(timeOptions).then(({ timeAction, minute, hour }) => {
            if (timeAction !== TimePickerAndroid.dismissedAction) {
              const selectedDate = new Date(year, month, day, hour, minute);
              this.props.onConfirm(selectedDate);
              this.props.onHideAfterConfirm(selectedDate);
            } else {
              this.props.onCancel();
            }
          });
        } else {
          this.props.onConfirm(date);
          this.props.onHideAfterConfirm(date);
        }
      } else {
        this.props.onCancel();
      }
    } catch ({ code, message }) {
      console.warn('Cannot open date picker', message);
    }
  };

  _showTimePickerAndroid = async () => {
    try {
      const { action, hour, minute } = await TimePickerAndroid.open({
        hour: moment(this.props.date).hour(),
        minute: moment(this.props.date).minute(),
        is24Hour: this.props.is24Hour,
      });
      if (action !== TimePickerAndroid.dismissedAction) {
        const date = moment({ hour, minute }).toDate();
        this.props.onConfirm(date);
        this.props.onHideAfterConfirm(date);
      } else {
        this.props.onCancel();
      }
    } catch ({ code, message }) {
      console.warn('Cannot open time picker', message);
    }
  };

  render() {
    return null;
  }
}
<commit_msg>Fix invalid date on Android datetime cancel<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { DatePickerAndroid, TimePickerAndroid } from 'react-native';
import moment from 'moment';

export default class CustomDatePickerAndroid extends Component {
  static propTypes = {
    date: PropTypes.instanceOf(Date),
    mode: PropTypes.oneOf(['date', 'time', 'datetime']),
    onCancel: PropTypes.func.isRequired,
    onConfirm: PropTypes.func.isRequired,
    onHideAfterConfirm: PropTypes.func,
    is24Hour: PropTypes.bool,
    isVisible: PropTypes.bool,
    datePickerModeAndroid: PropTypes.oneOf(['calendar', 'spinner', 'default']),
    minimumDate: PropTypes.instanceOf(Date),
    maximumDate: PropTypes.instanceOf(Date),
  };

  static defaultProps = {
    date: new Date(),
    mode: 'date',
    datePickerModeAndroid: 'calendar',
    is24Hour: true,
    isVisible: false,
    onHideAfterConfirm: () => {},
  };

  componentDidUpdate = prevProps => {
    if (!prevProps.isVisible && this.props.isVisible) {
      if (this.props.mode === 'date' || this.props.mode === 'datetime') {
        this._showDatePickerAndroid();
      } else {
        this._showTimePickerAndroid();
      }
    }
  };

  _showDatePickerAndroid = async () => {
    try {
      const { action, year, month, day } = await DatePickerAndroid.open({
        date: this.props.date,
        minDate: this.props.minimumDate,
        maxDate: this.props.maximumDate,
        mode: this.props.datePickerModeAndroid,
      });
      if (action !== DatePickerAndroid.dismissedAction) {
        const date = moment({ year, month, day }).toDate();

        if (this.props.mode === 'datetime') {
          // Prepopulate and show time picker
          const timeOptions = this.props.date
            ? { hour: this.props.date.getHours(), minute: this.props.date.getMinutes() }
            : {};
          const { action: timeAction, hour, minute } = await TimePickerAndroid.open(timeOptions);
          if (timeAction !== TimePickerAndroid.dismissedAction) {
            const selectedDate = new Date(year, month, day, hour, minute);
            this.props.onConfirm(selectedDate);
            this.props.onHideAfterConfirm(selectedDate);
          } else {
            this.props.onCancel();
          }
        } else {
          this.props.onConfirm(date);
          this.props.onHideAfterConfirm(date);
        }
      } else {
        this.props.onCancel();
      }
    } catch ({ code, message }) {
      console.warn('Cannot open date picker', message);
    }
  };

  _showTimePickerAndroid = async () => {
    try {
      const { action, hour, minute } = await TimePickerAndroid.open({
        hour: moment(this.props.date).hour(),
        minute: moment(this.props.date).minute(),
        is24Hour: this.props.is24Hour,
      });
      if (action !== TimePickerAndroid.dismissedAction) {
        const date = moment({ hour, minute }).toDate();
        this.props.onConfirm(date);
        this.props.onHideAfterConfirm(date);
      } else {
        this.props.onCancel();
      }
    } catch ({ code, message }) {
      console.warn('Cannot open time picker', message);
    }
  };

  render() {
    return null;
  }
}
<|endoftext|>


<commit_before>/**
 * @file DropdownFilter component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

import TextField from '../TextField';
import Popup from '../Popup';
import List from '../List';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';

export default class DropdownFilter extends Component {

    static Mode = List.Mode;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.triggerEl = null;

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false,
            isAbove: false
        };

        this.isAbove = ::this.isAbove;
        this.filterData = ::this.filterData;
        this.triggerFocusHandler = ::this.triggerFocusHandler;
        this.triggerBlurHandler = ::this.triggerBlurHandler;
        this.filterChangeHandler = ::this.filterChangeHandler;
        this.filterPressEnterHandler = ::this.filterPressEnterHandler;
        this.closePopup = ::this.closePopup;
        this.popupRenderHandler = ::this.popupRenderHandler;
        this.changeHandler = ::this.changeHandler;

    }

    isAbove() {

        const autoComplete = this.refs.autoComplete;

        if (!this.popupHeight || !autoComplete) {
            return false;
        }

        const {top} = Dom.getOffset(autoComplete),
            scrollTop = Dom.getScrollTop();

        if (top + this.triggerHeight + this.popupHeight - scrollTop > window.innerHeight) {
            return true;
        }

        return false;

    }

    filterData(filter = this.state.filter, data = this.props.data) {

        if (!filter) {
            return data;
        }

        const {displayField, filterCallback} = this.props;

        if (filterCallback) {
            return filterCallback(filter, data);
        }

        const filterFunc = (originData) => {
            return originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));
        };

        return filterFunc(data);

    }

    triggerFocusHandler(...args) {

        const {disabled, onFocus} = this.props,
            {filter} = this.state;

        onFocus && onFocus(...args);

        !disabled && filter && this.setState({
            popupVisible: true
        });

    }

    triggerBlurHandler(...args) {
        const {disabled, onBlur} = this.props;
        !disabled && onBlur && onBlur(...args);
    }

    filterChangeHandler(filter) {

        const value = this.state.value,
            state = {
                filter,
                popupVisible: !!filter
            };

        if (!filter) {
            state.value = undefined;
        }

        this.setState(state, () => {
            const {onFilterChange} = this.props;
            onFilterChange && onFilterChange(filter);
        });

    }

    filterPressEnterHandler(e, filter) {

        const {autoClose} = this.props,
            callback = () => {
                const {onFilterPressEnter} = this.props;
                onFilterPressEnter && onFilterPressEnter(filter);
            };

        if (autoClose) {
            this.setState({
                popupVisible: false
            }, () => {
                callback();
            });
        } else {
            callback();
        }

    }

    closePopup() {
        this.setState({
            popupVisible: false
        });
    }

    popupRenderHandler(popupEl) {

        this.popupEl = findDOMNode(popupEl);
        this.popupHeight = this.popupEl.offsetHeight;

        const isAbove = this.isAbove();

        if (isAbove !== this.state.isAbove) {
            this.setState({
                isAbove
            });
        }

    }

    changeHandler(value) {

        const state = {value};

        if (this.props.autoClose) {
            state.popupVisible = false;
        }

        this.setState(state, () => {
            const {onChange} = this.props;
            onChange && onChange(value);
        });

    }

    componentDidMount() {
        this.triggerEl = findDOMNode(this.refs.trigger);
        this.triggerHeight = this.triggerEl.clientHeight;
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: nextProps.value
            });
        }
    }

    render() {

        const {
                className, popupClassName, style, popupStyle, theme, popupTheme, name, placeholder, mode,
                disabled, iconCls, rightIconCls, valueField, displayField, descriptionField,
                noMatchedPopupVisible, noMatchedMsg, popupChildren, renderer, onItemTouchTap, onFilterClear,
                onTriggerMouseOver, onTriggerMouseOut
            } = this.props,
            {isAbove, value, filter, popupVisible} = this.state,

            emptyEl = [{
                itemRenderer() {
                    return (

                            {
                                noMatchedMsg ?
                                    noMatchedMsg
                                    :

                                        No matched value.

                            }

                    );
                },
                disableTouchRipple: true
            }],

            listData = this.filterData(),
            isEmpty = listData.length < 1,

            wrapperClassName = (className ? ' ' + className : ''),
            triggerClassName = (isEmpty && !noMatchedPopupVisible ? '' : (popupVisible ? ' activated' : ''))
                + (isAbove ? ' above' : ' blow'),
            autoCompletePopupClassName = (isAbove ? ' above' : ' blow') + (popupClassName ? ' ' + popupClassName : ''),
            autoCompletePopupStyle = Object.assign({
                width: this.triggerEl && getComputedStyle(this.triggerEl).width
            }, popupStyle);

        return (

                <TextField ref="trigger"
                           className={'dropdown-filter-trigger' + triggerClassName}
                           theme={theme}
                           value={filter}
                           placeholder={placeholder}
                           disabled={disabled}
                           iconCls={iconCls}
                           rightIconCls={rightIconCls}
                           onFocus={this.triggerFocusHandler}
                           onBlur={this.triggerBlurHandler}
                           onMouseOver={onTriggerMouseOver}
                           onMouseOut={onTriggerMouseOut}
                           onChange={this.filterChangeHandler}
                           onPressEnter={this.filterPressEnterHandler}
                           onClear={onFilterClear}
                           onRightIconTouchTap={this.filterPressEnterHandler}/>

                {
                    isEmpty && !noMatchedPopupVisible ?
                        null
                        :
                        <Popup className={'dropdown-filter-popup' + autoCompletePopupClassName}
                               style={autoCompletePopupStyle}
                               theme={popupTheme}
                               visible={popupVisible}
                               triggerEl={this.triggerEl}
                               hasTriangle={false}
                               triggerMode={Popup.TriggerMode.OPEN}
                               position={isAbove ? Popup.Position.TOP_LEFT : Popup.Position.BOTTOM_LEFT}
                               onRender={this.popupRenderHandler}
                               onRequestClose={this.closePopup}>

                            {
                                isEmpty ?
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          mode={List.Mode.NORMAL}
                                          data={emptyEl}/>
                                    :
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          value={value}
                                          mode={mode || List.Mode.NORMAL}
                                          data={listData}
                                          valueField={valueField}
                                          displayField={displayField}
                                          descriptionField={descriptionField}
                                          renderer={renderer}
                                          onItemTouchTap={onItemTouchTap}
                                          onChange={this.changeHandler}/>
                            }

                            {popupChildren}

                        </Popup>
                }

        );
    }

};

DropdownFilter.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the popup element.
     */
    popupClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The placeholder of the field.
     */
    placeholder: PropTypes.string,

    /**
     * Children passed into the List.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true, the list button will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onTouchTap: PropTypes.func

        }), PropTypes.string, PropTypes.number])),

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * If true, the auto complete will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the popup list automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * The type of dropDown list,can be normal,checkbox,radio.
     */
    mode: PropTypes.oneOf(Util.enumerateValue(DropdownFilter.Mode)),

    /**
     * Callback function fired when filter changed.
     */
    filterCallback: PropTypes.func,

    /**
     * Use this property to display an icon.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.
     */
    rightIconCls: PropTypes.string,

    /**
     * The visiblity of no matched popup.
     */
    noMatchedPopupVisible: PropTypes.bool,

    /**
     * The message of no matched value.
     */
    noMatchedMsg: PropTypes.string,

    popupChildren: PropTypes.any,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * The function that trigger when filter changes.
     */
    onFilterChange: PropTypes.func,

    /**
     * The function that trigger when press enter.
     */
    onFilterPressEnter: PropTypes.func,

    /**
     * The function that trigger when filter cleared.
     */
    onFilterClear: PropTypes.func,

    /**
     * The function that trigger when value changed.
     */
    onChange: PropTypes.func,

    /**
     * The function that trigger when touch-tap the list items.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter get focus.
     */
    onFocus: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter lose focus.
     */
    onBlur: PropTypes.func,

    onTriggerMouseOver: PropTypes.func,
    onTriggerMouseOut: PropTypes.func

};

DropdownFilter.defaultProps = {

    className: null,
    popupClassName: null,
    style: null,
    popupStyle: null,
    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: null,
    data: [],
    disabled: false,
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    autoClose: false,
    iconCls: null,
    rightIconCls: 'fa fa-search',
    noMatchedPopupVisible: true,
    noMatchedMsg: null,

    popupChildren: null

};<commit_msg>update DropdownFilter<commit_after>/**
 * @file DropdownFilter component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';

import TextField from '../TextField';
import Popup from '../Popup';
import List from '../List';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Dom from '../_vendors/Dom';

export default class DropdownFilter extends Component {

    static Mode = List.Mode;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.triggerEl = null;

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false,
            isAbove: false
        };

        this.isAbove = ::this.isAbove;
        this.filterData = ::this.filterData;
        this.triggerFocusHandler = ::this.triggerFocusHandler;
        this.triggerBlurHandler = ::this.triggerBlurHandler;
        this.filterChangeHandler = ::this.filterChangeHandler;
        this.filterPressEnterHandler = ::this.filterPressEnterHandler;
        this.closePopup = ::this.closePopup;
        this.popupRenderHandler = ::this.popupRenderHandler;
        this.changeHandler = ::this.changeHandler;

    }

    isAbove() {

        const autoComplete = this.refs.autoComplete;

        if (!this.popupHeight || !autoComplete) {
            return false;
        }

        const {top} = Dom.getOffset(autoComplete),
            scrollTop = Dom.getScrollTop();

        if (top + this.triggerHeight + this.popupHeight - scrollTop > window.innerHeight) {
            return true;
        }

        return false;

    }

    filterData(filter = this.state.filter, data = this.props.data) {

        if (!filter) {
            return data;
        }

        const {displayField, filterCallback} = this.props;

        if (filterCallback) {
            return filterCallback(filter, data);
        }

        const filterFunc = (originData) => {
            return originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));
        };

        return filterFunc(data);

    }

    triggerFocusHandler(...args) {

        const {disabled, onFocus} = this.props,
            {filter} = this.state;

        onFocus && onFocus(...args);

        !disabled && filter && this.setState({
            popupVisible: true
        });

    }

    triggerBlurHandler(...args) {
        const {disabled, onBlur} = this.props;
        !disabled && onBlur && onBlur(...args);
    }

    filterChangeHandler(filter) {

        const value = this.state.value,
            state = {
                filter,
                popupVisible: !!filter
            };

        if (!filter) {
            state.value = undefined;
        }

        this.setState(state, () => {
            const {onFilterChange} = this.props;
            onFilterChange && onFilterChange(filter);
        });

    }

    filterPressEnterHandler(e, filter) {

        const {autoClose} = this.props,
            callback = () => {
                const {onFilterPressEnter} = this.props;
                onFilterPressEnter && onFilterPressEnter(filter);
            };

        if (autoClose) {
            this.setState({
                popupVisible: false
            }, () => {
                callback();
            });
        } else {
            callback();
        }

    }

    closePopup() {
        this.setState({
            popupVisible: false
        }, () => {
            const {onPopupClosed} = this.props;
            onPopupClosed && onPopupClosed();
        });
    }

    popupRenderHandler(popupEl) {

        this.popupEl = findDOMNode(popupEl);
        this.popupHeight = this.popupEl.offsetHeight;

        const isAbove = this.isAbove();

        if (isAbove !== this.state.isAbove) {
            this.setState({
                isAbove
            });
        }

    }

    changeHandler(value) {

        const state = {value};

        if (this.props.autoClose) {
            state.popupVisible = false;
        }

        this.setState(state, () => {
            const {onChange} = this.props;
            onChange && onChange(value);
        });

    }

    componentDidMount() {
        this.triggerEl = findDOMNode(this.refs.trigger);
        this.triggerHeight = this.triggerEl.clientHeight;
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: nextProps.value
            });
        }
    }

    render() {

        const {
                className, popupClassName, style, popupStyle, theme, popupTheme, name, placeholder, mode,
                disabled, iconCls, rightIconCls, valueField, displayField, descriptionField,
                noMatchedPopupVisible, noMatchedMsg, popupChildren, renderer, onItemTouchTap, onFilterClear,
                onTriggerMouseOver, onTriggerMouseOut
            } = this.props,
            {isAbove, value, filter, popupVisible} = this.state,

            emptyEl = [{
                itemRenderer() {
                    return (

                            {
                                noMatchedMsg ?
                                    noMatchedMsg
                                    :

                                        No matched value.

                            }

                    );
                },
                disableTouchRipple: true
            }],

            listData = this.filterData(),
            isEmpty = listData.length < 1,

            wrapperClassName = (className ? ' ' + className : ''),
            triggerClassName = (isEmpty && !noMatchedPopupVisible ? '' : (popupVisible ? ' activated' : ''))
                + (isAbove ? ' above' : ' blow'),
            autoCompletePopupClassName = (isAbove ? ' above' : ' blow') + (popupClassName ? ' ' + popupClassName : ''),
            autoCompletePopupStyle = Object.assign({
                width: this.triggerEl && getComputedStyle(this.triggerEl).width
            }, popupStyle);

        return (

                <TextField ref="trigger"
                           className={'dropdown-filter-trigger' + triggerClassName}
                           theme={theme}
                           value={filter}
                           placeholder={placeholder}
                           disabled={disabled}
                           iconCls={iconCls}
                           rightIconCls={rightIconCls}
                           onFocus={this.triggerFocusHandler}
                           onBlur={this.triggerBlurHandler}
                           onMouseOver={onTriggerMouseOver}
                           onMouseOut={onTriggerMouseOut}
                           onChange={this.filterChangeHandler}
                           onPressEnter={this.filterPressEnterHandler}
                           onClear={onFilterClear}
                           onRightIconTouchTap={this.filterPressEnterHandler}/>

                {
                    isEmpty && !noMatchedPopupVisible ?
                        null
                        :
                        <Popup className={'dropdown-filter-popup' + autoCompletePopupClassName}
                               style={autoCompletePopupStyle}
                               theme={popupTheme}
                               visible={popupVisible}
                               triggerEl={this.triggerEl}
                               hasTriangle={false}
                               triggerMode={Popup.TriggerMode.OPEN}
                               position={isAbove ? Popup.Position.TOP_LEFT : Popup.Position.BOTTOM_LEFT}
                               onRender={this.popupRenderHandler}
                               onRequestClose={this.closePopup}>

                            {
                                isEmpty ?
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          mode={List.Mode.NORMAL}
                                          data={emptyEl}/>
                                    :
                                    <List className="dropdown-filter-list"
                                          theme={popupTheme}
                                          value={value}
                                          mode={mode || List.Mode.NORMAL}
                                          data={listData}
                                          valueField={valueField}
                                          displayField={displayField}
                                          descriptionField={descriptionField}
                                          renderer={renderer}
                                          onItemTouchTap={onItemTouchTap}
                                          onChange={this.changeHandler}/>
                            }

                            {popupChildren}

                        </Popup>
                }

        );
    }

};

DropdownFilter.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * The CSS class name of the popup element.
     */
    popupClassName: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The placeholder of the field.
     */
    placeholder: PropTypes.string,

    /**
     * Children passed into the List.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true, the list button will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onTouchTap: PropTypes.func

        }), PropTypes.string, PropTypes.number])),

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * If true, the auto complete will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the popup list automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * The type of dropDown list,can be normal,checkbox,radio.
     */
    mode: PropTypes.oneOf(Util.enumerateValue(DropdownFilter.Mode)),

    /**
     * Callback function fired when filter changed.
     */
    filterCallback: PropTypes.func,

    /**
     * Use this property to display an icon.
     */
    iconCls: PropTypes.string,

    /**
     * Use this property to display an icon.
     */
    rightIconCls: PropTypes.string,

    /**
     * The visiblity of no matched popup.
     */
    noMatchedPopupVisible: PropTypes.bool,

    /**
     * The message of no matched value.
     */
    noMatchedMsg: PropTypes.string,

    popupChildren: PropTypes.any,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * The function that trigger when filter changes.
     */
    onFilterChange: PropTypes.func,

    /**
     * The function that trigger when press enter.
     */
    onFilterPressEnter: PropTypes.func,

    /**
     * The function that trigger when filter cleared.
     */
    onFilterClear: PropTypes.func,

    /**
     * The function that trigger when value changed.
     */
    onChange: PropTypes.func,

    /**
     * The function that trigger when touch-tap the list items.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter get focus.
     */
    onFocus: PropTypes.func,

    /**
     * Callback function fired when DropdownFilter lose focus.
     */
    onBlur: PropTypes.func,

    onTriggerMouseOver: PropTypes.func,
    onTriggerMouseOut: PropTypes.func,
    onPopupClosed: PropTypes.func

};

DropdownFilter.defaultProps = {

    className: null,
    popupClassName: null,
    style: null,
    popupStyle: null,
    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: null,
    data: [],
    disabled: false,
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    autoClose: false,
    iconCls: null,
    rightIconCls: 'fa fa-search',
    noMatchedPopupVisible: true,
    noMatchedMsg: null,

    popupChildren: null

};<|endoftext|>