<commit_before>'use strict';

// Advents controller
angular.module('advents').controller('AdventsController', ['$scope', '$stateParams', '$location', 'Advents',
	function($scope, $stateParams, $location, Advents) {

        //MODAL TO OPEN ADVENT - USE GUARDIAN AS A TEMPLATE

		// Create new Advent
		$scope.create = function() {
			// Create new Advent object
			var advent = new Advents ({
				name: this.name,
				date:{
					day: this.day,
					month: this.month,
					year: this.year
				},
				description: this.description
			});

			// Redirect after save
			advent.$save(function(response) {
				$location.path('advents/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Advent
		$scope.remove = function(advent) {
			if ( advent ) {
				advent.$remove();

				for (var i in $scope.advents) {
					if ($scope.advents [i] === advent) {
						$scope.advents.splice(i, 1);
					}
				}
			} else {
				$scope.advent.$remove(function() {
					$location.path('advents');
				});
			}
		};

		// Update existing Advent
		$scope.update = function() {
			var advent = $scope.advent;

			advent.$update(function() {
				$location.path('advents/' + advent._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Advents
		$scope.find = function() {
			$scope.advents = Advents.query();
		};

		// Find existing Advent
		$scope.findOne = function() {
            $scope.advent = Advents.get({
                adventId: $stateParams.adventId
            });
        };
	}
]);

// Advents controller
angular.module('advents').controller('AdventsAttendModalController', ['$scope', '$http', '$stateParams', '$location', 'Advents', 'Children', 'Attendances',
    //CREATE ATTENDANCE ENTRY WHEN THIS FUNCTION IS CALLED
    //PASS IN - EVENT ID, CHILD ID
    function($scope, $http, $stateParams, $location, Advents, Children, Attendances) {

        this.processEvent = function (child, advent) {
            console.log(advent);
            var attendance;
            if(child.attending){
                //child is not attending event now, delete attendance
                console.log('deleteing attendance');
                console.log(child.attendance);
                if(child.attendance) {
                    attendance = child.attendance;
                    if ( attendance ) {
                        console.log('Attendance Before Remove');
                        console.log(attendance);
                        //GETTING THE ATTENDANCE
                        $http.get('/attendances/' + attendance._id).
                            success(function (data) {
                                console.log(data);
                                $scope.removingThisAttend = data;
                            }).then(function() {
                                console.log('complete');
                                $scope.removingThisAttend.$remove();
                        });
                    }else{
                        console.log('doesn\'t exist');
                    }
                }

            }else{
                //child is attending now, create attendance
                console.log('creating attendance');

                attendance = new Attendances({
                    childID: child._id,
                    childName: child.firstName + ' ' + child.lastName,
                    date: {
                        day: advent.date.day,
                        month: advent.date.month,
                        year: advent.date.year
                    },
                    adventB: true,
                    adventID: advent._id
                });
                console.log(attendance);
                attendance.$save();
            }
        };

        $scope.init = function (adventID) {
            //Get the Advent
            /*$scope.advent = Advents.get({
             adventId: $stateParams.adventIdForAttendance
             });*/

            console.log($scope);
            //Get the Calendar information
            $http.get('/calendar/' + adventID).
                success(function (data) {
                    console.log(data);
                    $scope.attendancesForAdvent = data;

                    $http.get('/children/').
                        success(function (data) {
                            console.log(data);
                            $scope.children = data;
                        }).then(function () {
                            console.log('complete');
                            for (var i in $scope.children) {
                                for (var j in $scope.attendancesForAdvent) {
                                    if ($scope.children[i]._id === $scope.attendancesForAdvent[j].childID) {
                                        console.log($scope.children[i].firstName + ' ' + $scope.children[i].lastName + ' is attending this event already');
                                        $scope.children[i].attending = true;
                                        $scope.children[i].attendance = $scope.attendancesForAdvent[j];
                                    }
                                }
                            }

                        });
                });
        };

        $scope.advents = Advents.query();
        $scope.attendances = Attendances.query();
    }

]);
<commit_msg>Delete Attendance from Event, after reloading modal<commit_after>'use strict';

// Advents controller
angular.module('advents').controller('AdventsController', ['$scope', '$stateParams', '$location', 'Advents',
	function($scope, $stateParams, $location, Advents) {

        //MODAL TO OPEN ADVENT - USE GUARDIAN AS A TEMPLATE

		// Create new Advent
		$scope.create = function() {
			// Create new Advent object
			var advent = new Advents ({
				name: this.name,
				date:{
					day: this.day,
					month: this.month,
					year: this.year
				},
				description: this.description
			});

			// Redirect after save
			advent.$save(function(response) {
				$location.path('advents/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Advent
		$scope.remove = function(advent) {
			if ( advent ) {
				advent.$remove();

				for (var i in $scope.advents) {
					if ($scope.advents [i] === advent) {
						$scope.advents.splice(i, 1);
					}
				}
			} else {
				$scope.advent.$remove(function() {
					$location.path('advents');
				});
			}
		};

		// Update existing Advent
		$scope.update = function() {
			var advent = $scope.advent;

			advent.$update(function() {
				$location.path('advents/' + advent._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Advents
		$scope.find = function() {
			$scope.advents = Advents.query();
		};

		// Find existing Advent
		$scope.findOne = function() {
            $scope.advent = Advents.get({
                adventId: $stateParams.adventId
            });
        };
	}
]);

// Advents controller
angular.module('advents').controller('AdventsAttendModalController', ['$scope', '$http', '$stateParams', '$location', 'Advents', 'Children', 'Attendances',
    //CREATE ATTENDANCE ENTRY WHEN THIS FUNCTION IS CALLED
    //PASS IN - EVENT ID, CHILD ID
    function($scope, $http, $stateParams, $location, Advents, Children, Attendances) {

        this.processEvent = function (child, advent) {
            console.log(advent);
            var attendance;
            if(child.attending){
                //child is not attending event now, delete attendance
                console.log('deleteing attendance');
                if(child.attendance) {
                    attendance = child.attendance;
                    if ( attendance ) {
                        $http.delete('/attendances/' + attendance._id).
                            success(function (data) {
                                console.log(data);
                            });
                    }else{
                        console.log('doesn\'t exist');
                    }
                }

            }else{
                //child is attending now, create attendance
                console.log('creating attendance');

                attendance = new Attendances({
                    childID: child._id,
                    childName: child.firstName + ' ' + child.lastName,
                    date: {
                        day: advent.date.day,
                        month: advent.date.month,
                        year: advent.date.year
                    },
                    adventB: true,
                    adventID: advent._id
                });
                attendance.$save();
                console.log(attendance);
                child.attendence = attendance;
            }
        };

        $scope.init = function (adventID) {
            //Get the Advent
            /*$scope.advent = Advents.get({
             adventId: $stateParams.adventIdForAttendance
             });*/

            console.log($scope);
            //Get the Calendar information
            $http.get('/calendar/' + adventID).
                success(function (data) {
                    console.log(data);
                    $scope.attendancesForAdvent = data;

                    $http.get('/children/').
                        success(function (data) {
                            console.log(data);
                            $scope.children = data;
                        }).then(function () {
                            console.log('complete');
                            for (var i in $scope.children) {
                                for (var j in $scope.attendancesForAdvent) {
                                    if ($scope.children[i]._id === $scope.attendancesForAdvent[j].childID) {
                                        console.log($scope.children[i].firstName + ' ' + $scope.children[i].lastName + ' is attending this event already');
                                        $scope.children[i].attending = true;
                                        $scope.children[i].attendance = $scope.attendancesForAdvent[j];
                                    }
                                }
                            }

                        });
                });
        };

        $scope.advents = Advents.query();
        $scope.attendances = Attendances.query();
    }

]);
<|endoftext|>


<commit_before>'use strict'

function FPSControls(camera) {
    this.__init__(camera)
}

FPSControls.prototype = {
    camera       : null,
    pitch        : null,
    yaw          : null,
    half_pie     : null,
    enabled      : null,

    // Movement.
    forward      : null,
    backward     : null,
    left         : null,
    right        : null,
    velocity     : null,
    acceleration : null,

    __init__: function (camera) {
        this.half_pie = Math.PI / 2

        this.camera = camera
        this.camera.rotation.set(0, 0, 0)

        this.pitch = new THREE.Object3D()
        this.pitch.add(camera)

        this.yaw = new THREE.Object3D()
        this.yaw.position.y = 5
        this.yaw.add(this.pitch)

        this.enabled = false

        this.velocity = new THREE.Vector3()

        document.addEventListener('mousemove', this.on_mouse_move.bind(this), false)
        document.addEventListener('keydown', this.on_key_down.bind(this), false)
        document.addEventListener('keyup', this.on_key_up.bind(this), false)
    },

    physics: function(delta) {
        if (this.enabled) {
            if (this.forward) {
                this.velocity.z -= 400.0 * delta
            }
            if (this.backward) {
                this.velocity.z += 400.0 * delta
            }
            if (this.left) {
                this.velocity.x -= 400.0 * delta
            }
            if (this.right) {
                this.velocity.x += 400.0 * delta
            }
            this.velocity.x -= this.velocity.x * 10.0 * delta
            this.velocity.z -= this.velocity.z * 10.0 * delta
            this.yaw.translateX(this.velocity.x * delta)
            this.yaw.translateY(this.velocity.y * delta)
            this.yaw.translateZ(this.velocity.z * delta)
        }
    },

    enable: function() {
        this.enabled = true
    },

    disable: function() {
        this.enabled = false
    },

    on_key_down: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.forward = true
            break
        case 37: // left
        case 65: // a
            this.left = true
            break
        case 40: // down
        case 83: // s
            this.down = true
            break
        case 39: // right
        case 68: // d
            this.right = true
            break
        }
    },

    on_key_up: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.forward = false
            break
        case 37: // left
        case 65: // a
            this.left = false
            break
        case 40: // down
        case 83: // s
            this.down = false
            break
        case 39: // right
        case 68: // d
            this.right = false
            break
        }
    },

    on_mouse_move: function(event) {
        if (this.enabled) {
            var movement_x = event.movementX || event.mozMovementX || event.webkitMovementX || 0
            var movement_y = event.movementY || event.mozMovementY || event.webkitMovementY || 0

            this.yaw.rotation.y -= movement_x * 0.002
            this.pitch.rotation.x -= movement_y * 0.002

            this.pitch.rotation.x = Math.max( - this.half_pie, Math.min( this.half_pie, this.pitch.rotation.x))
        }
    },

    get_object: function() {
        return this.yaw
    },

    get_direction: function() {
        var direction = new THREE.Vector3(0, 0, -1)
        var rotation  = new THREE.Euler(0, 0, 0, 'YXZ')
        return function( v ) {
            rotation.set( this.pitch.rotation.x, this.yaw.rotation.y, 0 )
            v.copy(direction).applyEuler(rotation)
            return v
        }
    }
}<commit_msg>js testing and debugging 43<commit_after>'use strict'

function FPSControls(camera) {
    this.__init__(camera)
}

FPSControls.prototype = {
    camera       : null,
    pitch        : null,
    yaw          : null,
    half_pie     : null,
    enabled      : null,

    // Movement.
    up           : null,
    down         : null,
    left         : null,
    right        : null,
    velocity     : null,
    acceleration : null,

    __init__: function (camera) {
        this.half_pie = Math.PI / 2

        this.camera = camera
        this.camera.rotation.set(0, 0, 0)

        this.pitch = new THREE.Object3D()
        this.pitch.add(camera)

        this.yaw = new THREE.Object3D()
        this.yaw.position.y = 5
        this.yaw.add(this.pitch)

        this.enabled = false

        this.velocity = new THREE.Vector3()

        document.addEventListener('mousemove', this.on_mouse_move.bind(this), false)
        document.addEventListener('keydown', this.on_key_down.bind(this), false)
        document.addEventListener('keyup', this.on_key_up.bind(this), false)
    },

    physics: function(delta) {
        if (this.enabled) {
            if (this.up) {
                this.velocity.z -= 400.0 * delta
            }
            if (this.down) {
                this.velocity.z += 400.0 * delta
            }
            if (this.left) {
                this.velocity.x -= 400.0 * delta
            }
            if (this.right) {
                this.velocity.x += 400.0 * delta
            }
            this.velocity.x -= this.velocity.x * 10.0 * delta
            this.velocity.z -= this.velocity.z * 10.0 * delta
            this.yaw.translateX(this.velocity.x * delta)
            this.yaw.translateY(this.velocity.y * delta)
            this.yaw.translateZ(this.velocity.z * delta)
        }
    },

    enable: function() {
        this.enabled = true
    },

    disable: function() {
        this.enabled = false
    },

    on_key_down: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = true
            break
        case 37: // left
        case 65: // a
            this.left = true
            break
        case 40: // down
        case 83: // s
            this.down = true
            break
        case 39: // right
        case 68: // d
            this.right = true
            break
        }
    },

    on_key_up: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = false
            break
        case 37: // left
        case 65: // a
            this.left = false
            break
        case 40: // down
        case 83: // s
            this.down = false
            break
        case 39: // right
        case 68: // d
            this.right = false
            break
        }
    },

    on_mouse_move: function(event) {
        if (this.enabled) {
            var movement_x = event.movementX || event.mozMovementX || event.webkitMovementX || 0
            var movement_y = event.movementY || event.mozMovementY || event.webkitMovementY || 0

            this.yaw.rotation.y -= movement_x * 0.002
            this.pitch.rotation.x -= movement_y * 0.002

            this.pitch.rotation.x = Math.max( - this.half_pie, Math.min( this.half_pie, this.pitch.rotation.x))
        }
    },

    get_object: function() {
        return this.yaw
    },

    get_direction: function() {
        var direction = new THREE.Vector3(0, 0, -1)
        var rotation  = new THREE.Euler(0, 0, 0, 'YXZ')
        return function( v ) {
            rotation.set( this.pitch.rotation.x, this.yaw.rotation.y, 0 )
            v.copy(direction).applyEuler(rotation)
            return v
        }
    }
}<|endoftext|>


<commit_before>require('enyo');

var utils = require('./utils');

/**
* Determines OS versions of platforms that need special treatment. Can have one of the following
* properties:
*
* * android
* * androidChrome (Chrome on Android, standard starting in 4.1)
* * androidFirefox
* * ie
* * edge
* * ios
* * webos
* * windowsPhone
* * blackberry
* * tizen
* * safari (desktop version)
* * chrome (desktop version)
* * firefox (desktop version)
* * firefoxOS
*
* If the property is defined, its value will be the major version number of the platform.
*
* Example:
* ```javascript
* // android 2 does not have 3d css
* if (enyo.platform.android < 3) {
* 	t = 'translate(30px, 50px)';
* } else {
* 	t = 'translate3d(30px, 50px, 0)';
* }
* this.applyStyle('-webkit-transform', t);
* ```
*
* @module enyo/platform
*/
exports = module.exports = {
	/**
	* `true` if the platform has native single-finger [events]{@glossary event}.
	* @public
	*/
	touch: Boolean(('ontouchstart' in window) || window.navigator.msMaxTouchPoints || (window.navigator.msManipulationViewsEnabled && window.navigator.maxTouchPoints)),
	/**
	* `true` if the platform has native double-finger [events]{@glossary event}.
	* @public
	*/
	gesture: Boolean(('ongesturestart' in window) || ('onmsgesturestart' in window && window.navigator.msMaxTouchPoints && window.navigator.msMaxTouchPoints > 1) || ('onmsgesturestart' in window && window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1))

	/**
	* The name of the platform that was detected or `undefined` if the platform
	* was unrecognized. This value is the key name for the major version of the
	* platform on the exported object.
	* @member {String} platformName
	* @public
	*/

};

var ua = navigator.userAgent;
var ep = exports;
var platforms = [
	// Windows Phone 7 - 10
	{platform: 'windowsPhone', regex: /Windows Phone (?:OS )?(\d+)[.\d]+/},
	// Android 4+ using Chrome
	{platform: 'androidChrome', regex: /Android .* Chrome\/(\d+)[.\d]+/},
	// Android 2 - 4
	{platform: 'android', regex: /Android(?:\s|\/)(\d+)/},
	// Kindle Fire
	// Force version to 2, (desktop mode does not list android version)
	{platform: 'android', regex: /Silk\/1./, forceVersion: 2, extra: {silk: 1}},
	// Kindle Fire HD (Silk versions 2 or 3)
	// Force version to 4
	{platform: 'android', regex: /Silk\/2./, forceVersion: 4, extra: {silk: 2}},
	{platform: 'android', regex: /Silk\/3./, forceVersion: 4, extra: {silk: 3}},
	// IE 8 - 10
	{platform: 'ie', regex: /MSIE (\d+)/},
	// IE 11
	{platform: 'ie', regex: /Trident\/.*; rv:(\d+)/},
	// Edge
	{platform: 'edge', regex: /Edge\/(\d+)/},
	// iOS 3 - 5
	// Apple likes to make this complicated
	{platform: 'ios', regex: /iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/},
	// webOS 1 - 3
	{platform: 'webos', regex: /(?:web|hpw)OS\/(\d+)/},
	// webOS 4 / OpenWebOS
	{platform: 'webos', regex: /WebAppManager|Isis|webOS\./, forceVersion: 4},
	// Open webOS release LuneOS
	{platform: 'webos', regex: /LuneOS/, forceVersion: 4, extra: {luneos: 1}},
	// desktop Safari
	{platform: 'safari', regex: /Version\/(\d+)[.\d]+\s+Safari/},
	// desktop Chrome
	{platform: 'chrome', regex: /Chrome\/(\d+)[.\d]+/},
	// Firefox on Android
	{platform: 'androidFirefox', regex: /Android;.*Firefox\/(\d+)/},
	// FirefoxOS
	{platform: 'firefoxOS', regex: /Mobile;.*Firefox\/(\d+)/},
	// desktop Firefox
	{platform: 'firefox', regex: /Firefox\/(\d+)/},
	// Blackberry Playbook
	{platform: 'blackberry', regex: /PlayBook/i, forceVersion: 2},
	// Blackberry 10+
	{platform: 'blackberry', regex: /BB1\d;.*Version\/(\d+\.\d+)/},
	// Tizen
	{platform: 'tizen', regex: /Tizen (\d+)/}
];
for (var i = 0, p, m, v; (p = platforms[i]); i++) {
	m = p.regex.exec(ua);
	if (m) {
		if (p.forceVersion) {
			v = p.forceVersion;
		} else {
			v = Number(m[1]);
		}
		ep[p.platform] = v;
		if (p.extra) {
			utils.mixin(ep, p.extra);
		}
		ep.platformName = p.platform;
		break;
	}
}
<commit_msg>spacing<commit_after>require('enyo');

var utils = require('./utils');

/**
* Determines OS versions of platforms that need special treatment. Can have one of the following
* properties:
*
* * android
* * androidChrome (Chrome on Android, standard starting in 4.1)
* * androidFirefox
* * ie
* * edge
* * ios
* * webos
* * windowsPhone
* * blackberry
* * tizen
* * safari (desktop version)
* * chrome (desktop version)
* * firefox (desktop version)
* * firefoxOS
*
* If the property is defined, its value will be the major version number of the platform.
*
* Example:
* ```javascript
* // android 2 does not have 3d css
* if (enyo.platform.android < 3) {
* 	t = 'translate(30px, 50px)';
* } else {
* 	t = 'translate3d(30px, 50px, 0)';
* }
* this.applyStyle('-webkit-transform', t);
* ```
*
* @module enyo/platform
*/
exports = module.exports = {
	/**
	* `true` if the platform has native single-finger [events]{@glossary event}.
	* @public
	*/
	touch: Boolean(('ontouchstart' in window) || window.navigator.msMaxTouchPoints || (window.navigator.msManipulationViewsEnabled && window.navigator.maxTouchPoints)),
	/**
	* `true` if the platform has native double-finger [events]{@glossary event}.
	* @public
	*/
	gesture: Boolean(('ongesturestart' in window) || ('onmsgesturestart' in window && window.navigator.msMaxTouchPoints && window.navigator.msMaxTouchPoints > 1) || ('onmsgesturestart' in window && window.navigator.maxTouchPoints && window.navigator.maxTouchPoints > 1))

	/**
	* The name of the platform that was detected or `undefined` if the platform
	* was unrecognized. This value is the key name for the major version of the
	* platform on the exported object.
	* @member {String} platformName
	* @public
	*/

};

var ua = navigator.userAgent;
var ep = exports;
var platforms = [
	// Windows Phone 7 - 10
	{platform: 'windowsPhone', regex: /Windows Phone (?:OS )?(\d+)[.\d]+/},
	// Android 4+ using Chrome
	{platform: 'androidChrome', regex: /Android .* Chrome\/(\d+)[.\d]+/},
	// Android 2 - 4
	{platform: 'android', regex: /Android(?:\s|\/)(\d+)/},
	// Kindle Fire
	// Force version to 2, (desktop mode does not list android version)
	{platform: 'android', regex: /Silk\/1./, forceVersion: 2, extra: {silk: 1}},
	// Kindle Fire HD (Silk versions 2 or 3)
	// Force version to 4
	{platform: 'android', regex: /Silk\/2./, forceVersion: 4, extra: {silk: 2}},
	{platform: 'android', regex: /Silk\/3./, forceVersion: 4, extra: {silk: 3}},
	// IE 8 - 10
	{platform: 'ie', regex: /MSIE (\d+)/},
	// IE 11
	{platform: 'ie', regex: /Trident\/.*; rv:(\d+)/},
	// Edge
	{platform: 'edge', regex: /Edge\/(\d+)/},
	// iOS 3 - 5
	// Apple likes to make this complicated
	{platform: 'ios', regex: /iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/},
	// webOS 1 - 3
	{platform: 'webos', regex: /(?:web|hpw)OS\/(\d+)/},
	// webOS 4 / OpenWebOS
	{platform: 'webos', regex: /WebAppManager|Isis|webOS\./, forceVersion: 4},
	// Open webOS release LuneOS
	{platform: 'webos', regex: /LuneOS/, forceVersion: 4, extra: {luneos: 1}},
	// desktop Safari
	{platform: 'safari', regex: /Version\/(\d+)[.\d]+\s+Safari/},
	// desktop Chrome
	{platform: 'chrome', regex: /Chrome\/(\d+)[.\d]+/},
	// Firefox on Android
	{platform: 'androidFirefox', regex: /Android;.*Firefox\/(\d+)/},
	// FirefoxOS
	{platform: 'firefoxOS', regex: /Mobile;.*Firefox\/(\d+)/},
	// desktop Firefox
	{platform: 'firefox', regex: /Firefox\/(\d+)/},
	// Blackberry Playbook
	{platform: 'blackberry', regex: /PlayBook/i, forceVersion: 2},
	// Blackberry 10+
	{platform: 'blackberry', regex: /BB1\d;.*Version\/(\d+\.\d+)/},
	// Tizen
	{platform: 'tizen', regex: /Tizen (\d+)/}
];
for (var i = 0, p, m, v; (p = platforms[i]); i++) {
	m = p.regex.exec(ua);
	if (m) {
		if (p.forceVersion) {
			v = p.forceVersion;
		} else {
			v = Number(m[1]);
		}
		ep[p.platform] = v;
		if (p.extra) {
			utils.mixin(ep, p.extra);
		}
		ep.platformName = p.platform;
		break;
	}
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { propType } from 'graphql-anywhere';

import Box from 'react/components/UI/Box';
import HorizontalRule from 'react/components/UI/HorizontalRule';

import channelFragment from 'react/components/Cell/components/Konnectable/components/Channel/fragments/channel';
import Text from 'react/components/UI/Text';

const Row = styled(Box).attrs({
  mb: 9,
  // Accomodate connect menu outline border from getting cut off
  pt: 3,
  pr: 3,
  pl: 3,
})`
  overflow: hidden;

  // Neutralize the padding for the connect outline
  margin-top: -${x => x.theme.space[3]};
  margin-left: -${x => x.theme.space[3]};

  > * {
    flex-wrap: nowrap;
  }
`;

const Line = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
`;

const HR = styled(HorizontalRule).attrs({ my: 0, color: 'gray.light' })`
  flex: 1;
  margin-right: ${x => x.theme.space[5]};
`;

const Count = styled(Text).attrs({
  f: 1,
  underlineLinks: true,
  color: 'gray.medium',
})``;

const ChannelRow = ({ children, channel, ...rest }) => (
  <Row {...rest}>
    {children}
    <Line>

      <Count underlineLinks>

          +{channel.counts.contents} more blocks

      </Count>
    </Line>
  </Row>
);

ChannelRow.propTypes = {
  channel: propType(channelFragment).isRequired,
  children: PropTypes.node.isRequired,
};

export default ChannelRow;
<commit_msg>Listen to changes in width to get the proper count<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { propType } from 'graphql-anywhere';

import WithBlocksGridCount from 'react/hocs/WithBlocksGridCount';
import constants from 'react/styles/constants';
import Box from 'react/components/UI/Box';
import HorizontalRule from 'react/components/UI/HorizontalRule';

import channelFragment from 'react/components/Cell/components/Konnectable/components/Channel/fragments/channel';
import Text from 'react/components/UI/Text';
import Count from 'react/components/UI/Count';

const Row = styled(Box).attrs({
  mb: 9,
  // Accomodate connect menu outline border from getting cut off
  pt: 3,
  pr: 3,
  pl: 3,
})`
  overflow: hidden;

  // Neutralize the padding for the connect outline
  margin-top: -${x => x.theme.space[3]};
  margin-left: -${x => x.theme.space[3]};

  > * {
    flex-wrap: nowrap;
  }
`;

const Line = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-right: ${constants.doubleBlockGutter}
`;

const HR = styled(HorizontalRule).attrs({ my: 0, color: 'gray.light' })`
  flex: 1;
  margin-right: ${x => x.theme.space[5]};
`;

const CountLine = styled(Text).attrs({
  f: 1,
  underlineLinks: true,
  color: 'gray.medium',
})``;

const ChannelRow = ({
  children, channel, blocksGridCount, ...rest
}) => (
  <Row {...rest}>
    {children}
    <Line>

      <CountLine>

          +<Count
            label="more block"
            amount={((channel.counts.contents - blocksGridCount) + 1)}
          />

      </CountLine>
    </Line>
  </Row>
);

ChannelRow.propTypes = {
  channel: propType(channelFragment).isRequired,
  children: PropTypes.node.isRequired,
  blocksGridCount: PropTypes.number.isRequired,
};

export default WithBlocksGridCount(ChannelRow);
<|endoftext|>


<commit_before>import Promise from './index';
import promiseFinally from './finally';
import allSettled from './allSettled';

/** @suppress {undefinedVars} */
var globalNS = (function() {
  // the only reliable means to get the global object is
  // `Function('return this')()`
  // However, this causes CSP violations in Chrome apps.
  if (typeof self !== 'undefined') {
    return self;
  }
  if (typeof window !== 'undefined') {
    return window;
  }
  if (typeof global !== 'undefined') {
    return global;
  }
  throw new Error('unable to locate global object');
})();

// Expose the polyfill if Promise is undefined or set to a
// non-function value. The latter can be due to a named HTMLElement
// being exposed by browsers for legacy reasons.
// https://github.com/taylorhakes/promise-polyfill/issues/114
if (typeof globalNS['Promise'] !== 'function') {
  globalNS['Promise'] = Promise;
} else if (!globalNS.Promise.prototype['finally']) {
  globalNS.Promise.prototype['finally'] = promiseFinally;
} else if (!globalNS.Promise.allSettled) {
  globalNS.Promise.allSettled = allSettled;
}
<commit_msg>Revert "Revert "Bugfix: `allSettled` is not registered when `finally` is missing (#127)""<commit_after>import Promise from './index';
import promiseFinally from './finally';
import allSettled from './allSettled';

/** @suppress {undefinedVars} */
var globalNS = (function() {
  // the only reliable means to get the global object is
  // `Function('return this')()`
  // However, this causes CSP violations in Chrome apps.
  if (typeof self !== 'undefined') {
    return self;
  }
  if (typeof window !== 'undefined') {
    return window;
  }
  if (typeof global !== 'undefined') {
    return global;
  }
  throw new Error('unable to locate global object');
})();

// Expose the polyfill if Promise is undefined or set to a
// non-function value. The latter can be due to a named HTMLElement
// being exposed by browsers for legacy reasons.
// https://github.com/taylorhakes/promise-polyfill/issues/114
if (typeof globalNS['Promise'] !== 'function') {
  globalNS['Promise'] = Promise;
} else {
  if (!globalNS.Promise.prototype['finally']) {
    globalNS.Promise.prototype['finally'] = promiseFinally;
  }
  if (!globalNS.Promise.allSettled) {
    globalNS.Promise.allSettled = allSettled;
  }
}
<|endoftext|>


<commit_before>/**
 * Created by roy on 15/9/8.
 * 处理popup中的item分组样式
 * 一个item分组中的成员大于一时，该分组设置为单选，并且默认状态第一个成员设置为已选择项
 */
BI.MultiLayerDownListPopup = BI.inherit(BI.Pane, {
    constants: {
        nextIcon: "pull-right-e-font",
        height: 25,
        iconHeight: 12,
        iconWidth: 12,
        hgap: 0,
        vgap: 0,
        border: 1
    },
    _defaultConfig: function () {
        var conf = BI.MultiLayerDownListPopup.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            baseCls: "bi-down-list-popup",
            items: [],
            chooseType: BI.Selection.Multi
        });
    },
    _init: function () {
        BI.MultiLayerDownListPopup.superclass._init.apply(this, arguments);
        this.singleValues = [];
        this.childValueMap = {};
        this.fatherValueMap = {};
        var self = this, o = this.options, children = this._createPopupItems(o.items);
        this.popup = BI.createWidget({
            type: "bi.button_tree",
            items: BI.createItems(children,
                {}, {
                    adjustLength: -2
                }
            ),
            layouts: [{
                type: "bi.vertical",
                hgap: this.constants.hgap,
                vgap: this.constants.vgap
            }],
            value: this._digest(o.value),
            chooseType: o.chooseType
        });

        this.popup.on(BI.ButtonTree.EVENT_CHANGE, function (value, object) {
            var changedValue = value;
            if (BI.isNotNull(self.childValueMap[value])) {
                changedValue = self.childValueMap[value];
                var fatherValue = self.fatherValueMap[value];
                var fatherArrayValue = (fatherValue + "").split("_");
                self.fireEvent(BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, fatherArrayValue.length > 1 ? fatherArrayValue : fatherValue);
            } else {
                self.fireEvent(BI.MultiLayerDownListPopup.EVENT_CHANGE, changedValue, object);
            }

            if (!BI.contains(self.singleValues, changedValue)) {
                var item = self.getValue();
                var result = [];
                BI.each(item, function (i, valueObject) {
                    if (valueObject.value != changedValue) {
                        result.push(valueObject);
                    }
                });
                self.setValue(result);
            }

        });

        BI.createWidget({
            type: "bi.vertical",
            element: this,
            items: [this.popup],
            vgap: 5
        });

    },
    _createPopupItems: function (items) {
        var self = this, result = [];
        BI.each(items, function (i, it) {
            var item_done = {
                type: "bi.down_list_group",
                items: []
            };

            BI.each(it, function (i, item) {
                if (BI.isNotEmptyArray(item.children) && !BI.isEmpty(item.el)) {
                    item.type = "bi.combo_group";
                    item.cls = "down-list-group";
                    item.trigger = "hover";
                    item.isNeedAdjustWidth = false;
                    item.el.title = item.el.title || item.el.text;
                    item.el.type = "bi.down_list_group_item";
                    item.el.logic = {
                        dynamic: true
                    };
                    item.el.height = item.el.height || self.constants.height;
                    item.el.iconCls2 = self.constants.nextIcon;
                    item.popup = {
                        lgap: 1,
                        el: {
                            type: "bi.button_tree",
                            chooseType: 0,
                            layouts: [{
                                type: "bi.vertical"
                            }]

                        },
                        innerVGap: 5
                    };
                    self._createChildren(item);
                } else {
                    item.type = item.type || "bi.down_list_item";
                    item.title = item.title || item.text;
                    item.textRgap = 10;
                    item.isNeedAdjustWidth = false;
                    item.logic = {
                        dynamic: true
                    };
                }
                var el_done = {};
                el_done.el = item;
                item_done.items.push(el_done);
            });
            if (self._isGroup(item_done.items)) {
                BI.each(item_done.items, function (i, item) {
                    self.singleValues.push(item.el.value);
                });
            }

            result.push(item_done);
            if (self._needSpliter(i, items.length)) {
                var spliter_container = BI.createWidget({
                    type: "bi.vertical",
                    items: [{
                        el: {
                            type: "bi.layout",
                            cls: "bi-down-list-spliter bi-border-top cursor-pointer",
                            height: 0
                        }

                    }],
                    cls: "bi-down-list-spliter-container cursor-pointer",
                    vgap: 5,
                    lgap: 10
                });
                result.push(spliter_container);
            }
        });
        return result;
    },

    _createChildren: function (item) {
        var self = this;
        this._formatEL(item).el.childValues = [];
        BI.each(item.children, function (i, child) {
            child = child.el ? BI.extend(child.el, {children: child.children}) : child;
            var fatherValue = BI.deepClone(self._formatEL(item).el.value);
            var childValue = BI.deepClone(child.value);
            self.singleValues.push(child.value);
            child.type = child.type || "bi.down_list_item";
            child.extraCls = " child-down-list-item";
            child.title = child.title || child.text;
            child.textRgap = 10;
            child.isNeedAdjustWidth = false;
            child.logic = {
                dynamic: true
            };
            child.father = fatherValue;
            self.fatherValueMap[self._createChildValue(fatherValue, childValue)] = fatherValue;
            self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue;
            child.value = self._createChildValue(fatherValue, childValue);
            self._formatEL(item).el.childValues.push(child.value);
            if (BI.isNotEmptyArray(child.children)) {
                child.type = "bi.down_list_group_item";
                child.iconCls2 = self.constants.nextIcon;
                child.height = child.height || self.constants.height;
                self._createChildren(child);
            }
        });
    },

    _formatEL: function(obj) {
        if (obj && obj.el) {
            return obj;
        }

        return {
            el: obj
        };
    },

    _isGroup: function (i) {
        return i.length > 1;
    },

    _needSpliter: function (i, itemLength) {
        return i < itemLength - 1;
    },

    _createChildValue: function (fatherValue, childValue) {
        var fValue = fatherValue;
        if(BI.isArray(fatherValue)) {
            fValue = fatherValue.join("_");
        }
        return fValue + "_" + childValue;
    },

    _digest: function (valueItem) {
        var self = this;
        var valueArray = [];
        BI.each(valueItem, function (i, item) {
                var value;
                if (BI.isNotNull(item.childValue)) {
                    value = self._createChildValue(item.value, item.childValue);
                } else {
                    value = item.value;
                }
                valueArray.push(value);
            }
        );
        return valueArray;
    },

    _checkValues: function (values) {
        var self = this, o = this.options;
        var value = [];
        BI.each(o.items, function (idx, itemGroup) {
            BI.each(itemGroup, function (id, item) {
                if(BI.isNotNull(item.children)) {
                    var childValues = getChildrenValue(item);
                    var v = joinValue(childValues, values[idx]);
                    if(BI.isNotEmptyString(v)) {
                        value.push(v);
                    }
                }else{
                    if(item.value === values[idx][0]) {
                        value.push(values[idx][0]);
                    }
                }
            });
        });
        return value;

        function joinValue (sources, targets) {
            var value = "";
            BI.some(sources, function (idx, s) {
                return BI.some(targets, function (id, t) {
                    if(s === t) {
                        value = s;
                        return true;
                    }
                });
            });
            return value;
        }

        function getChildrenValue (item) {
            var children = [];
            if(BI.isNotNull(item.children)) {
                BI.each(item.children, function (idx, child) {
                    children = BI.concat(children, getChildrenValue(child));
                });
            } else {
                children.push(item.value);
            }
            return children;
        }
    },

    populate: function (items) {
        BI.MultiLayerDownListPopup.superclass.populate.apply(this, arguments);
        var self = this;
        self.childValueMap = {};
        self.fatherValueMap = {};
        self.singleValues = [];
        var children = self._createPopupItems(items);
        var popupItem = BI.createItems(children,
            {}, {
                adjustLength: -2
            }
        );
        self.popup.populate(popupItem);
    },

    setValue: function (valueItem) {
        this.popup.setValue(this._digest(valueItem));
    },

    _getValue: function () {
        var v = [];
        BI.each(this.popup.getAllButtons(), function (i, item) {
            i % 2 === 0 && v.push(item.getValue());
        });
        return v;
    },

    getValue: function () {
        var self = this, result = [];
        var values = this._checkValues(this._getValue());
        BI.each(values, function (i, value) {
            var valueItem = {};
            if (BI.isNotNull(self.childValueMap[value])) {
                var fartherValue = self.fatherValueMap[value];
                valueItem.childValue = self.childValueMap[value];
                var fatherArrayValue = (fartherValue + "").split("_");
                valueItem.value = fatherArrayValue.length > 1 ? fatherArrayValue : fartherValue;
            } else {
                valueItem.value = value;
            }
            result.push(valueItem);
        });
        return result;
    }

});

BI.MultiLayerDownListPopup.EVENT_CHANGE = "EVENT_CHANGE";
BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE";
BI.shortcut("bi.multi_layer_down_list_popup", BI.MultiLayerDownListPopup);<commit_msg>Pull request #2207: BI-94616 fix: 同步downlist修改<commit_after>/**
 * Created by roy on 15/9/8.
 * 处理popup中的item分组样式
 * 一个item分组中的成员大于一时，该分组设置为单选，并且默认状态第一个成员设置为已选择项
 */
BI.MultiLayerDownListPopup = BI.inherit(BI.Pane, {
    constants: {
        nextIcon: "pull-right-e-font",
        height: 25,
        iconHeight: 12,
        iconWidth: 12,
        hgap: 0,
        vgap: 0,
        border: 1
    },
    _defaultConfig: function () {
        var conf = BI.MultiLayerDownListPopup.superclass._defaultConfig.apply(this, arguments);
        return BI.extend(conf, {
            baseCls: "bi-down-list-popup",
            items: [],
            chooseType: BI.Selection.Multi
        });
    },
    _init: function () {
        BI.MultiLayerDownListPopup.superclass._init.apply(this, arguments);
        this.singleValues = [];
        this.childValueMap = {};
        this.fatherValueMap = {};
        var self = this, o = this.options, children = this._createPopupItems(o.items);
        this.popup = BI.createWidget({
            type: "bi.button_tree",
            items: BI.createItems(children,
                {}, {
                    adjustLength: -2
                }
            ),
            layouts: [{
                type: "bi.vertical",
                hgap: this.constants.hgap,
                vgap: this.constants.vgap
            }],
            value: this._digest(o.value),
            chooseType: o.chooseType
        });

        this.popup.on(BI.ButtonTree.EVENT_CHANGE, function (value, object) {
            var changedValue = value;
            if (BI.isNotNull(self.childValueMap[value])) {
                changedValue = self.childValueMap[value];
                var fatherValue = self.fatherValueMap[value];
                var fatherArrayValue = (fatherValue + "").split(BI.BlankSplitChar);
                self.fireEvent(BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, fatherArrayValue.length > 1 ? fatherArrayValue : fatherValue);
            } else {
                self.fireEvent(BI.MultiLayerDownListPopup.EVENT_CHANGE, changedValue, object);
            }

            if (!BI.contains(self.singleValues, changedValue)) {
                var item = self.getValue();
                var result = [];
                BI.each(item, function (i, valueObject) {
                    if (valueObject.value != changedValue) {
                        result.push(valueObject);
                    }
                });
                self.setValue(result);
            }

        });

        BI.createWidget({
            type: "bi.vertical",
            element: this,
            items: [this.popup],
            vgap: 5
        });

    },
    _createPopupItems: function (items) {
        var self = this, result = [];
        BI.each(items, function (i, it) {
            var item_done = {
                type: "bi.down_list_group",
                items: []
            };

            BI.each(it, function (i, item) {
                if (BI.isNotEmptyArray(item.children) && !BI.isEmpty(item.el)) {
                    item.type = "bi.combo_group";
                    item.cls = "down-list-group";
                    item.trigger = "hover";
                    item.isNeedAdjustWidth = false;
                    item.el.title = item.el.title || item.el.text;
                    item.el.type = "bi.down_list_group_item";
                    item.el.logic = {
                        dynamic: true
                    };
                    item.el.height = item.el.height || self.constants.height;
                    item.el.iconCls2 = self.constants.nextIcon;
                    item.popup = {
                        lgap: 1,
                        el: {
                            type: "bi.button_tree",
                            chooseType: 0,
                            layouts: [{
                                type: "bi.vertical"
                            }]

                        },
                        innerVGap: 5
                    };
                    self._createChildren(item);
                } else {
                    item.type = item.type || "bi.down_list_item";
                    item.title = item.title || item.text;
                    item.textRgap = 10;
                    item.isNeedAdjustWidth = false;
                    item.logic = {
                        dynamic: true
                    };
                }
                var el_done = {};
                el_done.el = item;
                item_done.items.push(el_done);
            });
            if (self._isGroup(item_done.items)) {
                BI.each(item_done.items, function (i, item) {
                    self.singleValues.push(item.el.value);
                });
            }

            result.push(item_done);
            if (self._needSpliter(i, items.length)) {
                var spliter_container = BI.createWidget({
                    type: "bi.vertical",
                    items: [{
                        el: {
                            type: "bi.layout",
                            cls: "bi-down-list-spliter bi-border-top cursor-pointer",
                            height: 0
                        }

                    }],
                    cls: "bi-down-list-spliter-container cursor-pointer",
                    vgap: 5,
                    lgap: 10
                });
                result.push(spliter_container);
            }
        });
        return result;
    },

    _createChildren: function (item) {
        var self = this;
        this._formatEL(item).el.childValues = [];
        BI.each(item.children, function (i, child) {
            child = child.el ? BI.extend(child.el, {children: child.children}) : child;
            var fatherValue = BI.deepClone(self._formatEL(item).el.value);
            var childValue = BI.deepClone(child.value);
            self.singleValues.push(child.value);
            child.type = child.type || "bi.down_list_item";
            child.extraCls = " child-down-list-item";
            child.title = child.title || child.text;
            child.textRgap = 10;
            child.isNeedAdjustWidth = false;
            child.logic = {
                dynamic: true
            };
            child.father = fatherValue;
            self.fatherValueMap[self._createChildValue(fatherValue, childValue)] = fatherValue;
            self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue;
            child.value = self._createChildValue(fatherValue, childValue);
            self._formatEL(item).el.childValues.push(child.value);
            if (BI.isNotEmptyArray(child.children)) {
                child.type = "bi.down_list_group_item";
                child.iconCls2 = self.constants.nextIcon;
                child.height = child.height || self.constants.height;
                self._createChildren(child);
            }
        });
    },

    _formatEL: function(obj) {
        if (obj && obj.el) {
            return obj;
        }

        return {
            el: obj
        };
    },

    _isGroup: function (i) {
        return i.length > 1;
    },

    _needSpliter: function (i, itemLength) {
        return i < itemLength - 1;
    },

    _createChildValue: function (fatherValue, childValue) {
        var fValue = fatherValue;
        if(BI.isArray(fatherValue)) {
            fValue = fatherValue.join(BI.BlankSplitChar);
        }
        return fValue + BI.BlankSplitChar + childValue;
    },

    _digest: function (valueItem) {
        var self = this;
        var valueArray = [];
        BI.each(valueItem, function (i, item) {
                var value;
                if (BI.isNotNull(item.childValue)) {
                    value = self._createChildValue(item.value, item.childValue);
                } else {
                    value = item.value;
                }
                valueArray.push(value);
            }
        );
        return valueArray;
    },

    _checkValues: function (values) {
        var self = this, o = this.options;
        var value = [];
        BI.each(o.items, function (idx, itemGroup) {
            BI.each(itemGroup, function (id, item) {
                if(BI.isNotNull(item.children)) {
                    var childValues = getChildrenValue(item);
                    var v = joinValue(childValues, values[idx]);
                    if(BI.isNotEmptyString(v)) {
                        value.push(v);
                    }
                }else{
                    if(item.value === values[idx][0]) {
                        value.push(values[idx][0]);
                    }
                }
            });
        });
        return value;

        function joinValue (sources, targets) {
            var value = "";
            BI.some(sources, function (idx, s) {
                return BI.some(targets, function (id, t) {
                    if(s === t) {
                        value = s;
                        return true;
                    }
                });
            });
            return value;
        }

        function getChildrenValue (item) {
            var children = [];
            if(BI.isNotNull(item.children)) {
                BI.each(item.children, function (idx, child) {
                    children = BI.concat(children, getChildrenValue(child));
                });
            } else {
                children.push(item.value);
            }
            return children;
        }
    },

    populate: function (items) {
        BI.MultiLayerDownListPopup.superclass.populate.apply(this, arguments);
        var self = this;
        self.childValueMap = {};
        self.fatherValueMap = {};
        self.singleValues = [];
        var children = self._createPopupItems(items);
        var popupItem = BI.createItems(children,
            {}, {
                adjustLength: -2
            }
        );
        self.popup.populate(popupItem);
    },

    setValue: function (valueItem) {
        this.popup.setValue(this._digest(valueItem));
    },

    _getValue: function () {
        var v = [];
        BI.each(this.popup.getAllButtons(), function (i, item) {
            i % 2 === 0 && v.push(item.getValue());
        });
        return v;
    },

    getValue: function () {
        var self = this, result = [];
        var values = this._checkValues(this._getValue());
        BI.each(values, function (i, value) {
            var valueItem = {};
            if (BI.isNotNull(self.childValueMap[value])) {
                var fartherValue = self.fatherValueMap[value];
                valueItem.childValue = self.childValueMap[value];
                var fatherArrayValue = (fartherValue + "").split(BI.BlankSplitChar);
                valueItem.value = fatherArrayValue.length > 1 ? fatherArrayValue : fartherValue;
            } else {
                valueItem.value = value;
            }
            result.push(valueItem);
        });
        return result;
    }

});

BI.MultiLayerDownListPopup.EVENT_CHANGE = "EVENT_CHANGE";
BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE";
BI.shortcut("bi.multi_layer_down_list_popup", BI.MultiLayerDownListPopup);<|endoftext|>


<commit_before>'use strict';

var Substance = require('substance');
var $$ = React.createElement;

// TagSubjectTool
// ----------------

var TagSubjectTool = React.createClass({
  displayName: "TagSubjectTool",

  componentDidMount: function() {
    var writerCtrl = this.props.writerCtrl;
    writerCtrl.connect(this, {
      'selection:changed': this.handleSelectionChange
    });
  },

  handleSelectionChange: function(sel) {
    var writerCtrl = this.props.writerCtrl;
    // Note: toggling of a subject reference is only possible when
    // the subject reference is selected and the
    // TODO: Deleting the reference this way is IMO not a good experience
    // as 1. data get 'lost' easily, 2. the interaction is not at all a convention
    // (-> compare with links in word or gdocs).
    if (sel.isNull() || sel.isCollapsed() ) {
      return this.setState({
        active: false,
        selected: false
      });
    } else {
      var newState = {
        active: true,
        selected: false
      };
      if (writerCtrl.state.contextId === "editSubjectReference") {
        var container = writerCtrl.getSurface().getContainer();
        if (!container) {
          return this.setState({
            active: false,
            selected: false
          });
        }
        var anno = writerCtrl.doc.get(writerCtrl.state.subjectReferenceId);
        if (!anno) {
          console.error("Ooops. Could not find subject-reference while being in 'editSubjectReference'.");
          return this.setState({
            active: false,
            selected: false
          });
        }
        var annoSel = Substance.Document.Selection.create(container,
          anno.startPath, anno.startOffset, anno.endPath, anno.endOffset);
        if (!annoSel.overlaps(sel)) {
          return this.setState({
            active: false,
            selected: false
          });
        }
        if (annoSel.includesWithOneBoundary(sel)) {
          newState.mode = 'truncate';
          newState.selected = true;
        } else if (annoSel.includes(sel)) {
          newState.mode = 'delete';
          newState.selected = true;
        } else {
          newState.mode = 'expand';
        }
        newState.annotationSelection = annoSel;
      } else {
        newState.mode = 'create';
      }
      this.setState(newState);
    }
  },

  handleMouseDown: function(e) {
    e.preventDefault();
    if (!this.state.active) {
      return;
    }
    // toggle subject_reference on or off
    var writerCtrl = this.props.writerCtrl;
    var doc = writerCtrl.doc;
    var sel = writerCtrl.getSelection();
    if (sel.isNull() || sel.isCollapsed()) return;
    var range = sel.getRange();

    var tx = doc.startTransaction({selection: sel});
    if (this.state.mode === 'create') {
      try {
        var subjectReference = {
          type: "subject_reference",
          id: Substance.uuid("subject_reference"),
          startPath: range.start.path,
          startOffset: range.start.offset,
          endPath: range.end.path,
          endOffset: range.end.offset,
          target: []
        };
        tx.create(subjectReference);
        tx.save({selection: sel.collapse('left')});
        writerCtrl.replaceState({
          contextId: "editSubjectReference",
          subjectReferenceId: subjectReference.id,
          range: range
        });
        // HACK: using a custom event instead of automatic data bindings
        doc.emit('container-annotation-update');
      } finally {
        tx.cleanup();
      }
    } else if (this.state.mode === 'delete') {
      try {
        tx.delete(writerCtrl.state.subjectReferenceId);
        tx.save({selection: sel.collapse('left')});
        writerCtrl.replaceState({
          contextId: "subjects"
        });
      } finally {
        tx.cleanup();
      }
    } else if (this.state.mode === 'expand' || this.state.mode === 'truncate') {
      try {
        var anno = writerCtrl.doc.get(writerCtrl.state.subjectReferenceId);
        if (this.state.mode === 'expand') {
          sel = this.state.annotationSelection.expand(sel);
        } else {
          sel = this.state.annotationSelection.truncate(sel);
        }
        var newRange = sel.getRange();
        if (!Substance.isEqual(anno.startPath, newRange.start.path)) {
          tx.set([anno.id, 'startPath'], newRange.start.path);
        }
        if (!Substance.isEqual(anno.endPath, newRange.end.path)) {
          tx.set([anno.id, 'endPath'], newRange.end.path);
        }
        if (!Substance.isEqual(anno.startOffset, newRange.start.offset)) {
          tx.set([anno.id, 'startOffset'], newRange.start.offset);
        }
        if (!Substance.isEqual(anno.endOffset, newRange.end.offset)) {
          tx.set([anno.id, 'endOffset'], newRange.end.offset);
        }
        tx.save({});
        // HACK: using a custom event instead of automatic data bindings
        doc.emit('container-annotation-update');
      } finally {
        tx.cleanup();
      }
    } else  {
      throw new Error('Illegal state');
    }
  },

  getInitialState: function() {
    return {
      active: false,
      selected: false
    };
  },

  render: function() {
    var classNames = ['tag-subject-tool-component', 'tool'];
    if (this.state.active) classNames.push("active");
    if (this.state.selected) classNames.push("selected");
    return $$("a", {
      className: classNames.join(' '),
      href: "#",
      dangerouslySetInnerHTML: {__html: ''},
      title: 'Tag Subject',
      onMouseDown: this.handleMouseDown
    });
  }
});

module.exports = TagSubjectTool;<commit_msg>Fixes.<commit_after>'use strict';

var Substance = require('substance');
var $$ = React.createElement;

// TagSubjectTool
// ----------------

var TagSubjectTool = React.createClass({
  displayName: "TagSubjectTool",

  componentDidMount: function() {
    var writerCtrl = this.props.writerCtrl;
    writerCtrl.connect(this, {
      'selection:changed': this.handleSelectionChange
    });
  },

  handleSelectionChange: function(sel) {
    var writerCtrl = this.props.writerCtrl;
    // Note: toggling of a subject reference is only possible when
    // the subject reference is selected and the
    // TODO: Deleting the reference this way is IMO not a good experience
    // as 1. data get 'lost' easily, 2. the interaction is not at all a convention
    // (-> compare with links in word or gdocs).
    if (sel.isNull() || sel.isCollapsed() ) {
      return this.setState({
        active: false,
        selected: false
      });
    } else {
      var container = writerCtrl.getSurface().getContainer();
      if (!container) {
        return this.setState({
          active: false,
          selected: false
        });
      }
      var newState = {
        active: true,
        selected: false,
        containerId: container.id
      };
      if (writerCtrl.state.contextId === "editSubjectReference") {
        var anno = writerCtrl.doc.get(writerCtrl.state.subjectReferenceId);
        if (!anno) {
          console.error("Ooops. Could not find subject-reference while being in 'editSubjectReference'.");
          return this.setState({
            active: false,
            selected: false
          });
        }
        var annoSel = Substance.Document.Selection.create(container,
          anno.startPath, anno.startOffset, anno.endPath, anno.endOffset);
        if (!annoSel.overlaps(sel)) {
          return this.setState({
            active: false,
            selected: false
          });
        }
        if (annoSel.includesWithOneBoundary(sel)) {
          newState.mode = 'truncate';
          newState.selected = true;
        } else if (annoSel.includes(sel)) {
          newState.mode = 'delete';
          newState.selected = true;
        } else {
          newState.mode = 'expand';
        }
        newState.annotationSelection = annoSel;
      } else {
        newState.mode = 'create';
      }
      this.setState(newState);
    }
  },

  handleMouseDown: function(e) {
    e.preventDefault();
    if (!this.state.active) {
      return;
    }
    // toggle subject_reference on or off
    var writerCtrl = this.props.writerCtrl;
    var doc = writerCtrl.doc;
    var sel = writerCtrl.getSelection();
    if (sel.isNull() || sel.isCollapsed()) return;
    var range = sel.getRange();

    var tx = doc.startTransaction({selection: sel});
    if (this.state.mode === 'create') {
      try {
        var subjectReference = {
          type: "subject_reference",
          id: Substance.uuid("subject_reference"),
          container: this.state.containerId,
          startPath: range.start.path,
          startOffset: range.start.offset,
          endPath: range.end.path,
          endOffset: range.end.offset,
          target: []
        };
        tx.create(subjectReference);
        tx.save({selection: sel.collapse('left')});
        writerCtrl.replaceState({
          contextId: "editSubjectReference",
          subjectReferenceId: subjectReference.id,
          range: range
        });
        // HACK: using a custom event instead of automatic data bindings
        doc.emit('container-annotation-update');
      } finally {
        tx.cleanup();
      }
    } else if (this.state.mode === 'delete') {
      try {
        tx.delete(writerCtrl.state.subjectReferenceId);
        tx.save({selection: sel.collapse('left')});
        writerCtrl.replaceState({
          contextId: "subjects"
        });
      } finally {
        tx.cleanup();
      }
    } else if (this.state.mode === 'expand' || this.state.mode === 'truncate') {
      try {
        var anno = writerCtrl.doc.get(writerCtrl.state.subjectReferenceId);
        if (this.state.mode === 'expand') {
          sel = this.state.annotationSelection.expand(sel);
        } else {
          sel = this.state.annotationSelection.truncate(sel);
        }
        var newRange = sel.getRange();
        if (!Substance.isEqual(anno.startPath, newRange.start.path)) {
          tx.set([anno.id, 'startPath'], newRange.start.path);
        }
        if (!Substance.isEqual(anno.endPath, newRange.end.path)) {
          tx.set([anno.id, 'endPath'], newRange.end.path);
        }
        if (!Substance.isEqual(anno.startOffset, newRange.start.offset)) {
          tx.set([anno.id, 'startOffset'], newRange.start.offset);
        }
        if (!Substance.isEqual(anno.endOffset, newRange.end.offset)) {
          tx.set([anno.id, 'endOffset'], newRange.end.offset);
        }
        tx.save({});
        // HACK: using a custom event instead of automatic data bindings
        doc.emit('container-annotation-update');
      } finally {
        tx.cleanup();
      }
    } else  {
      throw new Error('Illegal state');
    }
  },

  getInitialState: function() {
    return {
      active: false,
      selected: false
    };
  },

  render: function() {
    var classNames = ['tag-subject-tool-component', 'tool'];
    if (this.state.active) classNames.push("active");
    if (this.state.selected) classNames.push("selected");
    return $$("a", {
      className: classNames.join(' '),
      href: "#",
      dangerouslySetInnerHTML: {__html: ''},
      title: 'Tag Subject',
      onMouseDown: this.handleMouseDown
    });
  }
});

module.exports = TagSubjectTool;<|endoftext|>


<commit_before><commit_msg>missing has_filter javascript file<commit_after>Filter = {
	select_filter: function(event) {
		var set = this.parentNode;
		var name = this.options[this.selectedIndex].value;

		Element.select(set, '.filter').each(function(e) { e.removeClassName('selected'); });
		Element.select(set, '.filter_' + name)[0].addClassName('selected');
	},
	add_filter: function(event) {
		this.blur();
		var form = this.parentNode.parentNode.parentNode;
		var set = this.parentNode.parentNode.cloneNode(true);

		form.insertBefore(set, this.parentNode.nextSibling);
		Element.select(set, '.remove_filter')[0].removeClassName('first')

		Event.observe(Element.select(set, '.selected_filter')[0], 'click', Filter.select_filter);
		Event.observe(Element.select(set, '.add_filter')[0], 'click', Filter.add_filter);
		Event.observe(Element.select(set, '.remove_filter')[0], 'click', Filter.remove_filter);

		event.preventDefault();
	},
	remove_filter: function(event) {
		this.blur();
		var filter = this.parentNode.parentNode;
		Element.remove(filter);
		event.preventDefault();
	}
}

Event.addBehavior({
  '.selected_filter:click': Filter.select_filter,
	'.add_filter:click':      Filter.add_filter,
	'.remove_filter:click':   Filter.remove_filter
});
<|endoftext|>


<commit_before>// Base object for different progress bar shapes

var Path = require('./path');
var utils = require('./utils');

var DESTROYED_ERROR = 'Object is destroyed';

var Progress = function Progress(container, opts) {
    // Throw a better error if progress bars are not initialized with `new`
    // keyword
    if (!(this instanceof Progress)) {
        throw new Error('Constructor was called without new keyword');
    }

    // Prevent calling constructor without parameters so inheritance
    // works correctly. To understand, this is how Progress is inherited:
    //
    //   Line.prototype = new Progress();
    //
    // We just want to set the prototype for Line.
    if (arguments.length === 0) return;

    // Default parameters for progress bar creation
    this._opts = utils.extend({
        color: '#555',
        strokeWidth: 1.0,
        trailColor: null,
        trailWidth: null,
        fill: null,
        text: {
            autoStyle: true,
            color: null,
            value: '',
            className: 'progressbar-text'
        }
    }, opts, true);  // Use recursive extend

    var svgView = this._createSvgView(this._opts);

    var element;
    if (utils.isString(container)) {
        element = document.querySelector(container);
    } else {
        element = container;
    }

    if (!element) {
        throw new Error('Container does not exist: ' + container);
    }

    this._container = element;
    this._container.appendChild(svgView.svg);

    this.text = null;
    if (this._opts.text.value) {
        this.text = this._createTextElement(this._opts, this._container);
        this._container.appendChild(this.text);
    }

    var newOpts = utils.extend({
        attachment: this
    }, this._opts);
    this._progressPath = new Path(svgView.path, newOpts);

    // Expose public attributes
    this.svg = svgView.svg;
    this.path = svgView.path;
    this.trail = svgView.trail;
    // this.text is also a public attribute
};

Progress.prototype.animate = function animate(progress, opts, cb) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.animate(progress, opts, cb);
};

Progress.prototype.stop = function stop() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.stop();
};

Progress.prototype.destroy = function destroy() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);

    this.stop();
    this.svg.parentNode.removeChild(this.svg);
    this.svg = null;
    this.path = null;
    this.trail = null;
    this._progressPath = null;

    if (this.text !== null) {
        this.text.parentNode.removeChild(this.text);
        this.text = null;
    }
};

Progress.prototype.set = function set(progress) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.set(progress);
};

Progress.prototype.value = function value() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    return this._progressPath.value();
};

Progress.prototype.setText = function setText(text) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);

    if (this.text === null) {
        this.text = this._createTextElement(this._container, text);
        this._container.appendChild(this.text);
        return;
    }

    this.text.removeChild(this.text.firstChild);
    this.text.appendChild(document.createTextNode(text));
};

