<commit_before>'use babel';

// import TabPairHeaderSourceView from './tab-pair-header-source-view';
import { CompositeDisposable } from 'atom';
const path = require('path');

//TODO: what if multiple instances of a file are open in a single pane? can that happen?

export default {
  subscriptions: null,
  sourceExtensions: null,
  headerExtensions: null,

  config: {
    headerExtensions: {
      type: "array",
      "default": ["h", "hh", "hpp", "hxx", "h++", "cuh"],
      items: {
        "type": "string",
      }
    },
    sourceExtensions: {
      type: "array",
      "default": ["c", "cc", "cpp", "cp", "cxx", "c++", "cu"],
      items: {
        type: "string",
      }
    }
  },

  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    this.sourceExtensions = atom.config.get('tab-pair-header-source.sourceExtensions');
    this.headerExtensions = atom.config.get('tab-pair-header-source.headerExtensions');
    for(let index=0; index < this.sourceExtensions.length; index++) {
      this.sourceExtensions[index] = "."+this.sourceExtensions[index].toLowerCase();
    }
    for(let index=0; index < this.headerExtensions.length; index++) {
      this.headerExtensions[index] = "."+this.headerExtensions[index].toLowerCase();
    }

    // Register command that toggles this view
    // this.subscriptions.add(atom.workspace.onDidDestroyPaneItem(this.destroyedPaneItem));
    // // this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(this.setTitle));
    // this.subscriptions.add(atom.workspace.onDidAddPane(this.openedPane));
    // this.subscriptions.add(atom.workspace.onDidAddPaneItem(this.openedPaneItem));

    // this.subscriptions.add(atom.workspace.observeTextEditors((editor) => {
    //     this.subscriptions.add(editor.onDidChangePath(this.TEsetTitle));
    //     // this.subscriptions.add(editor.onDidChangeTitle(this.TEsetTitle));
    // }));

    this.subscriptions.add(atom.workspace.observePanes((pane) => {
        this.subscriptions.add(pane.onDidMoveItem((ev) => {
            // wait a moment so the DOM has time to reflow
            // setTimeout(this.movedInSamePane(pane, ev), 5);
            this.movedInSamePane(pane, ev);
        }));
        this.subscriptions.add(pane.onWillRemoveItem((ev)=>{
              this.removedPaneItem(pane, ev);
            }));
        this.subscriptions.add(pane.onDidAddItem((ev)=>{
              this.addedPaneItem(pane, ev);
            }));
    }));

    //TODO: add subscription for when active editor is changed,
    // need callback for editor that gains focus and editor that loses focus

    // this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(callback)((pane) => {
    //     this.subscriptions.add(pane.onDidActivate(()=>{this.changedActive();}));
    // }));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  // serialize() {
  //   return {
  //     tabPairHeaderSourceViewState: this.tabPairHeaderSourceView.serialize()
  //   };
  // },

  isSource(ext) {
    var retval = false;
    if(this.sourceExtensions.indexOf(ext.toLowerCase()) >= 0) {
      retval = true;
    }
    return retval;
  },

  isHeader(ext) {
    var retval = false;
    if(this.headerExtensions.indexOf(ext.toLowerCase()) >= 0) {
      retval = true;
    }
    return retval;
  },

  isSourceHeaderPair(path1, path2) {
    var retval = false;
    if ( path1.name == path2.name &&
         ( (this.isSource(path1.ext) && this.isHeader(path2.ext)) ||
           (this.isSource(path2.ext) && this.isHeader(path1.ext)) ) ) {
          retval = true;
    }
    return retval;
  },

  expandTabTitle(editor) {
    console.log("expandTabTitle: "+editor.getPath());
  },

  compressTabTitle(editor) {
      console.log("compressTabTitle: "+editor.getPath());
  },

  addedPaneItem(pane, ev) {
    console.log("addedPaneItem");

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }

    console.log("  new index: " + ev.index);

    var newIndex = -1;
    var panes = pane.getItems();
    for (let index=0; index < panes.length; index++)
    {
      //Only check text editors
      if (!atom.workspace.isTextEditor(panes[index])) {
        continue;
      }
      let editor_parsedPath = path.parse(panes[index].getPath());
      if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
        if (this.isSource(parsedPath.ext))
        {
          newIndex = index; //put source on left side
        }
        else { //isHeader
          newIndex = index+1; //put header on right side
        }
        break;
      }
    }
    if (newIndex >= 0) {
      //TODO: move, does moving to exising index cause move event?
      if (newIndex == ev.index) {
        console.log("Item was moved to same location, did move event trigger?")
      }
      //TODO: should new index be calculated as though the item isn't in the array?
      // else if (index > ev.index) {
      //   index--;
      // }
      pane.moveItem(ev.item, newIndex);
    }

    //if the source/header file is in current pane,
       //if source file, place to left of exisiting header file
       //else place to right of existing source file
       //change the title of the existing source/header file to minimum size
    //else, behave normally,
  },

  removedPaneItem(pane, ev) {
    console.log("removedPaneItem");

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }
    // expandTabTitle(ev.item); //TODO: does this need to be done here?

    if (pane.getItems().length > ev.index+1) {
      editor = pane.getItems()[ev.index+1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.expandTabTitle(editor);
        }
      }
    }
    if (pane.getItems().length > 1) {
      editor = pane.getItems()[ev.index-1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.expandTabTitle(editor);
        }
      }
    }
  },

  movedInSamePane(pane, ev) {
    console.log("movedInSamePane");
    //can you tell if the user requested it moved or the application moved it?

    // TODO: moved to same spot, should something be done?
    // if(ev.nexIndex == ev.oldIndex) {
    //   return;
    // }

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }

    this.expandTabTitle(ev.item); //TODO: does this need to be done here?

    if (pane.getItems().length > ev.newIndex+1) {
      let editor = pane.getItems()[ev.newIndex+1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.compressTabTitle(editor);
        }
      }
    }
    if (pane.getItems().length > 1) {
      let editor = pane.getItems()[ev.newIndex-1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.compressTabTitle(editor);
        }
      }
    }

    //TODO: if a paneitem (not just text editor) is moved between a compressed header/source pair, then that header/source pair needs to be expanded.

    //if new position is not next to source/header, then expand both source and header
    //if new position is next to source/header, then shrink the non selected source/header, maybe after a slight delay
  },
};
<commit_msg>removed trailing whitespace<commit_after>'use babel';

// import TabPairHeaderSourceView from './tab-pair-header-source-view';
import { CompositeDisposable } from 'atom';
const path = require('path');

//TODO: what if multiple instances of a file are open in a single pane? can that happen?

export default {
  subscriptions: null,
  sourceExtensions: null,
  headerExtensions: null,

  config: {
    headerExtensions: {
      type: "array",
      "default": ["h", "hh", "hpp", "hxx", "h++", "cuh"],
      items: {
        "type": "string",
      }
    },
    sourceExtensions: {
      type: "array",
      "default": ["c", "cc", "cpp", "cp", "cxx", "c++", "cu"],
      items: {
        type: "string",
      }
    }
  },

  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    this.sourceExtensions = atom.config.get('tab-pair-header-source.sourceExtensions');
    this.headerExtensions = atom.config.get('tab-pair-header-source.headerExtensions');
    for(let index=0; index < this.sourceExtensions.length; index++) {
      this.sourceExtensions[index] = "."+this.sourceExtensions[index].toLowerCase();
    }
    for(let index=0; index < this.headerExtensions.length; index++) {
      this.headerExtensions[index] = "."+this.headerExtensions[index].toLowerCase();
    }

    // Register command that toggles this view
    // this.subscriptions.add(atom.workspace.onDidDestroyPaneItem(this.destroyedPaneItem));
    // // this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(this.setTitle));
    // this.subscriptions.add(atom.workspace.onDidAddPane(this.openedPane));
    // this.subscriptions.add(atom.workspace.onDidAddPaneItem(this.openedPaneItem));

    // this.subscriptions.add(atom.workspace.observeTextEditors((editor) => {
    //     this.subscriptions.add(editor.onDidChangePath(this.TEsetTitle));
    //     // this.subscriptions.add(editor.onDidChangeTitle(this.TEsetTitle));
    // }));

    this.subscriptions.add(atom.workspace.observePanes((pane) => {
        this.subscriptions.add(pane.onDidMoveItem((ev) => {
            // wait a moment so the DOM has time to reflow
            // setTimeout(this.movedInSamePane(pane, ev), 5);
            this.movedInSamePane(pane, ev);
        }));
        this.subscriptions.add(pane.onWillRemoveItem((ev)=>{
              this.removedPaneItem(pane, ev);
            }));
        this.subscriptions.add(pane.onDidAddItem((ev)=>{
              this.addedPaneItem(pane, ev);
            }));
    }));

    //TODO: add subscription for when active editor is changed,
    // need callback for editor that gains focus and editor that loses focus

    // this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(callback)((pane) => {
    //     this.subscriptions.add(pane.onDidActivate(()=>{this.changedActive();}));
    // }));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  // serialize() {
  //   return {
  //     tabPairHeaderSourceViewState: this.tabPairHeaderSourceView.serialize()
  //   };
  // },

  isSource(ext) {
    var retval = false;
    if(this.sourceExtensions.indexOf(ext.toLowerCase()) >= 0) {
      retval = true;
    }
    return retval;
  },

  isHeader(ext) {
    var retval = false;
    if(this.headerExtensions.indexOf(ext.toLowerCase()) >= 0) {
      retval = true;
    }
    return retval;
  },

  isSourceHeaderPair(path1, path2) {
    var retval = false;
    if ( path1.name == path2.name &&
         ( (this.isSource(path1.ext) && this.isHeader(path2.ext)) ||
           (this.isSource(path2.ext) && this.isHeader(path1.ext)) ) ) {
          retval = true;
    }
    return retval;
  },

  expandTabTitle(editor) {
    console.log("expandTabTitle: "+editor.getPath());
  },

  compressTabTitle(editor) {
      console.log("compressTabTitle: "+editor.getPath());
  },

  addedPaneItem(pane, ev) {
    console.log("addedPaneItem");

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }

    console.log("  new index: " + ev.index);

    var newIndex = -1;
    var panes = pane.getItems();
    for (let index=0; index < panes.length; index++)
    {
      //Only check text editors
      if (!atom.workspace.isTextEditor(panes[index])) {
        continue;
      }
      let editor_parsedPath = path.parse(panes[index].getPath());
      if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
        if (this.isSource(parsedPath.ext))
        {
          newIndex = index; //put source on left side
        }
        else { //isHeader
          newIndex = index+1; //put header on right side
        }
        break;
      }
    }
    if (newIndex >= 0) {
      //TODO: move, does moving to exising index cause move event?
      if (newIndex == ev.index) {
        console.log("Item was moved to same location, did move event trigger?")
      }
      //TODO: should new index be calculated as though the item isn't in the array?
      // else if (index > ev.index) {
      //   index--;
      // }
      pane.moveItem(ev.item, newIndex);
    }

    //if the source/header file is in current pane,
       //if source file, place to left of exisiting header file
       //else place to right of existing source file
       //change the title of the existing source/header file to minimum size
    //else, behave normally,
  },

  removedPaneItem(pane, ev) {
    console.log("removedPaneItem");

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }
    // expandTabTitle(ev.item); //TODO: does this need to be done here?

    if (pane.getItems().length > ev.index+1) {
      editor = pane.getItems()[ev.index+1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.expandTabTitle(editor);
        }
      }
    }
    if (pane.getItems().length > 1) {
      editor = pane.getItems()[ev.index-1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.expandTabTitle(editor);
        }
      }
    }
  },

  movedInSamePane(pane, ev) {
    console.log("movedInSamePane");
    //can you tell if the user requested it moved or the application moved it?

    // TODO: moved to same spot, should something be done?
    // if(ev.nexIndex == ev.oldIndex) {
    //   return;
    // }

    //only worry about text editors
    if (!atom.workspace.isTextEditor(ev.item)) {
      return;
    }

    var parsedPath = path.parse(ev.item.getPath());
    if( !(this.isSource(parsedPath.ext) || this.isHeader(parsedPath.ext)) ){
      return;
    }

    this.expandTabTitle(ev.item); //TODO: does this need to be done here?

    if (pane.getItems().length > ev.newIndex+1) {
      let editor = pane.getItems()[ev.newIndex+1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.compressTabTitle(editor);
        }
      }
    }
    if (pane.getItems().length > 1) {
      let editor = pane.getItems()[ev.newIndex-1];
      if (atom.workspace.isTextEditor(editor)) {
        let editor_parsedPath = path.parse(editor.getPath());
        if (this.isSourceHeaderPair(parsedPath, editor_parsedPath)) {
            this.compressTabTitle(editor);
        }
      }
    }

    //TODO: if a paneitem (not just text editor) is moved between a compressed header/source pair, then that header/source pair needs to be expanded.

    //if new position is not next to source/header, then expand both source and header
    //if new position is next to source/header, then shrink the non selected source/header, maybe after a slight delay
  },
};
<|endoftext|>


