<commit_before>/*
 Copyright 2010 WebDriver committers
 Copyright 2010 Google Inc.

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

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

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

/**
 * @fileoverview Methods for dealing with modal dialogs
 */

goog.provide('webdriver.modals');

goog.require('ErrorCode');
goog.require('Logger');
goog.require('Timer');
goog.require('webdriver.firefox.utils');

var CI = Components.interfaces;
var CC = Components.classes;

webdriver.modals.isModalPresent = function(callback, timeout) {
  var timer = new Timer();
  timer.runWhenTrue(
    function() { return webdriver.modals.find_() },
    function() { callback(true) },
    timeout,
    function() { callback(false) });
};

webdriver.modals.acceptAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "accept");
  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.dismissAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "cancel");

  if (!button) {
    Logger.dumpn('No cancel button Falling back to the accept button');
    button = webdriver.modals.findButton_(modal, "accept");
  }

  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.getText = function(driver) {
  return driver.modalOpen
};

webdriver.modals.setValue = function(driver, value) {
  var modal = webdriver.modals.find_();
  var textbox = modal.document.getElementById('loginTextbox');
  try {
    var trueIfTextboxExists = textbox.selectionStart > -1;
    if (trueIfTextboxExists) {
      textbox.value = value;
    }
  } catch (e) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE, 'Alert did not have a text box');
  }
};

webdriver.modals.find_ = function() {
  var window = webdriver.firefox.utils.windowMediator().getMostRecentWindow('');
  window = webdriver.firefox.utils.unwrap(window);

  // Get the WebBrowserChrome and check if it's a modal window
  var chrome = window.QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebNavigation).
      QueryInterface(CI.nsIDocShellTreeItem).
      treeOwner.
      QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebBrowserChrome);
  if (!chrome.isWindowModal()) {
    return null;
  }

  return window;
};

webdriver.modals.findButton_ = function(modal, value) {
  var doc = modal.document;
  var dialog = doc.getElementsByTagName("dialog")[0];
  return dialog.getButton(value);
};

webdriver.modals.setFlag = function(driver, flagValue) {
  driver.modalOpen = flagValue;
};

webdriver.modals.clearFlag_ = function(driver) {
  webdriver.modals.setFlag(driver, false);
};

webdriver.modals.findAssociatedDriver_ = function(window) {
  var ww = CC["@mozilla.org/embedcomp/window-watcher;1"].getService(CI["nsIWindowWatcher"]);

  var parent = window ? window : ww.activeWindow;
  if (parent.wrappedJSObject) {
    parent = parent.wrappedJSObject;
  }
  var top = parent.top;

  // Now iterate over all open browsers to find the one we belong to
  var wm = CC["@mozilla.org/appshell/window-mediator;1"].getService(CI["nsIWindowMediator"]);
  var allWindows = wm.getEnumerator("navigator:browser");
  while (allWindows.hasMoreElements()) {
    var chrome = allWindows.getNext().QueryInterface(CI.nsIDOMWindow);
    if (chrome.content == window) {
      return chrome.fxdriver;
    } else if(chrome.content.parent == window.parent) {
      return chrome.fxdriver;
    }
  }

  // There's no meaningful way we can reach this.
  Logger.dumpn('Unable to find the associated driver');
  return undefined;
};

webdriver.modals.signalOpenModal = function(parent, text) {
  Logger.dumpn("signalOpenModal");
  // Try to grab the top level window
  var driver = webdriver.modals.findAssociatedDriver_(parent);
  if (driver && driver.response_) {
    webdriver.modals.setFlag(driver, text);
    var res = driver.response_;
    res.value = {
      text: text
    };
    res.statusCode = ErrorCode.MODAL_DIALOG_OPENED;
    res.send();
  }
};
<commit_msg>DanielWagnerHall: Add missing ;<commit_after>/*
 Copyright 2010 WebDriver committers
 Copyright 2010 Google Inc.

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

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

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

/**
 * @fileoverview Methods for dealing with modal dialogs
 */

goog.provide('webdriver.modals');

goog.require('ErrorCode');
goog.require('Logger');
goog.require('Timer');
goog.require('webdriver.firefox.utils');

var CI = Components.interfaces;
var CC = Components.classes;

webdriver.modals.isModalPresent = function(callback, timeout) {
  var timer = new Timer();
  timer.runWhenTrue(
    function() { return webdriver.modals.find_() },
    function() { callback(true) },
    timeout,
    function() { callback(false) });
};

webdriver.modals.acceptAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "accept");
  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.dismissAlert = function(driver) {
  var modal = webdriver.modals.find_();
  var button = webdriver.modals.findButton_(modal, "cancel");

  if (!button) {
    Logger.dumpn('No cancel button Falling back to the accept button');
    button = webdriver.modals.findButton_(modal, "accept");
  }

  button.click();
  webdriver.modals.clearFlag_(driver);
};

webdriver.modals.getText = function(driver) {
  return driver.modalOpen;
};

webdriver.modals.setValue = function(driver, value) {
  var modal = webdriver.modals.find_();
  var textbox = modal.document.getElementById('loginTextbox');
  try {
    var trueIfTextboxExists = textbox.selectionStart > -1;
    if (trueIfTextboxExists) {
      textbox.value = value;
    }
  } catch (e) {
    throw new WebDriverError(ErrorCode.ELEMENT_NOT_VISIBLE, 'Alert did not have a text box');
  }
};

webdriver.modals.find_ = function() {
  var window = webdriver.firefox.utils.windowMediator().getMostRecentWindow('');
  window = webdriver.firefox.utils.unwrap(window);

  // Get the WebBrowserChrome and check if it's a modal window
  var chrome = window.QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebNavigation).
      QueryInterface(CI.nsIDocShellTreeItem).
      treeOwner.
      QueryInterface(CI.nsIInterfaceRequestor).
      getInterface(CI.nsIWebBrowserChrome);
  if (!chrome.isWindowModal()) {
    return null;
  }

  return window;
};

webdriver.modals.findButton_ = function(modal, value) {
  var doc = modal.document;
  var dialog = doc.getElementsByTagName("dialog")[0];
  return dialog.getButton(value);
};

webdriver.modals.setFlag = function(driver, flagValue) {
  driver.modalOpen = flagValue;
};

webdriver.modals.clearFlag_ = function(driver) {
  webdriver.modals.setFlag(driver, false);
};

webdriver.modals.findAssociatedDriver_ = function(window) {
  var ww = CC["@mozilla.org/embedcomp/window-watcher;1"].getService(CI["nsIWindowWatcher"]);

  var parent = window ? window : ww.activeWindow;
  if (parent.wrappedJSObject) {
    parent = parent.wrappedJSObject;
  }
  var top = parent.top;

  // Now iterate over all open browsers to find the one we belong to
  var wm = CC["@mozilla.org/appshell/window-mediator;1"].getService(CI["nsIWindowMediator"]);
  var allWindows = wm.getEnumerator("navigator:browser");
  while (allWindows.hasMoreElements()) {
    var chrome = allWindows.getNext().QueryInterface(CI.nsIDOMWindow);
    if (chrome.content == window) {
      return chrome.fxdriver;
    } else if(chrome.content.parent == window.parent) {
      return chrome.fxdriver;
    }
  }

  // There's no meaningful way we can reach this.
  Logger.dumpn('Unable to find the associated driver');
  return undefined;
};

webdriver.modals.signalOpenModal = function(parent, text) {
  Logger.dumpn("signalOpenModal");
  // Try to grab the top level window
  var driver = webdriver.modals.findAssociatedDriver_(parent);
  if (driver && driver.response_) {
    webdriver.modals.setFlag(driver, text);
    var res = driver.response_;
    res.value = {
      text: text
    };
    res.statusCode = ErrorCode.MODAL_DIALOG_OPENED;
    res.send();
  }
};
<|endoftext|>