Progress.prototype._createSvgView = function _createSvgView(opts) {
    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    this._initializeSvg(svg, opts);

    var trailPath = null;
    // Each option listed in the if condition are 'triggers' for creating
    // the trail path
    if (opts.trailColor || opts.trailWidth) {
        trailPath = this._createTrail(opts);
        svg.appendChild(trailPath);
    }

    var path = this._createPath(opts);
    svg.appendChild(path);

    return {
        svg: svg,
        path: path,
        trail: trailPath
    };
};

Progress.prototype._initializeSvg = function _initializeSvg(svg, opts) {
    svg.setAttribute('viewBox', '0 0 100 100');
};

Progress.prototype._createPath = function _createPath(opts) {
    var pathString = this._pathString(opts);
    return this._createPathElement(pathString, opts);
};

Progress.prototype._createTrail = function _createTrail(opts) {
    // Create path string with original passed options
    var pathString = this._trailString(opts);

    // Prevent modifying original
    var newOpts = utils.extend({}, opts);

    // Defaults for parameters which modify trail path
    if (!newOpts.trailColor) newOpts.trailColor = '#eee';
    if (!newOpts.trailWidth) newOpts.trailWidth = newOpts.strokeWidth;

    newOpts.color = newOpts.trailColor;
    newOpts.strokeWidth = newOpts.trailWidth;

    // When trail path is set, fill must be set for it instead of the
    // actual path to prevent trail stroke from clipping
    newOpts.fill = null;

    return this._createPathElement(pathString, newOpts);
};