<commit_before>/**
 * This file is used to create a simple node
 */

// Include the config.js file
Ti.include("../config.js");

// Include the tiajax.js library
//~Ti.include("../lib/tiajax.js");

//~$ = {}
//~$.ajax = Titanium.Network.ajax;

//Define the variable win to contain the current window
var win = Ti.UI.currentWindow;

if(Titanium.App.Properties.getInt("userUid")) {
  // Create a user variable to hold some information about the user
  var user = {
    uid: Titanium.App.Properties.getInt("userUid"),
    sessid: Titanium.App.Properties.getString("userSessionId"),
    session_name: Titanium.App.Properties.getString("userSessionName"),
    name: Titanium.App.Properties.getString("userName"),
  }

  // Create a new view "view" to hold the form
  var view = Ti.UI.createView({
    top: 0,
  });

  // Add the view to the window
  win.add(view);

  var slide_in =  Titanium.UI.createAnimation({bottom:0});
  var slide_out =  Titanium.UI.createAnimation({bottom:-251});

  var picker_view = Titanium.UI.createView({
    height:251,
    bottom:-251
  });

  var cancel =  Titanium.UI.createButton({
    title:'Cancel',
    style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
  });

  cancel.addEventListener('click', function() {
    picker_view.animate(slide_out);
  })

  var done =  Titanium.UI.createButton({
    title:'Done',
    style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  });

  var spacer =  Titanium.UI.createButton({
    systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
  });

  var toolbar =  Titanium.UI.iOS.createToolbar({
    top:0,
    items:[cancel,spacer,done]
  });

  picker_view.add(toolbar);

  var url = REST_PATH + 'organizations.json';

  // Create a connection inside the variable xhr
  var xhr = Titanium.Network.createHTTPClient();

  // Open the xhr
  xhr.open("GET", url);

  var sessName = Titanium.App.Properties.getString("userSessionName");
  var sessId = Titanium.App.Properties.getString("userSessionId");
  xhr.setRequestHeader('Cookie', sessName+'='+sessId);

  // Send the xhr
  xhr.send();

  // When the xhr loads we do:
  xhr.onload = function() {
    // Save the status of the xhr in a variable
    // this will be used to see if we have a xhr (200) or not
    var statusCode = xhr.status;
    Ti.API.info('blargh2');
    // Check if we have a xhr
    if(statusCode == 200) {

      // Save the responseText from the xhr in the response variable
      var response = xhr.responseText;

      // Parse (build data structure) the JSON response into an object (data)
      var result = JSON.parse(response);

      var results = new Array();

      // Start loop
      var i = 0;
      for(var key in result) {
        // Create the data variable and hold every result
        var data = result[key];

        results[i] = Ti.UI.createPickerRow({title: data.title, nid:data.nid});

        i = i + 1;
        // results[key] = {title: data.title, nid:data.nid};
      }

      var picker = Ti.UI.createPicker({
        top:43,
        selectionIndicator:true,
      });

      picker.add(results);

      // add our table to the view
      picker_view.add(picker);
      win.add(picker_view);

      done.addEventListener('click',function() {
        clientText.value =  picker.getSelectedRow(0).title;
        picker_view.animate(slide_out);
      });

    }
    else {
      // Create a label for the node title
      var errorMessage = Ti.UI.createLabel({
        // The text of the label will be the node title (data.title)
        text: "Please check your internet xhr.",
        color:'#000',
        textAlign:'left',
        font:{fontSize:24, fontWeight:'bold'},
        top:25,
        left:15,
        height:18
      });

      // Add the error message to the window
      win.add(errorMessage);
    }
  }

  // Create the label for the node title
  var nodeTitleLabel = Titanium.UI.createLabel({
    text:'Description',
    left:10,
    top:5,
    right:10,
    height:40,
  });

  // Add the label to the window
  view.add(nodeTitleLabel);

  // Create the textfield to hold the node title
  var nodeTitleTextfield = Titanium.UI.createTextField({
    height:35,
    top:40,
    left:10,
    width:300,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textfield to the window
  view.add(nodeTitleTextfield);

  // Create the label for the date
  var dateLabel = Titanium.UI.createLabel({
    text:'Date',
    left:10,
    top:80,
    right:10,
    height:40,
  });

  // Add the label to the window
  view.add(dateLabel);

  var currentDate = new Date();
  var day = currentDate.getDate().toString();
  var month = (currentDate.getMonth() + 1).toString();
  var year = currentDate.getFullYear();
  if (day.length == 1) {
    day = '0' + day;
  }
  if (month.length == 1) {
    month = '0' + month;
  }

  // Create the textarea to hold the body
  var dateText = Titanium.UI.createTextField({
    value:year+'-'+month+'-'+day,
    height:35,
    top:115,
    left:10,
    width:300,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(dateText);

  var beginLabel = Titanium.UI.createLabel({
    text:'From',
    left:10,
    top:166,
    width:50,
    height:40,
  });

  view.add(beginLabel);

  // Create the textarea to hold the body
  var beginText = Titanium.UI.createTextField({
    right:10,
    top:160,
    height:35,
    left:65,
    width:60,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(beginText);

  // Create the label for the date
  var endLabel = Titanium.UI.createLabel({
    text:'To',
    left:135,
    top:160,
    height:40,
    width:30,
  });

  // Add the label to the window
  view.add(endLabel);

  var hours = currentDate.getHours().toString();
  var minutes = currentDate.getMinutes().toString();
  if (hours.length == 1) {
    hours = '0' + hours;
  }
  if (minutes.length == 1) {
    minutes = '0' + minutes;
  }

  // Create the textarea to hold the body
  var endText = Titanium.UI.createTextField({
    value:hours+':'+minutes,
    top:160,
    height:35,
    left:165,
    width:60,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(endText);

  var tr = Titanium.UI.create2DMatrix();
  tr = tr.rotate(90);

  var drop_button =  Titanium.UI.createButton({
    style:Titanium.UI.iPhone.SystemButton.DISCLOSURE,
    transform:tr
  });

  var clientText = Titanium.UI.createTextField({
    hintText:"Choose a client",
    height:40,
    width:300,
    top:200,
    borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
    rightButton:drop_button,
    rightButtonMode:Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
    enabled:true,
  });

  clientText.addEventListener('focus', function() {
    picker_view.animate(slide_out);
  });

  drop_button.addEventListener('click', function() {
    picker_view.animate(slide_in);
    clientText.blur();
  });

  win.add(clientText)

  var drop_button2 =  Titanium.UI.createButton({
    style:Titanium.UI.iPhone.SystemButton.DISCLOSURE,
    transform:tr
  });

  var projectText = Titanium.UI.createTextField({
    hintText:"Choose a project",
    height:40,
    width:300,
    top:245,
    borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
    rightButton:drop_button2,
    rightButtonMode:Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
    enabled:true,
  });

  projectText.addEventListener('focus', function() {
    picker_view.animate(slide_out);
  });

  drop_button2.addEventListener('click', function() {
    picker_view.animate(slide_in);
    clientText.blur();
  });

  win.add(projectText);

  // Add the save button
  var saveButton = Titanium.UI.createButton({
    title:'Save',
    height:35,
    width:150,
    top:315
  });

  // Add the button to the window
  view.add(saveButton);

  win.addEventListener("focus", function(e) {
    if (e.source.top == 50) {
      nodeTitleTextfield.value = '';
      dateText.value = year+'-'+month+'-'+day;
      beginText.value = '';
      endText.value = hours+':'+minutes;
    }
  });

  // Add the event listener for when the button is created
  saveButton.addEventListener("click", function() {

    // Create a new node object
    var node = {
      node:{
        title: nodeTitleTextfield.value,
        type:'stormtimetracking',
        organization_nid:943,
        trackingdate: {popup: {date: dateText.value}},
        timebegin: beginText.value,
        timeend: endText.value,
        uid: user.uid,
      }
    };

    // Define the url
    // in this case, we'll connecting to http://example.com/api/rest/node
    var url = REST_PATH + 'node';

    // Create a connection
    var xhr = Titanium.Network.createHTTPClient();

    // Open the connection using POST
    xhr.open("POST",url);

    xhr.setRequestHeader('Content-Type','application/json; charset=utf-8');
    xhr.setRequestHeader('Cookie', user.session_name+'='+user.sessid);

    // Send the connection and the user object as argument
    xhr.send(JSON.stringify(node));

    xhr.onload = function() {
      // Save the status of the connection in a variable
      // this will be used to see if we have a connection (200) or not
      var statusCode = xhr.status;

      // Check if we have a valid status
      if(statusCode == 200) {

        // Create a variable response to hold the response
        var response = xhr.responseText;

        // Parse (build data structure) the JSON response into an object (data)
        var data = JSON.parse(response);

        alert("Content created with id " + data.nid);
      }
      else {
        alert("There was an error");
      }
    }

  });
}
else {
  alert("You need to login first");
}

if (Titanium.Platform.osname == 'android') {
  var activity = win.activity;

  activity.onCreateOptionsMenu = function(e) {
    var menu = e.menu;
    var postButton = menu.add({title: 'Settings'});
    postButton.addEventListener('click', function(e) {
      Ti.App.settingsWin.open();
    });

    var logoutMenuButton = menu.add({title: 'Logout'});
    logoutMenuButton.addEventListener('click', function(e) {
      Ti.App.logoutWin.open();
      Ti.App.tabGroup.close();
    });
  };
}
else if (Titanium.Platform.osname == 'iphone' || Titanium.Platform.osname == 'ipad') {
  // Create a new button
  // var rightButton = Ti.UI.createButton({
    // title: 'Settings',
    // style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  // });
//
  // // Create a new event listener for the rightButton
  // rightButton.addEventListener("click", function() {
    // Ti.App.settingsWin.open();
  // });

  var leftButton = Ti.UI.createButton({
    title: 'Logout',
    style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  });

  leftButton.addEventListener('click', function() {
    Ti.App.logoutWin.open();
    Ti.App.tabGroup.close();
  });

  // We don't add the button to the window, instead, we tell the app
  // to set the button as the right navigation button
  // win.setRightNavButton(rightButton);
  win.setLeftNavButton(leftButton);
}
<commit_msg>save works<commit_after>/**
 * This file is used to create a simple node
 */

// Include the config.js file
Ti.include("../config.js");

// Include the tiajax.js library
//~Ti.include("../lib/tiajax.js");

//~$ = {}
//~$.ajax = Titanium.Network.ajax;

//Define the variable win to contain the current window
var win = Ti.UI.currentWindow;

if(Titanium.App.Properties.getInt("userUid")) {
  // Create a user variable to hold some information about the user
  var user = {
    uid: Titanium.App.Properties.getInt("userUid"),
    sessid: Titanium.App.Properties.getString("userSessionId"),
    session_name: Titanium.App.Properties.getString("userSessionName"),
    name: Titanium.App.Properties.getString("userName"),
  }

  // Create a new view "view" to hold the form
  var view = Ti.UI.createView({
    top: 0,
  });

  // Add the view to the window
  win.add(view);

  var slide_in =  Titanium.UI.createAnimation({bottom:0});
  var slide_out =  Titanium.UI.createAnimation({bottom:-251});

  var picker_view = Titanium.UI.createView({
    height:251,
    bottom:-251
  });

  var cancel =  Titanium.UI.createButton({
    title:'Cancel',
    style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
  });

  cancel.addEventListener('click', function() {
    picker_view.animate(slide_out);
  })

  var done =  Titanium.UI.createButton({
    title:'Done',
    style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  });

  var spacer =  Titanium.UI.createButton({
    systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
  });

  var toolbar =  Titanium.UI.iOS.createToolbar({
    top:0,
    items:[cancel,spacer,done]
  });

  picker_view.add(toolbar);

  var clientnid = 0;

  var url = REST_PATH + 'organizations.json';

  // Create a connection inside the variable xhr
  var xhr = Titanium.Network.createHTTPClient();

  // Open the xhr
  xhr.open("GET", url);

  var sessName = Titanium.App.Properties.getString("userSessionName");
  var sessId = Titanium.App.Properties.getString("userSessionId");
  xhr.setRequestHeader('Cookie', sessName+'='+sessId);

  // Send the xhr
  xhr.send();

  // When the xhr loads we do:
  xhr.onload = function() {
    // Save the status of the xhr in a variable
    // this will be used to see if we have a xhr (200) or not
    var statusCode = xhr.status;
    Ti.API.info('blargh2');
    // Check if we have a xhr
    if(statusCode == 200) {

      // Save the responseText from the xhr in the response variable
      var response = xhr.responseText;

      // Parse (build data structure) the JSON response into an object (data)
      var result = JSON.parse(response);

      var results = new Array();

      // Start loop
      var i = 0;
      for(var key in result) {
        // Create the data variable and hold every result
        var data = result[key];

        results[i] = Ti.UI.createPickerRow({title: data.title, nid:data.nid});

        i = i + 1;
        // results[key] = {title: data.title, nid:data.nid};
      }

      var picker = Ti.UI.createPicker({
        top:43,
        selectionIndicator:true,
      });

      picker.add(results);

      // add our table to the view
      picker_view.add(picker);
      win.add(picker_view);

      done.addEventListener('click',function() {
        clientText.value =  picker.getSelectedRow(0).title;
        clientnid = picker.getSelectedRow(0).nid;
        picker_view.animate(slide_out);
      });

    }
    else {
      // Create a label for the node title
      var errorMessage = Ti.UI.createLabel({
        // The text of the label will be the node title (data.title)
        text: "Please check your internet xhr.",
        color:'#000',
        textAlign:'left',
        font:{fontSize:24, fontWeight:'bold'},
        top:25,
        left:15,
        height:18
      });

      // Add the error message to the window
      win.add(errorMessage);
    }
  }

  // Create the label for the node title
  var nodeTitleLabel = Titanium.UI.createLabel({
    text:'Description',
    left:10,
    top:5,
    right:10,
    height:40,
  });

  // Add the label to the window
  view.add(nodeTitleLabel);

  // Create the textfield to hold the node title
  var nodeTitleTextfield = Titanium.UI.createTextField({
    height:35,
    top:40,
    left:10,
    width:300,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textfield to the window
  view.add(nodeTitleTextfield);

  // Create the label for the date
  var dateLabel = Titanium.UI.createLabel({
    text:'Date',
    left:10,
    top:80,
    right:10,
    height:40,
  });

  // Add the label to the window
  view.add(dateLabel);

  var currentDate = new Date();
  var day = currentDate.getDate().toString();
  var month = (currentDate.getMonth() + 1).toString();
  var year = currentDate.getFullYear();
  if (day.length == 1) {
    day = '0' + day;
  }
  if (month.length == 1) {
    month = '0' + month;
  }

  // Create the textarea to hold the body
  var dateText = Titanium.UI.createTextField({
    value:year+'-'+month+'-'+day,
    height:35,
    top:115,
    left:10,
    width:300,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(dateText);

  var beginLabel = Titanium.UI.createLabel({
    text:'From',
    left:10,
    top:166,
    width:50,
    height:40,
  });

  view.add(beginLabel);

  // Create the textarea to hold the body
  var beginText = Titanium.UI.createTextField({
    right:10,
    top:160,
    height:35,
    left:65,
    width:60,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(beginText);

  // Create the label for the date
  var endLabel = Titanium.UI.createLabel({
    text:'To',
    left:135,
    top:160,
    height:40,
    width:30,
  });

  // Add the label to the window
  view.add(endLabel);

  var hours = currentDate.getHours().toString();
  var minutes = currentDate.getMinutes().toString();
  if (hours.length == 1) {
    hours = '0' + hours;
  }
  if (minutes.length == 1) {
    minutes = '0' + minutes;
  }

  // Create the textarea to hold the body
  var endText = Titanium.UI.createTextField({
    value:hours+':'+minutes,
    top:160,
    height:35,
    left:165,
    width:60,
    font:{fontSize:16},
    borderWidth:2,
    borderColor:'#bbb',
    borderRadius:5,
    paddingLeft: 5,
    paddingRight: 5,
  });

  // Add the textarea to the window
  view.add(endText);

  var tr = Titanium.UI.create2DMatrix();
  tr = tr.rotate(90);

  var drop_button =  Titanium.UI.createButton({
    style:Titanium.UI.iPhone.SystemButton.DISCLOSURE,
    transform:tr
  });

  var clientText = Titanium.UI.createTextField({
    hintText:"Choose a client",
    height:40,
    width:300,
    top:200,
    borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
    rightButton:drop_button,
    rightButtonMode:Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
    enabled:true,
  });

  clientText.addEventListener('focus', function() {
    picker_view.animate(slide_out);
  });

  drop_button.addEventListener('click', function() {
    picker_view.animate(slide_in);
    clientText.blur();
  });

  win.add(clientText)

  var drop_button2 =  Titanium.UI.createButton({
    style:Titanium.UI.iPhone.SystemButton.DISCLOSURE,
    transform:tr
  });

  var projectText = Titanium.UI.createTextField({
    hintText:"Choose a project",
    height:40,
    width:300,
    top:245,
    borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
    rightButton:drop_button2,
    rightButtonMode:Titanium.UI.INPUT_BUTTONMODE_ALWAYS,
    enabled:true,
  });

  projectText.addEventListener('focus', function() {
    picker_view.animate(slide_out);
  });

  drop_button2.addEventListener('click', function() {
    picker_view.animate(slide_in);
    clientText.blur();
  });

  win.add(projectText);

  // Add the save button
  var saveButton = Titanium.UI.createButton({
    title:'Save',
    height:35,
    width:150,
    top:315
  });

  // Add the button to the window
  view.add(saveButton);

  win.addEventListener("focus", function(e) {
    if (e.source.top == 50) {
      nodeTitleTextfield.value = '';
      dateText.value = year+'-'+month+'-'+day;
      beginText.value = '';
      endText.value = hours+':'+minutes;
    }
  });

  // Add the event listener for when the button is created
  saveButton.addEventListener("click", function() {

    // Create a new node object
    var node = {
      node:{
        title: nodeTitleTextfield.value,
        type:'stormtimetracking',
        organization_nid:clientnid,
        trackingdate: {popup: {date: dateText.value}},
        timebegin: beginText.value,
        timeend: endText.value,
        uid: user.uid,
      }
    };

    // Define the url
    // in this case, we'll connecting to http://example.com/api/rest/node
    var url = REST_PATH + 'node';

    // Create a connection
    var xhr = Titanium.Network.createHTTPClient();

    // Open the connection using POST
    xhr.open("POST", url);
    xhr.setRequestHeader('Content-Type','application/json; charset=utf-8');
    xhr.setRequestHeader('Cookie', user.session_name+'='+user.sessid);

    // Send the connection and the user object as argument
    xhr.send(JSON.stringify(node));

    xhr.onload = function() {
      // Save the status of the connection in a variable
      // this will be used to see if we have a connection (200) or not
      var statusCode = xhr.status;
      // Check if we have a valid status
      if(statusCode == 200) {

        // Create a variable response to hold the response
        var response = xhr.responseText;

        // Parse (build data structure) the JSON response into an object (data)
        var data = JSON.parse(response);

        alert("Content created with id " + data.nid);
        Ti.API.info("Content created with id " + data.nid);
      }
      else {
        alert("There was an error");
      }
    }

  });
}
else {
  alert("You need to login first");
}

if (Titanium.Platform.osname == 'android') {
  var activity = win.activity;

  activity.onCreateOptionsMenu = function(e) {
    var menu = e.menu;
    var postButton = menu.add({title: 'Settings'});
    postButton.addEventListener('click', function(e) {
      Ti.App.settingsWin.open();
    });

    var logoutMenuButton = menu.add({title: 'Logout'});
    logoutMenuButton.addEventListener('click', function(e) {
      Ti.App.logoutWin.open();
      Ti.App.tabGroup.close();
    });
  };
}
else if (Titanium.Platform.osname == 'iphone' || Titanium.Platform.osname == 'ipad') {
  // Create a new button
  // var rightButton = Ti.UI.createButton({
    // title: 'Settings',
    // style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  // });
//
  // // Create a new event listener for the rightButton
  // rightButton.addEventListener("click", function() {
    // Ti.App.settingsWin.open();
  // });

  var leftButton = Ti.UI.createButton({
    title: 'Logout',
    style:Titanium.UI.iPhone.SystemButtonStyle.DONE
  });

  leftButton.addEventListener('click', function() {
    Ti.App.logoutWin.open();
    Ti.App.tabGroup.close();
  });

  // We don't add the button to the window, instead, we tell the app
  // to set the button as the right navigation button
  // win.setRightNavButton(rightButton);
  win.setLeftNavButton(leftButton);
}
<|endoftext|>


<commit_before>var gamejs = require('gamejs');

// $gamejs.preload([]);

gamejs.ready(function() {

    var display = gamejs.display.setMode([600, 400]);
    display.blit(
        (new gamejs.font.Font('30px Sans-serif')).render('Hello World')
    );

    /**
    function tick() {
        // game loop
        return;
    };
    gamejs.time.fpsCallback(tick, this, 26);
    **/
});
<commit_msg>fix commented code in skeleton<commit_after>var gamejs = require('gamejs');

// gamejs.preload([]);

gamejs.ready(function() {

    var display = gamejs.display.setMode([600, 400]);
    display.blit(
        (new gamejs.font.Font('30px Sans-serif')).render('Hello World')
    );

    /**
    function tick(msDuration) {
        // game loop
        return;
    };
    gamejs.time.fpsCallback(tick, this, 26);
    **/
});
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import { getWindowSize } from 'ui/utils/measurements';
import Editor from 'ui/components/Editor';
import MockedRequestsSidebar from 'ui/components/MockedRequestsSidebar';
import MimicControls from 'ui/components/MimicControls';
import MainControls from 'ui/components/common/MainControls';
import GroupView from 'ui/components/GroupView';
import API from 'api';
import UIState, { UIStateListener } from 'ui/UIState';
import MultiSelectView from 'ui/components/MultiSelectView';
import ResizeHandle from 'ui/components/common/ResizeHandle';
import deleteIcon from 'ui/assets/images/delete@2x.png';
import addIcon from 'ui/assets/images/plus@2x.png';
import recordIcon from 'ui/assets/images/rec@2x.png';
import searchIcon from 'ui/assets/images/loupe@2x.png';
import clearIcon from 'ui/assets/images/clear@2x.png';

const Container = styled.div`
  display: flex;
  width: 100%;
  height: 100%;
  background-color: white;
  border-top: 1px solid #e7e7e7;
  font-size: 14px;
  font-family: Arial, sans-serif;
  flex-direction: column;
`;

const Actions = styled.div`
  height: 25px;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 8px;
  border-top: 1px solid #e7e7e7;
  position: relative;
  justify-content: flex-end;
`;

const SidebarActions = styled.div`
  width: 234px;
  height: 96%;
  border-top: 0;
  display: flex;
  align-items: center;
  border-right: 1px solid #e7e7e7;
  padding-right: 3px;
`;

const MainSection = styled.div`
  display: flex;
  flex-direction: column;
  flex: 1;
`;

const Main = styled.div`
  display: flex;
  flex-direction: row;
  flex: 1;
`;

const Icon = styled.img`
  height: 16px;
  user-select: none;
  cursor: pointer;
`;

const SidebarIcons = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
`;

const Search = styled.input`
  border: none;
  height: 100%;
  flex-grow: 1;
  outline: none;
  padding-left: 5px;
`;

class FullEdit extends React.Component {

  componentDidMount() {
    window.addEventListener('keyup', this.closeOnEscape);
  }

  componentWillUnmount() {
    window.removeEventListener('keyup', this.closeOnEscape);
  }

  closeOnEscape = (event) => {
    if (event.keyCode === 27) {
      UIState.update({ viewMode: 'closed' });
    }
  };

  selectMock = (selectedMock, multiple) => {
    let selectedMocks = [selectedMock];

    if (multiple) {
      const isSelected = UIState.selectedMocks.indexOf(selectedMock) > -1;

      if (isSelected) {
        selectedMocks = UIState.selectedMocks.filter((mock) => mock !== selectedMock);
      } else {
        selectedMocks = [...UIState.selectedMocks, selectedMock];
      }
    }

    UIState.update({ selectedMocks, selectedGroup: null });
  };

  selectGroup = (selectedGroup) => {
    UIState.update({ selectedGroup, selectedMocks: [] })
  };

  onSearchTermChange = (event) => {
    UIState.update({ searchTerm: event.target.value });
  };

  clearSearch = () => {
    UIState.update({ searchTerm: '' });
  };

  clearSelection = () => {
    UIState.update({ selectedMocks: [], selectedGroup: null });
  };

  deleteSelected = () => {
    UIState.selectedMocks.forEach((mock) => API.removeMock(mock.id));

    if (UIState.selectedGroup) {
      API.removeGroup(UIState.selectedGroup.id);
    }

    this.clearSelection();
  };

  renderMainPanel() {
    if (UIState.selectedGroup) {
      return <GroupView id={ UIState.selectedGroup.id } clearSelection={ this.clearSelection }/>;
    }

    if (UIState.selectedMocks.length > 1) {
      return (
        <MultiSelectView selectMock={ this.selectMock }/>
      );
    }

    const mock = API.getMock((UIState.selectedMocks[0] || {}).id);

    return (
      <Editor
        selectedMock={ mock }
        onClose={ this.props.closeFullEditor }/>
    )
  }

  renderEdit() {
    return (
      <Container>

          <MockedRequestsSidebar
            searchTerm={ UIState.searchTerm }
            selectMock={ this.selectMock }
            selectGroup={ this.selectGroup }/>

          <MainSection>
            { this.renderMainPanel() }
          </MainSection>

      </Container>
    );
  }

  render() {
    return (

        <ResizeHandle horizontal/>

        <MimicControls fullWidth>
          <Actions>
            <SidebarActions>
              <Icon src={ searchIcon }/>
              <Search value={ UIState.searchTerm } onChange={ this.onSearchTermChange }/>
              { UIState.searchTerm && <Icon src={ clearIcon } onClick={ this.clearSearch }/> }
              <SidebarIcons>
                <Icon src={ addIcon }/>
                <Icon src={ recordIcon }/>
                <Icon src={ deleteIcon } onClick={ this.deleteSelected }/>
              </SidebarIcons>
            </SidebarActions>

            <MainControls/>
          </Actions>
        </MimicControls>

        { this.renderEdit() }

    );
  }
}

export default UIStateListener(FullEdit);

<commit_msg>minor code changes in full edit<commit_after>import React from 'react';
import styled from 'styled-components';
import { getWindowSize } from 'ui/utils/measurements';
import Editor from 'ui/components/Editor';
import MockedRequestsSidebar from 'ui/components/MockedRequestsSidebar';
import MimicControls from 'ui/components/MimicControls';
import MainControls from 'ui/components/common/MainControls';
import GroupView from 'ui/components/GroupView';
import API from 'api';
import UIState, { UIStateListener } from 'ui/UIState';
import MultiSelectView from 'ui/components/MultiSelectView';
import ResizeHandle from 'ui/components/common/ResizeHandle';
import deleteIcon from 'ui/assets/images/delete@2x.png';
import addIcon from 'ui/assets/images/plus@2x.png';
import recordIcon from 'ui/assets/images/rec@2x.png';
import searchIcon from 'ui/assets/images/loupe@2x.png';
import clearIcon from 'ui/assets/images/clear@2x.png';

const Container = styled.div`
  display: flex;
  width: 100%;
  height: 100%;
  background-color: white;
  border-top: 1px solid #e7e7e7;
  font-size: 14px;
  font-family: Arial, sans-serif;
  flex-direction: column;
`;

const Actions = styled.div`
  height: 25px;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 8px;
  border-top: 1px solid #e7e7e7;
  position: relative;
  justify-content: flex-end;
`;

const SidebarActions = styled.div`
  width: 234px;
  height: 96%;
  border-top: 0;
  display: flex;
  align-items: center;
  border-right: 1px solid #e7e7e7;
  padding-right: 3px;
`;

const MainSection = styled.div`
  display: flex;
  flex-direction: column;
  flex: 1;
`;

const Main = styled.div`
  display: flex;
  flex-direction: row;
  flex: 1;
`;

const Icon = styled.img`
  height: 16px;
  user-select: none;
  cursor: pointer;
`;

const SidebarIcons = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
`;

const Search = styled.input`
  border: none;
  height: 100%;
  flex-grow: 1;
  outline: none;
  padding-left: 5px;
`;

class FullEdit extends React.Component {

  componentDidMount() {
    window.addEventListener('keyup', this.closeOnEscape);
  }

  componentWillUnmount() {
    window.removeEventListener('keyup', this.closeOnEscape);
  }

  closeOnEscape = (event) => {
    if (event.keyCode === 27) {
      UIState.update({ viewMode: 'closed' });
    }
  };

  selectMock = (selectedMock, multiple) => {
    let selectedMocks = [selectedMock];

    if (multiple) {
      const isSelected = UIState.selectedMocks.indexOf(selectedMock) > -1;

      if (isSelected) {
        selectedMocks = UIState.selectedMocks.filter((mock) => mock !== selectedMock);
      } else {
        selectedMocks = [...UIState.selectedMocks, selectedMock];
      }
    }

    UIState.update({ selectedMocks, selectedGroup: null });
  };

  selectGroup = (selectedGroup) => {
    UIState.update({ selectedGroup, selectedMocks: [] })
  };

  onSearchTermChange = (event) => {
    UIState.update({ searchTerm: event.target.value });
  };

  clearSearch = () => {
    UIState.update({ searchTerm: '' });
  };

  clearSelection = () => {
    UIState.update({ selectedMocks: [], selectedGroup: null });
  };

  deleteSelected = () => {
    UIState.selectedMocks.forEach((mock) => API.removeMock(mock.id));

    if (UIState.selectedGroup) {
      API.removeGroup(UIState.selectedGroup.id);
    }

    this.clearSelection();
  };

  renderMainPanel() {
    if (UIState.selectedGroup) {
      return <GroupView id={ UIState.selectedGroup.id } clearSelection={ this.clearSelection }/>;
    }

    if (UIState.selectedMocks.length > 1) {
      return <MultiSelectView selectMock={ this.selectMock }/>;
    }

    const mock = API.getMock((UIState.selectedMocks[0] || {}).id);

    return (
      <Editor selectedMock={ mock }
              onClose={ this.props.closeFullEditor }/>
    )
  }

  render() {
    return (

        <ResizeHandle horizontal/>

        <MimicControls fullWidth>
          <Actions>
            <SidebarActions>
              <Icon src={ searchIcon }/>
              <Search value={ UIState.searchTerm } onChange={ this.onSearchTermChange }/>
              { UIState.searchTerm && <Icon src={ clearIcon } onClick={ this.clearSearch }/> }
              <SidebarIcons>
                <Icon src={ addIcon }/>
                <Icon src={ recordIcon }/>
                <Icon src={ deleteIcon } onClick={ this.deleteSelected }/>
              </SidebarIcons>
            </SidebarActions>

            <MainControls/>
          </Actions>
        </MimicControls>

        <Container>

            <MockedRequestsSidebar
              searchTerm={ UIState.searchTerm }
              selectMock={ this.selectMock }
              selectGroup={ this.selectGroup }/>

            <MainSection>
              { this.renderMainPanel() }
            </MainSection>

        </Container>

    );
  }
}

export default UIStateListener(FullEdit);

<|endoftext|>


<commit_before>var _ = require('lodash');

var React = require('react');

var MessagesSection = require('./dialog/MessagesSection.react');
var ComposeSection = require('./dialog/ComposeSection.react');

var DialogStore = require('../stores/DialogStore');
var MessageStore = require('../stores/MessageStore');

var _renderMessagesStep = 100;
var _renderMessagesCount = 100;

var getStateFromStores = function() {
  var messages = MessageStore.getAll();

  var messagesToRender;

  if (messages.length > _renderMessagesCount) {
    messagesToRender = messages.slice(messages.length - _renderMessagesCount);
  } else {
    messagesToRender = messages;
  }

  return({
    dialog: DialogStore.getSelectedDialog(),
    messages: messages,
    messagesToRender: messagesToRender
  });
};

var _lastScrolledFromBottom = 0;

var DialogSection = React.createClass({
  getInitialState: function() {
    return(getStateFromStores());
  },

  componentDidMount: function() {
    DialogStore.addSelectListener(this._onChange);
    MessageStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    MessageStore.removeChangeListener(this._onChange);
    DialogStore.removeSelectListener(this._onChange);
  },

  componentDidUpdate: function() {
    this._fixScroll()
  },

  render: function() {
    if (this.state.dialog) {
      return (

          <MessagesSection peer={this.state.dialog.peer.peer}
                           messages={this.state.messagesToRender}
                           ref="MessagesSection"/>
          <ComposeSection dialog={this.state.dialog}/>

      )
    } else {
      return(

      )
    }
  },

  _fixScroll: function() {
    var node = this.refs.MessagesSection.getDOMNode();
    node.scrollTop = node.scrollHeight - _lastScrolledFromBottom;
  },

  _onChange: _.debounce(function() {
    this.setState(getStateFromStores());
  }, 10, {maxWait: 50, leading: true}),

  _onScroll: _.debounce(function() {
    var node = this.refs.MessagesSection.getDOMNode();

    var scrollTop = node.scrollTop;
    _lastScrolledFromBottom = node.scrollHeight - scrollTop;

    if (node.scrollTop == 0) {
      if (this.state.messages.length > this.state.messagesToRender.length) {
        _renderMessagesCount += _renderMessagesStep;

        if (_renderMessagesCount > this.state.messages.length) {
          _renderMessagesCount = this.state.messages.length;
        }

        this.setState(getStateFromStores());
      }
    }
  }, 10)
});

module.exports = DialogSection;
<commit_msg>perf(web): way faster messages rendering<commit_after>var _ = require('lodash');

var React = require('react');

var MessagesSection = require('./dialog/MessagesSection.react');
var ComposeSection = require('./dialog/ComposeSection.react');

var DialogStore = require('../stores/DialogStore');
var MessageStore = require('../stores/MessageStore');

var _renderMessagesStep = 20;
var _renderMessagesCount = 10;

var getStateFromStores = function() {
  var messages = MessageStore.getAll();

  var messagesToRender;

  if (messages.length > _renderMessagesCount) {
    messagesToRender = messages.slice(messages.length - _renderMessagesCount);
  } else {
    messagesToRender = messages;
  }

  return({
    dialog: DialogStore.getSelectedDialog(),
    messages: messages,
    messagesToRender: messagesToRender
  });
};

var _lastScrolledFromBottom = 0;

var DialogSection = React.createClass({
  getInitialState: function() {
    return(getStateFromStores());
  },

  componentDidMount: function() {
    DialogStore.addSelectListener(this._onChange);
    MessageStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    MessageStore.removeChangeListener(this._onChange);
    DialogStore.removeSelectListener(this._onChange);
  },

  componentDidUpdate: function() {
    this._fixScroll();
    this._loadMessagesByScroll();
  },

  render: function() {
    if (this.state.dialog) {
      return (

          <MessagesSection peer={this.state.dialog.peer.peer}
                           messages={this.state.messagesToRender}
                           ref="MessagesSection"/>
          <ComposeSection dialog={this.state.dialog}/>

      )
    } else {
      return(

      )
    }
  },

  _fixScroll: function() {
    var node = this.refs.MessagesSection.getDOMNode();
    node.scrollTop = node.scrollHeight - _lastScrolledFromBottom;
  },

  _onChange: _.debounce(function() {
    this.setState(getStateFromStores());
  }, 10, {maxWait: 50, leading: true}),

  _loadMessagesByScroll: _.debounce(function() {
    var node = this.refs.MessagesSection.getDOMNode();

    var scrollTop = node.scrollTop;
    _lastScrolledFromBottom = node.scrollHeight - scrollTop;

    if (node.scrollTop == 0) {
      if (this.state.messages.length > this.state.messagesToRender.length) {
        _renderMessagesCount += _renderMessagesStep;

        if (_renderMessagesCount > this.state.messages.length) {
          _renderMessagesCount = this.state.messages.length;
        }

        this.setState(getStateFromStores());
      }
    }
  }, 10)
});

module.exports = DialogSection;
<|endoftext|>


<commit_before>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	eval("'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = Config;\nexports.exportForWebpack = exportForWebpack;\n\nvar _debug = __webpack_require__(1);\n\nvar _debug2 = _interopRequireDefault(_debug);\n\nvar _immutable = __webpack_require__(2);\n\nvar _fp = __webpack_require__(3);\n\nvar _fp2 = _interopRequireDefault(_fp);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar error = (0, _debug2.default)('webpack-config-builder:error');\nvar debug = (0, _debug2.default)('webpack-config-builder:debug');\n\nvar defaultReducers = [function (c) {\n  return c;\n}];\n\n/**\n * @type Config\n * @param {Object|Immutable.Map} state\n * @param {Function[]} reducers\n */\nfunction Config(state) {\n  var reducers = arguments.length <= 1 || arguments[1] === undefined ? defaultReducers : arguments[1];\n\n  state = _immutable.Map.isMap(state) ? state : (0, _immutable.fromJS)(state || {});\n\n  return {\n    use: use,\n    useIf: useIf,\n    toJs: toJs,\n    compose: compose,\n    getReducers: function getReducers() {\n      return reducers;\n    },\n    getState: function getState() {\n      return state;\n    },\n    plugin: plugin\n  };\n\n  /**\n  \t * Plugin\n   * @param {Function} pluginFn\n   * @returns {Config}\n   */\n  function plugin(pluginFn) {\n    return pluginFn.apply(this, [this]);\n  }\n\n  /**\n   * @param {Config} config\n   */\n  function compose(config) {\n    return Config(config.getState().mergeDeep(state), reducers.concat(config.getReducers()));\n  }\n\n  /**\n   * toJs\n   * @returns {Object|Boolean}\n   */\n  function toJs() {\n    try {\n      return _fp2.default.flow(reducers)(state).toJS();\n    } catch (err) {\n      error(err);\n\n      return false;\n    }\n  }\n\n  /**\n   * Use\n   * @param {Function} reducer - function that receives the state object\n   * @returns {Config}\n   */\n  function use(reducer) {\n    debug('Added reducer: \\'' + (reducer.name || 'Anonymous') + '\\'');\n    return Config(state, reducers.concat(reducer));\n  }\n\n  /**\n   * Run reducer only if condition in config is met\n   * @param {String[]} getInPath - Path in configurator to value\n   * @param {Function} reducer   - state 'changer'\n   * @returns {Config}\n   */\n  function useIf(getInPath, reducer) {\n    return this.use(function (c) {\n      if (c.getIn(getInPath)) {\n        return reducer(c);\n      }\n      return c;\n    });\n  }\n}\n\n/**\n * exportForWebpack\n * @note exportForWebpack doesn't cover all webpack settings that require mapping from object to array.\n */\nfunction exportForWebpack(c) {\n  return c.withMutations(function (c) {\n    return c.updateIn(['module', 'loaders'], objectToArray).updateIn(['plugins'], objectToArray).updateIn(['resolve', 'modulesDirectories'], objectToArray).updateIn(['externals'], objectToArray);\n  });\n}\n\nfunction objectToArray(obj) {\n  return obj ? obj.toArray() : void 0;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMC5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9zcmMvaW5kZXguanM/MWZkZiJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGVidWcgZnJvbSAnZGVidWcnO1xuaW1wb3J0IHsgZnJvbUpTLCBNYXAgfSBmcm9tICdpbW11dGFibGUnO1xuaW1wb3J0IGZwIGZyb20gJ2xvZGFzaC9mcCc7XG5cbmNvbnN0IGVycm9yID0gRGVidWcoJ3dlYnBhY2stY29uZmlnLWJ1aWxkZXI6ZXJyb3InKTtcbmNvbnN0IGRlYnVnID0gRGVidWcoJ3dlYnBhY2stY29uZmlnLWJ1aWxkZXI6ZGVidWcnKTtcblxuY29uc3QgZGVmYXVsdFJlZHVjZXJzID0gW2MgPT4gY107XG5cbi8qKlxuICogQHR5cGUgQ29uZmlnXG4gKiBAcGFyYW0ge09iamVjdHxJbW11dGFibGUuTWFwfSBzdGF0ZVxuICogQHBhcmFtIHtGdW5jdGlvbltdfSByZWR1Y2Vyc1xuICovXG5leHBvcnQgZGVmYXVsdCBmdW5jdGlvbiBDb25maWcoc3RhdGUsIHJlZHVjZXJzID0gZGVmYXVsdFJlZHVjZXJzKSB7XG4gIHN0YXRlID0gTWFwLmlzTWFwKHN0YXRlKSA/IHN0YXRlIDogZnJvbUpTKHN0YXRlIHx8IHt9KTtcblxuICByZXR1cm4ge1xuICAgIHVzZTogdXNlLFxuICAgIHVzZUlmOiB1c2VJZixcbiAgICB0b0pzOiB0b0pzLFxuICAgIGNvbXBvc2U6IGNvbXBvc2UsXG4gICAgZ2V0UmVkdWNlcnM6ICgpID0+IHJlZHVjZXJzLFxuICAgIGdldFN0YXRlOiAoKSA9PiBzdGF0ZSxcblx0XHRwbHVnaW46IHBsdWdpblxuICB9O1xuXG5cdC8qKlxuIFx0ICogUGx1Z2luXG5cdCAqIEBwYXJhbSB7RnVuY3Rpb259IHBsdWdpbkZuXG5cdCAqIEByZXR1cm5zIHtDb25maWd9XG5cdCAqL1xuXHRmdW5jdGlvbiBwbHVnaW4ocGx1Z2luRm4pIHtcblx0XHRyZXR1cm4gcGx1Z2luRm4uYXBwbHkodGhpcywgW3RoaXNdKTtcblx0fVxuXG4gIC8qKlxuICAgKiBAcGFyYW0ge0NvbmZpZ30gY29uZmlnXG4gICAqL1xuICBmdW5jdGlvbiBjb21wb3NlKGNvbmZpZykge1xuICAgIHJldHVybiBDb25maWcoXG4gICAgICBjb25maWcuZ2V0U3RhdGUoKS5tZXJnZURlZXAoc3RhdGUpLFxuICAgICAgcmVkdWNlcnMuY29uY2F0KGNvbmZpZy5nZXRSZWR1Y2VycygpKVxuICAgICk7XG4gIH1cblxuICAvKipcbiAgICogdG9Kc1xuICAgKiBAcmV0dXJucyB7T2JqZWN0fEJvb2xlYW59XG4gICAqL1xuICBmdW5jdGlvbiB0b0pzKCkge1xuICAgIHRyeSB7XG4gICAgICByZXR1cm4gZnAuZmxvdyhyZWR1Y2Vycykoc3RhdGUpLnRvSlMoKTtcbiAgICB9IGNhdGNoKGVycikge1xuICAgICAgZXJyb3IoZXJyKTtcblxuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIC8qKlxuICAgKiBVc2VcbiAgICogQHBhcmFtIHtGdW5jdGlvbn0gcmVkdWNlciAtIGZ1bmN0aW9uIHRoYXQgcmVjZWl2ZXMgdGhlIHN0YXRlIG9iamVjdFxuICAgKiBAcmV0dXJucyB7Q29uZmlnfVxuICAgKi9cbiAgZnVuY3Rpb24gdXNlKHJlZHVjZXIpIHtcbiAgICBkZWJ1ZyhgQWRkZWQgcmVkdWNlcjogJyR7cmVkdWNlci5uYW1lIHx8ICdBbm9ueW1vdXMnfSdgKTtcbiAgICByZXR1cm4gQ29uZmlnKHN0YXRlLCByZWR1Y2Vycy5jb25jYXQocmVkdWNlcikpO1xuICB9XG5cbiAgLyoqXG4gICAqIFJ1biByZWR1Y2VyIG9ubHkgaWYgY29uZGl0aW9uIGluIGNvbmZpZyBpcyBtZXRcbiAgICogQHBhcmFtIHtTdHJpbmdbXX0gZ2V0SW5QYXRoIC0gUGF0aCBpbiBjb25maWd1cmF0b3IgdG8gdmFsdWVcbiAgICogQHBhcmFtIHtGdW5jdGlvbn0gcmVkdWNlciAgIC0gc3RhdGUgJ2NoYW5nZXInXG4gICAqIEByZXR1cm5zIHtDb25maWd9XG4gICAqL1xuICBmdW5jdGlvbiB1c2VJZihnZXRJblBhdGgsIHJlZHVjZXIpIHtcbiAgICByZXR1cm4gdGhpcy51c2UoYyA9PiB7XG4gICAgICBpZiAoYy5nZXRJbihnZXRJblBhdGgpKSB7XG4gICAgICAgIHJldHVybiByZWR1Y2VyKGMpO1xuICAgICAgfVxuICAgICAgcmV0dXJuIGM7XG4gICAgfSk7XG4gIH1cbn1cblxuLyoqXG4gKiBleHBvcnRGb3JXZWJwYWNrXG4gKiBAbm90ZSBleHBvcnRGb3JXZWJwYWNrIGRvZXNuJ3QgY292ZXIgYWxsIHdlYnBhY2sgc2V0dGluZ3MgdGhhdCByZXF1aXJlIG1hcHBpbmcgZnJvbSBvYmplY3QgdG8gYXJyYXkuXG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBleHBvcnRGb3JXZWJwYWNrKGMpIHtcbiAgcmV0dXJuIGMud2l0aE11dGF0aW9ucyhjID0+IHtcbiAgICByZXR1cm4gY1xuICAgICAgLnVwZGF0ZUluKFsnbW9kdWxlJywgJ2xvYWRlcnMnXSwgb2JqZWN0VG9BcnJheSlcbiAgICAgIC51cGRhdGVJbihbJ3BsdWdpbnMnXSwgb2JqZWN0VG9BcnJheSlcbiAgICAgIC51cGRhdGVJbihbJ3Jlc29sdmUnLCAnbW9kdWxlc0RpcmVjdG9yaWVzJ10sIG9iamVjdFRvQXJyYXkpXG4gICAgICAudXBkYXRlSW4oWydleHRlcm5hbHMnXSwgb2JqZWN0VG9BcnJheSk7XG4gIH0pO1xufVxuXG5mdW5jdGlvbiBvYmplY3RUb0FycmF5KG9iaikge1xuICByZXR1cm4gb2JqID8gb2JqLnRvQXJyYXkoKTogdm9pZCgwKTtcbn1cblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIHNyYy9pbmRleC5qc1xuICoqLyJdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFjQTtBQTRFQTtBQUNBO0FBM0ZBO0FBQ0E7OztBQUFBO0FBQ0E7QUFBQTtBQUNBOzs7OztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQUE7QUFBQTtBQUNBOzs7Ozs7QUFNQTtBQUFBO0FBQ0E7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQUE7QUFBQTtBQUNBO0FBQUE7QUFBQTtBQUNBO0FBUEE7QUFDQTs7Ozs7O0FBY0E7QUFDQTtBQUNBO0FBQ0E7Ozs7QUFJQTtBQUNBO0FBSUE7QUFDQTs7Ozs7QUFLQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7O0FBTUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQU9BO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOzs7OztBQUtBO0FBQ0E7QUFDQTtBQUtBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Iiwic291cmNlUm9vdCI6IiJ9");

/***/ },
/* 1 */
/***/ function(module, exports) {

	eval("module.exports = require(\"debug\");\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMS5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9leHRlcm5hbCBcImRlYnVnXCI/ZmIxYSJdLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cyA9IHJlcXVpcmUoXCJkZWJ1Z1wiKTtcblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIGV4dGVybmFsIFwiZGVidWdcIlxuICoqIG1vZHVsZSBpZCA9IDFcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJtYXBwaW5ncyI6IkFBQUEiLCJzb3VyY2VSb290IjoiIn0=");

/***/ },
/* 2 */
/***/ function(module, exports) {

	eval("module.exports = require(\"immutable\");\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9leHRlcm5hbCBcImltbXV0YWJsZVwiPzFkMjAiXSwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKFwiaW1tdXRhYmxlXCIpO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogZXh0ZXJuYWwgXCJpbW11dGFibGVcIlxuICoqIG1vZHVsZSBpZCA9IDJcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJtYXBwaW5ncyI6IkFBQUEiLCJzb3VyY2VSb290IjoiIn0=");

/***/ },
/* 3 */
/***/ function(module, exports) {

	eval("module.exports = require(\"lodash/fp\");\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMy5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy9leHRlcm5hbCBcImxvZGFzaC9mcFwiPzc5MDAiXSwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKFwibG9kYXNoL2ZwXCIpO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogZXh0ZXJuYWwgXCJsb2Rhc2gvZnBcIlxuICoqIG1vZHVsZSBpZCA9IDNcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJtYXBwaW5ncyI6IkFBQUEiLCJzb3VyY2VSb290IjoiIn0=");

/***/ }
/******/ ]);<commit_msg>Update lib<commit_after>module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.default = Config;
	exports.exportForWebpack = exportForWebpack;

	var _debug = __webpack_require__(1);

	var _debug2 = _interopRequireDefault(_debug);

	var _immutable = __webpack_require__(2);

	var _fp = __webpack_require__(3);

	var _fp2 = _interopRequireDefault(_fp);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	var error = (0, _debug2.default)('webpack-config-builder:error');
	var debug = (0, _debug2.default)('webpack-config-builder:debug');
	var HOOKS_KEY = '_hooks';
	var defaultReducers = [function (c) {
	  return c;
	}];

	/**
	 * @type Config
	 * @param {Object|Immutable.Map} state
	 * @param {Function[]} reducers
	 */
	function Config(state) {
	  var reducers = arguments.length <= 1 || arguments[1] === undefined ? defaultReducers : arguments[1];

	  state = _immutable.Map.isMap(state) ? state : (0, _immutable.fromJS)(state || {});

	  return {
	    use: use,
	    useIf: useIf,
	    toJs: toJs,
	    compose: compose,
	    getReducers: function getReducers() {
	      return reducers;
	    },
	    getState: function getState() {
	      return state;
	    },
	    plugin: plugin,
	    hook: useHook,
	    emit: useEmit
	  };

	  /**
	    * Plugin
	   * @param {Function} pluginFn
	   * @returns {Config}
	   */
	  function plugin(pluginFn) {
	    return pluginFn.apply(this, [this]);
	  }

	  /**
	   * @param {Config} config
	   */
	  function compose(config) {
	    return Config(config.getState().mergeDeep(state), reducers.concat(config.getReducers()));
	  }

	  /**
	   * toJs
	   * @returns {Object|Boolean}
	   */
	  function toJs() {
	    try {
	      return _fp2.default.flow(reducers)(state).remove(HOOKS_KEY).toJS();
	    } catch (err) {
	      error(err);

	      return false;
	    }
	  }

	  /**
	   * Use
	   * @param {Function} reducer - function that receives the state object
	   * @returns {Config}
	   */
	  function use(reducer) {
	    debug('Added reducer: \'' + (reducer.name || 'Anonymous') + '\'');
	    return Config(state, reducers.concat(reducer));
	  }

	  /**
	   * Run reducer only if condition in config is met
	   * @param {String[]} getInPath - Path in configurator to value
	   * @param {Function} reducer   - state 'changer'
	   * @returns {Config}
	   */
	  function useIf(getInPath, reducer) {
	    return this.use(function (c) {
	      if (c.getIn(getInPath)) {
	        return reducer(c);
	      }
	      return c;
	    });
	  }
	}

	/**
	 * exportForWebpack
	 * @note exportForWebpack doesn't cover all webpack settings that require mapping from object to array.
	 */
	function exportForWebpack(c) {
	  return c.withMutations(function (c) {
	    return c.updateIn(['module', 'loaders'], objectToArray).updateIn(['plugins'], objectToArray).updateIn(['resolve', 'modulesDirectories'], objectToArray).updateIn(['externals'], objectToArray);
	  });
	}

	function objectToArray(obj) {
	  return obj ? obj.toArray() : void 0;
	}

	function useHook(hook, reducer) {
	  return this.use(function (c) {
	    return c.updateIn([HOOKS_KEY, hook], function (reducers) {
	      reducers = !reducers ? [] : reducers;
	      reducers.push(reducer);
	      return reducers;
	    });
	  });
	}

	function useEmit(hook) {
	  return this.use(function (c) {
	    var reducers = c.getIn([HOOKS_KEY, hook], false);

	    if (reducers) {
	      c = _fp2.default.flow(reducers)(c);
	    }

	    return c;
	  });
	}

/***/ },
/* 1 */
/***/ function(module, exports) {

	module.exports = require("debug");

/***/ },
/* 2 */
/***/ function(module, exports) {

	module.exports = require("immutable");

/***/ },
/* 3 */
/***/ function(module, exports) {

	module.exports = require("lodash/fp");

/***/ }
/******/ ]);<|endoftext|>


<commit_before>/**
 * 默认webpack配置
 */
"use strict";

const path = require('path');

module.exports = function (options) {
    options || (options = {});

    const cwd = options.cwd ? options.cwd : process.cwd();

    return {
        context: cwd,

        profile: true,

        output: {
            libraryTarget: 'var',

            publicPath: '',

            path: 'dist',

            templateDir: 'html',
            jsDir: 'js',
            cssDir: 'css',
            imageDir: 'images',
            fontDir: 'fonts'
        },

        module: {
            rules: []
        },

        externals: [{
            'react': {
                root: 'React',
                var: 'React',
                commonjs2: 'react',
                commonjs: 'react',
                amd: 'react',
                umd: 'react'
            },

            'react-dom': {
                root: 'ReactDOM',
                var: 'ReactDOM',
                commonjs2: 'react-dom',
                commonjs: 'react-dom',
                amd: 'react-dom',
                umd: 'react-dom'
            },

            'jquery': {
                root: 'window.jQuery',
                var: 'window.jQuery',
                commonjs2: 'jquery',
                commonjs: 'jquery',
                amd: 'jquery',
                umd: 'jquery'
            }
        }],

        resolve: {
            // tree-shaking优化, http://imweb.io/topic/5868e1abb3ce6d8e3f9f99bb
            mainFields: ['jsnext:main','main'],
            modules: [
                path.join(__dirname, '..', 'node_modules'),
                path.join(cwd, 'node_modules')
            ],
            // 配置别名，在项目中可缩减引用路径
            alias: {
                // handlebars-loader默认所使用的runtime，每次都会重新构建
                // 此方法不用重新构建，加快整体构建速度
                'handlebars/runtime': require.resolve('handlebars/dist/handlebars.runtime')
            },
            extensions: ['.js', 'jsx', '.json']
        },
        resolveLoader: {
            modules: [
                path.join(__dirname, '..', 'node_modules'),
                path.join(cwd, 'node_modules')
            ]
        },
        plugins: []
    }
};
<commit_msg>refactor: improve default webpack config resolve.mainFields<commit_after>/**
 * 默认webpack配置
 */
"use strict";

const path = require('path');

module.exports = function (options) {
    options || (options = {});

    const cwd = options.cwd ? options.cwd : process.cwd();

    return {
        context: cwd,

        profile: true,

        output: {
            libraryTarget: 'var',

            publicPath: '',

            path: 'dist',

            templateDir: 'html',
            jsDir: 'js',
            cssDir: 'css',
            imageDir: 'images',
            fontDir: 'fonts'
        },

        module: {
            rules: []
        },

        externals: [{
            'react': {
                root: 'React',
                var: 'React',
                commonjs2: 'react',
                commonjs: 'react',
                amd: 'react',
                umd: 'react'
            },

            'react-dom': {
                root: 'ReactDOM',
                var: 'ReactDOM',
                commonjs2: 'react-dom',
                commonjs: 'react-dom',
                amd: 'react-dom',
                umd: 'react-dom'
            },

            'jquery': {
                root: 'window.jQuery',
                var: 'window.jQuery',
                commonjs2: 'jquery',
                commonjs: 'jquery',
                amd: 'jquery',
                umd: 'jquery'
            }
        }],

        resolve: {
            // tree-shaking优化, http://imweb.io/topic/5868e1abb3ce6d8e3f9f99bb
            // https://github.com/webpack/webpack-dev-server/issues/727
            mainFields: ['jsnext:main', 'browser', 'module', 'main'],
            modules: [
                path.join(__dirname, '..', 'node_modules'),
                path.join(cwd, 'node_modules')
            ],
            // 配置别名，在项目中可缩减引用路径
            alias: {
                // handlebars-loader默认所使用的runtime，每次都会重新构建
                // 此方法不用重新构建，加快整体构建速度
                'handlebars/runtime': require.resolve('handlebars/dist/handlebars.runtime')
            },
            extensions: ['.js', 'jsx', '.json']
        },
        resolveLoader: {
            modules: [
                path.join(__dirname, '..', 'node_modules'),
                path.join(cwd, 'node_modules')
            ]
        },
        plugins: []
    }
};
<|endoftext|>


<commit_before>//	***********************************************
//	WINE LIFE
//	PROFILE WINDOW  - ProfileWindow.js
//
//	MEN+1
//	Programmer:  David Wells
//	***********************************************

function ProfileWindow(title) {
	var global = require('ui/common/globals');

	// Creates the default window with global color scheme
	var self = global.createWindow(title);

	//  Table view that scrolls the entire contents of the profile page.
	var tbl_data = [];

	var profile_row = Ti.UI.createTableViewRow({
		hasChild:false,
	});

	var fname = global.api.profileInformation = function(callback){
		getResponse('http://winelife.ericwooley.com/user/profile/', fname, callback);
	};

	// USER IMAGE - upper left of view
	// Will be populated with image data from user's account in database.
	var user_image = Ti.UI.createImageView({

  		height: 100,
  		width: 100,
  		top: 10,
  		left: 10,
  		color: global.colors.dark,
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/user_david.jpg',
  		layout:'vertical'
	});
	profile_row.add(user_image);

	//  FIRST NAME TEXT FIELD
	var firstName = Ti.UI.createLabel({
		layout: 'relative',
  		color: global.colors.dark,
  		font: { fontSize:28 },
		//borderWidth: 1,
  		text: 'David',

  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 10,
  		//right: 10,
  		height: 'auto',
  		width: '25%'
	});
	profile_row.add(firstName);

	// LAST NAME TEXT FIELD
	var lastName = Ti.UI.createLabel({
		layout: 'relative',
  		color: global.colors.dark,
  		font: { fontSize:28 },
		//borderWidth: 1,
  		text: 'Wells',

  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 10,
  		//right: 70,
  		left: 200,
  		height: 'auto',
  		width: '25%'
	});
	profile_row.add(lastName);

//create label & text field in same place.
//set text field to hidden
//add event listener to the label
//in event listener function, hide label, and show text field
//copy text from label into text field

	// ABOUT ME TITLE FIELD
	var aboutMe = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:18 },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		text: 'About Me',

  		//borderWidth: 1,
  		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 40,
  		right: 10,
 		width: 'auto',
 		//height: 'auto',
	});
	profile_row.add(aboutMe);

	// ABOUT ME TEXT FIELD
	var aboutMe_Text = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:12 },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		//borderWidth: 1,

  		text: 'Hi, my name is David. I love all wines!  Current favorite is Cabernet Sauvignon.  Follow me to see which wines I am drinking.',
  		textAlign: Ti.UI.TEXT_ALIGNMENT_RIGHT,
  		top: 60,
  		right: 10,
 		width: '55%',
 		height: 'auto',
	});
	profile_row.add(aboutMe_Text);

	// RECENT CHECK-INS LABEL
	var recent_check_ins = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:18, fontWeight: 'bold' },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		//borderWidth: 1,

  		text: 'Recent Check-Ins',
  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 120,
  		left: 10,
 		//width: 'auto',
 		//height: 'auto',
	});
	profile_row.add(recent_check_ins);

	// Add User Profile Data to top row of table
	profile_row.add(user_image);

	tbl_data.push(profile_row);

