<commit_before>import moment from 'moment';
import 'jquery-datetimepicker';

/**
 * transform a event modal-form for course events
 * @param modal {DOM-Element} - the given modal which will be transformed
 * @param event {object} - a event, maybe a course-event
 */
function transformCourseOrTeamEvent(modal, event) {
	if (event['x-sc-courseId']) {
		const courseId = event['x-sc-courseId'];
		$.getJSON(`/courses/${  courseId  }/json`, (course) => {
			let $title = modal.find('.modal-title');
			$title.html(`${$title.html()  } , Kurs: ${  course.course.name}`);

			// if not teacher, not allow editing course events
			if ($('.create-course-event').length <= 0) {
				modal.find('.modal-form :input').attr('disabled', true);
			}

			// set fix course on editing
			modal.find("input[name='scopeId']").attr('value', event['x-sc-courseId']);
			modal.find('.modal-form').append(`<input name='courseId' value='${  courseId }' type='hidden'>`);
			modal.find('.create-course-event').remove();
			modal.find('.create-team-event').remove();
		});
	} else if (event['x-sc-teamId']) {
		const teamId = event['x-sc-teamId'];
		$.getJSON(`/teams/${  teamId  }/json`, (team) => {
			let $title = modal.find('.modal-title');
			$title.html(`${$title.html()  } , Team: ${  team.team.name}`);

			// if not teacher, not allow editing team events
			if ($('.create-team-event').length <= 0) {
				modal.find('.modal-form :input').attr('disabled', true);
			}

			// set fix team on editing
			modal.find("input[name='scopeId']").attr('value', event['x-sc-teamId']);
			modal.find('.modal-form').append(`<input name='teamId' value='${  teamId }' type='hidden'>`);
			modal.find('.create-team-event').remove();
			modal.find('.create-course-event').remove();
		});
	}
}

$(document).ready(() => {
	let $createEventModal = $('.create-event-modal');
	let $editEventModal = $('.edit-event-modal');
	let $filePermissionsModal = $('.file-permissions-modal');

	const handler = {
		get (target, name) {
      return name in target ?
        target[name] :
        '';
    },
		set (obj, prop, value) {
      obj[prop] = value;
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set#Return_value
      return obj[prop] === value;
    },
	};

	const state = new Proxy({
		currentEvent: {},
	}, handler);

	$('.btn-create-event').click((e) => {
    // open create event modal
    var _startDate = moment().format("DD.MM.YYYY HH:mm");
    var _endDate = moment().add(1, 'hour').format("DD.MM.YYYY HH:mm");

    $.datetimepicker.setLocale('de');
    $('input[data-datetime]').datetimepicker({
      format:'d.m.Y H:i',
      mask: '39.19.9999 29:59'
    });

    populateModalForm($createEventModal, {
        title: 'Termin hinzufügen',
        closeLabel: 'Abbrechen',
        submitLabel: 'Hinzufügen',
        fields: {
            startDate: _startDate,
            endDate: _endDate
        }
    });

    $createEventModal.appendTo('body').modal('show');
  });

	$('.btn-edit-event').click(function (e) {
    e.preventDefault();
    const event = $(this).parents('.events-card').data('event');
    event.start = moment(event.start);
    event.end = moment(event.end);
    state.event = event;

    $.datetimepicker.setLocale('de');
    $('input[data-datetime]').datetimepicker({
      format:'d.m.Y H:i',
      mask: '39.19.9999 29:59'
    });

    if (event.url) {
        window.location.href = event.url;
        return false;
    }
        // personal event
        event.startDate = event.start.format("DD.MM.YYYY HH:mm");
        event.endDate = (event.end || event.start).format("DD.MM.YYYY HH:mm");
        populateModalForm($editEventModal, {
            title: 'Termin - Details',
            closeLabel: 'Abbrechen',
            submitLabel: 'Speichern',
            fields: event,
            action: '/teams/calendar/events/' + event.attributes.uid
        });

        transformCourseOrTeamEvent($editEventModal, event);

        $editEventModal.find('.btn-delete').click(e => {
            $.ajax({
                url: '/calendar/events/' + event.attributes.uid,
                type: 'DELETE',
                success: function(result) {
                    window.location.reload();
                },
            });
        });
        $editEventModal.appendTo('body').modal('show');

  });

	$editEventModal.on('submit', (e) => {
    e.stopPropagation();
    e.preventDefault();

    $.ajax({
        url: '/teams/events/' + state.event.attributes.uid,
        type: 'PUT',
        data: $('.edit-event-modal form').serialize(),
        success: function(result) {
            window.location.reload();
        },
    });
  });

	$('.btn-file-permissions').click((e) => {
    populateModalForm($filePermissionsModal, {
        title: 'Freigabe-Einstellungen ändern',
        closeLabel: 'Abbrechen',
        submitLabel: 'Speichern',
    });
    $filePermissionsModal.appendTo('body').modal('show');
  });

	$('.file-permissions-modal form').on('submit', (e) => {
    e.stopPropagation();
    e.preventDefault();

    $.ajax({
      url: '/teams/' + $('.section-teams').data('id') + '/json',
      method: 'GET'
    })
    .done(function(data) {
      const allowed = {
        'teamexpert': $('.file-permissions-modal input[name="externalExperts"]').prop('checked'),
        'teammember': $('.file-permissions-modal input[name="teamMembers"]').prop('checked'),
      };

      const filePermission = data.team.filePermission;

      const newPermission = filePermission
        .filter(permission => ['teamexpert', 'teammember'].indexOf(permission.roleName) > -1)
        .map(permission => {

            const setPermission = ['create', 'read', 'delete', 'write'].reduce((obj, right) => {
                obj[right] = allowed[permission.roleName];
                return obj;
            }, {});

            return Object.assign(permission, setPermission);
        });

      $.ajax({
        url: '/teams/' + $('.section-teams').data('id') + '/permissions',
        method: 'PATCH',
        data: { filePermission: Object.assign(filePermission, newPermission) }
      })
      .done(function() {
        $.showNotification('Standard-Berechtigungen erfolgreich geändert', "success", true);
        $('.file-permissions-modal').modal('hide');
      })
      .fail(function() {
        $.showNotification('Problem beim Ändern der Berechtigungen', "danger", true);
      });
    })
    .fail(function() {
      $.showNotification('Problem beim Ändern der Berechtigungen', "danger", true);
    });
  });

	/**
   	* Leave Team
   	*
   	*/
	$('.dropdown-leave-team').click(function leaveTeam(e) {
		e.stopPropagation();
		e.preventDefault();
		const $leaveTeamModal = $('.leave-team-modal');
		const userId = $(this).data('user-id');
		populateModalForm($leaveTeamModal, {
			title: 'Team verlassen',
			closeLabel: 'Abbrechen',
			submitLabel: 'Team verlassen',
			payload: { userId },
		});

		const $modalForm = $leaveTeamModal.find('.modal-form');
		$leaveTeamModal.appendTo('body').modal('show');
	});

	$('.leave-team-modal form').on('submit', function leaveTeamModal(e) {
		e.stopPropagation();
		e.preventDefault();
		const userIdToRemove = $(this).data('payload').userId;

		$.ajax({
			url: $(this).attr('action'),
			method: 'DELETE',
			data: {
				userIdToRemove,
			},
		}).done(() => {
			location.reload();
		}).fail(() => {
			$.showNotification('Problem beim Löschen des Teilnehmers', 'danger', true);
		});

		return false;
	});
});
<commit_msg>added redirect after team leave<commit_after>import moment from 'moment';
import 'jquery-datetimepicker';

/**
 * transform a event modal-form for course events
 * @param modal {DOM-Element} - the given modal which will be transformed
 * @param event {object} - a event, maybe a course-event
 */
function transformCourseOrTeamEvent(modal, event) {
	if (event['x-sc-courseId']) {
		const courseId = event['x-sc-courseId'];
		$.getJSON(`/courses/${  courseId  }/json`, (course) => {
			let $title = modal.find('.modal-title');
			$title.html(`${$title.html()  } , Kurs: ${  course.course.name}`);

			// if not teacher, not allow editing course events
			if ($('.create-course-event').length <= 0) {
				modal.find('.modal-form :input').attr('disabled', true);
			}

			// set fix course on editing
			modal.find("input[name='scopeId']").attr('value', event['x-sc-courseId']);
			modal.find('.modal-form').append(`<input name='courseId' value='${  courseId }' type='hidden'>`);
			modal.find('.create-course-event').remove();
			modal.find('.create-team-event').remove();
		});
	} else if (event['x-sc-teamId']) {
		const teamId = event['x-sc-teamId'];
		$.getJSON(`/teams/${  teamId  }/json`, (team) => {
			let $title = modal.find('.modal-title');
			$title.html(`${$title.html()  } , Team: ${  team.team.name}`);

			// if not teacher, not allow editing team events
			if ($('.create-team-event').length <= 0) {
				modal.find('.modal-form :input').attr('disabled', true);
			}

			// set fix team on editing
			modal.find("input[name='scopeId']").attr('value', event['x-sc-teamId']);
			modal.find('.modal-form').append(`<input name='teamId' value='${  teamId }' type='hidden'>`);
			modal.find('.create-team-event').remove();
			modal.find('.create-course-event').remove();
		});
	}
}