Progress.prototype._createPathElement = function _createPathElement(pathString, opts) {
    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', pathString);
    path.setAttribute('stroke', opts.color);
    path.setAttribute('stroke-width', opts.strokeWidth);

    if (opts.fill) {
        path.setAttribute('fill', opts.fill);
    } else {
        path.setAttribute('fill-opacity', '0');
    }

    return path;
};

Progress.prototype._createTextElement = function _createTextElement(opts, container) {
    var element = document.createElement('p');
    element.appendChild(document.createTextNode(opts.text.value));

    if (opts.text.autoStyle) {
        // Center text
        container.style.position = 'relative';
        element.style.position = 'absolute';
        element.style.top = '50%';
        element.style.left = '50%';
        element.style.padding = 0;
        element.style.margin = 0;
        utils.setStyle(element, 'transform', 'translate(-50%, -50%');

        if (opts.text.color) {
            element.style.color = opts.text.color;
        } else {
            element.style.color = opts.color;
        }
    }
    element.className = opts.text.className;

    return element;
};

Progress.prototype._pathString = function _pathString(opts) {
    throw new Error('Override this function for each progress bar');
};

Progress.prototype._trailString = function _trailString(opts) {
    throw new Error('Override this function for each progress bar');
};

module.exports = Progress;
<commit_msg>Fix bug where setting text without initial text definition failed<commit_after>// Base object for different progress bar shapes