// create an array of anonymous objects
// Create an array of explicitly defined custom TableViewRows

for (var i = 0; i < 5; i++) {
	var row = Ti.UI.createTableViewRow({
		hasChild:true,
		height:90,

	});

	// Wine Picture
	var wine_image = Ti.UI.createImageView({
  		height: 80,
  		width: 80,
  		left: 10,
  		borderColor: 'black',
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/logo.png',
  		layout:'vertical',
  		width: 70,
  		height: 70
	});

	// This is the Label for the location of the wine within the row
	var wine_location = Ti.UI.createLabel({
		left:'30%',
		bottom:10,
		text: "Wine Location",
		color: global.colors.dark,
		font:{fontSize:18,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

	// This is the label of the type of wine within the row
	var wine_name = Ti.UI.createLabel({
		left:'30%',
		text: 'Wine Name and year',
		bottom:wine_location.top,
		font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		color: global.colors.dark,
		touchEnabled:false

	});

	// This is the Label for the location of the wine within the row
	var lbl_date = Ti.UI.createLabel({
		right:5,
		top:5,
		text: "Date",
		font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		color: global.colors.dark,
		touchEnabled:false
	});

	// Add objects to each row
	row.add(wine_image);
	row.add(wine_name);
	row.add(wine_location);
	row.add(lbl_date);

	row.addEventListener('click', function() {
		var win_review = require('ui/handheld/WineReview');
		self.containingTab.open(wine_review(wine));
	});

	tbl_data.push(row);
}

	// SCROLLING TABLE VIEW FOR ENTIRE PROFILE PAGE
	var table = Titanium.UI.createTableView({
		backgroundColor:'transparent',
		top:0,
		width:'100%',
		height:'100%',

		data: tbl_data

	});
	self.add(table);

	global.outputHook(self);
	return self;
};

module.exports = ProfileWindow;<commit_msg>Profile Page<commit_after>//	***********************************************
//	WINE LIFE
//	PROFILE WINDOW  - ProfileWindow.js
//
//	MEN+1
//	Programmer:  David Wells
//	***********************************************

function ProfileWindow(title) {
	var global = require('ui/common/globals');

	// Creates the default window with global color scheme
	var self = global.createWindow(title);

	//  Table view that scrolls the entire contents of the profile page.
	var tbl_data = [];

	var profile_row = Ti.UI.createTableViewRow({
		hasChild:false,
	});

	var user = global.api.profileInformation = function(callback){
		getResponse('http://winelife.ericwooley.com/user/profile/', {}, callback);
	};

	// USER IMAGE - upper left of view
	// Will be populated with image data from user's account in database.
	var user_image = Ti.UI.createImageView({

  		height: 100,
  		width: 100,
  		top: 10,
  		left: 10,
  		color: global.colors.dark,
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/user_david.jpg',
  		layout:'vertical'
	});
	profile_row.add(user_image);

	//  FIRST NAME TEXT FIELD
	var firstName = Ti.UI.createLabel({
		layout: 'relative',
  		color: global.colors.dark,
  		font: { fontSize:28 },
		//borderWidth: 1,
  		text: 'David',

  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 10,
  		//right: 10,
  		height: 'auto',
  		width: '25%'
	});
	profile_row.add(firstName);

	// LAST NAME TEXT FIELD
	var lastName = Ti.UI.createLabel({
		layout: 'relative',
  		color: global.colors.dark,
  		font: { fontSize:28 },
		//borderWidth: 1,
  		text: 'Wells',

  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 10,
  		//right: 70,
  		left: 200,
  		height: 'auto',
  		width: '25%'
	});
	profile_row.add(lastName);

//create label & text field in same place.
//set text field to hidden
//add event listener to the label
//in event listener function, hide label, and show text field
//copy text from label into text field

	// ABOUT ME TITLE FIELD
	var aboutMe = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:18 },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		text: 'About Me',

  		//borderWidth: 1,
  		textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 40,
  		right: 10,
 		width: 'auto',
 		//height: 'auto',
	});
	profile_row.add(aboutMe);

	// ABOUT ME TEXT FIELD
	var aboutMe_Text = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:12 },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		//borderWidth: 1,

  		text: 'Hi, my name is David. I love all wines!  Current favorite is Cabernet Sauvignon.  Follow me to see which wines I am drinking.',
  		textAlign: Ti.UI.TEXT_ALIGNMENT_RIGHT,
  		top: 60,
  		right: 10,
 		width: '55%',
 		height: 'auto',
	});
	profile_row.add(aboutMe_Text);

	// RECENT CHECK-INS LABEL
	var recent_check_ins = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:18, fontWeight: 'bold' },
  		//shadowColor: '#aaa',
  		//shadowOffset: {x:5, y:5},
  		//borderWidth: 1,

  		text: 'Recent Check-Ins',
  		//textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
  		top: 120,
  		left: 10,
 		//width: 'auto',
 		//height: 'auto',
	});
	profile_row.add(recent_check_ins);

	// Add User Profile Data to top row of table
	profile_row.add(user_image);

	tbl_data.push(profile_row);