<commit_before>(function () {
  "use strict"
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var BaseButtons = function ($elms, opts) {
    var addOptionAsProperty = function (instance) {
          return function (optionName, optionObj) {
            instance[optionName] = opts[optionName];
          };
        }(this);

    this.$elms = $elms;
    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, addOptionAsProperty);
    }
    this.setEventNames();
    this.getSelections();
    this.bindEvents();
  };
  BaseButtons.prototype.setEventNames = function () {
    this.selectionEvents = 'click';
    this.focusEvents = 'focus blur';
  };
  BaseButtons.prototype.markFocused = function ($elm, state) {
    var elmId = $elm.attr('id');

    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  BaseButtons.prototype.bindEvents = function () {
    var selectionEventHandler = this.markSelected.bind(this),
        focusEventHandler = this.markFocused.bind(this);

    this.$elms
      .on(this.selectionEvents, function (e) {
        selectionEventHandler($(e.target));
      })
      .on(this.focusEvents, function (e) {
        var state = (e.type === 'focus') ? 'focused' : 'blurred';

        focusEventHandler($(e.target), state);
      });
  };

  var RadioButtons = function ($elms, opts) {
    BaseButtons.apply(this, arguments);
  };
  RadioButtons.prototype.setEventNames = function () {
    // some browsers fire the 'click' when the selected radio changes by keyboard
    this.selectionEvents = 'click change';
    this.focusEvents = 'focus blur';
  };
  RadioButtons.prototype.getSelections = function () {
    var selectionEventHandler = this.markSelected.bind(this),
        selections = {};

    $.each(this.$elms, function (index, elm) {
      var $elm = $(elm),
          radioName = $elm.attr('name');

      if (typeof selections[radioName] === 'undefined') {
        selections[radioName] = false;
      }
      if ($elm.is(':checked')) {
        selectionEventHandler($elm);
        selections[radioName] = $elm;
      }
    });
    this.selections = selections;
  };
  RadioButtons.prototype.bindEvents = function () {
    BaseButtons.prototype.bindEvents.call(this);
  };
  RadioButtons.prototype.markSelected = function ($elm) {
    var radioName = $elm.attr('name'),
        $previousSelection = this.selections[radioName];

    if ($previousSelection) {
      $previousSelection.parent('label').removeClass(this.selectedClass);
    }
    $elm.parent('label').addClass(this.selectedClass);
    this.selections[radioName] = $elm;
  };
  RadioButtons.prototype.markFocused = function ($elm) {
    BaseButtons.prototype.markFocused.apply(this, arguments);
  };

  var CheckboxButtons = function ($elms, opts) {
    BaseButtons.apply(this, arguments);
  };
  CheckboxButtons.prototype.setEventNames = function () {
    BaseButtons.prototype.setEventNames.call(this);
  };
  CheckboxButtons.prototype.getSelections = function () {
    var selectionEventHandler = this.markSelected.bind(this);

    this.$elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        selectionEventHandler($elm);
      }
    });
  };
  CheckboxButtons.prototype.bindEvents = function () {
    BaseButtons.prototype.bindEvents.call(this);
  };
  CheckboxButtons.prototype.markSelected = function ($elm) {
    if ($elm.is(':checked')) {
      $elm.parent('label').addClass(this.selectedClass);
    } else {
      $elm.parent('label').removeClass(this.selectedClass);
    }
  };
  CheckboxButtons.prototype.markFocused = function ($elm) {
    BaseButtons.prototype.markFocused.apply(this, arguments);
  };

  root.GOVUK.RadioButtons = RadioButtons;
  root.GOVUK.CheckboxButtons = CheckboxButtons;

  var selectionButtons = function ($elms, opts) {
    var $radios = $elms.filter('[type=radio]'),
        $checkboxes = $elms.filter('[type=checkbox]');

    if ($radios) {
      new GOVUK.RadioButtons($radios, opts);
    }
    if ($checkboxes) {
      new GOVUK.CheckboxButtons($checkboxes, opts);
    }
  };

  root.GOVUK.selectionButtons = selectionButtons;
}).call(this);
<commit_msg>Add better option binding<commit_after>(function () {
  "use strict"
  var root = this,
      $ = root.jQuery;

  if (typeof GOVUK === 'undefined') { root.GOVUK = {}; }

  var BaseButtons = function ($elms, opts) {
    this.$elms = $elms;
    this.selectedClass = 'selected';
    this.focusedClass = 'focused';
    if (opts !== undefined) {
      $.each(opts, function (optionName, optionObj) {
        this[optionName] = optionObj;
      }.bind(this));
    }
    this.setEventNames();
    this.getSelections();
    this.bindEvents();
  };
  BaseButtons.prototype.setEventNames = function () {
    this.selectionEvents = 'click';
    this.focusEvents = 'focus blur';
  };
  BaseButtons.prototype.markFocused = function ($elm, state) {
    var elmId = $elm.attr('id');

    if (state === 'focused') {
      $elm.parent('label').addClass(this.focusedClass);
    } else {
      $elm.parent('label').removeClass(this.focusedClass);
    }
  };
  BaseButtons.prototype.bindEvents = function () {
    var selectionEventHandler = this.markSelected.bind(this),
        focusEventHandler = this.markFocused.bind(this);

    this.$elms
      .on(this.selectionEvents, function (e) {
        selectionEventHandler($(e.target));
      })
      .on(this.focusEvents, function (e) {
        var state = (e.type === 'focus') ? 'focused' : 'blurred';

        focusEventHandler($(e.target), state);
      });
  };

  var RadioButtons = function ($elms, opts) {
    BaseButtons.apply(this, arguments);
  };
  RadioButtons.prototype.setEventNames = function () {
    // some browsers fire the 'click' when the selected radio changes by keyboard
    this.selectionEvents = 'click change';
    this.focusEvents = 'focus blur';
  };
  RadioButtons.prototype.getSelections = function () {
    var selectionEventHandler = this.markSelected.bind(this),
        selections = {};

    $.each(this.$elms, function (index, elm) {
      var $elm = $(elm),
          radioName = $elm.attr('name');

      if (typeof selections[radioName] === 'undefined') {
        selections[radioName] = false;
      }
      if ($elm.is(':checked')) {
        selectionEventHandler($elm);
        selections[radioName] = $elm;
      }
    });
    this.selections = selections;
  };
  RadioButtons.prototype.bindEvents = function () {
    BaseButtons.prototype.bindEvents.call(this);
  };
  RadioButtons.prototype.markSelected = function ($elm) {
    var radioName = $elm.attr('name'),
        $previousSelection = this.selections[radioName];

    if ($previousSelection) {
      $previousSelection.parent('label').removeClass(this.selectedClass);
    }
    $elm.parent('label').addClass(this.selectedClass);
    this.selections[radioName] = $elm;
  };
  RadioButtons.prototype.markFocused = function ($elm) {
    BaseButtons.prototype.markFocused.apply(this, arguments);
  };

  var CheckboxButtons = function ($elms, opts) {
    BaseButtons.apply(this, arguments);
  };
  CheckboxButtons.prototype.setEventNames = function () {
    BaseButtons.prototype.setEventNames.call(this);
  };
  CheckboxButtons.prototype.getSelections = function () {
    var selectionEventHandler = this.markSelected.bind(this);

    this.$elms.each(function (idx, elm) {
      var $elm = $(elm);

      if ($elm.is(':checked')) {
        selectionEventHandler($elm);
      }
    });
  };
  CheckboxButtons.prototype.bindEvents = function () {
    BaseButtons.prototype.bindEvents.call(this);
  };
  CheckboxButtons.prototype.markSelected = function ($elm) {
    if ($elm.is(':checked')) {
      $elm.parent('label').addClass(this.selectedClass);
    } else {
      $elm.parent('label').removeClass(this.selectedClass);
    }
  };
  CheckboxButtons.prototype.markFocused = function ($elm) {
    BaseButtons.prototype.markFocused.apply(this, arguments);
  };

  root.GOVUK.RadioButtons = RadioButtons;
  root.GOVUK.CheckboxButtons = CheckboxButtons;

  var selectionButtons = function ($elms, opts) {
    var $radios = $elms.filter('[type=radio]'),
        $checkboxes = $elms.filter('[type=checkbox]');

    if ($radios) {
      new GOVUK.RadioButtons($radios, opts);
    }
    if ($checkboxes) {
      new GOVUK.CheckboxButtons($checkboxes, opts);
    }
  };

  root.GOVUK.selectionButtons = selectionButtons;
}).call(this);
<|endoftext|>


<commit_before>var AWS = require('aws-sdk')

// Load environment variables from .env file.
require('dotenv-extended').load()

AWS.config.update({
  region: process.env.AWS_REGION,
  endpoint: process.env.DYNAMODB_ENDPOINT,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
})

module.exports = AWS
<commit_msg>Use config for test AWS client.<commit_after>import config from '../../config'
var AWS = require('aws-sdk')

var dynamoDBEndpoint
if (!config.DYNAMODB_ENDPOINT) {
  dynamoDBEndpoint = 'http://localhost:8000'
  console.warn(`Env var DYNAMODB_ENDPOINT is not set. Using default ${dynamoDBEndpoint}.`)
} else {
  dynamoDBEndpoint = config.DYNAMODB_ENDPOINT
}

AWS.config.update({
  region: config.AWS_REGION || 'us-west-2',
  endpoint: dynamoDBEndpoint,
  accessKeyId: config.AWS_ACCESS_KEY_ID || 'fakeKey123',
  secretAccessKey: config.AWS_SECRET_ACCESS_KEY || 'fakeSecretKey123'
})

module.exports = AWS
<|endoftext|>


<commit_before>// import Signal from "signals";
import * as AreaLightsData from "./area-light-data.js";

class AreaLight {
  constructor(opts) {
    this.type = "AreaLight";
    this.enabled = true;
    // this.changed = new Signal();
    this.color = [1, 1, 1, 1];
    this.intensity = 1;
    this.castShadows = false;

    this.set(opts);

    const ctx = opts.ctx;

    // TODO: area light textures
    if (!AreaLight.areaLightTexturesRefs) {
      AreaLight.ltc_mat_texture = ctx.texture2D({
        data: AreaLightsData.mat,
        width: 64,
        height: 64,
        pixelFormat: ctx.PixelFormat.RGBA32F,
        encoding: ctx.Encoding.Linear,
        min: ctx.Filter.Linear,
        mag: ctx.Filter.Linear,
      });
      AreaLight.ltc_mag_texture = ctx.texture2D({
        data: AreaLightsData.mag,
        width: 64,
        height: 64,
        pixelFormat: ctx.PixelFormat.R32F,
        encoding: ctx.Encoding.Linear,
        min: ctx.Filter.Linear,
        mag: ctx.Filter.Linear,
      });
    }
    AreaLight.areaLightTexturesRefs =
      (AreaLight.areaLightTexturesRefs || 0) + 1;
    this.ltc_mat_texture = AreaLight.ltc_mat_texture;
    this.ltc_mag_texture = AreaLight.ltc_mag_texture;
  }