var Path = require('./path');
var utils = require('./utils');

var DESTROYED_ERROR = 'Object is destroyed';

var Progress = function Progress(container, opts) {
    // Throw a better error if progress bars are not initialized with `new`
    // keyword
    if (!(this instanceof Progress)) {
        throw new Error('Constructor was called without new keyword');
    }

    // Prevent calling constructor without parameters so inheritance
    // works correctly. To understand, this is how Progress is inherited:
    //
    //   Line.prototype = new Progress();
    //
    // We just want to set the prototype for Line.
    if (arguments.length === 0) return;

    // Default parameters for progress bar creation
    this._opts = utils.extend({
        color: '#555',
        strokeWidth: 1.0,
        trailColor: null,
        trailWidth: null,
        fill: null,
        text: {
            autoStyle: true,
            color: null,
            value: '',
            className: 'progressbar-text'
        }
    }, opts, true);  // Use recursive extend

    var svgView = this._createSvgView(this._opts);

    var element;
    if (utils.isString(container)) {
        element = document.querySelector(container);
    } else {
        element = container;
    }

    if (!element) {
        throw new Error('Container does not exist: ' + container);
    }

    this._container = element;
    this._container.appendChild(svgView.svg);

    this.text = null;
    if (this._opts.text.value) {
        this.text = this._createTextElement(this._opts, this._container);
        this._container.appendChild(this.text);
    }

    var newOpts = utils.extend({
        attachment: this
    }, this._opts);
    this._progressPath = new Path(svgView.path, newOpts);

    // Expose public attributes
    this.svg = svgView.svg;
    this.path = svgView.path;
    this.trail = svgView.trail;
    // this.text is also a public attribute
};