$(document).ready(() => {
	let $createEventModal = $('.create-event-modal');
	let $editEventModal = $('.edit-event-modal');
	let $filePermissionsModal = $('.file-permissions-modal');

	const handler = {
		get (target, name) {
      return name in target ?
        target[name] :
        '';
    },
		set (obj, prop, value) {
      obj[prop] = value;
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set#Return_value
      return obj[prop] === value;
    },
	};

	const state = new Proxy({
		currentEvent: {},
	}, handler);

	$('.btn-create-event').click((e) => {
    // open create event modal
    var _startDate = moment().format("DD.MM.YYYY HH:mm");
    var _endDate = moment().add(1, 'hour').format("DD.MM.YYYY HH:mm");

    $.datetimepicker.setLocale('de');
    $('input[data-datetime]').datetimepicker({
      format:'d.m.Y H:i',
      mask: '39.19.9999 29:59'
    });

    populateModalForm($createEventModal, {
        title: 'Termin hinzufügen',
        closeLabel: 'Abbrechen',
        submitLabel: 'Hinzufügen',
        fields: {
            startDate: _startDate,
            endDate: _endDate
        }
    });

    $createEventModal.appendTo('body').modal('show');
  });

	$('.btn-edit-event').click(function (e) {
    e.preventDefault();
    const event = $(this).parents('.events-card').data('event');
    event.start = moment(event.start);
    event.end = moment(event.end);
    state.event = event;

    $.datetimepicker.setLocale('de');
    $('input[data-datetime]').datetimepicker({
      format:'d.m.Y H:i',
      mask: '39.19.9999 29:59'
    });

    if (event.url) {
        window.location.href = event.url;
        return false;
    }
        // personal event
        event.startDate = event.start.format("DD.MM.YYYY HH:mm");
        event.endDate = (event.end || event.start).format("DD.MM.YYYY HH:mm");
        populateModalForm($editEventModal, {
            title: 'Termin - Details',
            closeLabel: 'Abbrechen',
            submitLabel: 'Speichern',
            fields: event,
            action: '/teams/calendar/events/' + event.attributes.uid
        });

        transformCourseOrTeamEvent($editEventModal, event);

        $editEventModal.find('.btn-delete').click(e => {
            $.ajax({
                url: '/calendar/events/' + event.attributes.uid,
                type: 'DELETE',
                success: function(result) {
                    window.location.reload();
                },
            });
        });
        $editEventModal.appendTo('body').modal('show');

  });

	$editEventModal.on('submit', (e) => {
    e.stopPropagation();
    e.preventDefault();

    $.ajax({
        url: '/teams/events/' + state.event.attributes.uid,
        type: 'PUT',
        data: $('.edit-event-modal form').serialize(),
        success: function(result) {
            window.location.reload();
        },
    });
  });

	$('.btn-file-permissions').click((e) => {
    populateModalForm($filePermissionsModal, {
        title: 'Freigabe-Einstellungen ändern',
        closeLabel: 'Abbrechen',
        submitLabel: 'Speichern',
    });
    $filePermissionsModal.appendTo('body').modal('show');
  });

	$('.file-permissions-modal form').on('submit', (e) => {
    e.stopPropagation();
    e.preventDefault();

    $.ajax({
      url: '/teams/' + $('.section-teams').data('id') + '/json',
      method: 'GET'
    })
    .done(function(data) {
      const allowed = {
        'teamexpert': $('.file-permissions-modal input[name="externalExperts"]').prop('checked'),
        'teammember': $('.file-permissions-modal input[name="teamMembers"]').prop('checked'),
      };

      const filePermission = data.team.filePermission;

      const newPermission = filePermission
        .filter(permission => ['teamexpert', 'teammember'].indexOf(permission.roleName) > -1)
        .map(permission => {

            const setPermission = ['create', 'read', 'delete', 'write'].reduce((obj, right) => {
                obj[right] = allowed[permission.roleName];
                return obj;
            }, {});

            return Object.assign(permission, setPermission);
        });

      $.ajax({
        url: '/teams/' + $('.section-teams').data('id') + '/permissions',
        method: 'PATCH',
        data: { filePermission: Object.assign(filePermission, newPermission) }
      })
      .done(function() {
        $.showNotification('Standard-Berechtigungen erfolgreich geändert', "success", true);
        $('.file-permissions-modal').modal('hide');
      })
      .fail(function() {
        $.showNotification('Problem beim Ändern der Berechtigungen', "danger", true);
      });
    })
    .fail(function() {
      $.showNotification('Problem beim Ändern der Berechtigungen', "danger", true);
    });
  });

	/**
   	* Leave Team
   	*
   	*/
	$('.dropdown-leave-team').click(function leaveTeam(e) {
		e.stopPropagation();
		e.preventDefault();
		const $leaveTeamModal = $('.leave-team-modal');
		const userId = $(this).data('user-id');
		populateModalForm($leaveTeamModal, {
			title: 'Team verlassen',
			closeLabel: 'Abbrechen',
			submitLabel: 'Team verlassen',
			payload: { userId },
		});

		const $modalForm = $leaveTeamModal.find('.modal-form');
		$leaveTeamModal.appendTo('body').modal('show');
	});

	$('.leave-team-modal form').on('submit', function leaveTeamModal(e) {
		e.stopPropagation();
		e.preventDefault();
		const userIdToRemove = $(this).data('payload').userId;

		$.ajax({
			url: $(this).attr('action'),
			method: 'DELETE',
			data: {
				userIdToRemove,
			},
		}).done(() => {
			window.location.replace('/teams');
		}).fail(() => {
			$.showNotification('Problem beim Löschen des Teilnehmers', 'danger', true);
		});

		return false;
	});
});
<|endoftext|>


<commit_before>/** Represents a single project in the work carousel */
import Parallax3D from '../parallax';

export class CarouselCard {
  constructor(elem, tags) {
    this.elem = elem;
    this.elem.classList.add('carousel-card');
    // Move elem into a wrapper div
    this.wrapper = document.createElement('div');
    this.wrapper.className = 'carousel-card-wrapper';
    this.elem.parentNode.insertBefore(this.wrapper, this.elem);
    this.wrapper.appendChild(this.elem);

    this.tags = tags || elem.dataset.tags.split(',').map(t => t.trim());
    this.titleElem = elem.getElementsByTagName('h1')[0];

    this.transitionTime = this.baseTransitionTime = 0.5;
    this.parallax = new Parallax3D(this.elem);

    // Title manipulation interface

    const _this2 = this;
    /**
     * Interface for updating styles on the title.
     * Examples:
     *   this.title.translate = '-10px'
     *   this.title.opacity = 0.5
     */
    this.title = {
      _apply() {
        _this2.titleElem.style.transform = `translateZ(25px) translateX(${this._translate})`;
        _this2.titleElem.style.opacity = this._opacity;
      },
      get translate() { return this._translate; },
      set translate(t) { this._translate = t; this._apply(); },
      get opacity() { return this._opacity; },
      set opacity(o) { this._opacity = o; this._apply(); },
    };
  }

  /**
   * Update the card wrapper's CSS in order to reflect changes that were made to its JS
   * representation.
   */
  _applyTransform() {
    this.wrapper.style.transform = [
      'translate(-50%, -50%)',
      `translateX(${this._translate})`,
    ].join(' ');
  }

  // Translation

  get translate() { return this._translate; }
  set translate(val) { this._translate = val; this._applyTransform(); }

  // Transition time

  get transitionTime() { return this._transitionTime; }
  set transitionTime(secs) {
    this._transitionTime = secs;
    this.wrapper.style.transition = `transform ${secs}s`;
    this.titleElem.style.transition = `transform ${secs}s, opacity ${secs}s`;
  }

  setEnabled(enable = true) {
    const totalTime = this.transitionTime * 1000;
    const startTime = new Date();

    function step(parallax) {
      const timeElapsed = new Date() - startTime;
      // Still going
      if (timeElapsed < totalTime) {
        const progress = (timeElapsed / totalTime);
        if (enable) parallax.rotmax = progress * 10;
        else parallax.rotmax = (1 - progress) * 10;
        parallax.rotate();
        requestAnimationFrame(() => step(parallax));
      } else {
        parallax.rotmax = enable ? 10 : 0;
      }
    }
    step(this.parallax);
  }
}

/** Collects and orchestrates multiple CarouselCards */
export class Carousel {
  constructor(cards) {
    this.cards = cards;
    this._position = 0;
    // Trigger immediate layout of cards
    this.position = this._position;
  }

  // Transition time logic