  init(entity) {
    this.entity = entity;
  }

  set(opts) {
    Object.assign(this, opts);
    Object.keys(opts).forEach((prop) => this.changed.dispatch(prop));

    if (opts.color !== undefined || opts.intensity !== undefined) {
      this.color[3] = this.intensity;
    }
  }

  dispose() {
    if (--AreaLight.areaLightTexturesRefs === 0) {
      this.ctx.dispose(AreaLight.ltc_mat_texture);
      AreaLight.ltc_mat_texture = null;
      this.ctx.dispose(AreaLight.ltc_mag_texture);
      AreaLight.ltc_mag_texture = null;
    }
  }
}

export default (opts) => {
  return new AreaLight(opts);
};
<commit_msg>fix(components/area-light): return plain object<commit_after>// import Signal from "signals";
import * as AreaLightsData from "./area-light-data.js";

class AreaLight {
  constructor(opts) {
    this.type = "AreaLight";
    this.enabled = true;
    // this.changed = new Signal();
    this.color = [1, 1, 1, 1];
    this.intensity = 1;
    this.castShadows = false;

    this.set(opts);

    const ctx = opts.ctx;

    // TODO: area light textures
    if (!AreaLight.areaLightTexturesRefs) {
      AreaLight.ltc_mat_texture = ctx.texture2D({
        data: AreaLightsData.mat,
        width: 64,
        height: 64,
        pixelFormat: ctx.PixelFormat.RGBA32F,
        encoding: ctx.Encoding.Linear,
        min: ctx.Filter.Linear,
        mag: ctx.Filter.Linear,
      });
      AreaLight.ltc_mag_texture = ctx.texture2D({
        data: AreaLightsData.mag,
        width: 64,
        height: 64,
        pixelFormat: ctx.PixelFormat.R32F,
        encoding: ctx.Encoding.Linear,
        min: ctx.Filter.Linear,
        mag: ctx.Filter.Linear,
      });
    }
    AreaLight.areaLightTexturesRefs =
      (AreaLight.areaLightTexturesRefs || 0) + 1;
    this.ltc_mat_texture = AreaLight.ltc_mat_texture;
    this.ltc_mag_texture = AreaLight.ltc_mag_texture;
  }

  init(entity) {
    this.entity = entity;
  }

  set(opts) {
    Object.assign(this, opts);
    Object.keys(opts).forEach((prop) => this.changed.dispatch(prop));

    if (opts.color !== undefined || opts.intensity !== undefined) {
      this.color[3] = this.intensity;
    }
  }

  dispose() {
    if (--AreaLight.areaLightTexturesRefs === 0) {
      this.ctx.dispose(AreaLight.ltc_mat_texture);
      AreaLight.ltc_mat_texture = null;
      this.ctx.dispose(AreaLight.ltc_mag_texture);
      AreaLight.ltc_mag_texture = null;
    }
  }
}

export default (opts) => {
  return {
    ...opts,
  };
};
<|endoftext|>


<commit_before>import React from 'react';
import { browserHistory, Link} from 'react-router';

import { Jumbotron, Button, Grid, Row, Col } from 'react-bootstrap';
import { connect } from 'react-redux';

// import ConnectReducer from '../../reducers/ConnectReducer';
import Connectlist from './ConnecterList';
import Validation from './Validation';
import  {Component, PropTypes} from 'react';
import SweetAlert from 'sweetalert-react';
import axios from 'axios';

class ConnectContainer extends React.Component {
  constructor(){
    super();
    this.state = {
      Zipcode :'',
      Distance: '',
      Technology : '',
      users :[],
      text : false
    };
  }

componentDidMount () {

 }

handlesubmit(event){
  console.log("Hellooo U called", event.target);
  event.preventDefault();
 let Zipcode = this.ZIP.state.value;
  let Distance = this.Distance.value;
  let Technology = this.Technology.value;
   console.log("Zipcode", Zipcode);
   console.log("Distance", Distance);
   console.log("Technology", Technology);
  this.setState({
     Zipcode:Zipcode,
     Distance: Distance,
     Technology:Technology,
     })

 let self = this;
  let newarr = []

  axios.get(`http://localhost:3000/connect/${Zipcode}/${Distance}`)
      .then(response => {
        return response.data
      })
      .then(data => {
        // self.setState({
        //   users: data
        // })
        console.log("hellooo Dattaaa", data);
          if(this.state.Technology){
          for(let i=0; i < data.length; i++){
             if(data[i].tech[0] === this.state.Technology){
             newarr.push(data[i]);
           }
           }
            self.setState({
               users: newarr
              })

             }
           else{

            self.setState({
              users: data
               })
           }
      return data
      }).then(data1 => {
      if(data1.length===0){
       this.setState({
          text: true
        })

         }
      })
      .catch(err => {
        console.log('dddd', err.message)
      })
  }
  render() {
  let Techfilter  = (this.state.users.length) ? <Connectlist userdata={this.state.users}/> :<SweetAlert
       title="Sorry No Users Near by"
        show = {this.state.text}
        text="Please Try Again"
         onConfirm={ () => this.setState({
          text :false
         })
       }
        />;
    return (

     <Validation.components.Form ref={c => { this.form = c }} onSubmit = {this.handlesubmit.bind(this)}>
     <Validation.components.Input placeholder = "ZIP" className="whitecolor" ref = {(value) => this.ZIP = value} validations={['required','lenght']}/>
     <input placeholder = "Distance" className = "whitecolor" ref = {(value) => this.Distance = value}/>
     <input placeholder = "Technology" className ="whitecolor" ref = {(input) => this.Technology = input}/>
     <button type = "submit"> Search For Hunters </button>
      </Validation.components.Form>
      {Techfilter }

      )

  }

}

module.exports = ConnectContainer;<commit_msg>removes react redux from connect container<commit_after>import React from 'react';
import { browserHistory, Link} from 'react-router';

import { Jumbotron, Button, Grid, Row, Col } from 'react-bootstrap';

// import ConnectReducer from '../../reducers/ConnectReducer';
import Connectlist from './ConnecterList';
import Validation from './Validation';
import  {Component, PropTypes} from 'react';
import SweetAlert from 'sweetalert-react';
import axios from 'axios';

class ConnectContainer extends React.Component {
  constructor(){
    super();
    this.state = {
      Zipcode :'',
      Distance: '',
      Technology : '',
      users :[],
      text : false
    };
  }

componentDidMount () {

 }

handlesubmit(event){
  console.log("Hellooo U called", event.target);
  event.preventDefault();
 let Zipcode = this.ZIP.state.value;
  let Distance = this.Distance.value;
  let Technology = this.Technology.value;
   console.log("Zipcode", Zipcode);
   console.log("Distance", Distance);
   console.log("Technology", Technology);
  this.setState({
     Zipcode:Zipcode,
     Distance: Distance,
     Technology:Technology,
     })

 let self = this;
  let newarr = []

  axios.get(`http://localhost:3000/connect/${Zipcode}/${Distance}`)
      .then(response => {
        return response.data
      })
      .then(data => {
        // self.setState({
        //   users: data
        // })
        console.log("hellooo Dattaaa", data);
          if(this.state.Technology){
          for(let i=0; i < data.length; i++){
             if(data[i].tech[0] === this.state.Technology){
             newarr.push(data[i]);
           }
           }
            self.setState({
               users: newarr
              })

             }
           else{

            self.setState({
              users: data
               })
           }
      return data
      }).then(data1 => {
      if(data1.length===0){
       this.setState({
          text: true
        })

         }
      })
      .catch(err => {
        console.log('dddd', err.message)
      })
  }
  render() {
  let Techfilter  = (this.state.users.length) ? <Connectlist userdata={this.state.users}/> :<SweetAlert
       title="Sorry No Users Near by"
        show = {this.state.text}
        text="Please Try Again"
         onConfirm={ () => this.setState({
          text :false
         })
       }
        />;
    return (

     <Validation.components.Form ref={c => { this.form = c }} onSubmit = {this.handlesubmit.bind(this)}>
     <Validation.components.Input placeholder = "ZIP" className="whitecolor" ref = {(value) => this.ZIP = value} validations={['required','lenght']}/>
     <input placeholder = "Distance" className = "whitecolor" ref = {(value) => this.Distance = value}/>
     <input placeholder = "Technology" className ="whitecolor" ref = {(input) => this.Technology = input}/>
     <button type = "submit"> Search For Hunters </button>
      </Validation.components.Form>
      {Techfilter }

      )

  }

}

module.exports = ConnectContainer;<|endoftext|>


<commit_before>const React = require('react')
const e = React.createElement
const Component = React.Component
const bindActionCreators = require('redux').bindActionCreators
const connect = require('react-redux').connect
const RaisedButton = require('material-ui/RaisedButton').default
const FlatButton = require('material-ui/FlatButton').default
const RefreshIcon = require('material-ui/svg-icons/navigation/refresh').default
const n = require('../utils/nodegit')
const nodegit = n.nodegit
const getCommonTopCommit = n.getCommonTopCommit
const IntegratorActions = require('../actions/integrator')
const LoadingActions = require('../actions/loading')
const StatusActions = require('../actions/status')
const Diff = require('./Diff')
const hashHistory = require('react-router').hashHistory

class IntegrateChanges extends Component {

	constructor(props) {
		super(props)

		this.state = {
			updating: false,
			shaA: null,
			shaB: null,
		}

		this.repo = null
		this.localBranch = null
		this.remoteBranch = null
		this.localTopCommit = null
		this.remoteTopCommit = null
		this.commonTopCommit = null
	}