Progress.prototype.animate = function animate(progress, opts, cb) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.animate(progress, opts, cb);
};

Progress.prototype.stop = function stop() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.stop();
};

Progress.prototype.destroy = function destroy() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);

    this.stop();
    this.svg.parentNode.removeChild(this.svg);
    this.svg = null;
    this.path = null;
    this.trail = null;
    this._progressPath = null;

    if (this.text !== null) {
        this.text.parentNode.removeChild(this.text);
        this.text = null;
    }
};

Progress.prototype.set = function set(progress) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    this._progressPath.set(progress);
};

Progress.prototype.value = function value() {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);
    return this._progressPath.value();
};

Progress.prototype.setText = function setText(text) {
    if (this._progressPath === null) throw new Error(DESTROYED_ERROR);

    if (this.text === null) {
        this.text = this._createTextElement(this._opts, this._container);
        this._container.appendChild(this.text);
        return;
    }

    this.text.removeChild(this.text.firstChild);
    this.text.appendChild(document.createTextNode(text));
};

Progress.prototype._createSvgView = function _createSvgView(opts) {
    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    this._initializeSvg(svg, opts);

    var trailPath = null;
    // Each option listed in the if condition are 'triggers' for creating
    // the trail path
    if (opts.trailColor || opts.trailWidth) {
        trailPath = this._createTrail(opts);
        svg.appendChild(trailPath);
    }

    var path = this._createPath(opts);
    svg.appendChild(path);

    return {
        svg: svg,
        path: path,
        trail: trailPath
    };
};