// create an array of anonymous objects
// Create an array of explicitly defined custom TableViewRows

for (var i = 0; i < 5; i++) {
	var row = Ti.UI.createTableViewRow({
		hasChild:true,
		height:90,

	});

	// Wine Picture
	var wine_image = Ti.UI.createImageView({
  		height: 80,
  		width: 80,
  		left: 10,
  		borderColor: 'black',
		borderWidth: 1,
  		contentMode: 'aspectfill',
  		clipsToBounds: false,
  		image:'/images/logo.png',
  		layout:'vertical',
  		width: 70,
  		height: 70
	});

	// This is the Label for the location of the wine within the row
	var wine_location = Ti.UI.createLabel({
		left:'30%',
		bottom:10,
		text: "Wine Location",
		color: global.colors.dark,
		font:{fontSize:18,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		touchEnabled:false
	});

	// This is the label of the type of wine within the row
	var wine_name = Ti.UI.createLabel({
		left:'30%',
		text: 'Wine Name and year',
		bottom:wine_location.top,
		font:{fontSize:18,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		color: global.colors.dark,
		touchEnabled:false

	});

	// This is the Label for the location of the wine within the row
	var lbl_date = Ti.UI.createLabel({
		right:5,
		top:5,
		text: "Date",
		font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
		color: global.colors.dark,
		touchEnabled:false
	});

	// Add objects to each row
	row.add(wine_image);
	row.add(wine_name);
	row.add(wine_location);
	row.add(lbl_date);

	row.addEventListener('click', function() {
		var win_review = require('ui/handheld/WineReview');
		self.containingTab.open(wine_review(wine));
	});

	tbl_data.push(row);
}

	// SCROLLING TABLE VIEW FOR ENTIRE PROFILE PAGE
	var table = Titanium.UI.createTableView({
		backgroundColor:'transparent',
		top:0,
		width:'100%',
		height:'100%',

		data: tbl_data

	});
	self.add(table);

	global.outputHook(self);
	return self;
};

module.exports = ProfileWindow;<|endoftext|>


<commit_before>var q = require('q');
var util = require("util");
var extend = require("node.extend");

module.exports = function(name,base_client,transform, provider_config, credentials, filefog_options){

    var ClientWrapper = function(name,transform, provider_config, credentials, filefog_options){
        this.name = name;
        this.config = provider_config || {};
        this.credentials = credentials || {};
        this.filefog_options = extend(true, {transform:true, include_raw:true}, filefog_options || {});
        this._transform = transform;

        base_client.call(this);
    };
    util.inherits(ClientWrapper, base_client);

    ClientWrapper.prototype.getConfig = function () {
        return this.config;
    };
    ClientWrapper.prototype.setConfig = function (new_config) {
        this.config = extend(true, this.config, new_config || {});
    };
    ClientWrapper.prototype.getCredentials = function () {
        return this.credentials;
    };
    ClientWrapper.prototype.setCredentials = function (new_creds) {
        this.credentials = extend(true, this.credentials, new_creds || {});
    };

    //TODO:Look at possible ways to deduplicate this code later.
    ClientWrapper.prototype.accountInfo = function(provider_options, filefog_options){
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.accountInfo.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.accountInfo(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }
    ClientWrapper.prototype.checkQuota = function (provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.checkQuota.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.checkQuota(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }

    ClientWrapper.prototype.createFile = function (fileName, parentIdentifier, content_buffer, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.createFile.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.createFile(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    };
    ClientWrapper.prototype.deleteFile = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.deleteFile.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.deleteFile(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }
    ClientWrapper.prototype.downloadFile = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.downloadFile.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.downloadFile(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }
    ClientWrapper.prototype.getFileInformation = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.getFileInformation.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.getFileInformation(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }

    ClientWrapper.prototype.createFolder = function (folderName, parentIdentifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.createFolder.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.createFolder(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    };
    ClientWrapper.prototype.deleteFolder = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.deleteFolder.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.deleteFolder(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }
    ClientWrapper.prototype.getFolderInformation = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.getFolderInformation.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.getFolderInformation(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }
    ClientWrapper.prototype.retrieveFolderItems = function (identifier,provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return ClientWrapper.super_.prototype.retrieveFolderItems.apply(this, arguments)
            .then(function (raw_response) {
                if (!filefog_options.transform)
                    return raw_response;
                var transform = this._transform.retrieveFolderItems(raw_response);
                if(!filefog_options.include_raw){
                    delete transform._raw
                }
                return transform;
            })
    }

    return new ClientWrapper(name,transform,provider_config, credentials, filefog_options)
}<commit_msg>update the client wrapper with a method wrapper to reduce duplicate code.<commit_after>var q = require('q');
var util = require("util");
var extend = require("node.extend");

module.exports = function(name,base_client,transform, provider_config, credentials, filefog_options){

    var ClientWrapper = function(name,transform, provider_config, credentials, filefog_options){
        this.name = name;
        this.config = provider_config || {};
        this.credentials = credentials || {};
        this.filefog_options = extend(true, {transform:true, include_raw:true}, filefog_options || {});
        this._transform = transform;

        base_client.call(this);
    };
    util.inherits(ClientWrapper, base_client);

    ClientWrapper.prototype.getConfig = function () {
        return this.config;
    };
    ClientWrapper.prototype.setConfig = function (new_config) {
        this.config = extend(true, this.config, new_config || {});
    };
    ClientWrapper.prototype.getCredentials = function () {
        return this.credentials;
    };
    ClientWrapper.prototype.setCredentials = function (new_creds) {
        this.credentials = extend(true, this.credentials, new_creds || {});
    };

    ClientWrapper.prototype._methodWrapper = function(method, args, filefog_options){
        //TODO: pop the filefog variable off the args object, it should only be used to configure Filefog.
        var self = this;
        try{
            var promise = ClientWrapper.super_.prototype[method].apply(this, args)
                .then(function (raw_response) {
                    if (!filefog_options.transform)
                        return raw_response;
                    var transform = self._transform[method](raw_response);
                    if(!filefog_options.include_raw){
                        delete transform._raw
                    }
                    return transform;
                })
            return promise;
        }
        catch(ex){
            //this catch block will send errors as rejected promises if the underlying provider causes an error.
            return q.reject(ex);
        }
    }

    ClientWrapper.prototype.accountInfo = function(provider_options, filefog_options){
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("accountInfo",arguments,filefog_options);
//        return ClientWrapper.super_.prototype.accountInfo.apply(this, arguments)
//            .then(function (raw_response) {
//                if (!filefog_options.transform)
//                    return raw_response;
//                var transform = this._transform.accountInfo(raw_response);
//                if(!filefog_options.include_raw){
//                    delete transform._raw
//                }
//                return transform;
//            })
    }
    ClientWrapper.prototype.checkQuota = function (provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("checkQuota",arguments,filefog_options);

    }

    ClientWrapper.prototype.createFile = function (fileName, parentIdentifier, content_buffer, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("createFile",arguments,filefog_options);

    };
    ClientWrapper.prototype.deleteFile = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("deleteFile",arguments,filefog_options);

    }
    ClientWrapper.prototype.downloadFile = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("downloadFile",arguments,filefog_options);

    }

    ClientWrapper.prototype.getFileInformation = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("getFileInformation",arguments,filefog_options);
    }

    ClientWrapper.prototype.createFolder = function (folderName, parentIdentifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("createFolder",arguments,filefog_options);

    };
    ClientWrapper.prototype.deleteFolder = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("deleteFolder",arguments,filefog_options);

    }
    ClientWrapper.prototype.getFolderInformation = function (identifier, provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("getFolderInformation",arguments,filefog_options);

    }
    ClientWrapper.prototype.retrieveFolderItems = function (identifier,provider_options,filefog_options) {
        filefog_options = extend(true, {}, this.filefog_options, filefog_options|| {});
        return this._methodWrapper("retrieveFolderItems",arguments,filefog_options);

    }

    return new ClientWrapper(name,transform,provider_config, credentials, filefog_options)
}<|endoftext|>