	setUpdating(updating) {
		this.setState(Object.assign({}, this.state, { updating }))
		if (updating) {
			this.props.actions.loading.IncrementLoadingJobs()
		} else {
			this.props.actions.loading.DecrementLoadingJobs()
		}
	}

	componentDidMount() {
		this.refresh()
		this.props.actions.integrator.dismissNotification()
	}

	refresh() {
		if (!this.props.projects.active) {
			hashHistory.push('/projects')
			return
		}
		this.setUpdating(true)
		let localBranch
		let remoteBranch
		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				this.repo = r
				return this.repo.getCurrentBranch()
			})
			.then((reference) => {
				this.localBranch = reference
				return this.repo.getBranchCommit(this.localBranch)
					.then((commit) => this.localTopCommit = commit)
					.then(() => nodegit.Branch.upstream(this.localBranch))
			})
			.then((reference) => {
				this.remoteBranch = reference
				return this.repo.getBranchCommit(this.remoteBranch)
					.then((commit) => this.remoteTopCommit = commit)
			})
			.then(() => {
				return getCommonTopCommit(this.repo, this.localTopCommit, this.remoteTopCommit)
			})
			.then((commit) => {
				this.commonTopCommit = commit
				if (this.commonTopCommit && this.remoteTopCommit) {
					this.setState(Object.assign({}, this.state, {
						shaA: this.remoteTopCommit.sha(),
						shaB: this.commonTopCommit.sha(),
					}))
				}
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setUpdating(false)
			})
	}

	accept() {
		if (!this.repo || !this.remoteTopCommit) {
			return
		}
		this.setUpdating(true)
		Promise.resolve()
			.then(() => this.merge())
			.catch((error) => {
				console.error(error)
			})
			.then((success) => {
				this.setUpdating(false)
				if (success) {
					if (typeof success === 'string') {
						hashHistory.push(`/commitDetail/${success}`)
					} else {
						hashHistory.push('/history')
					}
				} else {
					this.refresh()
				}
			})

	}

	merge() {
		const author = this.repo.defaultSignature()
		return Promise.resolve()
			.then((commit) => nodegit.Reset(this.repo, this.localTopCommit, nodegit.Reset.TYPE.MIXED))
			.then(() => this.repo.mergeBranches(this.localBranch, this.remoteBranch, author))
			.then(() => {
				this.props.actions.status.addStatus(
					'Nové změny byly začleněny'
				)
				return true
			})
			.catch((index) => {
				if (typeof index === 'object' && index.hasConflicts && index.hasConflicts()) {
					return this.solveConflict(index)
				} else {
					throw index // Actually it is not an index
				}
			})
	}

	solveConflict(index) {
		const author = this.repo.defaultSignature()
		return Promise.resolve()
			.then(() => this.repo.mergeBranches(this.localBranch, this.remoteBranch, author, null, {
				fileFavor: nodegit.Merge.FILE_FAVOR.THEIRS,
			}))
			.then((oid) => {
				this.props.actions.status.addStatus(
					'Zkontrolujte, že vaše změny nebyly smazány.'
				)
				return this.repo.getCommit(oid)
			})
			.then((commit) => {
				return nodegit.Reset(this.repo, commit, nodegit.Reset.TYPE.HARD)
					.then(() => commit.sha())
			})
	}

	render() {
		return (
			e(
				'div',
				null,
				e(
					'div',
					null,
					e('h1', null, 'Začlenit změny'),
					e(
						RaisedButton,
						{
							label: 'Přijmout změny',
							secondary: true,
							onTouchTap: this.accept.bind(this),
							disabled: this.state.updating,
						}
					),
					e(
						FlatButton,
						{
							icon: e(RefreshIcon),
							onTouchTap: this.refresh.bind(this),
							disabled: this.state.updating,
						}
					)
				),
				e(
					'div',
					{
						style: {
							marginTop: 20,
						},
					},
					e(
						Diff,
						{
							shaA: this.state.shaA,
							shaB: this.state.shaB,
						}
					)
				)
			)
		)
	}
}

function mapStateToProps(state) {
	return {
		loading: state.loading,
		projects: state.projects,
		settings: state.settings,
	}
}

function mapDispatchToProps(dispatch) {
	return {
		actions: {
			integrator: bindActionCreators(IntegratorActions, dispatch),
			loading: bindActionCreators(LoadingActions, dispatch),
			status: bindActionCreators(StatusActions, dispatch),
		}
	}
}

module.exports = connect(mapStateToProps, mapDispatchToProps)(IntegrateChanges)
<commit_msg>Integrate: show whole history<commit_after>const React = require('react')
const e = React.createElement
const Component = React.Component
const bindActionCreators = require('redux').bindActionCreators
const connect = require('react-redux').connect
const RaisedButton = require('material-ui/RaisedButton').default
const FlatButton = require('material-ui/FlatButton').default
const RefreshIcon = require('material-ui/svg-icons/navigation/refresh').default
const n = require('../utils/nodegit')
const nodegit = n.nodegit
const getCommonTopCommit = n.getCommonTopCommit
const IntegratorActions = require('../actions/integrator')
const LoadingActions = require('../actions/loading')
const StatusActions = require('../actions/status')
const Diff = require('./Diff')
const hashHistory = require('react-router').hashHistory

class IntegrateChanges extends Component {

	constructor(props) {
		super(props)

		this.state = {
			updating: false,
			shaA: null,
			shaB: null,
		}

		this.repo = null
		this.localBranch = null
		this.remoteBranch = null
		this.localTopCommit = null
		this.remoteTopCommit = null
		this.commonTopCommit = null
	}

	setUpdating(updating) {
		this.setState(Object.assign({}, this.state, { updating }))
		if (updating) {
			this.props.actions.loading.IncrementLoadingJobs()
		} else {
			this.props.actions.loading.DecrementLoadingJobs()
		}
	}

	componentDidMount() {
		this.refresh()
		this.props.actions.integrator.dismissNotification()
	}

	refresh() {
		if (!this.props.projects.active) {
			hashHistory.push('/projects')
			return
		}
		this.setUpdating(true)
		let localBranch
		let remoteBranch
		nodegit.Repository.open(this.props.projects.active.path)
			.then((r) => {
				this.repo = r
				return this.repo.getCurrentBranch()
			})
			.then((reference) => {
				this.localBranch = reference
				return this.repo.getBranchCommit(this.localBranch)
					.then((commit) => this.localTopCommit = commit)
					.then(() => nodegit.Branch.upstream(this.localBranch))
			})
			.then((reference) => {
				this.remoteBranch = reference
				return this.repo.getBranchCommit(this.remoteBranch)
					.then((commit) => this.remoteTopCommit = commit)
			})
			.then(() => {
				return getCommonTopCommit(this.repo, this.localTopCommit, this.remoteTopCommit)
			})
			.then((commit) => {
				this.commonTopCommit = commit
				if (this.remoteTopCommit) {
					Promise.resolve()
						.then(() => {
							if (this.commonTopCommit) {
								return this.commonTopCommit
							} else {
								return null
							}
						})
						.then((secondCommit) => {
							this.setState(Object.assign({}, this.state, {
								shaA: this.remoteTopCommit.sha(),
								shaB: secondCommit && secondCommit.sha(),
							}))
						})
				}
			})
			.catch((error) => {
				console.error(error)
			})
			.then(() => {
				this.setUpdating(false)
			})
	}

	accept() {
		if (!this.repo || !this.remoteTopCommit) {
			return
		}
		this.setUpdating(true)
		Promise.resolve()
			.then(() => this.merge())
			.catch((error) => {
				console.error(error)
			})
			.then((success) => {
				this.setUpdating(false)
				if (success) {
					if (typeof success === 'string') {
						hashHistory.push(`/commitDetail/${success}`)
					} else {
						hashHistory.push('/history')
					}
				} else {
					this.refresh()
				}
			})

	}

	merge() {
		const author = this.repo.defaultSignature()
		return Promise.resolve()
			.then((commit) => nodegit.Reset(this.repo, this.localTopCommit, nodegit.Reset.TYPE.MIXED))
			.then(() => this.repo.mergeBranches(this.localBranch, this.remoteBranch, author))
			.then(() => {
				this.props.actions.status.addStatus(
					'Nové změny byly začleněny'
				)
				return true
			})
			.catch((index) => {
				if (typeof index === 'object' && index.hasConflicts && index.hasConflicts()) {
					return this.solveConflict(index)
				} else {
					throw index // Actually it is not an index
				}
			})
	}

	solveConflict(index) {
		const author = this.repo.defaultSignature()
		return Promise.resolve()
			.then(() => this.repo.mergeBranches(this.localBranch, this.remoteBranch, author, null, {
				fileFavor: nodegit.Merge.FILE_FAVOR.THEIRS,
			}))
			.then((oid) => {
				this.props.actions.status.addStatus(
					'Zkontrolujte, že vaše změny nebyly smazány.'
				)
				return this.repo.getCommit(oid)
			})
			.then((commit) => {
				return nodegit.Reset(this.repo, commit, nodegit.Reset.TYPE.HARD)
					.then(() => commit.sha())
			})
	}