Progress.prototype._initializeSvg = function _initializeSvg(svg, opts) {
    svg.setAttribute('viewBox', '0 0 100 100');
};

Progress.prototype._createPath = function _createPath(opts) {
    var pathString = this._pathString(opts);
    return this._createPathElement(pathString, opts);
};

Progress.prototype._createTrail = function _createTrail(opts) {
    // Create path string with original passed options
    var pathString = this._trailString(opts);

    // Prevent modifying original
    var newOpts = utils.extend({}, opts);

    // Defaults for parameters which modify trail path
    if (!newOpts.trailColor) newOpts.trailColor = '#eee';
    if (!newOpts.trailWidth) newOpts.trailWidth = newOpts.strokeWidth;

    newOpts.color = newOpts.trailColor;
    newOpts.strokeWidth = newOpts.trailWidth;

    // When trail path is set, fill must be set for it instead of the
    // actual path to prevent trail stroke from clipping
    newOpts.fill = null;

    return this._createPathElement(pathString, newOpts);
};

Progress.prototype._createPathElement = function _createPathElement(pathString, opts) {
    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', pathString);
    path.setAttribute('stroke', opts.color);
    path.setAttribute('stroke-width', opts.strokeWidth);

    if (opts.fill) {
        path.setAttribute('fill', opts.fill);
    } else {
        path.setAttribute('fill-opacity', '0');
    }

    return path;
};