  get baseTransitionTime() {
    const answer = this.cards[0].baseTransitionTime;
    // Warn if not every card has the same baseTransitionTime
    if (!this.cards.every(card => card.baseTransitionTime === answer)) console.warn('Carousel.baseTransitionTime called but baseTransitionTime of cards is inconsistent');
    return answer;
  }
  get transitionTime() {
    const answer = this.cards[0].transitionTime;
    // Warn if not every card has the same transitionTime
    if (!this.cards.every(card => card.transitionTime === answer)) console.warn('Carousel.transitionTime called but transitionTime of cards is inconsistent');
    return answer;
  }
  set transitionTime(secs) {
    this.cards.forEach((c) => { c.transitionTime = secs; });
  }

  // Rearrange

  get position() { return this._position; }
  set position(pos) {
    const delta = Math.abs(this._position - pos);
    // mx + b
    this.transitionTime = ((0.5 * this.baseTransitionTime) * (delta - 1)) + this.baseTransitionTime;

    this.cards.forEach((card, index) => {
      const cardPosition = index - pos;
      const cardTranslation = `${48 * cardPosition}vw`;
      card.translate = cardTranslation;
      if (cardPosition === 0) {
        card.title.opacity = 1;
        card.title.translate = 0;
      } else {
        card.title.opacity = 0;
        card.title.translate = (pos > this._position) ? '5vw' : '-5vw';
      }
    });

    this._position = pos;
  }
}
<commit_msg>Disable non-central carousel cards<commit_after>/** Represents a single project in the work carousel */
import Parallax3D from '../parallax';

export class CarouselCard {
  constructor(elem, tags) {
    this.elem = elem;
    this.elem.classList.add('carousel-card');
    // Move elem into a wrapper div
    this.wrapper = document.createElement('div');
    this.wrapper.className = 'carousel-card-wrapper';
    this.elem.parentNode.insertBefore(this.wrapper, this.elem);
    this.wrapper.appendChild(this.elem);

    this.tags = tags || elem.dataset.tags.split(',').map(t => t.trim());
    this.titleElem = elem.getElementsByTagName('h1')[0];

    this.transitionTime = this.baseTransitionTime = 0.5;
    this.parallax = new Parallax3D(this.elem);

    // Title manipulation interface

    const _this2 = this;
    /**
     * Interface for updating styles on the title.
     * Examples:
     *   this.title.translate = '-10px'
     *   this.title.opacity = 0.5
     */
    this.title = {
      _apply() {
        _this2.titleElem.style.transform = `translateZ(25px) translateX(${this._translate})`;
        _this2.titleElem.style.opacity = this._opacity;
      },
      get translate() { return this._translate; },
      set translate(t) { this._translate = t; this._apply(); },
      get opacity() { return this._opacity; },
      set opacity(o) { this._opacity = o; this._apply(); },
    };
  }

  /**
   * Update the card wrapper's CSS in order to reflect changes that were made to its JS
   * representation.
   */
  _applyTransform() {
    this.wrapper.style.transform = [
      'translate(-50%, -50%)',
      `translateX(${this._translate})`,
    ].join(' ');
  }

  // Translation

  get translate() { return this._translate; }
  set translate(val) { this._translate = val; this._applyTransform(); }

  // Transition time

  get transitionTime() { return this._transitionTime; }
  set transitionTime(secs) {
    this._transitionTime = secs;
    this.wrapper.style.transition = `transform ${secs}s`;
    this.titleElem.style.transition = `transform ${secs}s, opacity ${secs}s`;
  }

  setEnabled(enable = true) {
    const totalTime = this.transitionTime * 1000;
    const startTime = new Date();

    // Recursively adjust using setAnimationFrame until transitionTime is reached
    function step(parallax) {
      const timeElapsed = new Date() - startTime;
      // Still going
      if (timeElapsed < totalTime) {
        const progress = (timeElapsed / totalTime);
        if (enable) parallax.rotmax = progress * 10;
        else parallax.rotmax = (1 - progress) * 10;
        parallax.rotate();
        requestAnimationFrame(() => step(parallax));
      } else {
        parallax.rotmax = enable ? 10 : 0;
      }
    }
    step(this.parallax);
  }

  disable() { this.setEnabled(false); }
  enable() { this.setEnabled(true); }
}

/** Collects and orchestrates multiple CarouselCards */
export class Carousel {
  constructor(cards) {
    this.cards = cards;
    this._position = 0;
    // Trigger immediate layout of cards
    this.position = this._position;
  }

  // Transition time logic

  get baseTransitionTime() {
    const answer = this.cards[0].baseTransitionTime;
    // Warn if not every card has the same baseTransitionTime
    if (!this.cards.every(card => card.baseTransitionTime === answer)) console.warn('Carousel.baseTransitionTime called but baseTransitionTime of cards is inconsistent');
    return answer;
  }
  get transitionTime() {
    const answer = this.cards[0].transitionTime;
    // Warn if not every card has the same transitionTime
    if (!this.cards.every(card => card.transitionTime === answer)) console.warn('Carousel.transitionTime called but transitionTime of cards is inconsistent');
    return answer;
  }
  set transitionTime(secs) {
    this.cards.forEach((c) => { c.transitionTime = secs; });
  }

  // Rearrange

  get position() { return this._position; }
  set position(pos) {
    const delta = Math.abs(this._position - pos);
    // mx + b
    this.transitionTime = ((0.5 * this.baseTransitionTime) * (delta - 1)) + this.baseTransitionTime;

    this.cards.forEach((card, index) => {
      const cardPosition = index - pos;
      const cardTranslation = `${48 * cardPosition}vw`;
      card.translate = cardTranslation;
      // Center card
      if (cardPosition === 0) {
        card.title.opacity = 1;
        card.title.translate = 0;
        card.enable();
      // Not center card
      } else {
        card.title.opacity = 0;
        card.title.translate = (pos > this._position) ? '5vw' : '-5vw';
        card.disable();
      }
    });

    this._position = pos;
  }
}
<|endoftext|>


<commit_before>/**
 * Created by kamalnrf
 */

'use strict';

const msg_me = require('../msg-me');
const connection = require('./handlers/connection');
const newUser = require('./handlers/createUserOperator');
const feedback = require('./handlers/feedback');
const shrImage = require('./handlers/shrImage');

const postback = (bot) => {
    bot.on('postback', (payload, chat) => {
       console.log(payload);

       if (payload.postback.payload === '_stop') {
           const fbID = payload.sender.id;

           msg_me.isConnected(fbID)
               .then(connected => {
                   if (connected === 'true' || connected === true)
                       msg_me.conectedTo(fbID)
                           .then(recieverID => {
                               msg_me.disconnect(fbID, recieverID);

                               chat.say(`Conversation has ended`);
                               bot.say(recieverID, `Conection has been ended.`);
                           });
                   else
                       chat.say(`You have to be in a conversation to stop a conversation`);
               })
       }
    });

    bot.on('postback:REQ_YES', (payload, chat) => {
        console.log(payload);
        const senderID = payload.sender.id;

        msg_me.whatIsOnHold(senderID)
            .then(recieverID => {
                if (recieverID !== '-1') {
                    if (msg_me.connect(senderID, recieverID) === true) {
                        chat.say(`A connection has been established`);
                        bot.say(recieverID, `A connection has been established`);
                    }
                }else {
                    chat.say(`Your request has been, expired.`);
                }
            });
    });

    bot.on('postback:REQ_NO', (payload, chat) => {
        console.log(payload);
        const senderID = payload.sender.id;

        msg_me.whatIsOnHold(senderID)
            .then(recieverID => {
                if (recieverID !== '-1') {
                    if (msg_me.disconnect(senderID, recieverID) === true) {
                        chat.say(`Ok`);
                        bot.say(recieverID, `Your request has been rejected, try connecting with someone else.`);
                        msg_me.removeQueuedUsers(recieverID);
                    }
                }else {
                    chat.say(`OK.`);
                }
            });
    });
    //----------Online/Offline--------//
    bot.on('postback:online/offline', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.isOnline(fbID)
            .then(isOnline => {
                console.log(`isOnline ${isOnline}\nType: ${typeof isOnline}`);
                if (isOnline === 'true' || isOnline === true) {
                    msg_me.turnOffline(fbID)
                        .then(result => result ? chat.say("You’re now Offline. Friends will not be able to connect with you. Please turn back to Online if you want to chat anonymously with your friends.") : chat.say("Something went wrong tryagain"));
                }
                else if (isOnline === false || isOnline === "false") {
                    msg_me.turnOnline(fbID)
                        .then(result => result ? chat.say("You’re now Online. Hold on! Any friend of yours maybe contacting you soon.") : chat.say("Something went wrong tryagain"));

                    msg_me.getAllQueuedUsers(fbID)
                        .then(queuedUsers => {
                            console.log(queuedUsers);
                            queuedUsers.map(element => {
                                msg_me.getMyName(fbID)
                                    .then(name => {
                                        console.log(element);
                                        bot.sendTextMessage(element, `${name} is online. Now you can connect with him.`);
                                    });
                            });
                        });

                    msg_me.removeQueuedUsers(fbID);
                }
                else
                    chat.say("You need to create a user name first.")
                        .then(() => {
                            chat.conversation((convo) => {
                                convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                            })
                        });
            }).catch(error => console.log(error));
    });

    //----------Start a conversation----//
    bot.on('postback:start-conversation', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.isConnected(fbID)
            .then(connected => {
                try {
                    if (connected === 'true' || connected === true)
                        chat.say("When you are in a conversation you can't start a new one.");
                    else if (connected === 'false' || connected === false)
                        chat.conversation((convo) => {
                            convo.sendTypingIndicator(1000)
                                .then(() => connection.estConnection(convo, payload, bot))
                                .catch(error => console.log(error));
                        });
                    else
                        chat.say("You need to create a username first.")
                            .then(() => {
                                chat.conversation((convo) => {
                                    convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                                })
                            });
                }catch (error){
                    chat.say('Seems like something went wrong, try sending a message...');
                }

            }).catch(error => console.log(error));
    });

    //----------My User Name-----------//
    bot.on('postback:myName', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.getMyName(fbID)
            .then(userName => {
                if (userName !== null) {
                    msg_me.getMyImage(fbID)
                        .then(link => {
                            if (link === null || link === undefined) {
                                console.log(`link is null`);
                                chat.getUserProfile()
                                    .then((user) => {
                                        shrImage.genImage(user.profile_pic, userName)
                                            .then(image => {
                                                shrImage.getLink(image, userName)
                                                    .then(link => {
                                                        console.log(link);
                                                        msg_me.saveImage(fbID, link);
                                                        chat.say({
                                                            attachment: 'image',
                                                            url: link
                                                        });
                                                        chat.say(`Your username is ${userName}. Share it with your friends.`);
                                                    })
                                            });
                                    });
                            }
                            else {
                                chat.say({
                                    attachment: 'image',
                                    url: link
                                }).then(() => chat.say(`Your username is ${userName}. Share it with your friends.`));
                            }
                        });
                }
                else
                    chat.say("You need to create a username first.")
                        .then(() => {
                            chat.conversation((convo) => {
                                convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                            })
                        });
            })
            .catch(error => {
                console.log(error);
                chat.say("You need to create a username first.")
                    .then(() => {
                        chat.conversation((convo) => {
                            convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                        })
                    });
            })
    });

    //----------Feedback----------//
    bot.on('postback:feedback', (payload, chat) => {
       console.log(payload);

       try {

           chat.conversation(convo => {
               convo.sendTypingIndicator(1000).then(() => feedback.sendFeedBack(payload, convo));
           })
       }catch (error){

       }
    });

    console.log(`Initialized the postbacks.`);
};