	render() {
		return (
			e(
				'div',
				null,
				e(
					'div',
					null,
					e('h1', null, 'Začlenit změny'),
					e(
						RaisedButton,
						{
							label: 'Přijmout změny',
							secondary: true,
							onTouchTap: this.accept.bind(this),
							disabled: this.state.updating,
						}
					),
					e(
						FlatButton,
						{
							icon: e(RefreshIcon),
							onTouchTap: this.refresh.bind(this),
							disabled: this.state.updating,
						}
					)
				),
				e(
					'div',
					{
						style: {
							marginTop: 20,
						},
					},
					e(
						Diff,
						{
							shaA: this.state.shaA,
							shaB: this.state.shaB,
						}
					)
				)
			)
		)
	}
}

function mapStateToProps(state) {
	return {
		loading: state.loading,
		projects: state.projects,
		settings: state.settings,
	}
}

function mapDispatchToProps(dispatch) {
	return {
		actions: {
			integrator: bindActionCreators(IntegratorActions, dispatch),
			loading: bindActionCreators(LoadingActions, dispatch),
			status: bindActionCreators(StatusActions, dispatch),
		}
	}
}

module.exports = connect(mapStateToProps, mapDispatchToProps)(IntegrateChanges)
<|endoftext|>


<commit_before>var init = function(){
  if (!("open" in document.getElementsByTagName("details")[0])){
    var elements = document.getElementsByTagName("details");

    var onClick = function(e){
      var summary = e.target;
      var parent = e.target.parentElement;
      var contents = e.target.nextElementSibling;

      if (parent.hasAttribute("open")){
        parent.removeAttribute("open");
        summary.setAttribute("aria-expanded", "false");
        contents.setAttribute("aria-hidden", "true");
        contents.style.display = "none";
      }
      else{
        parent.setAttribute("open", "");
        summary.setAttribute("aria-expanded", "true");
        contents.setAttribute("aria-hidden", "false");
        contents.style.display = "block";
      }
    };

    var onKey = function(e){
      if (e.keyCode === 13 || e.keyCode === 32){
        onClick(e);
      }
    };

    for(var index = 0; index < elements.length; index++){
      var ele = elements[index];

      if (ele.childElementCount === 2){
        var summary = ele.children[0];
        var contents = ele.children[1];

        ele.style.display = "block";
        ele.setAttribute("role", "group");

        summary.setAttribute("role", "button");
        summary.setAttribute("aria-expanded", "false");
        summary.setAttribute("tabindex", 0);
        summary.addEventListener("click", onClick);
        summary.addEventListener("keydown", onKey);

        contents.setAttribute("aria-hidden", "true");
        contents.style.display = "none";
      }
    }
  }
  else if ("WebkitAppearance" in document.documentElement.style){
    var elements = document.getElementsByTagName("summary");

    var onMouseDown = function(e){
      e.target.classList.add("webkit-workaround");
    };

    var onMouseUp = function(e){
      e.target.classList.remove("webkit-workaround");
      e.target.blur();
    };

    for(var index = 0; index < elements.length; index++){
      elements[index].addEventListener("mousedown", onMouseDown);
      elements[index].addEventListener("mouseup", onMouseUp);
    }
  }

  if (location.hash.length > 1){
    var element = document.getElementById(location.hash.substring(1));

    if (element && element.tagName === "SUMMARY"){
      element.click();
      element.scrollIntoView(true);
    }
  }
};

if (document.readyState !== "loading"){
  init();
}
else{
  document.addEventListener("DOMContentLoaded", init);
}
<commit_msg>Fix idiot chromium being unable to figure out window size while loading guide<commit_after>var init = function(){
  if (!("open" in document.getElementsByTagName("details")[0])){
    var elements = document.getElementsByTagName("details");

    var onClick = function(e){
      var summary = e.target;
      var parent = e.target.parentElement;
      var contents = e.target.nextElementSibling;

      if (parent.hasAttribute("open")){
        parent.removeAttribute("open");
        summary.setAttribute("aria-expanded", "false");
        contents.setAttribute("aria-hidden", "true");
        contents.style.display = "none";
      }
      else{
        parent.setAttribute("open", "");
        summary.setAttribute("aria-expanded", "true");
        contents.setAttribute("aria-hidden", "false");
        contents.style.display = "block";
      }
    };

    var onKey = function(e){
      if (e.keyCode === 13 || e.keyCode === 32){
        onClick(e);
      }
    };

    for(var index = 0; index < elements.length; index++){
      var ele = elements[index];

      if (ele.childElementCount === 2){
        var summary = ele.children[0];
        var contents = ele.children[1];

        ele.style.display = "block";
        ele.setAttribute("role", "group");

        summary.setAttribute("role", "button");
        summary.setAttribute("aria-expanded", "false");
        summary.setAttribute("tabindex", 0);
        summary.addEventListener("click", onClick);
        summary.addEventListener("keydown", onKey);

        contents.setAttribute("aria-hidden", "true");
        contents.style.display = "none";
      }
    }
  }
  else if ("WebkitAppearance" in document.documentElement.style){
    var elements = document.getElementsByTagName("summary");

    var onMouseDown = function(e){
      e.target.classList.add("webkit-workaround");
    };

    var onMouseUp = function(e){
      e.target.classList.remove("webkit-workaround");
      e.target.blur();
    };

    for(var index = 0; index < elements.length; index++){
      elements[index].addEventListener("mousedown", onMouseDown);
      elements[index].addEventListener("mouseup", onMouseUp);
    }
  }

  if (location.hash.length > 1){
    var element = document.getElementById(location.hash.substring(1));

    if (element && element.tagName === "SUMMARY"){
      element.click();
      element.scrollIntoView(true);

      if (window.innerWidth === 0){
        var ffs = function(){
          element.scrollIntoView(true);
          window.removeEventListener("resize", ffs);
        };

        window.addEventListener("resize", ffs);
      }
    }
  }
};

if (document.readyState !== "loading"){
  init();
}
else{
  document.addEventListener("DOMContentLoaded", init);
}
<|endoftext|>


<commit_before>adsApp.controller('NavigationController', function NavigationController($scope, $location, userDataService) {
    $scope.changeSelectedNavigationItem = changeSelectedNavigationItem;
    $scope.isNavigationItemSelected = isNavigationItemSelected;
    $scope.navItems = configureNavigationItems(userDataService.isUserLoggedIn());

    $scope.$on('$locationChangeStart', function() {
        if ($location.url() == '/view/ads') {
            changeSelectedNavigationItem($scope.navItems[0]);
        } else if ($location.url() == '/login') {
            $scope.selectedNavigationItem = $scope.navItems[1];
        } else if ($location.url() == '/register') {
            $scope.selectedNavigationItem = $scope.navItems[2];
        } else if ($location.url() == '/add/ad') {
            $scope.selectedNavigationItem = $scope.navItems[2];
        } else if ($location.url() == '/view/user/ads') {
            $scope.selectedNavigationItem = $scope.navItems[1];
        }
    });

    userDataService.currentUserWatch().then(null, null, function (user) {
         $scope.navItems = configureNavigationItems(userDataService.isUserLoggedIn());
    });

    function configureNavigationItems(isUserLoggedIn) {
        if (isUserLoggedIn) {
           return [
                {
                    text: "Home",
                    url: "#/view/ads"
                },
                {
                    text: "My Ads",
                    url: "#/view/user/ads"
                },
                {
                    text: "Publish New Ad",
                    url: "#/add/ad"
                },
                {
                    text: "Edit Profile",
                    url: "#/edit/profile"
                }
            ];
        } else {
            return [
                {
                    text: "Home",
                    url: "#/view/ads"
                },
                {
                    text: "Login",
                    url: "#/login"
                },

                {
                    text: "Register",
                    url: "#/register"
                }
            ];
        }
    }

    function changeSelectedNavigationItem (navItem) {
        $scope.selectedNavigationItem = navItem;
    }
    function isNavigationItemSelected (navItem) {
        return $scope.selectedNavigationItem === navItem;
    }
});<commit_msg>Using $location.path() in NavigationController. Added status filter for user ads, not completely working for now<commit_after>adsApp.controller('NavigationController', function NavigationController($scope, $location, userDataService) {
    $scope.changeSelectedNavigationItem = changeSelectedNavigationItem;
    $scope.isNavigationItemSelected = isNavigationItemSelected;
    $scope.navItems = configureNavigationItems(userDataService.isUserLoggedIn());

    $scope.$on('$locationChangeStart', function() {
        var location = $location.path();
        switch (location) {
            case '/view/ads':
                changeSelectedNavigationItem($scope.navItems[0]);
                break;
            case '/login':
                changeSelectedNavigationItem($scope.navItems[1]);
                break;
            case '/register':
                changeSelectedNavigationItem($scope.navItems[2]);
                break;
            case '/add/ad':
                changeSelectedNavigationItem($scope.navItems[2]);
                break;
            case '/view/user/ads':
                changeSelectedNavigationItem($scope.navItems[1]);
                break;
        }
    });

    userDataService.currentUserWatch().then(null, null, function (user) {
         $scope.navItems = configureNavigationItems(userDataService.isUserLoggedIn());
    });

    function configureNavigationItems(isUserLoggedIn) {
        if (isUserLoggedIn) {
           return [
                {
                    text: "Home",
                    url: "#/view/ads"
                },
                {
                    text: "My Ads",
                    url: "#/view/user/ads"
                },
                {
                    text: "Publish New Ad",
                    url: "#/add/ad"
                },
                {
                    text: "Edit Profile",
                    url: "#/edit/profile"
                }
            ];
        } else {
            return [
                {
                    text: "Home",
                    url: "#/view/ads"
                },
                {
                    text: "Login",
                    url: "#/login"
                },

                {
                    text: "Register",
                    url: "#/register"
                }
            ];
        }
    }

    function changeSelectedNavigationItem (navItem) {
        $scope.selectedNavigationItem = navItem;
    }
    function isNavigationItemSelected (navItem) {
        return $scope.selectedNavigationItem === navItem;
    }
});<|endoftext|>