Progress.prototype._createTextElement = function _createTextElement(opts, container) {
    var element = document.createElement('p');
    element.appendChild(document.createTextNode(opts.text.value));

    if (opts.text.autoStyle) {
        // Center text
        container.style.position = 'relative';
        element.style.position = 'absolute';
        element.style.top = '50%';
        element.style.left = '50%';
        element.style.padding = 0;
        element.style.margin = 0;
        utils.setStyle(element, 'transform', 'translate(-50%, -50%');

        if (opts.text.color) {
            element.style.color = opts.text.color;
        } else {
            element.style.color = opts.color;
        }
    }
    element.className = opts.text.className;

    return element;
};

Progress.prototype._pathString = function _pathString(opts) {
    throw new Error('Override this function for each progress bar');
};

Progress.prototype._trailString = function _trailString(opts) {
    throw new Error('Override this function for each progress bar');
};

module.exports = Progress;
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('chaise.viewer')

    .controller('CommentsController', ['AuthService', 'CommentsService', '$scope', '$uibModal', 'comments', function AnnotationsController(AuthService, CommentsService, $scope, $uibModal, comments) {
        var vm = this;
        vm.comments = comments;
        vm.newComment = {
            annotationId: null,
            comment: null,
            author: null
        };

        vm.allowCreate = AuthService.createComment;
        vm.allowEdit = AuthService.editComment;
        vm.allowDelete = AuthService.deleteComment;

        vm.createComment = createComment;
        vm.deleteComment = deleteComment;

        vm.editedComment = null; // Used to track which comment was editted so we can show the form properly
        var originalComment = null; // For reseting the comment data incase the user clicks cancel
        vm.editComment = editComment;
        vm.cancelEdit = cancelEdit;
        vm.updateComment = updateComment;

        vm.authorName = authorName;

        function createComment(annotationId) {
            vm.newComment.annotationId = annotationId;
            CommentsService.createComment(vm.newComment);
            resetNewComment();
        }

        function editComment(comment) {
            vm.editedComment = comment.table.name + '-' + comment.data.id;
            originalComment = {
                comment: comment.data.comment
            }
        }

        function cancelEdit(comment) {
            vm.editedComment = null;
            comment.data.comment = originalComment.comment;
        }

        function updateComment(comment) {
            CommentsService.updateComment(comment);
            vm.editedComment = null;
        }

        function deleteComment(comment) {
            if (chaiseConfig.confirmDelete == undefined ||  chaiseConfig.confirmDelete){
                var modalInstance = $uibModal.open({
                    templateUrl: 'annotations/confirm_delete.html',
                    controller: 'ConfirmDeleteController',
                    size: 'sm'
                });

                modalInstance.result.then(function () {
                    CommentsService.deleteComment(comment);
                    console.log('comment deleted');
                }, function () {
                    console.log('Modal dismissed');
                });
            } else {
                CommentsService.deleteComment(comment);
                console.log('comment deleted');
            }
        }

        // Set newComment back to its default vaules
        function resetNewComment() {
            vm.newComment = {
                annotationId: null,
                comment: null,
                author: null
            };
        }

        // Used to set the author based on the info object from the user object (user.info) that is set on every comment
        // The info object is the session.client object and may contain a combination of display_name, full_name, and email
        function authorName(client) {
            return (client.display_name ? client.display_name : (client.full_name ? client.full_name : client.email ));
        }
    }]);
})();
<commit_msg>Changes for Controller As syntax for confiermation dialog weren't added to the Comments Controller. Works properly now<commit_after>(function() {
    'use strict';

    angular.module('chaise.viewer')

    .controller('CommentsController', ['AuthService', 'CommentsService', '$scope', '$uibModal', 'comments', function AnnotationsController(AuthService, CommentsService, $scope, $uibModal, comments) {
        var vm = this;
        vm.comments = comments;
        vm.newComment = {
            annotationId: null,
            comment: null,
            author: null
        };

        vm.allowCreate = AuthService.createComment;
        vm.allowEdit = AuthService.editComment;
        vm.allowDelete = AuthService.deleteComment;

        vm.createComment = createComment;
        vm.deleteComment = deleteComment;

        vm.editedComment = null; // Used to track which comment was editted so we can show the form properly
        var originalComment = null; // For reseting the comment data incase the user clicks cancel
        vm.editComment = editComment;
        vm.cancelEdit = cancelEdit;
        vm.updateComment = updateComment;

        vm.authorName = authorName;

        function createComment(annotationId) {
            vm.newComment.annotationId = annotationId;
            CommentsService.createComment(vm.newComment);
            resetNewComment();
        }

        function editComment(comment) {
            vm.editedComment = comment.table.name + '-' + comment.data.id;
            originalComment = {
                comment: comment.data.comment
            }
        }

        function cancelEdit(comment) {
            vm.editedComment = null;
            comment.data.comment = originalComment.comment;
        }

        function updateComment(comment) {
            CommentsService.updateComment(comment);
            vm.editedComment = null;
        }

        function deleteComment(comment) {
            if (chaiseConfig.confirmDelete == undefined ||  chaiseConfig.confirmDelete){
                var modalInstance = $uibModal.open({
                    templateUrl: 'annotations/confirm_delete.html',
                    controller: 'ConfirmDeleteController',
                    controllerAs: 'ctrl',
                    size: 'sm'
                });

                modalInstance.result.then(function () {
                    CommentsService.deleteComment(comment);
                    console.log('comment deleted');
                }, function () {
                    console.log('Modal dismissed');
                });
            } else {
                CommentsService.deleteComment(comment);
                console.log('comment deleted');
            }
        }

        // Set newComment back to its default vaules
        function resetNewComment() {
            vm.newComment = {
                annotationId: null,
                comment: null,
                author: null
            };
        }

        // Used to set the author based on the info object from the user object (user.info) that is set on every comment
        // The info object is the session.client object and may contain a combination of display_name, full_name, and email
        function authorName(client) {
            return (client.display_name ? client.display_name : (client.full_name ? client.full_name : client.email ));
        }
    }]);
})();
<|endoftext|>