module.exports = postback;<commit_msg>patch<commit_after>/**
 * Created by kamalnrf
 */

'use strict';

const msg_me = require('../msg-me');
const connection = require('./handlers/connection');
const newUser = require('./handlers/createUserOperator');
const feedback = require('./handlers/feedback');
const shrImage = require('./handlers/shrImage');

const postback = (bot) => {
    bot.on('postback', (payload, chat) => {
       console.log(payload);

       if (payload.postback.payload === '_stop') {
           const fbID = payload.sender.id;

           msg_me.isConnected(fbID)
               .then(connected => {
                   if (connected === 'true' || connected === true)
                       msg_me.conectedTo(fbID)
                           .then(recieverID => {
                               msg_me.disconnect(fbID, recieverID);

                               chat.say(`Conversation has ended`);
                               bot.say(recieverID, `Conection has been ended.`);
                           });
                   else
                       chat.say(`You have to be in a conversation to stop a conversation`);
               })
       }
    });

    bot.on('postback:REQ_YES', (payload, chat) => {
        console.log(payload);
        const senderID = payload.sender.id;

        msg_me.whatIsOnHold(senderID)
            .then(recieverID => {
                if (recieverID !== '-1') {
                    if (msg_me.connect(senderID, recieverID) === true) {
                        chat.say(`A connection has been established.If at any point you feel like closing the connection send '#stop'`);
                        bot.say(recieverID, `A connection has been established.If at any point you feel like closing the connection send '#stop'`);
                    }
                }else {
                    chat.say(`Your request has been, expired.`);
                }
            });
    });

    bot.on('postback:REQ_NO', (payload, chat) => {
        console.log(payload);
        const senderID = payload.sender.id;

        msg_me.whatIsOnHold(senderID)
            .then(recieverID => {
                if (recieverID !== '-1') {
                    if (msg_me.disconnect(senderID, recieverID) === true) {
                        chat.say(`Ok`);
                        bot.say(recieverID, `Your request has been rejected, try connecting with someone else.`);
                        msg_me.removeQueuedUsers(recieverID);
                    }
                }else {
                    chat.say(`OK.`);
                }
            });
    });
    //----------Online/Offline--------//
    bot.on('postback:online/offline', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.isOnline(fbID)
            .then(isOnline => {
                console.log(`isOnline ${isOnline}\nType: ${typeof isOnline}`);
                if (isOnline === 'true' || isOnline === true) {
                    msg_me.turnOffline(fbID)
                        .then(result => result ? chat.say("You’re now Offline. Friends will not be able to connect with you. Please turn back to Online if you want to chat anonymously with your friends.") : chat.say("Something went wrong tryagain"));
                }
                else if (isOnline === false || isOnline === "false") {
                    msg_me.turnOnline(fbID)
                        .then(result => result ? chat.say("You’re now Online. Hold on! Any friend of yours maybe contacting you soon.") : chat.say("Something went wrong tryagain"));

                    msg_me.getAllQueuedUsers(fbID)
                        .then(queuedUsers => {
                            console.log(queuedUsers);
                            queuedUsers.map(element => {
                                msg_me.getMyName(fbID)
                                    .then(name => {
                                        console.log(element);
                                        bot.sendTextMessage(element, `${name} is online. Now you can connect with him.`);
                                    });
                            });
                        });

                    msg_me.removeQueuedUsers(fbID);
                }
                else
                    chat.say("You need to create a user name first.")
                        .then(() => {
                            chat.conversation((convo) => {
                                convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                            })
                        });
            }).catch(error => console.log(error));
    });

    //----------Start a conversation----//
    bot.on('postback:start-conversation', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.isConnected(fbID)
            .then(connected => {
                try {
                    if (connected === 'true' || connected === true)
                        chat.say("When you are in a conversation you can't start a new one.");
                    else if (connected === 'false' || connected === false)
                        chat.conversation((convo) => {
                            convo.sendTypingIndicator(1000)
                                .then(() => connection.estConnection(convo, payload, bot))
                                .catch(error => console.log(error));
                        });
                    else
                        chat.say("You need to create a username first.")
                            .then(() => {
                                chat.conversation((convo) => {
                                    convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                                })
                            });
                }catch (error){
                    chat.say('Seems like something went wrong, try sending a message...');
                }

            }).catch(error => console.log(error));
    });

    //----------My User Name-----------//
    bot.on('postback:myName', (payload, chat) => {
        console.log(payload);

        const fbID = payload.sender.id;

        msg_me.getMyName(fbID)
            .then(userName => {
                if (userName !== null) {
                    msg_me.getMyImage(fbID)
                        .then(link => {
                            if (link === null || link === undefined) {
                                console.log(`link is null`);
                                chat.getUserProfile()
                                    .then((user) => {
                                        shrImage.genImage(user.profile_pic, userName)
                                            .then(image => {
                                                shrImage.getLink(image, userName)
                                                    .then(link => {
                                                        console.log(link);
                                                        msg_me.saveImage(fbID, link);
                                                        chat.say({
                                                            attachment: 'image',
                                                            url: link
                                                        });
                                                        chat.say(`Your username is ${userName}. Share it with your friends.`);
                                                    })
                                            });
                                    });
                            }
                            else {
                                chat.say({
                                    attachment: 'image',
                                    url: link
                                }).then(() => chat.say(`Your username is ${userName}. Share it with your friends.`));
                            }
                        });
                }
                else
                    chat.say("You need to create a username first.")
                        .then(() => {
                            chat.conversation((convo) => {
                                convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                            })
                        });
            })
            .catch(error => {
                console.log(error);
                chat.say("You need to create a username first.")
                    .then(() => {
                        chat.conversation((convo) => {
                            convo.sendTypingIndicator(1000).then(() => newUser.createUser(convo, payload));
                        })
                    });
            })
    });

    //----------Feedback----------//
    bot.on('postback:feedback', (payload, chat) => {
       console.log(payload);

       try {

           chat.conversation(convo => {
               convo.sendTypingIndicator(1000).then(() => feedback.sendFeedBack(payload, convo));
           })
       }catch (error){

       }
    });

    console.log(`Initialized the postbacks.`);
};

module.exports = postback;<|endoftext|>