<commit_before>/*global s9e, hljs*/

import Post from 'flarum/components/Post';
import classList from 'flarum/utils/classList';
import PostUser from 'flarum/components/PostUser';
import PostMeta from 'flarum/components/PostMeta';
import PostEdited from 'flarum/components/PostEdited';
import EditPostComposer from 'flarum/components/EditPostComposer';
import Composer from 'flarum/components/Composer';
import ItemList from 'flarum/utils/ItemList';
import listItems from 'flarum/helpers/listItems';
import Button from 'flarum/components/Button';

/**
 * The `CommentPost` component displays a standard `comment`-typed post. This
 * includes a number of item lists (controls, header, and footer) surrounding
 * the post's HTML content.
 *
 * ### Props
 *
 * - `post`
 */
export default class CommentPost extends Post {
  init() {
    super.init();

    /**
     * If the post has been hidden, then this flag determines whether or not its
     * content has been expanded.
     *
     * @type {Boolean}
     */
    this.revealContent = false;

    // Create an instance of the component that displays the post's author so
    // that we can force the post to rerender when the user card is shown.
    this.postUser = new PostUser({post: this.props.post});
    this.subtree.check(
      () => this.postUser.cardVisible,
      () => this.isEditing()
    );
  }

  content() {
    return super.content().concat([

{listItems(this.headerItems().toArray())}
,

        {this.isEditing()
          ?

          : m.trust(this.props.post.contentHtml())}

    ]);
  }