<commit_before>import React from 'react'
import R from 'ramda'
import h from "lib/ui/hyperscript_with_helpers"
import {twitterShortTs} from 'lib/utils/date'
import {imagePath} from "lib/ui"
import {capitalize} from "lib/utils/string"
import SmallLoader from 'components/shared/small_loader'
import KeyIcon from "components/shared/key_icon"

export default function ({
  onRenew,
  onRevoke,
  isRemoving,
  getUserFn,
  isGeneratingAssocKey,
  isRevokingAssocKey,
  keyGeneratedAt,
  keyGeneratedById,
  envkey,
  passphrase,
  permissions,
  isCurrentUser=false,
  currentUser
}){
  const
    canGenerate = ()=> permissions.generateKey && !isRemoving,

    renderUpdateButtons = ()=> h.div(".update-buttons", [
        renderRevokeButton(),
        renderGenerateButton()
    ]),

    renderGenerateLabel = ()=> keyGeneratedAt ? "Renew" : "Generate",

    renderGenerateButton = ()=> h.button(".renew",{
      onClick: onRenew
    }, renderGenerateLabel()),

    renderRevokeButton = ()=> {
      return h.button(".revoke", {
        onClick: onRevoke
      }, "Revoke")
    },

    renderButtons = ()=> {
      if (isRemoving)return ""
      if (isGeneratingAssocKey || isRevokingAssocKey){
        return h(SmallLoader)
      } else if (canGenerate()) {
        if (keyGeneratedAt){
          return renderUpdateButtons()
        } else {
          return renderGenerateButton()
        }
      }
    },

    renderKeyLabel = ()=> {
      let contents

      if (isGeneratingAssocKey){
        contents = [
          h.span(".secondary", "Generating key...")
        ]
      } else if (isRevokingAssocKey){
        contents = [
          h.span(".secondary", "Revoking key...")
        ]
      } else if (keyGeneratedAt){
        const {firstName, lastName} = isCurrentUser ? currentUser : getUserFn(keyGeneratedById),
              fullName = [firstName, lastName].join(" ")
        contents = [
          h.span(".secondary", `${fullName} `),
          h.span(".key-date", "・ " + twitterShortTs(keyGeneratedAt))
        ]
      } else {
        contents = [
          h.span(".secondary", "No envkey generated")
        ]
      }

      return h.span(".key-label", contents)
    }

  return h.div(".keyable-actions", {
    className: [
      (keyGeneratedAt ? "has-key" : ""),
      (isGeneratingAssocKey ? "generating-key" : "")
    ].join(" ")

  },[
    h.div(".key-info", [
      h(KeyIcon),
      renderKeyLabel()
    ]),
    h.div(".actions", [
      renderButtons()
    ])
  ])

}<commit_msg>temporary fix for handling deleted user who generated server key<commit_after>import React from 'react'
import R from 'ramda'
import h from "lib/ui/hyperscript_with_helpers"
import {twitterShortTs} from 'lib/utils/date'
import {imagePath} from "lib/ui"
import {capitalize} from "lib/utils/string"
import SmallLoader from 'components/shared/small_loader'
import KeyIcon from "components/shared/key_icon"

export default function ({
  onRenew,
  onRevoke,
  isRemoving,
  getUserFn,
  isGeneratingAssocKey,
  isRevokingAssocKey,
  keyGeneratedAt,
  keyGeneratedById,
  envkey,
  passphrase,
  permissions,
  isCurrentUser=false,
  currentUser
}){
  const
    canGenerate = ()=> permissions.generateKey && !isRemoving,

    renderUpdateButtons = ()=> h.div(".update-buttons", [
        renderRevokeButton(),
        renderGenerateButton()
    ]),

    renderGenerateLabel = ()=> keyGeneratedAt ? "Renew" : "Generate",

    renderGenerateButton = ()=> h.button(".renew",{
      onClick: onRenew
    }, renderGenerateLabel()),

    renderRevokeButton = ()=> {
      return h.button(".revoke", {
        onClick: onRevoke
      }, "Revoke")
    },

    renderButtons = ()=> {
      if (isRemoving)return ""
      if (isGeneratingAssocKey || isRevokingAssocKey){
        return h(SmallLoader)
      } else if (canGenerate()) {
        if (keyGeneratedAt){
          return renderUpdateButtons()
        } else {
          return renderGenerateButton()
        }
      }
    },

    renderKeyLabel = ()=> {
      let contents

      if (isGeneratingAssocKey){
        contents = [
          h.span(".secondary", "Generating key...")
        ]
      } else if (isRevokingAssocKey){
        contents = [
          h.span(".secondary", "Revoking key...")
        ]
      } else if (keyGeneratedAt){
        const user = isCurrentUser ? currentUser : getUserFn(keyGeneratedById),
              fullName = user ? [user.firstName, user.lastName].join(" ") : "[deleted]"
        contents = [
          h.span(".secondary", `${fullName} `),
          h.span(".key-date", "・ " + twitterShortTs(keyGeneratedAt))
        ]
      } else {
        contents = [
          h.span(".secondary", "No envkey generated")
        ]
      }

      return h.span(".key-label", contents)
    }

  return h.div(".keyable-actions", {
    className: [
      (keyGeneratedAt ? "has-key" : ""),
      (isGeneratingAssocKey ? "generating-key" : "")
    ].join(" ")

  },[
    h.div(".key-info", [
      h(KeyIcon),
      renderKeyLabel()
    ]),
    h.div(".actions", [
      renderButtons()
    ])
  ])

}<|endoftext|>