<commit_before>module.exports = function(Sequelize, DataTypes) {

  var Transaction = Sequelize.define('Transaction', {
    type: DataTypes.STRING,
    description: DataTypes.STRING,
    amount: DataTypes.FLOAT,
    currency: {
      type: DataTypes.STRING,
      defaultValue: 'USD'
    },
    beneficiary: DataTypes.STRING,
    paidby: DataTypes.STRING,
    tags: DataTypes.ARRAY(DataTypes.STRING),
    status: DataTypes.STRING,
    comment: DataTypes.STRING,
    link: DataTypes.STRING,

    approved: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },

    createdAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },
    approvedAt: DataTypes.DATE,
    reimbursedAt: DataTypes.DATE
  }, {
    getterMethods: {
      // Info.
      info: function() {
        return {
          id: this.id,
          type: this.type,
          description: this.description,
          amount: this.amount,
          currency: this.currency,
          beneficiary: this.beneficiary,
          paidby: this.paidby,
          tags: this.tags,
          status: this.status,
          comment: this.comment,
          link: this.link,
          approved: this.approved,
          createdAt: this.createdAt,
          approvedAt: this.approvedAt,
          reimbursedAt: this.reimbursedAt
        };
      }
    }
  });

  return Transaction;
};
<commit_msg>add userid field to the transaction info<commit_after>module.exports = function(Sequelize, DataTypes) {

  var Transaction = Sequelize.define('Transaction', {
    type: DataTypes.STRING,
    description: DataTypes.STRING,
    amount: DataTypes.FLOAT,
    currency: {
      type: DataTypes.STRING,
      defaultValue: 'USD'
    },
    beneficiary: DataTypes.STRING,
    paidby: DataTypes.STRING,
    tags: DataTypes.ARRAY(DataTypes.STRING),
    status: DataTypes.STRING,
    comment: DataTypes.STRING,
    link: DataTypes.STRING,

    approved: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },

    createdAt: {
      type: DataTypes.DATE,
      defaultValue: Sequelize.NOW
    },
    approvedAt: DataTypes.DATE,
    reimbursedAt: DataTypes.DATE
  }, {
    getterMethods: {
      // Info.
      info: function() {
        return {
          id: this.id,
          type: this.type,
          description: this.description,
          amount: this.amount,
          currency: this.currency,
          beneficiary: this.beneficiary,
          paidby: this.paidby,
          tags: this.tags,
          status: this.status,
          comment: this.comment,
          link: this.link,
          approved: this.approved,
          createdAt: this.createdAt,
          approvedAt: this.approvedAt,
          reimbursedAt: this.reimbursedAt,
          UserId: this.UserId
        };
      }
    }
  });

  return Transaction;
};
<|endoftext|>


<commit_before>import { Inject, Parameter } from '@jymfony/decorators' optional;
const AbstractRecursivePass = Jymfony.Component.DependencyInjection.Compiler.AbstractRecursivePass;
const Definition = Jymfony.Component.DependencyInjection.Definition;
const DIParameter = Jymfony.Component.DependencyInjection.Parameter;
const Reference = Jymfony.Component.DependencyInjection.Reference;

/**
 * @memberOf Jymfony.Component.DependencyInjection.Compiler
 */
export default class ResolveInjectDecoratorPass extends AbstractRecursivePass {
    process(container) {
        if (undefined === Inject || undefined === Parameter) {
            // @jymfony/decorators is not installed.
            return;
        }

        super.process(container);
    }

    /**
     * @inheritdoc
     */
    _processValue(value, isRoot = false) {
        if (! (value instanceof Definition)) {
            return super._processValue(value, isRoot);
        }

        const class_ = value.getClass();
        if (! ReflectionClass.exists(class_)) {
            return;
        }

        const reflClass = new ReflectionClass(class_);
        for (const field of reflClass.fields) {
            const reflField = reflClass.getField(field);
            for (const [ , annotation ] of reflField.metadata) {
                if (annotation instanceof Inject) {
                    value.addProperty(field, new Reference(annotation.serviceId, annotation.invalidBehavior));
                } else if (annotation instanceof Parameter) {
                    value.addProperty(field, new DIParameter(annotation.parameterName));
                }
            }
        }

        for (const property of reflClass.properties) {
            if (! reflClass.hasWritableProperty(property)) {
                continue;
            }

            const reflProperty = reflClass.getWritableProperty(property);
            for (const [ , annotation ] of reflProperty.metadata) {
                if (annotation instanceof Inject) {
                    value.addProperty(property, new Reference(annotation.serviceId, annotation.invalidBehavior));
                } else if (annotation instanceof Parameter) {
                    value.addProperty(property, new DIParameter(annotation.parameterName));
                }
            }
        }
    }
}
<commit_msg>[DependencyInjection] add missing return values in ResolveInjectDecoratorPass<commit_after>import { Inject, Parameter } from '@jymfony/decorators' optional;
const AbstractRecursivePass = Jymfony.Component.DependencyInjection.Compiler.AbstractRecursivePass;
const Definition = Jymfony.Component.DependencyInjection.Definition;
const DIParameter = Jymfony.Component.DependencyInjection.Parameter;
const Reference = Jymfony.Component.DependencyInjection.Reference;

/**
 * @memberOf Jymfony.Component.DependencyInjection.Compiler
 */
export default class ResolveInjectDecoratorPass extends AbstractRecursivePass {
    process(container) {
        if (undefined === Inject || undefined === Parameter) {
            // @jymfony/decorators is not installed.
            return;
        }

        super.process(container);
    }