  config(isInitialized, context) {
    super.config(...arguments);

    const contentHtml = this.isEditing() ? '' : this.props.post.contentHtml();

    // If the post content has changed since the last render, we'll run through
    // all of the


<commit_before>///import core
///import plugins/inserthtml.js
///commands 插入代码
///commandsName  HighlightCode
///commandsTitle  插入代码
///commandsDialog  dialogs\highlightcode
UE.plugins['highlightcode'] = function() {
    var me = this;
    if(!/highlightcode/i.test(me.options.toolbars.join(''))){
        return;
    }

    me.commands['highlightcode'] = {
        execCommand: function (cmdName, code, syntax) {
            var range = this.selection.getRange(),
                start = domUtils.findParentByTagName(range.startContainer, 'table', true),
                end = domUtils.findParentByTagName(range.endContainer, 'table', true);
            if(start && end && start === end && domUtils.hasClass(start,'syntaxhighlighter')){
                if(start.nextSibling){
                    range.setStart(start.nextSibling,0)
                }else{
                    if(start.previousSibling){
                        range.setStartAtLast(start.previousSibling)
                    }else{
                        var p = me.document.createElement('p');
                        domUtils.fillNode(me.document,p);
                        range.setStart(p,0)
                    }
                }
                range.setCursor(false,true);
                domUtils.remove(start);
            }
            if(code && syntax){
                me.execCommand('inserthtml','
'+utils.unhtml(code)+'
',true);
                var pre = me.document.getElementById('highlightcode_id');
                if(pre){
                    domUtils.removeAttributes(pre,'id');
                    me.window.SyntaxHighlighter.highlight(pre);
                }
            }

        },
        queryCommandState: function(){
            return queryHighlight.call(this);
        }
    };

    function queryHighlight(){
        try{
            var range = this.selection.getRange(),start,end;
            range.adjustmentBoundary();
            start = domUtils.findParent(range.startContainer,function(node){
                return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
            },true);
            end = domUtils.findParent(range.endContainer,function(node){
                return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
            },true);
            return start && end && start == end  ? 1 : 0;
        }catch(e){
            return 0;
        }
    }

    //不需要判断highlight的command列表
    me.notNeedHighlightQuery ={
        help:1,
        undo:1,
        redo:1,
        source:1,
        print:1,
        searchreplace:1,
        fullscreen:1,
        autotypeset:1,
        pasteplain:1,
        preview:1,
        insertparagraph:1,
        elementpath:1,
        highlightcode:1
    };
    //将queyCommamndState重置
    var orgQuery = me.queryCommandState;
    me.queryCommandState = function(cmd){
        if(!me.notNeedHighlightQuery[cmd.toLowerCase()] && queryHighlight.call(this) == 1){
            return -1;
        }
        return orgQuery.apply(this,arguments)
    };

    me.addListener('beforeselectionchange afterselectionchange',function(type){
        me.highlight = /^b/.test(type) ? me.queryCommandState('highlightcode') : 0;
    });

    me.addListener("ready",function(){
        //避免重复加载高亮文件
        if(typeof me.XRegExp == "undefined"){
            utils.loadFile(me.document,{
                id : "syntaxhighlighter_js",
                src : me.options.highlightJsUrl || me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCore.js",
                tag : "script",
                type : "text/javascript",
                defer : "defer"
            },function(){
                changePre.call(me);
            });
        }
        if(!me.document.getElementById("syntaxhighlighter_css")){
            utils.loadFile(me.document,{
                id : "syntaxhighlighter_css",
                tag : "link",
                rel : "stylesheet",
                type : "text/css",
                href : me.options.highlightCssUrl ||me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCoreDefault.css"
            });
        }

    });
    me.addListener("beforegetcontent beforegetscene",function(){
        utils.each(domUtils.getElementsByTagName(me.body,'table','syntaxhighlighter'),function(di){
            var str = [],parentCode = '';
            utils.each(di.getElementsByTagName('code'),function(ci){
                if(parentCode !== ci.parentNode){
                    parentCode = ci.parentNode;
                    str.push(parentCode[browser.ie?'innerText':'textContent'])
                }

            });
            var pre = domUtils.createElement(me.document,'pre',{
                'class' : 'brush: '+di.className.replace(/\s+/g,' ').split(' ')[1]+';toolbar:false;'
            });
            pre.appendChild(me.document.createTextNode(str.join('\n')));
            di.parentNode.replaceChild(pre,di);
        });
    });
    me.addListener("aftergetcontent aftersetcontent aftergetscene",changePre);

    //避免table插件对于代码高亮的影响
    me.addListener('excludetable excludeNodeinautotype',function (cmd,target){
        if(target && domUtils.findParent(target,function(node){
            return node.tagName == '' && domUtils.hasClass(node,'syntaxhighlighter');
        },true)){
            return true;
        }
    });

    function changePre(){
        var me = this;
        if(!me.window||!me.window.SyntaxHighlighter)return;
        utils.each(domUtils.getElementsByTagName(me.document,"pre"),function(pi){
            if(domUtils.hasClass(pi,'brush')){
                me.window.SyntaxHighlighter.highlight(pi);
            }
        });
    }

    me.addListener('getAllHtml',function(type,headHtml){
        var coreHtml = '';
        for(var i= 0,ci,divs=domUtils.getElementsByTagName(me.document,'table');ci=divs[i++];){
            if(domUtils.hasClass(ci,'syntaxhighlighter')){
                coreHtml = ''
                break;
            }
        }
        if(!coreHtml){
            var tmpNode;
            if(tmpNode = me.document.getElementById('syntaxhighlighter_css')){
                domUtils.remove(tmpNode)
            }
            if(tmpNode = me.document.getElementById('syntaxhighlighter_js')){
                domUtils.remove(tmpNode)

            }
        }
        coreHtml && headHtml.push(coreHtml)
    });

};
<commit_msg>by zhanyi<commit_after>///import core
///import plugins/inserthtml.js
///commands 插入代码
///commandsName  HighlightCode
///commandsTitle  插入代码
///commandsDialog  dialogs\highlightcode
UE.plugins['highlightcode'] = function() {
    var me = this;
    if(!/highlightcode/i.test(me.options.toolbars.join(''))){
        return;
    }

    me.commands['highlightcode'] = {
        execCommand: function (cmdName, code, syntax) {
            var range = this.selection.getRange(),
                start = domUtils.findParentByTagName(range.startContainer, 'table', true),
                end = domUtils.findParentByTagName(range.endContainer, 'table', true);
            if(start && end && start === end && domUtils.hasClass(start,'syntaxhighlighter')){
                if(start.nextSibling){
                    range.setStart(start.nextSibling,0)
                }else{
                    if(start.previousSibling){
                        range.setStartAtLast(start.previousSibling)
                    }else{
                        var p = me.document.createElement('p');
                        domUtils.fillNode(me.document,p);
                        range.setStart(p,0)
                    }
                }
                range.setCursor(false,true);
                domUtils.remove(start);
            }
            if(code && syntax){
                me.execCommand('inserthtml','
'+utils.unhtml(code)+'
',true);
                var pre = me.document.getElementById('highlightcode_id');
                if(pre){
                    domUtils.removeAttributes(pre,'id');
                    me.window.SyntaxHighlighter.highlight(pre);
                }
            }

        },
        queryCommandState: function(){
            return queryHighlight.call(this);
        }
    };

    function queryHighlight(){
        try{
            var range = this.selection.getRange(),start,end;
            range.adjustmentBoundary();
            start = domUtils.findParent(range.startContainer,function(node){
                return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
            },true);
            end = domUtils.findParent(range.endContainer,function(node){
                return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
            },true);
            return start && end && start == end  ? 1 : 0;
        }catch(e){
            return 0;
        }
    }

    //不需要判断highlight的command列表
    me.notNeedHighlightQuery ={
        help:1,
        undo:1,
        redo:1,
        source:1,
        print:1,
        searchreplace:1,
        fullscreen:1,
        pasteplain:1,
        preview:1,
        insertparagraph:1,
        elementpath:1,
        highlightcode:1
    };
    //将queyCommamndState重置
    var orgQuery = me.queryCommandState;
    me.queryCommandState = function(cmd){
        if(!me.notNeedHighlightQuery[cmd.toLowerCase()] && queryHighlight.call(this) == 1){
            return -1;
        }
        return orgQuery.apply(this,arguments)
    };

    me.addListener('beforeselectionchange afterselectionchange',function(type){
        me.highlight = /^b/.test(type) ? me.queryCommandState('highlightcode') : 0;
    });

    me.addListener("ready",function(){
        //避免重复加载高亮文件
        if(typeof me.XRegExp == "undefined"){
            utils.loadFile(me.document,{
                id : "syntaxhighlighter_js",
                src : me.options.highlightJsUrl || me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCore.js",
                tag : "script",
                type : "text/javascript",
                defer : "defer"
            },function(){
                changePre.call(me);
            });
        }
        if(!me.document.getElementById("syntaxhighlighter_css")){
            utils.loadFile(me.document,{
                id : "syntaxhighlighter_css",
                tag : "link",
                rel : "stylesheet",
                type : "text/css",
                href : me.options.highlightCssUrl ||me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCoreDefault.css"
            });
        }

    });
    me.addListener("beforegetcontent beforegetscene",function(){
        utils.each(domUtils.getElementsByTagName(me.body,'table','syntaxhighlighter'),function(di){
            var str = [],parentCode = '';
            utils.each(di.getElementsByTagName('code'),function(ci){
                if(parentCode !== ci.parentNode){
                    parentCode = ci.parentNode;
                    str.push(parentCode[browser.ie?'innerText':'textContent'])
                }

            });
            var pre = domUtils.createElement(me.document,'pre',{
                'class' : 'brush: '+di.className.replace(/\s+/g,' ').split(' ')[1]+';toolbar:false;'
            });
            pre.appendChild(me.document.createTextNode(str.join('\n')));
            di.parentNode.replaceChild(pre,di);
        });
    });
    me.addListener("aftergetcontent aftersetcontent aftergetscene",changePre);

    //避免table插件对于代码高亮的影响
    me.addListener('excludetable excludeNodeinautotype',function (cmd,target){
        if(target && domUtils.findParent(target,function(node){
            return node.tagName == '' && domUtils.hasClass(node,'syntaxhighlighter');
        },true)){
            return true;
        }
    });

    function changePre(){
        var me = this;
        if(!me.window||!me.window.SyntaxHighlighter)return;
        utils.each(domUtils.getElementsByTagName(me.document,"pre"),function(pi){
            if(domUtils.hasClass(pi,'brush')){
                me.window.SyntaxHighlighter.highlight(pi);
            }
        });
    }

    me.addListener('getAllHtml',function(type,headHtml){
        var coreHtml = '';
        for(var i= 0,ci,divs=domUtils.getElementsByTagName(me.document,'table');ci=divs[i++];){
            if(domUtils.hasClass(ci,'syntaxhighlighter')){
                coreHtml = ''
                break;
            }
        }
        if(!coreHtml){
            var tmpNode;
            if(tmpNode = me.document.getElementById('syntaxhighlighter_css')){
                domUtils.remove(tmpNode)
            }
            if(tmpNode = me.document.getElementById('syntaxhighlighter_js')){
                domUtils.remove(tmpNode)

            }
        }
        coreHtml && headHtml.push(coreHtml)
    });

};
<|endoftext|>


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

'use strict';

var GitHubApi = require('github');
var Promise = require('digs-common').Promise;
var _ = require('digs-common').utils;
var childProcess = require('child-process-promise');
var binPath = Promise.promisify(require('bin-path')(require));
var format = require('util').format;
var path = require('path');

var github = new GitHubApi({
  version: "3.0.0",
  protocol: "https",
  host: "api.github.com",
  timeout: 5000,
  headers: {
    "user-agent": "digsjs-label-sync-script"
  }
});

var project = process.argv[2];
if (project) {
  console.log('Updating "digsjs/%s"', project);
} else {
  console.log('Querying GitHub for projects...');
}

binPath('github-labels')
  .get('labels')
  .then(function(executable) {
    function update(name) {
      return childProcess.spawn(executable,
        [
          '-c',
          require.resolve('./github-labels.json'),
          '-f',
          format('digsjs/%s', name)
        ])
        .then(function() {
          console.log('done.');
        });
    }

    console.log('Using github-labels executable "%s"',
      path.relative(process.cwd(), executable));

    if (project) {
      process.stdout.write(format('%s...', project));
      return update(project);
    }

    return Promise.promisify(github.repos.getFromOrg)({org: 'digsjs'})
      .then(function(data) {
        var names = _.pluck(data, 'name');
        console.log('Found %d repos to sync.', names.length);
        return Promise.each(names, function(name) {
          process.stdout.write(format('%s...', name));
          return update(name);
        });
      });
  })
  .catch(function(err) {
    console.log(err);
  });

<commit_msg>fix code style of label script<commit_after>#!/usr/bin/env node

'use strict';

const GitHubApi = require('github');
const Promise = require('digs-common').Promise;
const _ = require('digs-common').utils;
const childProcess = require('child-process-promise');
const binPath = Promise.promisify(require('bin-path')(require));
const path = require('path');

const github = new GitHubApi({
  version: '3.0.0',
  protocol: 'https',
  host: 'api.github.com',
  timeout: 5000,
  headers: {
    'user-agent': 'digsjs-label-sync-script'
  }
});

const project = process.argv[2];
if (project) {
  console.log(`Updating 'digsjs/${project}`, project);
} else {
  console.log('Querying GitHub for projects...');
}

binPath('github-labels')
  .get('labels')
  .then((executable) => {
    function update(name) {
      return childProcess.spawn(executable,
        [
          '-c',
          require.resolve('./github-labels.json'),
          '-f',
          `digsjs/${name}`
        ])
        .then(() => console.log('done.'));
    }

    console.log(`Using github-labels executable "%s"`,
      path.relative(process.cwd(), executable));

    if (project) {
      process.stdout.write(`${project}...`);
      return update(project);
    }

    return Promise.promisify(github.repos.getFromOrg)({org: 'digsjs'})
      .then((data) => {
        const names = _.pluck(data, 'name');
        console.log(`Found ${names.length} repos to sync.`);
        return Promise.each(names, (name) => {
          process.stdout.write(`${name}...`);
          return update(name);
        });
      });
  })
  .catch(err => console.log(err));

<|endoftext|>


<commit_before>window.Erika = window.Erika || {};

Erika.Dom = (function (options) {

    'use strict';

    var Dome = function (els) {
        for (var i = 0; i < els.length; i++) {
            this[i] = els[i];
        }
        this.length = els.length;

        this.config= __config;

        this.setConfig = function(k, v) {
            if (this.config.hasOwnProperty(k)) {
                this.config[k] = v;
            }
        };
    };

    var __config = {
        'default_display' : 'block',
        'defualt_width' : '100%',
    };

    Dome.prototype = {

        forEach: function (callback) {
            this.map(callback);
            return this;
        },

        map: function (callback) {
            var results = [];
            for (var i = 0; i < this.length; i++) {
                results.push(callback.call(this, this[i], i));
            }
            return results;
        },

        mapOne: function (callback) {
            var m = this.map(callback);
            return m.length > 1 ? m : m[0];
        },

        text: function (text) {
            if (typeof text !== "undefined") {
                return this.forEach(function (el) {
                    el.innerText = text;
                });
            } else {
                return this.mapOne(function (el) {
                    return el.innerText;
                });
            }
        },

        html: function (html) {
            if (typeof html !== "undefined") {
                return this.forEach(function (el) {
                    el.innerHTML = html;
                });
            } else {
                return this.mapOne(function (el) {
                    return el.innerHTML;
                });
            }
        },

        addClass: function (classes) {
            var className = "";
            if (typeof classes !== 'string') {
                for (var i = 0; i < classes.length; i++) {
                    className += " " + classes[i];
                }
            } else {
                className = " " + classes;
            }
            return this.forEach(function (el) {
                el.className += className;
            });
        },

        removeClass: function (clas) {
            return this.forEach(function (el) {
                var cs = el.className.split(' '),
                    i;

                while ((i = cs.indexOf(clas)) > -1) {
                    cs = cs.slice(0, i).concat(cs.slice(++i));
                }
                el.className = cs.join(' ');
            });
        },

        toggleClass: function(clas) {
            return this.forEach(function (el) {
                el.classList.toggle(clas);
            });
        },

        toggleClasses: function(clas) {
            return this.forEach(function (el) {
                clas.forEach(function (c) {
                    el.classList.toggle(c);
                });

            });
        },

        attr: function (attr, val) {
            if (typeof val !== 'undefined') {
                return this.forEach(function (el) {
                    el.setAttribute(attr, val);
                });
            } else {
                return this.mapOne(function (el) {
                    return el.getAttribute(attr);
                });
            }
        },

        hide: function() {
            return this.mapOne(function (ele){
                ele.hidden = true;
            });
        },

        show: function() {
            return this.mapOne(function (ele){
                ele.hidden = false;
            });
        },

        fadeIn: function (time) {

            return this.mapOne(function(el) {
                el.style.opacity = 0;
                el.hidden = false;
                var last = +new Date();
                var tick = function() {
                  el.style.opacity = +el.style.opacity + (new Date() - last) / time;
                  last = +new Date();

                  if (+el.style.opacity < 1) {
                    (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
                  }
                };

                tick();
            });

        },

        fadeOut: function (time) {

            return this.mapOne(function(el) {

                var last = +new Date();
                var tick = function() {
                  el.style.opacity = el.style.opacity - (new Date() - last) / time;
                  last = +new Date();

                  if (el.style.opacity > 0) {
                    (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
                  } else {
                    el.hidden = true;
                  }
                };

                tick();
            });

        },

        insertAfter:  function (newNode, referenceNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            return this;
        },

        append: function (els) {
            return this.forEach(function (parEl, i) {
                els.forEach(function (childEl) {
                    parEl.appendChild((i > 0) ? childEl.cloneNode(true) : childEl);
                });
            });
        },

        prepend: function (els) {
            return this.forEach(function (parEl, i) {
                for (var j = els.length - 1; j > -1; j--) {
                    parEl.insertBefore((i > 0) ? els[j].cloneNode(true) : els[j], parEl.firstChild);
                }
            });
        },

        remove: function () {
            return this.forEach(function (el) {
                return el.parentNode.removeChild(el);
            });
        },

        on: (function () {
            if (typeof document.addEventListener === 'function') {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.addEventListener(evt, fn, false);
                    });
                };
            } else if (typeof document.attachEvent === 'function') {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.attachEvent("on" + evt, fn);
                    });
                };
            } else {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el["on" + evt] = fn;
                    });
                };
            }
        }()),

        trigger: function(event, params) {
            const eve = new CustomEvent(event, params);
            //console.log(event, params);
            return this.forEach(function (el) {
                el.dispatchEvent(eve);
            });

        },

        off: (function () {
            if (document.removeEventListener) {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.removeEventListener(evt, fn, false);
                    });
                };
            } else if (document.detachEvent) {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.detachEvent("on" + evt, fn);
                    });
                };
            } else {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el["on" + evt] = null;
                    });
                };
            }
        }()),

        getElement: function(selector) {
            return get(selector);
        },

        version: '0.0.6 alpha',

    };

    var get = function (selector) {
        var els;
        if (typeof selector === 'string') {
            els = document.querySelectorAll(selector);
        } else if (selector.length) {
            els = selector;
        } else {
            els = [selector];
        }
        return new Dome(els);
    };

    var create = function (tagName, attrs) {
        var el = new Dome([document.createElement(tagName)]);
        if (attrs) {
            if (attrs.className) {
                el.addClass(attrs.className);
                delete attrs.className;
            }
            if (attrs.text) {
                el.text(attrs.text);
                delete attrs.text;
            }
            for (var key in attrs) {
                if (attrs.hasOwnProperty(key)) {
                    el.attr(key, attrs[key]);
                }
            }
        }
        return el;
    };

    return {
        create: create,
        get: get
    };

})();
<commit_msg>updates<commit_after>window.Erika = window.Erika || {};

Erika.Dom = (function (options) {

    'use strict';

    var Dome = function (els) {
        for (var i = 0; i < els.length; i++) {
            this[i] = els[i];
        }
        this.length = els.length;

        this.config= __config;

        this.setConfig = function(k, v) {
            if (this.config.hasOwnProperty(k)) {
                this.config[k] = v;
            }
        };
    };

    var __config = {
        'default_display' : 'block',
        'defualt_width' : '100%',
    };

    Dome.prototype = {

        forEach: function (callback) {
            this.map(callback);
            return this;
        },

        map: function (callback) {
            var results = [];
            for (var i = 0; i < this.length; i++) {
                results.push(callback.call(this, this[i], i));
            }
            return results;
        },

        mapOne: function (callback) {
            var m = this.map(callback);
            return m.length > 1 ? m : m[0];
        },

        text: function (text) {
            if (typeof text !== "undefined") {
                return this.forEach(function (el) {
                    el.innerText = text;
                });
            } else {
                return this.mapOne(function (el) {
                    return el.innerText;
                });
            }
        },

        html: function (html) {
            if (typeof html !== "undefined") {
                return this.forEach(function (el) {
                    el.innerHTML = html;
                });
            } else {
                return this.mapOne(function (el) {
                    return el.innerHTML;
                });
            }
        },

        addClass: function (classes) {
            var className = "";
            if (typeof classes !== 'string') {
                for (var i = 0; i < classes.length; i++) {
                    className += " " + classes[i];
                }
            } else {
                className = " " + classes;
            }
            return this.forEach(function (el) {
                el.className += className;
            });
        },

        hasClass: function(cls) {
            const el = this[0];
            const className = " " + cls + " ";
            return (" " + el.className + " ").replace(/[\n\t]/g, " ").indexOf(className) > -1 ;

        },

        removeClass: function (clas) {
            return this.forEach(function (el) {
                var cs = el.className.split(' '),
                    i;

                while ((i = cs.indexOf(clas)) > -1) {
                    cs = cs.slice(0, i).concat(cs.slice(++i));
                }
                el.className = cs.join(' ');
            });
        },

        toggleClass: function(clas) {
            return this.forEach(function (el) {
                el.classList.toggle(clas);
            });
        },

        toggleClasses: function(clas) {
            return this.forEach(function (el) {
                clas.forEach(function (c) {
                    el.classList.toggle(c);
                });

            });
        },

        css: function(attr, val) {
            if (typeof val !== 'undefined') {
                this[0].style[attr] = val;
                // console.log(this[0].style);
                return this;
            } else {
                // console.log(this[0].style);
                return this[0].style[attr];
            }
        },

        attr: function (attr, val) {
            if (typeof val !== 'undefined') {
                return this.forEach(function (el) {
                    el.setAttribute(attr, val);
                });
            } else {
                return this.mapOne(function (el) {
                    return el.getAttribute(attr);
                });
            }
        },

        hide: function() {
            return this.mapOne(function (ele){
                ele.hidden = true;
            });
        },

        show: function() {
            return this.mapOne(function (ele){
                ele.hidden = false;
            });
        },

        fadeIn: function (time) {

            return this.mapOne(function(el) {
                el.style.opacity = 0;
                el.hidden = false;
                var last = +new Date();
                var tick = function() {
                  el.style.opacity = +el.style.opacity + (new Date() - last) / time;
                  last = +new Date();

                  if (+el.style.opacity < 1) {
                    (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
                  }
                };

                tick();
            });

        },

        fadeOut: function (time) {

            return this.mapOne(function(el) {

                var last = +new Date();
                var tick = function() {
                  el.style.opacity = el.style.opacity - (new Date() - last) / time;
                  last = +new Date();

                  if (el.style.opacity > 0) {
                    (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
                  } else {
                    el.hidden = true;
                  }
                };

                tick();
            });

        },

        insertAfter:  function (newNode, referenceNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
            return this;
        },

        append: function (els) {
            return this.forEach(function (parEl, i) {
                els.forEach(function (childEl) {
                    parEl.appendChild((i > 0) ? childEl.cloneNode(true) : childEl);
                });
            });
        },

        prepend: function (els) {
            return this.forEach(function (parEl, i) {
                for (var j = els.length - 1; j > -1; j--) {
                    parEl.insertBefore((i > 0) ? els[j].cloneNode(true) : els[j], parEl.firstChild);
                }
            });
        },

        remove: function () {
            return this.forEach(function (el) {
                return el.parentNode.removeChild(el);
            });
        },

        on: (function () {
            if (typeof document.addEventListener === 'function') {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.addEventListener(evt, fn, false);
                    });
                };
            } else if (typeof document.attachEvent === 'function') {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.attachEvent("on" + evt, fn);
                    });
                };
            } else {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el["on" + evt] = fn;
                    });
                };
            }
        }()),

        trigger: function(event, params) {
            const eve = new CustomEvent(event, params);
            //console.log(event, params);
            return this.forEach(function (el) {
                el.dispatchEvent(eve);
            });

        },

        off: (function () {
            if (document.removeEventListener) {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.removeEventListener(evt, fn, false);
                    });
                };
            } else if (document.detachEvent) {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el.detachEvent("on" + evt, fn);
                    });
                };
            } else {
                return function (evt, fn) {
                    return this.forEach(function (el) {
                        el["on" + evt] = null;
                    });
                };
            }
        }()),

        getElement: function(selector) {
            return get(selector);
        },

        version: '0.0.6 alpha',

    };

    var get = function (selector) {
        var els;
        if (typeof selector === 'string') {
            els = document.querySelectorAll(selector);
        } else if (selector.length) {
            els = selector;
        } else {
            els = [selector];
        }
        return new Dome(els);
    };

    var create = function (tagName, attrs) {
        var el = new Dome([document.createElement(tagName)]);
        if (attrs) {
            if (attrs.className) {
                el.addClass(attrs.className);
                delete attrs.className;
            }
            if (attrs.text) {
                el.text(attrs.text);
                delete attrs.text;
            }
            for (var key in attrs) {
                if (attrs.hasOwnProperty(key)) {
                    el.attr(key, attrs[key]);
                }
            }
        }
        return el;
    };

    return {
        create: create,
        get: get
    };

})();
<|endoftext|>