    /**
     * @inheritdoc
     */
    _processValue(value, isRoot = false) {
        if (! (value instanceof Definition)) {
            return super._processValue(value, isRoot);
        }

        const class_ = value.getClass();
        if (! ReflectionClass.exists(class_)) {
            return value;
        }

        const reflClass = new ReflectionClass(class_);
        for (const field of reflClass.fields) {
            const reflField = reflClass.getField(field);
            for (const [ , annotation ] of reflField.metadata) {
                if (annotation instanceof Inject) {
                    value.addProperty(field, new Reference(annotation.serviceId, annotation.invalidBehavior));
                } else if (annotation instanceof Parameter) {
                    value.addProperty(field, new DIParameter(annotation.parameterName));
                }
            }
        }

        for (const property of reflClass.properties) {
            if (! reflClass.hasWritableProperty(property)) {
                continue;
            }

            const reflProperty = reflClass.getWritableProperty(property);
            for (const [ , annotation ] of reflProperty.metadata) {
                if (annotation instanceof Inject) {
                    value.addProperty(property, new Reference(annotation.serviceId, annotation.invalidBehavior));
                } else if (annotation instanceof Parameter) {
                    value.addProperty(property, new DIParameter(annotation.parameterName));
                }
            }
        }

        return value;
    }
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const path = require('path');
const es = require('event-stream');
const azure = require('gulp-azure-storage');
const vfs = require('vinyl-fs');
const util = require('../lib/util');
const root = path.dirname(path.dirname(__dirname));
const commit = util.getVersion(root);

// optionally allow to pass in explicit base/maps to upload
const args = process.argv.slice(2);
const base = args[0];
const maps = args[1];

const fetch = function (base, maps = `${base}/**/*.map`) {
	return vfs.src(maps, { base })
		.pipe(es.mapSync(f => {
			f.path = `${f.base}/core/${f.relative}`;
			return f;
		}));
};

function main() {
	const sources = [];

	// vscode client maps (default)
	if (!base) {
		const vs = fetch('out-vscode-min'); // client source-maps only
		sources.push(vs);

		const extensionsOut = vfs.src(['.build/extensions/**/*.js.map', '!**/node_modules/**'], { base: '.build' });
		sources.push(extensionsOut);
	}

	// specific client base/maps
	else {
		sources.push(fetch(base, maps));
	}

	return es.merge(...sources)
		.pipe(es.through(function (data) {
			console.log('Uploading Sourcemap', data.relative); // debug
			this.emit('data', data);
		}))
		.pipe(azure.upload({
			account: process.env.AZURE_STORAGE_ACCOUNT,
			key: process.env.AZURE_STORAGE_ACCESS_KEY,
			container: 'sourcemaps',
			prefix: commit + '/'
		}));
}

main();
<commit_msg>:lipstick:<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const path = require('path');
const es = require('event-stream');
const azure = require('gulp-azure-storage');
const vfs = require('vinyl-fs');
const util = require('../lib/util');
const root = path.dirname(path.dirname(__dirname));
const commit = util.getVersion(root);

// optionally allow to pass in explicit base/maps to upload
const [base, maps] = process.argv.slice(2);

const fetch = function (base, maps = `${base}/**/*.map`) {
	return vfs.src(maps, { base })
		.pipe(es.mapSync(f => {
			f.path = `${f.base}/core/${f.relative}`;
			return f;
		}));
};

function main() {
	const sources = [];

	// vscode client maps (default)
	if (!base) {
		const vs = fetch('out-vscode-min'); // client source-maps only
		sources.push(vs);

		const extensionsOut = vfs.src(['.build/extensions/**/*.js.map', '!**/node_modules/**'], { base: '.build' });
		sources.push(extensionsOut);
	}

	// specific client base/maps
	else {
		sources.push(fetch(base, maps));
	}

	return es.merge(...sources)
		.pipe(es.through(function (data) {
			console.log('Uploading Sourcemap', data.relative); // debug
			this.emit('data', data);
		}))
		.pipe(azure.upload({
			account: process.env.AZURE_STORAGE_ACCOUNT,
			key: process.env.AZURE_STORAGE_ACCESS_KEY,
			container: 'sourcemaps',
			prefix: commit + '/'
		}));
}

main();
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash');

const AtomicCounter = require('./atomic-counter.js');

class GlobalMembershipDescription extends AtomicCounter {
	static description() {
		return {
			"key": "global_membership_description"
		};
	}
	range() {
		if (!this.properties) return [];
		let len = "human-".length;
		let department = this.creation_params.department || false;

		return _.chain(this.properties.content)
			.filter(item => item.organization == department)
			.map('member')
			.map(item => item.slice(len, item.length))
			.value();
	}
	add(params, patchwerk) {
		//@NOTE: never use it without strong need
		//@NOTE: this method is fucking unsafe
		//@TODO: rework this ugly concept
		let id = params.id;
		let role = params.role || 'Operator';
		let organization = params.organization;

		this.properties.content.push({
			"@type": "Membership",
			"@id": "membership-" + this.properties.content.length,
			"member": id,
			"organization": organization,
			"role": role
		});

		return patchwerk.save(this)
	}
	inc() {
		throw new Error('not implemented');
	}
}

module.exports = GlobalMembershipDescription;
<commit_msg>to avoid "cannot read property" error<commit_after>'use strict'

const _ = require('lodash');

const AtomicCounter = require('./atomic-counter.js');

class GlobalMembershipDescription extends AtomicCounter {
	static description() {
		return {
			"key": "global_membership_description"
		};
	}
	range() {
		if (!this.properties) return [];
		let len = "human-".length;
		let department = this.creation_params && this.creation_params.department || false;

		return _.chain(this.properties.content)
			.filter(item => item.organization == department)
			.map('member')
			.map(item => item.slice(len, item.length))
			.value();
	}
	add(params, patchwerk) {
		//@NOTE: never use it without strong need
		//@NOTE: this method is fucking unsafe
		//@TODO: rework this ugly concept
		let id = params.id;
		let role = params.role || 'Operator';
		let organization = params.organization;

		this.properties.content.push({
			"@type": "Membership",
			"@id": "membership-" + this.properties.content.length,
			"member": id,
			"organization": organization,
			"role": role
		});

		return patchwerk.save(this)
	}
	inc() {
		throw new Error('not implemented');
	}
}

module.exports = GlobalMembershipDescription;<|endoftext|>


<commit_before>;(function(window, undefined) {
  var arrProto = window.Array.prototype,
      def = window.Object.defineProperty,
      defs = window.Object.defineProperties,
      getObjKeys = window.Object.keys,
      isArray = window.Array.isArray;
  function toArray(obj) {
    return arrProto.slice.call(obj);
  }
  function runWithScope(code, scope) {
    return (new Function('with(this) {return (' + code + ');}')).call(scope);
  }
  function differ($A, $B) {
    if ($A.innerHTML === $B.innerHTML) return;
    var $a, $b, needBind = false;
    if ($A.childNodes.length !== $B.childNodes.length) {
      $A.innerHTML = $B.innerHTML;
      needBind = true;
    } else {
      for (var i = 0, l = $B.childNodes.length; i < l; i++) {
        $a = $A.childNodes[i];
        $b = $B.childNodes[i];
        if ($a.childNodes.length > 1) {
          differ($a, $b);
          continue;
        }
        if ($a.innerHTML !== $b.innerHTML) {
          $a.innerHTML = $b.innerHTML;
          if ($a.querySelectorAll('[oscar-bind]').length || $a.querySelectorAll('[oscar-bind]').length) {
            needBind = true;
          }
        } else {
          if ($a.innerHTML === undefined) {
            if ($a.textContent !== $b.textContent) {
              $a.textContent = $b.textContent;
            }
          }
        }
        if ($a.value !== $b.value) {
          $a.value = $b.value;
        }
      }
    }
    return needBind;
  }
  var Model = (function() {
    function Model(obj) {
      this.$el = obj.$el;
      this.tpl = obj.tpl;
      this.data = obj.data;
      this.inited = obj.inited || false;
      this.eventObj = {};
    }
    var proto = Model.prototype;
    proto.on = function(e, cbk) {
      var self = this;
      if (self.eventObj[e] === undefined) {
        self.eventObj[e] = [];
      }
      self.eventObj[e].push(cbk);
    };
    proto.trigger = function(e) {
      var self = this;
      getObjKeys(self.eventObj).forEach(function(k) {
        if (k === e) {
          self.eventObj[k].forEach(function(cbk) {
            cbk.call(self);
          });
        }
      });
    };
    proto.watch = function(e, cbk) {
      var self = this;
      self.on('set:' + e, cbk);
      self.on('change:' + e, cbk);
      cbk();
    };
    proto.render = function() {
      var self = this,
          $tmp = window.document.createElement('div'),
          html = window.shani.compile(self.tpl.replace(/>/g, '>').replace(/</g, '<').replace(new RegExp("'", 'g'), "\\'"))(self.data),
          needBind = false,
          $classes,
          $binds,
          $actions;
      $tmp.innerHTML = html;
      if (!self.inited) {
        self.$el.innerHTML = html;
        self.$el.style.display = 'block';
      } else {
        needBind = differ(self.$el, $tmp);
      }
      needBind = needBind || !self.inited;
      $classes = toArray(self.$el.querySelectorAll('[oscar-class]'));
      $binds = toArray(self.$el.querySelectorAll('[oscar-bind]'));
      $actions = toArray(self.$el.querySelectorAll('[oscar-action]'));
      // oscar-class
      $classes.forEach(function($c, i) {
        var cc = $c.getAttribute('oscar-class'),
            ccl;
        try {
          cc = cc.replace(new window.RegExp("'", 'g'), '"');
          ccl = runWithScope(cc, self.data);
        } catch(err) {
          console.log(err);
          return;
        }
        getObjKeys(ccl).forEach(function(cls) {
          if (ccl[cls] === true) {
            $c.classList.add(cls);
          } else {
            $c.classList.remove(cls);
          }
        });
      });
      // oscar-class end
      // oscar-bind
      $binds.forEach(function($b, i) {
        var bc = $b.getAttribute('oscar-bind'),
            c = '',
            bcl;
        bc = bc.replace(/(\[|\])/g, '.');
        if (bc.lastIndexOf('.') === bc.length - 1) {
          bc = bc.substr(0, bc.length - 1);
        }
        bcl = bc.split('.');
        for (var x in bcl) {
          if (!bcl.hasOwnProperty(x)) continue;
          c += '[\'' + bcl[x] + '\']';
        }
        var s = '(self.data' + c + ' = this.value)';
        var eventType = 'input';
        if ($b.type === 'radio') {
          eventType = 'change';
        }
        if ($b.type === 'radio' && eval('(self.data' + c + ' === $b.value)')) {
          $b.checked = true;
        }
        if (!needBind) return;
        $b.addEventListener(eventType, function() {
          eval(s);
        });
      });
      // oscar-bind end
      // oscar-action
      if (!needBind) return;
      $actions.forEach(function($a, i) {
        var ac = $a.getAttribute('oscar-action'),
            acl = /(\w+):(.*)/g.exec(ac);
        if (acl.length !== 3) return;
        $a.addEventListener(acl[1], function() {
          runWithScope(acl[2], self.data);
        });
      });
      // oscar-action end
      self.inited = true;
    };
    return Model;
  })();
  window.Oscar = (function() {
    function Oscar() {
      this.modelList = [];
      this.__init__();
    }
    var proto = Oscar.prototype;
    proto.__init__ = function() {
    };
    proto.buildArray = function(arr, model) {
      var self = this,
          args;
      ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(function(method) {
        arr[method] = function() {
          args = toArray(arguments);
          _args = toArray(arguments);
          if (method === 'splice') {
            var subArgs = args.slice(2);
            self.buildObj([subArgs], model);
            args = args.slice(0, 2);
            arrProto.push.apply(args, subArgs);
          } else {
            self.buildObj(args, model);
          }
          arrProto[method].apply(this, args);
          arrProto[method].apply(this.__c__, _args);
          self.buildObj(this, model);
          if (model !== undefined) {
            model.render();
          }
        };
      });
      self.buildObj(arr, model);
    };
    proto.buildObj = function(obj, model) {
      var self = this,
          properties = {};
      if (obj.__c__ === undefined) {
        if (isArray(obj)) {
          obj.__c__ = [];
        } else {
          obj.__c__ = {};
        }
      }
      getObjKeys(obj).forEach(function(k) {
        if (k === '__c__') return;
        if (typeof obj[k] === 'function') return;
        obj.__c__[k] = obj[k];
        if (obj[k].constructor === window.Array) {
          self.buildArray(obj[k], model);
        }
        if (obj[k].constructor === window.Object) {
          self.buildObj(obj[k], model);
        }
        properties[k] = {
          get: function() {
            return this.__c__[k];
          },
          set: function(v) {
            switch(v.constructor) {
              case window.Array:
                self.buildArray(v, model);
                break;
              case window.Object:
                self.buildObj(v, model);
                break;
            }
            this.__c__[k] = v;
            if (model !== undefined) {
              model.trigger('change:' + k);
              model.render();
            }
          }
        }
        if (model !== undefined) {
          model.trigger('set:' + k);
        }
      });
      defs(obj, properties);
    };
    proto.modelRegister = function(obj) {
      if (typeof obj !== 'object' || typeof obj.el !== 'string' ||  typeof obj.data !== 'object') {
        throw new Error('invalid model type');
      }
      var $els = window.document.querySelectorAll(obj.el);
      if (!$els.length) {
        throw new Error('cannot find the element');
      }
      var $el = $els[0],
          $binds = toArray($el.querySelectorAll('[oscar-bind]')),
          model;
      $binds.forEach(function($b) {
        var v = $b.getAttribute('oscar-bind');
        $b.getAttribute('value') || $b.setAttribute('value', '{{' + v + '}}');
      });
      model = new Model({
        $el: $el,
        tpl: $el.innerHTML,
        data: obj.data
      });
      this.buildObj(model.data, model);
      this.modelList.push(model);
      model.render();
      return model;
    };
    proto.watcher = function() {
      var self = this;
      self.modelList.forEach(function(model) {
        model.render();
      });
    };
    return Oscar;
  })();
})(window);
<commit_msg>refactor<commit_after>;(function(window, undefined) {
  var arrProto = window.Array.prototype,
      def = window.Object.defineProperty,
      defs = window.Object.defineProperties,
      getObjKeys = window.Object.keys,
      isArray = window.Array.isArray;
  function toArray(obj) {
    return arrProto.slice.call(obj);
  }
  function runWithScope(code, scope) {
    return (new Function('with(this) {return (' + code + ');}')).call(scope);
  }
  function differ($A, $B) {
    if ($A.innerHTML === $B.innerHTML) {
      return false;
    }
    if ($A.childNodes.length !== $B.childNodes.length) {
      $A.innerHTML = $B.innerHTML;
      return true;
    }
    var $a, $b, needBind = false;
    for (var i = 0, l = $B.childNodes.length; i < l; i++) {
      $a = $A.childNodes[i];
      $b = $B.childNodes[i];
      if ($a.childNodes.length > 1) {
        differ($a, $b);
        continue;
      }
      if ($a.innerHTML !== $b.innerHTML) {
        $a.innerHTML = $b.innerHTML;
        if ($a.querySelectorAll('[oscar-bind]').length || $a.querySelectorAll('[oscar-bind]').length) {
          needBind = true;
        }
      } else {
        if ($a.innerHTML === undefined && $a.textContent !== $b.textContent) {
            $a.textContent = $b.textContent;
        }
      }
      if ($a.value !== $b.value) {
        $a.value = $b.value;
      }
    }
    return needBind;
  }
  var Model = (function() {
    function Model(obj) {
      this.$el = obj.$el;
      this.tpl = obj.tpl;
      this.data = obj.data;
      this.inited = obj.inited || false;
      this.eventObj = {};
    }
    var proto = Model.prototype;
    proto.on = function(e, cbk) {
      var self = this;
      if (self.eventObj[e] === undefined) {
        self.eventObj[e] = [];
      }
      self.eventObj[e].push(cbk);
    };
    proto.trigger = function(e) {
      var self = this;
      getObjKeys(self.eventObj).forEach(function(k) {
        if (k === e) {
          self.eventObj[k].forEach(function(cbk) {
            cbk.call(self);
          });
        }
      });
    };
    proto.watch = function(e, cbk) {
      var self = this;
      self.on('set:' + e, cbk);
      self.on('change:' + e, cbk);
      cbk();
    };
    proto.render = function() {
      var self = this,
          $tmp = window.document.createElement('div'),
          html = window.shani.compile(self.tpl.replace(/>/g, '>').replace(/</g, '<').replace(new RegExp("'", 'g'), "\\'"))(self.data),
          needBind = false,
          $classes,
          $binds,
          $actions;
      $tmp.innerHTML = html;
      if (!self.inited) {
        self.$el.innerHTML = html;
        self.$el.style.display = 'block';
      } else {
        needBind = differ(self.$el, $tmp);
      }
      needBind = needBind || !self.inited;
      $classes = toArray(self.$el.querySelectorAll('[oscar-class]'));
      $binds = toArray(self.$el.querySelectorAll('[oscar-bind]'));
      $actions = toArray(self.$el.querySelectorAll('[oscar-action]'));
      // oscar-class
      $classes.forEach(function($c, i) {
        var cc = $c.getAttribute('oscar-class'),
            ccl;
        try {
          cc = cc.replace(new window.RegExp("'", 'g'), '"');
          ccl = runWithScope(cc, self.data);
        } catch(err) {
          console.log(err);
          return;
        }
        getObjKeys(ccl).forEach(function(cls) {
          if (ccl[cls] === true) {
            $c.classList.add(cls);
          } else {
            $c.classList.remove(cls);
          }
        });
      });
      // oscar-class end
      // oscar-bind
      $binds.forEach(function($b, i) {
        var bc = $b.getAttribute('oscar-bind'),
            c = '',
            bcl;
        bc = bc.replace(/(\[|\])/g, '.');
        if (bc.lastIndexOf('.') === bc.length - 1) {
          bc = bc.substr(0, bc.length - 1);
        }
        bcl = bc.split('.');
        for (var x in bcl) {
          if (!bcl.hasOwnProperty(x)) continue;
          c += '[\'' + bcl[x] + '\']';
        }
        var s = '(self.data' + c + ' = this.value)';
        var eventType = 'input';
        if ($b.type === 'radio') {
          eventType = 'change';
        }
        if ($b.type === 'radio' && eval('(self.data' + c + ' === $b.value)')) {
          $b.checked = true;
        }
        if (!needBind) return;
        $b.addEventListener(eventType, function() {
          eval(s);
        });
      });
      // oscar-bind end
      // oscar-action
      if (!needBind) return;
      $actions.forEach(function($a, i) {
        var ac = $a.getAttribute('oscar-action'),
            acl = /(\w+):(.*)/g.exec(ac);
        if (acl.length !== 3) return;
        $a.addEventListener(acl[1], function() {
          runWithScope(acl[2], self.data);
        });
      });
      // oscar-action end
      self.inited = true;
    };
    return Model;
  })();
  window.Oscar = (function() {
    function Oscar() {
      this.modelList = [];
      this.__init__();
    }
    var proto = Oscar.prototype;
    proto.__init__ = function() {
    };
    proto.buildArray = function(arr, model) {
      var self = this,
          args;
      ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(function(method) {
        arr[method] = function() {
          args = toArray(arguments);
          _args = toArray(arguments);
          if (method === 'splice') {
            var subArgs = args.slice(2);
            self.buildObj([subArgs], model);
            args = args.slice(0, 2);
            arrProto.push.apply(args, subArgs);
          } else {
            self.buildObj(args, model);
          }
          arrProto[method].apply(this, args);
          arrProto[method].apply(this.__c__, _args);
          self.buildObj(this, model);
          if (model !== undefined) {
            model.render();
          }
        };
      });
      self.buildObj(arr, model);
    };
    proto.buildObj = function(obj, model) {
      var self = this,
          properties = {};
      if (obj.__c__ === undefined) {
        if (isArray(obj)) {
          obj.__c__ = [];
        } else {
          obj.__c__ = {};
        }
      }
      getObjKeys(obj).forEach(function(k) {
        if (k === '__c__') return;
        if (typeof obj[k] === 'function') return;
        obj.__c__[k] = obj[k];
        if (obj[k].constructor === window.Array) {
          self.buildArray(obj[k], model);
        }
        if (obj[k].constructor === window.Object) {
          self.buildObj(obj[k], model);
        }
        properties[k] = {
          get: function() {
            return this.__c__[k];
          },
          set: function(v) {
            switch(v.constructor) {
              case window.Array:
                self.buildArray(v, model);
                break;
              case window.Object:
                self.buildObj(v, model);
                break;
            }
            this.__c__[k] = v;
            if (model !== undefined) {
              model.trigger('change:' + k);
              model.render();
            }
          }
        }
        if (model !== undefined) {
          model.trigger('set:' + k);
        }
      });
      defs(obj, properties);
    };
    proto.modelRegister = function(obj) {
      if (typeof obj !== 'object' || typeof obj.el !== 'string' ||  typeof obj.data !== 'object') {
        throw new Error('invalid model type');
      }
      var $els = window.document.querySelectorAll(obj.el);
      if (!$els.length) {
        throw new Error('cannot find the element');
      }
      var $el = $els[0],
          $binds = toArray($el.querySelectorAll('[oscar-bind]')),
          model;
      $binds.forEach(function($b) {
        var v = $b.getAttribute('oscar-bind');
        $b.getAttribute('value') || $b.setAttribute('value', '{{' + v + '}}');
      });
      model = new Model({
        $el: $el,
        tpl: $el.innerHTML,
        data: obj.data
      });
      this.buildObj(model.data, model);
      this.modelList.push(model);
      model.render();
      return model;
    };
    proto.watcher = function() {
      var self = this;
      self.modelList.forEach(function(model) {
        model.render();
      });
    };
    return Oscar;
  })();
})(window);
<|endoftext|>


<commit_before>/*
 * patternlab-node - v0.10.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

(function () {
  'use strict';

  var path = require('path');

  // list of supported pattern engines
  var supportedPatternEngineNames = [
    'mustache',
    'handlebars'
  ];

  // mapping of file extensions to engine names, for lookup use
  var engineNameForExtension = {};

  // Object/hash of all loaded pattern engines, empty at first.
  // My intention here is to make this return an object that can be used to
  // obtain any loaded PatternEngine by addressing them like this:
  //
  // var PatternEngines = require('./pattern_engines/pattern_engines');
  // var Mustache = PatternEngines['mustache'];
  //
  var PatternEngines = Object.create({
    supportedPatternEngineNames: supportedPatternEngineNames,

    getEngineNameForPattern: function (pattern) {
      // avoid circular dependency by putting this in here. TODO: is this slow?
      var of = require('../object_factory');

      if (pattern instanceof of.oPattern && typeof pattern.fileExtension === 'string' && pattern.fileExtension) {
        return engineNameForExtension[pattern.fileExtension];
      }
      // otherwise, assume it's a plain mustache template string and act
      // accordingly
      return 'mustache';
    },

    getEngineForPattern: function (pattern) {
      if (pattern.isPseudoPattern) {
        return this.getEngineForPattern(pattern.basePattern);
      } else {
        var engineName = this.getEngineNameForPattern(pattern);
        return this[engineName];
      }
    },

    getSupportedFileExtensions: function () {
      var engineNames = Object.keys(PatternEngines);
      return engineNames.map(function (engineName) {
        return PatternEngines[engineName].engineFileExtension;
      });
    },

    isFileExtensionSupported: function (fileExtension) {
      var supportedExtensions = PatternEngines.getSupportedFileExtensions();
      return (supportedExtensions.lastIndexOf(fileExtension) !== -1);
    },

    // given a filename, return a boolean: whether or not the filename indicates
    // that the file is pseudopattern JSON
    isPseudoPatternJSON: function (filename) {
      var extension = path.extname(filename);
      return (extension === '.json' && filename.indexOf('~') > -1);
    },

    // takes a filename string, not a full path; a basename (plus extension)
    // ignore _underscored patterns, dotfiles, and anything not recognized by a
    // loaded pattern engine. Pseudo-pattern .json files ARE considered to be
    // pattern files!
    isPatternFile: function (filename) {
      // skip hidden patterns/files without a second thought
      var extension = path.extname(filename);
      if(filename.charAt(0) === '.' ||
         filename.charAt(0) === '_' ||
         (extension === '.json' && !PatternEngines.isPseudoPatternJSON(filename))) {
        return false;
      }

      // not a hidden pattern, let's dig deeper
      var supportedPatternFileExtensions = PatternEngines.getSupportedFileExtensions();
      return (supportedPatternFileExtensions.lastIndexOf(extension) !== -1 ||
             PatternEngines.isPseudoPatternJSON(filename));
    }
  });

  // try to load all supported engines
  (function loadAllEngines() {
    supportedPatternEngineNames.forEach(function (engineName) {
      try {
        PatternEngines[engineName] = require('./engine_' + engineName);
      } catch (err) {
        console.log(err, 'pattern engine "' + engineName + '" not loaded. Did you install its dependency with npm?');
      }
    });
  })();

  // produce a mapping between file extension and engine name for each of the
  // loaded engines
  engineNameForExtension = (function () {
    var mapping = {};

    Object.keys(PatternEngines).forEach(function (engineName) {
      var extensionForEngine = PatternEngines[engineName].engineFileExtension;
      mapping[extensionForEngine] = engineName;
    });

    return mapping;
  })();

  module.exports = PatternEngines;
})();
<commit_msg>Generate the list of supported pattern engines based on the presence to real plugin files rather than a hard-coded list. Also, better organize the PatternEngine setup functions to be cleaner, more functional and more testable<commit_after>/*
 * patternlab-node - v0.10.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

(function () {
  'use strict';

  var path = require('path');
  var diveSync = require('diveSync');
  var engineMatcher = /^engine_(.*)\.js/;
  var enginesDirectory = __dirname;

  var PatternEngines; // the main export object
  var engineNameForExtension; // generated mapping of extension to engine name

  // free private functions, for internal setup only

  function findSupportedPatternEngineNames() {
    var foundPatternEngineNames = [];

    console.log('patternEngines: begin diveSync ====================');

    // find
    diveSync(enginesDirectory, {
      recursive: false,
      filter: function (filePath, dir) {
        var baseName = path.basename(filePath),
            engineMatch = baseName.match(engineMatcher);

        if (dir || engineMatch !== null) { return true; }
        return false;
      }
    }, function (err, filePath) {
      if (err) { throw err; }
      var baseName = path.basename(filePath),
          engineMatch = baseName.match(engineMatcher),
          foundEngineName = engineMatch[1];

      console.log('patternEngines: FOUND ENGINE', foundEngineName);
      foundPatternEngineNames.push(foundEngineName);
    });

    return foundPatternEngineNames;
  }

  // try to load all supported engines
  function loadAllEngines(enginesObject) {
    enginesObject.supportedPatternEngineNames.forEach(function (engineName) {
      try {
        enginesObject[engineName] = require('./engine_' + engineName);
      } catch (err) {
        console.log(err, 'pattern engine "' + engineName + '" not loaded. Did you install its dependency with npm?');
      }
    });
  }

  // produce a mapping between file extension and engine name for each of the
  // loaded engines
  function createFileExtensionToEngineNameMap(enginesObject) {
    var mapping = {};

    Object.keys(enginesObject).forEach(function (engineName) {
      var extensionForEngine = enginesObject[engineName].engineFileExtension;
      mapping[extensionForEngine] = engineName;
    });

    return mapping;
  }

  //
  // PatternEngines: the main export of this module
  //
  // It's an Object/hash of all loaded pattern engines, empty at first.  My
  // intention here is to make this return an object that can be used to obtain
  // any loaded PatternEngine by addressing them like this:
  //
  //   var PatternEngines = require('./pattern_engines/pattern_engines');
  //   var Mustache = PatternEngines['mustache'];
  //
  // Object.create lets us create an object with a specified prototype. We want
  // this here because we would like the object's "own properties" to include
  // only the engine names so we can easily iterate over them; all the handy
  // methods and properites below should therefore be on its prototype.

  PatternEngines = Object.create({
    // build the list of supported pattern engines based on what plugins we have
    // in the pattern_engines directory
    supportedPatternEngineNames: findSupportedPatternEngineNames(),

    getEngineNameForPattern: function (pattern) {
      // avoid circular dependency by putting this in here. TODO: is this slow?
      var of = require('../object_factory');

      if (pattern instanceof of.oPattern && typeof pattern.fileExtension === 'string' && pattern.fileExtension) {
        return engineNameForExtension[pattern.fileExtension];
      }
      // otherwise, assume it's a plain mustache template string and act
      // accordingly
      return 'mustache';
    },

    getEngineForPattern: function (pattern) {
      if (pattern.isPseudoPattern) {
        return this.getEngineForPattern(pattern.basePattern);
      } else {
        var engineName = this.getEngineNameForPattern(pattern);
        return this[engineName];
      }
    },

    getSupportedFileExtensions: function () {
      var engineNames = Object.keys(PatternEngines);
      return engineNames.map(function (engineName) {
        return PatternEngines[engineName].engineFileExtension;
      });
    },

    isFileExtensionSupported: function (fileExtension) {
      var supportedExtensions = PatternEngines.getSupportedFileExtensions();
      return (supportedExtensions.lastIndexOf(fileExtension) !== -1);
    },

    // given a filename, return a boolean: whether or not the filename indicates
    // that the file is pseudopattern JSON
    isPseudoPatternJSON: function (filename) {
      var extension = path.extname(filename);
      return (extension === '.json' && filename.indexOf('~') > -1);
    },

    // takes a filename string, not a full path; a basename (plus extension)
    // ignore _underscored patterns, dotfiles, and anything not recognized by a
    // loaded pattern engine. Pseudo-pattern .json files ARE considered to be
    // pattern files!
    isPatternFile: function (filename) {
      // skip hidden patterns/files without a second thought
      var extension = path.extname(filename);
      if(filename.charAt(0) === '.' ||
         filename.charAt(0) === '_' ||
         (extension === '.json' && !PatternEngines.isPseudoPatternJSON(filename))) {
        return false;
      }

      // not a hidden pattern, let's dig deeper
      var supportedPatternFileExtensions = PatternEngines.getSupportedFileExtensions();
      return (supportedPatternFileExtensions.lastIndexOf(extension) !== -1 ||
             PatternEngines.isPseudoPatternJSON(filename));
    }
  });

  // load up the engines we found
  loadAllEngines(PatternEngines);

  // mapping of file extensions to engine names, for lookup use
  engineNameForExtension = createFileExtensionToEngineNameMap(PatternEngines);

  module.exports = PatternEngines;
})();
<|endoftext|>