<commit_before>var autoprefixer = require('autoprefixer');
var Core = require('css-modules-loader-core');
require('es6-promise');
var fs = require('fs');
var genericNames = require('generic-names');
var gulp = require('gulp');
var concat = require('gulp-concat');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var template = require('gulp-template');
var _ = require('lodash');
var _postcss = require('postcss');
var Parser = require('postcss-modules-parser');

var core = new Core([
  Core.values,
  Core.localByDefault,
  Core.extractImports,
  Core.scope({
    generateScopedName: genericNames("[name]__[local]"),
  }),
  autoprefixer,
]);

var templateData = {
  require: require,
};

require.extensions['.css'] = function(module, path) {
  var instance = _postcss(core.plugins.concat(new Parser));
  var css = fs.readFileSync(path, 'utf8');
  var tokens = instance.process(css, { from: path }).root.tokens;
  return module._compile("module.exports = " + JSON.stringify(tokens), path);
};

require.extensions['.html'] = function(module, path) {
  var templateHTML = fs.readFileSync(path, 'utf8');
  var html = _.template(templateHTML)(templateData);
  return module._compile("module.exports = " + JSON.stringify(html), path);
};

gulp.task('styles', ['templates'], function() {
  return gulp.src("./styles/*.css")
    .pipe(sourcemaps.init())
    .pipe(postcss(core.plugins))
    .pipe(concat("./styles.css"))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest("./build"));
});

gulp.task('templates', function() {
  Object.keys(require.cache).map(function(path) {
    if (/\.(css|html)$/.test(path)) delete require.cache[path];
  });
  return gulp.src("./*.html")
    .pipe(template(templateData))
    .pipe(gulp.dest("./build"));
});

gulp.task('watch', function() {
  gulp.watch("./styles/*.css", ['styles']);
  gulp.watch(["./*.html", "./includes/*.html"], ['templates']);
});

gulp.task('default', [
  'styles',
  'templates',
  'watch',
]);
<commit_msg>Add a build gulp task<commit_after>var autoprefixer = require('autoprefixer');
var Core = require('css-modules-loader-core');
require('es6-promise');
var fs = require('fs');
var genericNames = require('generic-names');
var gulp = require('gulp');
var concat = require('gulp-concat');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var template = require('gulp-template');
var _ = require('lodash');
var _postcss = require('postcss');
var Parser = require('postcss-modules-parser');

var core = new Core([
  Core.values,
  Core.localByDefault,
  Core.extractImports,
  Core.scope({
    generateScopedName: genericNames("[name]__[local]"),
  }),
  autoprefixer,
]);

var templateData = {
  require: require,
};

require.extensions['.css'] = function(module, path) {
  var instance = _postcss(core.plugins.concat(new Parser));
  var css = fs.readFileSync(path, 'utf8');
  var tokens = instance.process(css, { from: path }).root.tokens;
  return module._compile("module.exports = " + JSON.stringify(tokens), path);
};

require.extensions['.html'] = function(module, path) {
  var templateHTML = fs.readFileSync(path, 'utf8');
  var html = _.template(templateHTML)(templateData);
  return module._compile("module.exports = " + JSON.stringify(html), path);
};

gulp.task('styles', ['templates'], function() {
  return gulp.src("./styles/*.css")
    .pipe(sourcemaps.init())
    .pipe(postcss(core.plugins))
    .pipe(concat("./styles.css"))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest("./build"));
});

gulp.task('templates', function() {
  Object.keys(require.cache).map(function(path) {
    if (/\.(css|html)$/.test(path)) delete require.cache[path];
  });
  return gulp.src("./*.html")
    .pipe(template(templateData))
    .pipe(gulp.dest("./build"));
});

gulp.task('watch', function() {
  gulp.watch("./styles/*.css", ['styles']);
  gulp.watch(["./*.html", "./includes/*.html"], ['templates']);
});

gulp.task('build', [
  'styles',
  'templates',
]);

gulp.task('default', [
  'build',
  'watch',
]);
<|endoftext|>


<commit_before>'use strict';
/*jslint browser: true*/

var isic_app = angular.module('DermApp');

isic_app.controller('ApplicationController',
    ['$scope', '$location', '$http',
    function ($scope, $location, $http) {

        $("#angular_id").height(window.innerHeight - 80 - 100);
        $("#gridcontainer").height(window.innerHeight - 100 - 100);

        var url_path_components = $location.path().substring(1).split('/');
        // TODO: check these params exist
        $scope.gallery_type = url_path_components[0];
        $scope.gallery_id = url_path_components[1];

        var folder_url = '/api/v1/folder/' + $scope.gallery_id;
        var images_url = '/api/v1/item?limit=50&offset=0&folderId=' + $scope.gallery_id;

        var complete_submit_url;
        var complete_redirect_url;
        if ($scope.gallery_type === 'qc') {
            complete_submit_url = '/api/v1/uda/task/qc/' + $scope.gallery_id + '/complete';
            complete_redirect_url = '/uda/task';
        }
        else if ($scope.gallery_type === 'select') {
            complete_submit_url = '/api/v1/uda/task/select/' + $scope.gallery_id;
            complete_redirect_url = null;
        }

        $scope.sync = function () {
            // get folder details for name and times
            $http.get(folder_url).success(function (data) {
                $scope.folder_details = data;
            });

            // images in folder
            $scope.flagged_list = {};
            $http.get(images_url).success(function (data) {
                $scope.image_list = [];
                data.forEach(function (image) {
                    image.thumbnail = '/api/v1/image/' + image._id + '/download?contentDisposition=inline';

                    image.diagnosis_strings = [];
                    [
                        'benign_malignant',
                        'diagnosis data',
                        'pathology'
                    ].forEach(function (key) {
                        var value = image.meta.clinical[key];
                        if (value) {
                            image.diagnosis_strings.push(key + ': ' + value);
                        }
                    });

                    $scope.image_list.push(image);
                });
            });

        };
        $scope.sync();

        $scope.isFlagged = function (index) {
            return $scope.flagged_list.hasOwnProperty(index);
        };

        $scope.toggleFlagged = function (index) {
            var t = $scope.flagged_list[index];

            if (t === undefined) {
                $scope.flagged_list[index] = $scope.image_list[index];
            } else {
                delete $scope.flagged_list[index];
            }
        };

        function submit(include_accepted) {
            var flagged_images = [];
            for (var image_index in $scope.flagged_list) {
                if ($scope.flagged_list.hasOwnProperty(image_index)) {
                    flagged_images.push($scope.flagged_list[image_index]._id);
                }
            }

            var images_to_accept = [];
            if (include_accepted) {
                $scope.image_list.forEach(function (image, image_index) {
                    if (!$scope.flagged_list.hasOwnProperty(image_index)) {
                        images_to_accept.push($scope.image_list[image_index]._id);
                    }
                });
            }

            var payload = {
                flagged: flagged_images,
                good : images_to_accept
            };
            $http.post(complete_submit_url, payload).success(function() {
                if (include_accepted) {
                    if (complete_redirect_url === null) {
                        $scope.sync();
                    } else {
                        window.location.replace(complete_redirect_url);
                    }
                }
                else {
                    // TODO: disable buttons while request is pending
                    $scope.sync();
                }
            });
        }
        $scope.submitAll = function() {
            submit(true);
        };
        $scope.submitFlagged = function() {
            submit(false);
        };

        $scope.hover_image = undefined;

        $scope.mouse = {
            '.' : $scope.nextSet,
            ',' : $scope.previousSet
        };
    }
]);
<commit_msg>Prevent CSV files in Phase 0 folder from interfering with gallery<commit_after>'use strict';
/*jslint browser: true*/

var isic_app = angular.module('DermApp');

isic_app.controller('ApplicationController',
    ['$scope', '$location', '$http',
    function ($scope, $location, $http) {

        $("#angular_id").height(window.innerHeight - 80 - 100);
        $("#gridcontainer").height(window.innerHeight - 100 - 100);

        var url_path_components = $location.path().substring(1).split('/');
        // TODO: check these params exist
        $scope.gallery_type = url_path_components[0];
        $scope.gallery_id = url_path_components[1];

        var folder_url = '/api/v1/folder/' + $scope.gallery_id;
        var images_url = '/api/v1/item?limit=50&offset=0&folderId=' + $scope.gallery_id;

        var complete_submit_url;
        var complete_redirect_url;
        if ($scope.gallery_type === 'qc') {
            complete_submit_url = '/api/v1/uda/task/qc/' + $scope.gallery_id + '/complete';
            complete_redirect_url = '/uda/task';
        }
        else if ($scope.gallery_type === 'select') {
            complete_submit_url = '/api/v1/uda/task/select/' + $scope.gallery_id;
            complete_redirect_url = null;
        }

        $scope.sync = function () {
            // get folder details for name and times
            $http.get(folder_url).success(function (data) {
                $scope.folder_details = data;
            });

            // images in folder
            $scope.flagged_list = {};
            $http.get(images_url).success(function (data) {
                $scope.image_list = [];
                data.forEach(function (image) {
                    if (image.name.endsWith('.csv')) {
                        return;
                    }

                    image.thumbnail = '/api/v1/image/' + image._id + '/download?contentDisposition=inline';

                    image.diagnosis_strings = [];
                    [
                        'benign_malignant',
                        'diagnosis data',
                        'pathology'
                    ].forEach(function (key) {
                        var value = image.meta.clinical[key];
                        if (value) {
                            image.diagnosis_strings.push(key + ': ' + value);
                        }
                    });

                    $scope.image_list.push(image);
                });
            });

        };
        $scope.sync();

        $scope.isFlagged = function (index) {
            return $scope.flagged_list.hasOwnProperty(index);
        };

        $scope.toggleFlagged = function (index) {
            var t = $scope.flagged_list[index];

            if (t === undefined) {
                $scope.flagged_list[index] = $scope.image_list[index];
            } else {
                delete $scope.flagged_list[index];
            }
        };

        function submit(include_accepted) {
            var flagged_images = [];
            for (var image_index in $scope.flagged_list) {
                if ($scope.flagged_list.hasOwnProperty(image_index)) {
                    flagged_images.push($scope.flagged_list[image_index]._id);
                }
            }

            var images_to_accept = [];
            if (include_accepted) {
                $scope.image_list.forEach(function (image, image_index) {
                    if (!$scope.flagged_list.hasOwnProperty(image_index)) {
                        images_to_accept.push($scope.image_list[image_index]._id);
                    }
                });
            }

            var payload = {
                flagged: flagged_images,
                good : images_to_accept
            };
            $http.post(complete_submit_url, payload).success(function() {
                if (include_accepted) {
                    if (complete_redirect_url === null) {
                        $scope.sync();
                    } else {
                        window.location.replace(complete_redirect_url);
                    }
                }
                else {
                    // TODO: disable buttons while request is pending
                    $scope.sync();
                }
            });
        }
        $scope.submitAll = function() {
            submit(true);
        };
        $scope.submitFlagged = function() {
            submit(false);
        };

        $scope.hover_image = undefined;

        $scope.mouse = {
            '.' : $scope.nextSet,
            ',' : $scope.previousSet
        };
    }
]);
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2016 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function () {
	"use strict";

	angular.module("3drepo")
		.directive("walkthrough", walkthroughVr);

	function walkthroughVr() {
		return {
			restrict: "EA",
			scope: {
				account: "@",
				project: "@",
				autoPlay: "@",
				animate: "@",
				fps: "@",
				rollerCoaster: "@"
			},
			template: "walkthrough.html",
			controller: WalkthroughCtrl,
			controllerAs: "wt",
			bindToController: true
		};
	}

	var DEFAULT_FRAMES_PER_SECOND = 30;
	var USER_CONTROL_WAIT         = 60000;

	WalkthroughCtrl.$inject = ["$scope", "$q", "$interval", "$timeout", "WalkthroughService", "EventService"];

	function WalkthroughCtrl($scope, $q, $interval, $timeout, WalkthroughService, EventService) {
		var wt = this;

		wt.initialized = false;

		// Animation login
		wt.frames = [];

		wt.loading       = null;
		wt.frame         = 0;
		wt.autoPlay      = angular.isDefined(wt.autoPlay) ? wt.autoPlay : false;

		wt.fps           = angular.isDefined(wt.fps) ? wt.fps : DEFAULT_FRAMES_PER_SECOND;

		wt.rollerCoaster = angular.isDefined(wt.rollerCoaster);
		wt.animate       = angular.isDefined(wt.animate);

		wt.currentWalkthrough = wt.autoPlay ? wt.autoPlay : -1;

		wt.recording   = [];

		wt.isPlaying   = false;
		wt.isRecording = false;

		wt.playInterval      = null;
		wt.recordingInterval = null;
		wt.userWatchDog      = null;

        wt.stop = function () {
			if (wt.isPlaying)
			{
				$interval.cancel(wt.playInterval);
				wt.isPlaying = false;
			}
        };

		wt.play = function() {
			if (!wt.initialized)
			{
				wt.initialized = true;
				wt.isPlaying = true;
				$timeout.cancel(wt.userWatchDog);

				// Loop through the viewer frames
				wt.frame = 0;
				wt.playInterval = $interval(wt.tickFunction, wt.msPerFrame);

			}
		};

		wt.startRecording = function () {
            if (wt.currentWalkthrough !== -1) {
                wt.isRecording = true;
                wt.recording = [];
                wt.recordingInterval = $interval(function () {
					var viewpointPromise = $q.defer();

					EventService.send(EventService.EVENT.VIEWER.GET_CURRENT_VIEWPOINT,
					{
						promise: viewpointPromise.promise
					});

					viewpointPromise.then(function (viewpoint) {
                    	wt.recording.push({
	                        position: viewpoint.position,
    	                    up: viewpoint.up,
        	                view_dir: viewpoint.view_dir
            	        });
					});
                }, wt.msPerFrame);
            }
		};

		wt.stopRecording = function () {
            wt.isRecording = false;
            $interval.cancel(wt.recordingInterval);

			WalkthroughService.saveRecording(wt.account, wt.project, wt.currentWalkthrough, wt.recording);
        };

		wt.tickFunction = function() {
			if (wt.loading) {
				wt.loading.then(function() {
					EventService.send(EventService.EVENT.VIEWER.SET_CAMERA,
					{
						position:          wt.frames[wt.frame].position,
						up:                wt.frames[wt.frame].up,
						view_dir:          wt.frames[wt.frame].view_dir,
						rollerCoasterMode: wt.rollerCoaster,
						animate:           wt.animate
					});

					if (wt.frame === (wt.numFrames - 1)) {
						wt.frame = 0;
					}
					else {
						wt.frame += 1;
					}
				});
			}
		};

		/*
		wt.loadFrames = function () {
			var url = "/public/plugins/walkthroughVr/" + wt.account + "/" + wt.project + "/frames.csv";

			wt.loading = $q.defer();
			// Get the exported frames
			$http.get(url)
				.then(function (response) {
					var lines, line,
						i, length;

					wt.frames = [];

					// Convert the frames to viewer frames
					lines = response.data.split("\n");
					lines.splice(lines.length - 1);
					for(i = 0, length = lines.length; i < length; i += 1) {
						line = lines[i].split(",");
						wt.frames.push({
							position: [parseFloat(line[0]), parseFloat(line[2]), -1 * parseFloat(line[1])],
							view_dir: [parseFloat(line[3]), parseFloat(line[5]), -1 * parseFloat(line[4])],
							up: [parseFloat(line[6]), parseFloat(line[8]), -1 * parseFloat(line[7])]
						});
					}

					wt.numFrames = wt.frames.length;
					wt.loading.resolve();
			});
		};*/

		// Button control logic
		wt.recordButtonClass = "btn walkthroughButton btn-success";

        wt.record = function () {
            if (wt.currentWalkthrough !== -1) {
                if (wt.isRecording) {
                    wt.stopRecording();
                    wt.recordButtonClass = "btn walkthroughButton btn-success";
                }
                else {
                    wt.startRecording();
                    wt.recordButtonClass = "btn walkthroughButton btn-danger";
                }
            }
        };

        wt.userInControl = function () {
            wt.stop();

			$interval.cancel(wt.userWatchDog);
			wt.userWatchDog = $timeout(function () {
				wt.play();
			}, USER_CONTROL_WAIT);
        };

        wt.setCurrentWalkthrough = function (index) {
            wt.currentWalkthrough = index;
			wt.loading = WalkthroughService.getWalkthroughs(wt.account, wt.project, index);
        };

		// If the account changes then re-load the frames
		$scope.$watchGroup(["account", "project"], function() {
			wt.currentWalkthrough = 0;
			wt.loading = WalkthroughService.getWalkthroughs(wt.account, wt.project);
			wt.play();
		});

		$scope.$watch(["fps"], function (newFPS) {
			wt.fps = newFPS;
			wt.msPerFrame = Math.floor(1000.0 / wt.fps);
		});

		$scope.$on("$destroy", function handler() {
			wt.stop();
		});

		wt.setCurrentWalkthrough(wt.currentWalkthrough);
	}
}());<commit_msg>ISSUE #186 - Disable auto-play on walkthrough<commit_after>/**
 *  Copyright (C) 2016 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function () {
	"use strict";

	angular.module("3drepo")
		.directive("walkthrough", walkthroughVr);

	function walkthroughVr() {
		return {
			restrict: "EA",
			scope: {
				account: "@",
				project: "@",
				autoPlay: "@",
				animate: "@",
				fps: "@",
				rollerCoaster: "@"
			},
			template: "walkthrough.html",
			controller: WalkthroughCtrl,
			controllerAs: "wt",
			bindToController: true
		};
	}

	var DEFAULT_FRAMES_PER_SECOND = 30;
	var USER_CONTROL_WAIT         = 60000;

	WalkthroughCtrl.$inject = ["$scope", "$q", "$interval", "$timeout", "WalkthroughService", "EventService"];

	function WalkthroughCtrl($scope, $q, $interval, $timeout, WalkthroughService, EventService) {
		var wt = this;

		wt.initialized = false;

		// Animation login
		wt.frames = [];

		wt.loading       = null;
		wt.frame         = 0;
		wt.autoPlay      = angular.isDefined(wt.autoPlay) ? wt.autoPlay : false;

		wt.fps           = angular.isDefined(wt.fps) ? wt.fps : DEFAULT_FRAMES_PER_SECOND;

		wt.rollerCoaster = angular.isDefined(wt.rollerCoaster);
		wt.animate       = angular.isDefined(wt.animate);

		wt.currentWalkthrough = wt.autoPlay ? wt.autoPlay : -1;

		wt.recording   = [];

		wt.isPlaying   = false;
		wt.isRecording = false;

		wt.playInterval      = null;
		wt.recordingInterval = null;
		wt.userWatchDog      = null;

        wt.stop = function () {
			if (wt.isPlaying)
			{
				$interval.cancel(wt.playInterval);
				wt.isPlaying = false;
			}
        };

		wt.play = function() {
			if (!wt.initialized)
			{
				wt.initialized = true;
				wt.isPlaying = true;
				$timeout.cancel(wt.userWatchDog);

				// Loop through the viewer frames
				wt.frame = 0;
				wt.playInterval = $interval(wt.tickFunction, wt.msPerFrame);

			}
		};

		wt.startRecording = function () {
            if (wt.currentWalkthrough !== -1) {
                wt.isRecording = true;
                wt.recording = [];
                wt.recordingInterval = $interval(function () {
					var viewpointPromise = $q.defer();

					EventService.send(EventService.EVENT.VIEWER.GET_CURRENT_VIEWPOINT,
					{
						promise: viewpointPromise.promise
					});

					viewpointPromise.then(function (viewpoint) {
                    	wt.recording.push({
	                        position: viewpoint.position,
    	                    up: viewpoint.up,
        	                view_dir: viewpoint.view_dir
            	        });
					});
                }, wt.msPerFrame);
            }
		};

		wt.stopRecording = function () {
            wt.isRecording = false;
            $interval.cancel(wt.recordingInterval);

			WalkthroughService.saveRecording(wt.account, wt.project, wt.currentWalkthrough, wt.recording);
        };

		wt.tickFunction = function() {
			if (wt.loading) {
				wt.loading.then(function() {
					EventService.send(EventService.EVENT.VIEWER.SET_CAMERA,
					{
						position:          wt.frames[wt.frame].position,
						up:                wt.frames[wt.frame].up,
						view_dir:          wt.frames[wt.frame].view_dir,
						rollerCoasterMode: wt.rollerCoaster,
						animate:           wt.animate
					});

					if (wt.frame === (wt.numFrames - 1)) {
						wt.frame = 0;
					}
					else {
						wt.frame += 1;
					}
				});
			}
		};

		/*
		wt.loadFrames = function () {
			var url = "/public/plugins/walkthroughVr/" + wt.account + "/" + wt.project + "/frames.csv";

			wt.loading = $q.defer();
			// Get the exported frames
			$http.get(url)
				.then(function (response) {
					var lines, line,
						i, length;

					wt.frames = [];

					// Convert the frames to viewer frames
					lines = response.data.split("\n");
					lines.splice(lines.length - 1);
					for(i = 0, length = lines.length; i < length; i += 1) {
						line = lines[i].split(",");
						wt.frames.push({
							position: [parseFloat(line[0]), parseFloat(line[2]), -1 * parseFloat(line[1])],
							view_dir: [parseFloat(line[3]), parseFloat(line[5]), -1 * parseFloat(line[4])],
							up: [parseFloat(line[6]), parseFloat(line[8]), -1 * parseFloat(line[7])]
						});
					}

					wt.numFrames = wt.frames.length;
					wt.loading.resolve();
			});
		};*/

		// Button control logic
		wt.recordButtonClass = "btn walkthroughButton btn-success";

        wt.record = function () {
            if (wt.currentWalkthrough !== -1) {
                if (wt.isRecording) {
                    wt.stopRecording();
                    wt.recordButtonClass = "btn walkthroughButton btn-success";
                }
                else {
                    wt.startRecording();
                    wt.recordButtonClass = "btn walkthroughButton btn-danger";
                }
            }
        };

        wt.userInControl = function () {
            wt.stop();

			$interval.cancel(wt.userWatchDog);
			wt.userWatchDog = $timeout(function () {
				wt.play();
			}, USER_CONTROL_WAIT);
        };

        wt.setCurrentWalkthrough = function (index) {
            wt.currentWalkthrough = index;
			wt.loading = WalkthroughService.getWalkthroughs(wt.account, wt.project, index);
        };

		// If the account changes then re-load the frames
		$scope.$watchGroup(["account", "project"], function() {
			wt.currentWalkthrough = 0;
			wt.loading = WalkthroughService.getWalkthroughs(wt.account, wt.project);
			//wt.play();
		});

		$scope.$watch(["fps"], function (newFPS) {
			wt.fps = newFPS;
			wt.msPerFrame = Math.floor(1000.0 / wt.fps);
		});

		$scope.$on("$destroy", function handler() {
			wt.stop();
		});

		wt.setCurrentWalkthrough(wt.currentWalkthrough);
	}
}());<|endoftext|>


<commit_before>// candle.canvas.js

(function(){

// Candleオブジェクトがない場合は何もしない
if(!window.Candle){ return;}

// canvas描画可能条件
if(!document.createElement('canvas').getContext){ return;}

/* ------------- */
/*  const value  */
/* ------------- */
var Candle = window.Candle,
	_doc = document,
	_2PI = 2*Math.PI;

/* -------------------- */
/*   Canvas用ラッパー   */
/* -------------------- */
Candle.addTypes('canvas');

Candle.addWrapper('canvas:wrapperbase',{

	initialize : function(idname){
		Candle.wrapper.wrapperbase.prototype.initialize.call(this, idname);

		// variables for internal
		this.context  = null;	// 本来のCanvasRenderingContext2Dオブジェクト

		this.use = new Candle.TypeList('canvas');

		this.x0 = 0;
		this.y0 = 0;

		this.initElement();
	},

	/* extend functions (initialize) */
	initElement : function(){
		this.canvas = _doc.getElementById(this.idname);

		var rect = Candle.getRectSize(this.canvas);
		var top = _doc.createElement('canvas');
		top.id = this.canvasid;

		top.width  = rect.width;
		top.height = rect.height;
		top.style.position = 'relative';
		top.style.width  = rect.width + 'px';
		top.style.height = rect.height + 'px';
		this.canvas.appendChild(top);

		this.child = top;
		this.afterInit();
	},
	afterInit : function(){
		var parent = this.canvas;
		var child  = this.child;

		var self = this;
		parent.style.display  = 'block';
		parent.style.position = 'relative';
		parent.style.overflow = 'hidden';
		if(Candle.debugmode){
			parent.style.backgroundColor = "#efefef";
			parent.style.border = "solid 1px silver";
		}
		parent.getContext = function(type){ return self;};
		parent.toDataURL = function(type){ return (!!type?child.toDataURL(type):child.toDataURL());};

		this.setLayer();
		this.context = this.child.getContext('2d');

		Candle._initializing--;
		Candle.readyflag[this.idname] = true;
	},

	clear : function(){
		this.setProperties();
		this.context.setTransform(1,0,0,1,0,0); // 変形をリセット
		this.context.translate(this.x0, this.y0);
		var rect = Candle.getRectSize(this.canvas);
		this.context.clearRect(0,0,rect.width,rect.height);
	},

	/* layer functions */
	setLayer : function(layerid){
		this.currentLayerId = (!!layerid ? layerid : '_empty');
		if(this.isedgearray[this.currentLayerId] !== void 0)
			{ this.isedge = this.isedgearray[this.currentLayerId];}
		else
			{ this.isedge = this.isedgearray['_empty'];}
	},

	/* property functions */
	setRendering : function(render){
		this.isedgearray[this.currentLayerId] = (render==='crispEdges');
		this.isedge = this.isedgearray[this.currentLayerId];
	},
	setUnselectable : function(unsel){
		if(unsel===(void 0)){ unsel = true;}else{ unsel = !!unsel;}
		this.canvas.style.MozUserSelect    = (unsel ? 'none' : 'text');
		this.canvas.style.WebkitUserSelect = (unsel ? 'none' : 'text');
		this.canvas.style.userSelect       = (unsel ? 'none' : 'text');
	},

	getContextElement : function(){ return this.child;},
	getLayerElement   : function(){ return this.child;},

	changeSize : function(width,height){
		this.canvas.style.width  = width + 'px';
		this.canvas.style.height = height + 'px';

		var canvas = this.canvas.firstChild;
		var left = parseInt(canvas.style.left), top = parseInt(canvas.style.top);
		width += (left<0?-left:0); height += (top<0?-top:0);
		canvas.style.width  = width + 'px';
		canvas.style.height = height + 'px';
		canvas.width  = width;
		canvas.height = height;
	},

	/* 内部用関数 */
	setProperties : function(){
		this.context.fillStyle    = this.fillStyle;
		this.context.strokeStyle  = this.strokeStyle;
		this.context.lineWidth    = this.lineWidth;
		this.context.font         = this.font;
		this.context.textAlign    = this.textAlign;
		this.context.textBaseline = this.textBaseline;
	},

	/* Canvas API functions (for path) */
	beginPath : function(){ this.context.beginPath();},
	closePath : function(){ this.context.closePath();},

	moveTo : function(x,y){
		this.context.moveTo(this.ePos(x,true),this.ePos(y,true));
	},
	lineTo : function(x,y){
		this.context.lineTo(this.ePos(x,true),this.ePos(y,true));
	},
	rect : function(x,y,w,h){
		this.context.rect(this.ePos(x,true),this.ePos(y,true),w,h);
	},
	arc  : function(cx,cy,r,startRad,endRad,antiClockWise){
		this.context.arc(this.ePos(cx,false),this.ePos(cy,false),r,startRad,endRad,antiClockWise);
	},

	/* Canvas API functions (for drawing) */
	fill       : function(){ this.setProperties(); this.context.fill();},
	stroke     : function(){ this.setProperties(); this.context.stroke();},
	shape : function(){
		this.setProperties();
		this.context.fill();
		this.context.stroke();
	},

	/* Canvas API functions (rect) */
	fillRect   : function(x,y,w,h){
		this.setProperties();
		this.context.fillRect(this.ePos(x,false),this.ePos(y,false),w,h);
	},
	strokeRect : function(x,y,w,h){
		this.setProperties();
		this.context.strokeRect(this.ePos(x,true),this.ePos(y,true),w,h);
	},
	shapeRect : function(x,y,w,h){
		x=this.ePos(x,true); y=this.ePos(y,true); w=this.eLen(w); h=this.eLen(h);
		this.setProperties();
		this.context.fillRect(x,y,w,h);
		this.context.strokeRect(x,y,w,h);
	},

	/* Canvas API functions (for text) */
	fillText : function(text,x,y){
		this.setProperties();
		this.context.fillText(text,x,y);
	},

	/* Canvas API functions (for image) */
	drawImage : function(){
		this.context.drawImage.apply(this.context, arguments);
	},

	/* Canvas API functions (for transform) */
	translate : function(left,top){
		this.x0 = left;
		this.y0 = top;
		this.context.translate(left, top);
	},

	/* extended functions */
	setLinePath : function(){
		var _args=arguments, _len=_args.length, len=_len-((_len|1)?1:2), a=[];
		for(var i=0;i<len;i+=2){ a[i>>1] = [_args[i],_args[i+1]];}
		this.setLinePath_com.call(this,a);
		if(_args[_len-1]){ this.context.closePath();}
	},
	setOffsetLinePath : function(){
		var _args=arguments, _len=_args.length, len=_len-((_len|1)?1:2)-2, a=[];
		for(var i=0;i<len;i+=2){ a[i>>1] = [_args[i+2]+_args[0], _args[i+3]+_args[1]];}
		this.setLinePath_com.call(this,a);
		if(_args[_len-1]){ this.context.closePath();}
	},
	setLinePath_com : function(array){
		for(var i=0,len=array.length;i<len;i++){
			var a1=this.ePos(array[i][0],true), a2=this.ePos(array[i][1],true);
			if(i===0){ this.context.moveTo(a1,a2);}
			else     { this.context.lineTo(a1,a2);}
		}
	},
	setDashSize : function(size){ },

	strokeLine : function(x1,y1,x2,y2){
		this.setProperties();
		this.context.beginPath();
		this.context.moveTo(this.ePos(x1,true),this.ePos(y1,true));
		this.context.lineTo(this.ePos(x2,true),this.ePos(y2,true));
		this.context.stroke();
	},
	strokeCross : function(cx,cy,l){
		var x1=this.ePos(cx-l,true), y1=this.ePos(cy-l,true),
			x2=this.ePos(cx+l,true), y2=this.ePos(cy+l,true);

		this.setProperties();
		this.context.beginPath();
		this.context.moveTo(x1,y1);
		this.context.lineTo(x2,y2);
		this.context.moveTo(x1,y2);
		this.context.lineTo(x2,y1);
		this.context.stroke();
	},

	/* extended functions (circle) */
	fillCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,false),this.ePos(cy,false),r,0,_2PI,false);
		this.context.fill();
	},
	strokeCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,true),this.ePos(cy,true),r,0,_2PI,false);
		this.context.stroke();
	},
	shapeCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,true),this.ePos(cy,true),r,0,_2PI,false);
		this.context.fill();
		this.context.stroke();
	}
});

})();
<commit_msg>candle.canvas: setOffsetLinePath()関数でcanvasではbeginPath()を行うようにした<commit_after>// candle.canvas.js

(function(){

// Candleオブジェクトがない場合は何もしない
if(!window.Candle){ return;}

// canvas描画可能条件
if(!document.createElement('canvas').getContext){ return;}

/* ------------- */
/*  const value  */
/* ------------- */
var Candle = window.Candle,
	_doc = document,
	_2PI = 2*Math.PI;

/* -------------------- */
/*   Canvas用ラッパー   */
/* -------------------- */
Candle.addTypes('canvas');

Candle.addWrapper('canvas:wrapperbase',{

	initialize : function(idname){
		Candle.wrapper.wrapperbase.prototype.initialize.call(this, idname);

		// variables for internal
		this.context  = null;	// 本来のCanvasRenderingContext2Dオブジェクト

		this.use = new Candle.TypeList('canvas');

		this.x0 = 0;
		this.y0 = 0;

		this.initElement();
	},

	/* extend functions (initialize) */
	initElement : function(){
		this.canvas = _doc.getElementById(this.idname);

		var rect = Candle.getRectSize(this.canvas);
		var top = _doc.createElement('canvas');
		top.id = this.canvasid;

		top.width  = rect.width;
		top.height = rect.height;
		top.style.position = 'relative';
		top.style.width  = rect.width + 'px';
		top.style.height = rect.height + 'px';
		this.canvas.appendChild(top);

		this.child = top;
		this.afterInit();
	},
	afterInit : function(){
		var parent = this.canvas;
		var child  = this.child;

		var self = this;
		parent.style.display  = 'block';
		parent.style.position = 'relative';
		parent.style.overflow = 'hidden';
		if(Candle.debugmode){
			parent.style.backgroundColor = "#efefef";
			parent.style.border = "solid 1px silver";
		}
		parent.getContext = function(type){ return self;};
		parent.toDataURL = function(type){ return (!!type?child.toDataURL(type):child.toDataURL());};

		this.setLayer();
		this.context = this.child.getContext('2d');

		Candle._initializing--;
		Candle.readyflag[this.idname] = true;
	},

	clear : function(){
		this.setProperties();
		this.context.setTransform(1,0,0,1,0,0); // 変形をリセット
		this.context.translate(this.x0, this.y0);
		var rect = Candle.getRectSize(this.canvas);
		this.context.clearRect(0,0,rect.width,rect.height);
	},

	/* layer functions */
	setLayer : function(layerid){
		this.currentLayerId = (!!layerid ? layerid : '_empty');
		if(this.isedgearray[this.currentLayerId] !== void 0)
			{ this.isedge = this.isedgearray[this.currentLayerId];}
		else
			{ this.isedge = this.isedgearray['_empty'];}
	},

	/* property functions */
	setRendering : function(render){
		this.isedgearray[this.currentLayerId] = (render==='crispEdges');
		this.isedge = this.isedgearray[this.currentLayerId];
	},
	setUnselectable : function(unsel){
		if(unsel===(void 0)){ unsel = true;}else{ unsel = !!unsel;}
		this.canvas.style.MozUserSelect    = (unsel ? 'none' : 'text');
		this.canvas.style.WebkitUserSelect = (unsel ? 'none' : 'text');
		this.canvas.style.userSelect       = (unsel ? 'none' : 'text');
	},

	getContextElement : function(){ return this.child;},
	getLayerElement   : function(){ return this.child;},

	changeSize : function(width,height){
		this.canvas.style.width  = width + 'px';
		this.canvas.style.height = height + 'px';

		var canvas = this.canvas.firstChild;
		var left = parseInt(canvas.style.left), top = parseInt(canvas.style.top);
		width += (left<0?-left:0); height += (top<0?-top:0);
		canvas.style.width  = width + 'px';
		canvas.style.height = height + 'px';
		canvas.width  = width;
		canvas.height = height;
	},

	/* 内部用関数 */
	setProperties : function(){
		this.context.fillStyle    = this.fillStyle;
		this.context.strokeStyle  = this.strokeStyle;
		this.context.lineWidth    = this.lineWidth;
		this.context.font         = this.font;
		this.context.textAlign    = this.textAlign;
		this.context.textBaseline = this.textBaseline;
	},

	/* Canvas API functions (for path) */
	beginPath : function(){ this.context.beginPath();},
	closePath : function(){ this.context.closePath();},

	moveTo : function(x,y){
		this.context.moveTo(this.ePos(x,true),this.ePos(y,true));
	},
	lineTo : function(x,y){
		this.context.lineTo(this.ePos(x,true),this.ePos(y,true));
	},
	rect : function(x,y,w,h){
		this.context.rect(this.ePos(x,true),this.ePos(y,true),w,h);
	},
	arc  : function(cx,cy,r,startRad,endRad,antiClockWise){
		this.context.arc(this.ePos(cx,false),this.ePos(cy,false),r,startRad,endRad,antiClockWise);
	},

	/* Canvas API functions (for drawing) */
	fill       : function(){ this.setProperties(); this.context.fill();},
	stroke     : function(){ this.setProperties(); this.context.stroke();},
	shape : function(){
		this.setProperties();
		this.context.fill();
		this.context.stroke();
	},

	/* Canvas API functions (rect) */
	fillRect   : function(x,y,w,h){
		this.setProperties();
		this.context.fillRect(this.ePos(x,false),this.ePos(y,false),w,h);
	},
	strokeRect : function(x,y,w,h){
		this.setProperties();
		this.context.strokeRect(this.ePos(x,true),this.ePos(y,true),w,h);
	},
	shapeRect : function(x,y,w,h){
		x=this.ePos(x,true); y=this.ePos(y,true); w=this.eLen(w); h=this.eLen(h);
		this.setProperties();
		this.context.fillRect(x,y,w,h);
		this.context.strokeRect(x,y,w,h);
	},

	/* Canvas API functions (for text) */
	fillText : function(text,x,y){
		this.setProperties();
		this.context.fillText(text,x,y);
	},

	/* Canvas API functions (for image) */
	drawImage : function(){
		this.context.drawImage.apply(this.context, arguments);
	},

	/* Canvas API functions (for transform) */
	translate : function(left,top){
		this.x0 = left;
		this.y0 = top;
		this.context.translate(left, top);
	},

	/* extended functions */
	setLinePath : function(){
		var _args=arguments, _len=_args.length, len=_len-((_len|1)?1:2), a=[];
		for(var i=0;i<len;i+=2){ a[i>>1] = [_args[i],_args[i+1]];}
		this.setLinePath_com.call(this,a);
		if(_args[_len-1]){ this.context.closePath();}
	},
	setOffsetLinePath : function(){
		var _args=arguments, _len=_args.length, len=_len-((_len|1)?1:2)-2, a=[];
		for(var i=0;i<len;i+=2){ a[i>>1] = [_args[i+2]+_args[0], _args[i+3]+_args[1]];}
		this.context.beginPath();
		this.setLinePath_com.call(this,a);
		if(_args[_len-1]){ this.context.closePath();}
	},
	setLinePath_com : function(array){
		for(var i=0,len=array.length;i<len;i++){
			var a1=this.ePos(array[i][0],true), a2=this.ePos(array[i][1],true);
			if(i===0){ this.context.moveTo(a1,a2);}
			else     { this.context.lineTo(a1,a2);}
		}
	},
	setDashSize : function(size){ },

	strokeLine : function(x1,y1,x2,y2){
		this.setProperties();
		this.context.beginPath();
		this.context.moveTo(this.ePos(x1,true),this.ePos(y1,true));
		this.context.lineTo(this.ePos(x2,true),this.ePos(y2,true));
		this.context.stroke();
	},
	strokeCross : function(cx,cy,l){
		var x1=this.ePos(cx-l,true), y1=this.ePos(cy-l,true),
			x2=this.ePos(cx+l,true), y2=this.ePos(cy+l,true);

		this.setProperties();
		this.context.beginPath();
		this.context.moveTo(x1,y1);
		this.context.lineTo(x2,y2);
		this.context.moveTo(x1,y2);
		this.context.lineTo(x2,y1);
		this.context.stroke();
	},

	/* extended functions (circle) */
	fillCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,false),this.ePos(cy,false),r,0,_2PI,false);
		this.context.fill();
	},
	strokeCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,true),this.ePos(cy,true),r,0,_2PI,false);
		this.context.stroke();
	},
	shapeCircle : function(cx,cy,r){
		this.setProperties();
		this.context.beginPath();
		this.context.arc(this.ePos(cx,true),this.ePos(cy,true),r,0,_2PI,false);
		this.context.fill();
		this.context.stroke();
	}
});

})();
<|endoftext|>


<commit_before>

// vim: set ts=4 sw=4 et:
"use strict";

var SESSION_URL_JOIN = "/api/session/join";
var SESSION_URL_LEAVE = "/api/session/leave";
var SESSION_URL_UPDATE = "/api/session/update";

var SESSION_UPDATE_INTERVAL = 5000;

var SESSION_TYPE_DRAW = "draw";
var SESSION_TYPE_VIEW = "view";

function Session( session_type, callback ) {

    var self = this;

    this.brush = null;
    this.user_id = null;
    this.zone_column_count = null;
    this.zone_line_count = null;

    var _update_timer = null;

    var _current_drawing_id = 0;
    var _current_chat_id = 0;
    var _current_event_id = 0;

    var _drawing = null;
    var _view = null;
    var _chat = null;

    /**
     * Semi-Constructor
     */
    this.initialize = function() {

        var user_id = $.cookie('user_id');
        var user_name = $.cookie('user_name');
        var user_session = $.cookie('user_session');

        var session_url = SESSION_URL_JOIN + "?type=" + session_type;
        if ( user_id != null ) {
            session_url += "&user_id="+user_id;
        }
        if ( user_session != null ) {
            session_url += "&user_session="+user_session;
        }
        if ( user_name != null ) {
            session_url += "&user_name="+user_name;
        }

        // get session info from

        $.ajax({
            url: session_url,
            dataType: "json",
            type: 'GET',
            context: self,
            success: function( response ){
                console.log('session/join response : ' + JSON.stringify(response) );

                this.user_id = response.user_id;
                this.user_name = response.user_name;
                this.user_session = response.user_session;
                this.zone_column_count = response.zone_column_count;
                this.zone_line_count = response.zone_line_count;

                _current_event_id = response.event_id;
                _current_drawing_id = response.drawing_id;
                _current_chat_id = response.chat_id;

                $.cookie( 'user_id', this.user_id );
                $.cookie( 'user_name', this.user_name );
                $.cookie( 'user_session', this.user_session );
                console.log('session/join response mod : ' + JSON.stringify(this) );

                // FIXME: set cookie with user_id for next time
                // FIXME: set user_name with user_name for next time

                callback( self );
            }
        });
    }

    /**
     *
     */
    this.update = function(){

        var drawing_updates = [];
        var chat_updates = [];
        var req ;

        // assign real values if objets are present
        if (_drawing) {
            drawing_updates = _drawing.patches_get();
        }
        if (_chat) {
            chat_updates = _chat.patches_get();
        }
        console.log("drawing_updates = %s", drawing_updates);
        console.log("chat_updates = %s", chat_updates);

        req = {
            drawing_since : _current_drawing_id,
            chat_since : _current_chat_id,
            event_since : _current_event_id,

            drawing : drawing_updates,
            chat : chat_updates,
        }

        console.log("drawing/patches_update: req = %s", JSON.stringify( req ) );
        $.ajax({
            url: SESSION_URL_UPDATE,
            dataType: "json",
            data: JSON.stringify( req ),
            type: 'POST',
            context: self,
            success: function( response ){
                console.log('drawing/update response : ' + JSON.stringify( response ) );

                // FIXME: do something with drawing updates
                // FIXME: do something with event updates
                // FIXME: do something with chat updates
            }
        });

    };

    this.register_drawing = function( p_drawing ){
        _drawing = p_drawing;
    }

    this.register_view = function( p_view ) {
        _view = p_view
    }

    this.initialize();
    _update_timer = window.setInterval( self.update, SESSION_UPDATE_INTERVAL );
}

<commit_msg>js session: Fixed update timing issues with setTimeout.<commit_after>

// vim: set ts=4 sw=4 et:
"use strict";

var SESSION_URL_JOIN = "/api/session/join";
var SESSION_URL_LEAVE = "/api/session/leave";
var SESSION_URL_UPDATE = "/api/session/update";

var SESSION_UPDATE_INTERVAL = 10 * 1000 ;

var SESSION_TYPE_DRAW = "draw";
var SESSION_TYPE_VIEW = "view";

function Session( session_type, callback ) {

    var self = this;

    this.brush = null;
    this.user_id = null;
    this.zone_column_count = null;
    this.zone_line_count = null;

    var _current_drawing_id = 0;
    var _current_chat_id = 0;
    var _current_event_id = 0;

    var _drawing = null;
    var _view = null;
    var _chat = null;

    /**
     * Semi-Constructor
     */
    this.initialize = function() {

        var user_id = $.cookie('user_id');
        var user_name = $.cookie('user_name');
        var user_session = $.cookie('user_session');

        var session_url = SESSION_URL_JOIN + "?type=" + session_type;
        if ( user_id != null ) {
            session_url += "&user_id="+user_id;
        }
        if ( user_session != null ) {
            session_url += "&user_session="+user_session;
        }
        if ( user_name != null ) {
            session_url += "&user_name="+user_name;
        }

        // get session info from

        $.ajax({
            url: session_url,
            dataType: "json",
            type: 'GET',
            context: self,
            success: function( response ){
                console.log('session/join response : ' + JSON.stringify(response) );

                this.user_id = response.user_id;
                this.user_name = response.user_name;
                this.user_session = response.user_session;
                this.zone_column_count = response.zone_column_count;
                this.zone_line_count = response.zone_line_count;

                _current_event_id = response.event_id;
                _current_drawing_id = response.drawing_id;
                _current_chat_id = response.chat_id;

                $.cookie( 'user_id', this.user_id );
                $.cookie( 'user_name', this.user_name );
                $.cookie( 'user_session', this.user_session );
                console.log('session/join response mod : ' + JSON.stringify(this) );

                // FIXME: set cookie with user_id for next time
                // FIXME: set user_name with user_name for next time

                window.setTimeout( self.update, SESSION_UPDATE_INTERVAL );
                console.log("gotcha!");

                callback( self );
            }
        });

    }

    /**
     *
     */
    this.update = function(){

        var drawing_updates = [];
        var chat_updates = [];
        var req ;

        // skip if no user id assigned
        if (!self.user_id) {
            window.setTimeout( self.update, SESSION_UPDATE_INTERVAL );
            return null;
        }

        // assign real values if objets are present
        if (_drawing) {
            drawing_updates = _drawing.patches_get();
        }
        if (_chat) {
            chat_updates = _chat.patches_get();
        }
        console.log("drawing_updates = %s", drawing_updates);
        console.log("chat_updates = %s", chat_updates);

        req = {
            drawing_since : _current_drawing_id,
            chat_since : _current_chat_id,
            event_since : _current_event_id,

            drawing : drawing_updates,
            chat : chat_updates,
        }

        console.log("drawing/patches_update: req = %s", JSON.stringify( req ) );
        $.ajax({
            url: SESSION_URL_UPDATE,
            dataType: "json",
            data: JSON.stringify( req ),
            type: 'POST',
            context: self,
            success: function( response ){
                console.log('drawing/update response : ' + JSON.stringify( response ) );

                // FIXME: do something with drawing updates
                // FIXME: do something with event updates
                // FIXME: do something with chat updates
                window.setTimeout( self.update, SESSION_UPDATE_INTERVAL );
            },
            error: function( response ) {
               window.setTimeout( self.update, SESSION_UPDATE_INTERVAL * 2 );
           }
        });

    };

    this.register_drawing = function( p_drawing ){
        _drawing = p_drawing;
    }

    this.register_view = function( p_view ) {
        _view = p_view
    }

    this.initialize();
}

<|endoftext|>


<commit_before>alert("hello!")
alert("Bonjour")
alert("Coucou!")
<commit_msg>Hello devient addition<commit_after>var i=0;
var j=0;
alert(i*j);
<|endoftext|>


<commit_before>require('./support/helper');

var path = require("path")
  , expect = require("expect.js")
  , fs = require("fs")
  , generateTemplate = require("./support/generate_template")
  , Backbone = require('Backbone')
  , modelReaction = require('../lib/reactions/model')

delete require.cache[require.resolve('Backbone')]
var BackboneClone = require('Backbone') // To Test Bug. EndDash module might have a different Backbone then a client's
                                        // main application. Internally we use !(model instanceof Backbone.Model || ... instanceof Backbone.Collection)
                                        // this test is intended to check that our code now handles this case

describe("With a backbone model from a different backbone object", function(){
  it("Should still work properly", function(){
    var model = new BackboneClone.Model({persisted: "Chelsa Piers"})
      , template = generateTemplate({user: model}, "

")

    expect($('.persisted-').html()).to.be('Chelsa Piers')
    model.set('persisted', 'Changed')
    expect($('.persisted-').html()).to.be('Changed')
  })
})

describe("With a backbone model", function(){
  beforeEach(function(){
    var backModel = new Backbone.Model()
  })
  it("Should work as normal", function(){
    var model = new Backbone.Model({persisted: "Chelsa Piers"})
      , template = generateTemplate({user: model}, "

")

    expect($('.persisted-').html()).to.be('Chelsa Piers')
    model.set('persisted', 'Changed')
    expect($('.persisted-').html()).to.be('Changed')
  })
})

describe("With a backbone collection from a different backbone object", function(){
  beforeEach(function(){
    this.collection = new BackboneClone.Collection()
    this.templateString = "

"
  })

  describe("With models from a different backbone object", function(){
    it("Should still work properly", function(){
      var model1 = new BackboneClone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = new BackboneClone.Model({persisted: "Columbus circle", hook: '2'})
        , model3 = new BackboneClone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
      model1.set('persisted', 'Changed1')
      model2.set('persisted', 'Changed2')
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
    })
  })

  describe("With anonymous models", function(){
    it("Should still interpolate values but changes will not be updated", function(){
      var model1 = {persisted: "Chelsa Piers", hook: '1'}
        , model2 = {persisted: "Columbus circle", hook: '2'}
        , model3 = {persisted: "Soho", hook: '3'}
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.persisted)
      expect($('.2').html()).to.be(model2.persisted)
      expect($('.3').html()).to.be(model3.persisted)
      model1.persisted = 'Changed1'
      model2.persisted = 'Changed2'
      model3.persisted = 'Changed3'
      expect($('.1').html()).to.be("Chelsa Piers")
      expect($('.2').html()).to.be("Columbus circle")
      expect($('.3').html()).to.be("Soho")
    })
  })

})
<commit_msg>Collections with mixed model type specs added<commit_after>require('./support/helper');

var path = require("path")
  , expect = require("expect.js")
  , fs = require("fs")
  , generateTemplate = require("./support/generate_template")
  , Backbone = require('Backbone')

delete require.cache[require.resolve('Backbone')]
var BackboneClone = require('Backbone') // Internally we use !(model instanceof Backbone.Model || ... instanceof Backbone.Collection)
                                        // If the Backbone for EndDash is different then the clients, we want to handle this case.
                                        // See lib/reactions/model.js for fix.

describe("With a backbone model from a different backbone object", function(){
  it("Should still work properly", function(){
    var model = new BackboneClone.Model({persisted: "Chelsa Piers"})
      , template = generateTemplate({user: model}, "

")

    expect($('.persisted-').html()).to.be('Chelsa Piers')
    model.set('persisted', 'Changed')
    expect($('.persisted-').html()).to.be('Changed')
  })
})

describe("With a backbone model", function(){
  beforeEach(function(){
    var backModel = new Backbone.Model()
  })
  it("Should work as normal", function(){
    var model = new Backbone.Model({persisted: "Chelsa Piers"})
      , template = generateTemplate({user: model}, "

")

    expect($('.persisted-').html()).to.be('Chelsa Piers')
    model.set('persisted', 'Changed')
    expect($('.persisted-').html()).to.be('Changed')
  })
})

describe("With a backbone collection from a different backbone object", function(){
  beforeEach(function(){
    this.collection = new BackboneClone.Collection()
    this.templateString = "

"
  })

  describe("With models from a different backbone object", function(){
    it("Should still work properly", function(){
      var model1 = new BackboneClone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = new BackboneClone.Model({persisted: "Columbus circle", hook: '2'})
        , model3 = new BackboneClone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
      model1.set('persisted', 'Changed1')
      model2.set('persisted', 'Changed2')
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
    })
  })

  describe("With anonymous models", function(){
    it("Should still interpolate values but changes will not be updated", function(){
      var model1 = {persisted: "Chelsa Piers", hook: '1'}
        , model2 = {persisted: "Columbus circle", hook: '2'}
        , model3 = {persisted: "Soho", hook: '3'}
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.persisted)
      expect($('.2').html()).to.be(model2.persisted)
      expect($('.3').html()).to.be(model3.persisted)
      model1.persisted = 'Changed1'
      model2.persisted = 'Changed2'
      model3.persisted = 'Changed3'
      expect($('.1').html()).to.be("Chelsa Piers")
      expect($('.2').html()).to.be("Columbus circle")
      expect($('.3').html()).to.be("Soho")
    })
  })

  describe("With a mix of different model kinds", function(){
    it("Should still work properly", function(){
      var model1 = new BackboneClone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = {persisted: "Columbus circle", hook: '2'}
        , model3 = new Backbone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.persisted)
      expect($('.3').html()).to.be(undefined)
      model1.set('persisted', 'Changed1')
      model2.persisted = 'Changed2'
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be("Columbus circle")
      expect($('.3').html()).to.be(undefined)
    })
  })
})

describe("With a backbone collection from the same backbone object", function(){
  beforeEach(function(){
    this.collection = new Backbone.Collection()
    this.templateString = "

"
  })

  describe("With models from a different backbone object", function(){
    it("Does not work properly", function(){
      var model1 = new BackboneClone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = new BackboneClone.Model({persisted: "Columbus circle", hook: '2'})
        , model3 = new BackboneClone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(undefined)
      expect($('.2').html()).to.be(undefined)
      expect($('.3').html()).to.be(undefined)
      model1.set('persisted', 'Changed1')
      model2.set('persisted', 'Changed2')
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(undefined)
      expect($('.2').html()).to.be(undefined)
      expect($('.3').html()).to.be(undefined)
    })
  })

  describe("With models from the same backbone object", function(){
    it("Does not work properly", function(){
      var model1 = new Backbone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = new Backbone.Model({persisted: "Columbus circle", hook: '2'})
        , model3 = new Backbone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
      model1.set('persisted', 'Changed1')
      model2.set('persisted', 'Changed2')
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.get('persisted'))
      expect($('.3').html()).to.be(model3.get('persisted'))
    })
  })

  describe("With anonymous models", function(){
    it("Should still interpolate values but changes will not be updated", function(){
      var model1 = {persisted: "Chelsa Piers", hook: '1'}
        , model2 = {persisted: "Columbus circle", hook: '2'}
        , model3 = {persisted: "Soho", hook: '3'}
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.persisted)
      expect($('.2').html()).to.be(model2.persisted)
      expect($('.3').html()).to.be(model3.persisted)
      model1.persisted = 'Changed1'
      model2.persisted = 'Changed2'
      model3.persisted = 'Changed3'
      expect($('.1').html()).to.be("Chelsa Piers")
      expect($('.2').html()).to.be("Columbus circle")
      expect($('.3').html()).to.be("Soho")
    })
  })

  describe("With a mix of different model kinds", function(){
    it("Should still work properly", function(){
      var model1 = new Backbone.Model({persisted: "Chelsa Piers", hook: '1'})
        , model2 = {persisted: "Columbus circle", hook: '2'}
        , model3 = new BackboneClone.Model({persisted: "Soho", hook: '3'})
      this.collection.add([model1, model2, model3])
      var template = generateTemplate({users: this.collection}, this.templateString)
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be(model2.persisted)
      expect($('.3').html()).to.be(undefined)
      model1.set('persisted', 'Changed1')
      model2.persisted = 'Changed2'
      model3.set('persisted', 'Changed3')
      expect($('.1').html()).to.be(model1.get('persisted'))
      expect($('.2').html()).to.be("Columbus circle")
      expect($('.3').html()).to.be(undefined)
    })
  })
})
<|endoftext|>


<commit_before>// Unit test for a (the tiny part at beginning only)

module('a.js');

// Testing a found url...
test('a.url', function() {
    ok(a.url !== '', 'Test url not empty');
});

// Testing isNone
test('a.isNone', function() {
    strictEqual(a.isNone(null), true, 'Test null');
    strictEqual(a.isNone(undefined), true, 'Test undefined');
    strictEqual(a.isNone(''), false, 'Test empty string');
    strictEqual(a.isNone({}), false, 'Test empty object');
    strictEqual(a.isNone(0), false, 'Test 0 value');
});

// Testing a.isTrueObject
test('a.isTrueObject', function() {
    strictEqual(a.isTrueObject(null), false, 'Test null value');
    strictEqual(a.isTrueObject(undefined), false, 'Test undefined value');
    strictEqual(a.isTrueObject(function() {}), false, 'Test function value');
    strictEqual(a.isTrueObject({}), true, 'Test object value');
});

test('a.scope', function() {
    var scope = {
        test: 'ok'
    },
        se = strictEqual;

    var fct = a.scope(function() {
        se(this.test, 'ok', 'Test scope');
    }, scope);

    fct();
});<commit_msg>Adding unit test for trim and firstLetterUppercase function<commit_after>// Unit test for a (the tiny part at beginning only)

module('a.js');

// Testing a found url...
test('a.url', function() {
    ok(a.url !== '', 'Test url not empty');
});

// Testing isNone
test('a.isNone', function() {
    strictEqual(a.isNone(null), true, 'Test null');
    strictEqual(a.isNone(undefined), true, 'Test undefined');
    strictEqual(a.isNone(''), false, 'Test empty string');
    strictEqual(a.isNone({}), false, 'Test empty object');
    strictEqual(a.isNone(0), false, 'Test 0 value');
});

// Testing a.isTrueObject
test('a.isTrueObject', function() {
    strictEqual(a.isTrueObject(null), false, 'Test null value');
    strictEqual(a.isTrueObject(undefined), false, 'Test undefined value');
    strictEqual(a.isTrueObject(function() {}), false, 'Test function value');
    strictEqual(a.isTrueObject({}), true, 'Test object value');
});

test('a.scope', function() {
    var scope = {
        test: 'ok'
    },
        se = strictEqual;

    var fct = a.scope(function() {
        se(this.test, 'ok', 'Test scope');
    }, scope);

    fct();
});

test('a.trim', function() {
    strictEqual(a.trim('     something is good       '), 'something is good');
    strictEqual(a.trim('	with tab'), 'with tab');
});

test('a.firstLetterUppercase', function() {
    strictEqual(a.firstLetterUppercase('something', 'is'), 'isSomething');
    strictEqual(a.firstLetterUppercase('something'), 'Something');
    strictEqual(a.firstLetterUppercase('this is long'), 'This is long');
});<|endoftext|>


<commit_before>var CriticalInfoCard = {
    name: 'CriticalInfoCard',
    dom_target: undefined,
    render_init: function () {
        WSData.fetch_notice_data(CriticalInfoCard.render_upon_data, CriticalInfoCard.render_error);
    },
    render_upon_data: function () {
        if (!CriticalInfoCard._has_all_data()) {
            return;
        }
        CriticalInfoCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data()) {
            return true;
        }
        return false;
    },

    _render: function () {
        var source = $("#ns_critical_info").html();
        var template = Handlebars.compile(source);
        var notices = Notices.get_notices_for_tag("checklist_email");

        CriticalInfoCard.dom_target.html(template({'notices': notices}));
    },
    render_error: function () {
        CriticalInfoCard.dom_target.html(CardWithError.render(CriticalInfoCard.name));
    },
};
<commit_msg>display logic for critical info card<commit_after>var CriticalInfoCard = {
    name: 'CriticalInfoCard',
    dom_target: undefined,
    render_init: function () {
        WSData.fetch_notice_data(CriticalInfoCard.render_upon_data, CriticalInfoCard.render_error);
    },
    render_upon_data: function () {
        if (!CriticalInfoCard._has_all_data()) {
            return;
        }
        CriticalInfoCard._render();
    },

    _has_all_data: function () {
        if (WSData.notice_data()) {
            return true;
        }
        return false;
    },

    _render: function () {
        var source = $("#ns_critical_info").html();
        var template = Handlebars.compile(source);
        var notices = Notices.get_notices_for_tag("checklist_email");
        if (notices.length > 0){
            CriticalInfoCard.dom_target.html(template({'notices': notices}));
        } else {
            CriticalInfoCard.dom_target.hide()
        }

    },
    render_error: function () {
        CriticalInfoCard.dom_target.html(CardWithError.render(CriticalInfoCard.name));
    },
};
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";

import styled from "styled-components";

import { DateTime } from "luxon";
import Button from "@agir/front/genericComponents/Button";
import Collapsible from "@agir/front/genericComponents/Collapsible.js";
import Card from "@agir/front/genericComponents/Card";
import Spacer from "@agir/front/genericComponents/Spacer";

import style from "@agir/front/genericComponents/_variables.scss";

const DescriptionSection = styled.div`
  margin: 0;

  &:empty {
    margin: 0;
  }

  & + & {
    margin-top: 1rem;
  }

  & > * {
    margin-top: 0;
    margin-bottom: 1rem;

    &:empty,
    &:last-child {
      margin-bottom: 0;
    }
  }

  img {
    margin: 10px 0px;
  }
`;

const StyledButton = styled(Button)`
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: ${style.borderRadius};
  margin: 0 16px;
`;

const StyledActionButtons = styled.div`
  display: inline-grid;
  grid-gap: 0.5rem;
  grid-template-columns: auto auto;
  padding: 0.5rem 0;

  @media (max-width: ${style.collapse}px) {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(275px, 1fr));
  }

  ${Button} {
    margin: 0;
    justify-content: center;

    && *,
    && *::before {
      flex: 0 0 auto;
    }
  }

  ${Button} + ${Button} {
    margin-left: 0;
  }
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  overflow: hidden;
  border-bottom: 1px solid ${style.black50};
`;

const EventDescriptionCard = ({
  illustration,
  description,
  isOrganizer,
  endTime,
  routes,
}) => {
  return (
    <>
      {description ? (

              </StyledActionButtons>
            )}
          </DescriptionSection>
        </StyledCard>
      ) : null}

      {!description && isOrganizer && endTime > DateTime.local() && (

              {!illustration?.banner && (

              )}

          </DescriptionSection>
        </StyledCard>
      )}
    </>
  );
};

EventDescriptionCard.propTypes = {
  compteRendu: PropTypes.string,
  compteRenduPhotos: PropTypes.arrayOf(
    PropTypes.shape({
      image: PropTypes.string,
      thumbnail: PropTypes.string,
    })
  ),
  illustration: PropTypes.shape({
    banner: PropTypes.string,
    thumbnail: PropTypes.string,
  }),
  description: PropTypes.string,
  isOrganizer: PropTypes.bool,
  endTime: PropTypes.instanceOf(DateTime),
  routes: PropTypes.object,
  rsvp: PropTypes.string,
};

export default EventDescriptionCard;
<commit_msg>Auto stash before merge of "BenjaminL/FixCleanPageEvent" and "BenjaminL/fixNotificationCard"<commit_after>import React from "react";
import PropTypes from "prop-types";

import styled from "styled-components";

import { DateTime } from "luxon";
import Button from "@agir/front/genericComponents/Button";
import Collapsible from "@agir/front/genericComponents/Collapsible.js";
import Card from "@agir/front/genericComponents/Card";
import Spacer from "@agir/front/genericComponents/Spacer";

import style from "@agir/front/genericComponents/_variables.scss";
import { Hide } from "../../../front/components/genericComponents/grid";

const DescriptionSection = styled.div`
  margin: 0;

  &:empty {
    margin: 0;
  }

  & + & {
    margin-top: 1rem;
  }

  & > * {
    margin-top: 0;
    margin-bottom: 1rem;

    &:empty,
    &:last-child {
      margin-bottom: 0;
    }
  }

  img {
    margin: 10px 0px;
  }
`;

const StyledButton = styled(Button)`
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: ${style.borderRadius};
  margin: 0 16px;
`;

const StyledActionButtons = styled.div`
  display: inline-grid;
  grid-gap: 0.5rem;
  grid-template-columns: auto auto;
  padding: 0.5rem 0;

  @media (max-width: ${style.collapse}px) {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(275px, 1fr));
  }

  ${Button} {
    margin: 0;
    justify-content: center;

    && *,
    && *::before {
      flex: 0 0 auto;
    }
  }

  ${Button} + ${Button} {
    margin-left: 0;
  }
`;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  overflow: hidden;
  border-bottom: 1px solid ${style.black50};
`;

const EventDescriptionCard = ({
  illustration,
  description,
  isOrganizer,
  endTime,
  routes,
}) => {
  return (
    <>
      {description ? (

              </StyledActionButtons>
            )}
          </DescriptionSection>
        </StyledCard>
      ) : null}

      {!description && isOrganizer && endTime > DateTime.local() && (

              {!illustration?.banner && (

              )}

          </DescriptionSection>
        </StyledCard>
      )}
    </>
  );
};

EventDescriptionCard.propTypes = {
  compteRendu: PropTypes.string,
  compteRenduPhotos: PropTypes.arrayOf(
    PropTypes.shape({
      image: PropTypes.string,
      thumbnail: PropTypes.string,
    })
  ),
  illustration: PropTypes.shape({
    banner: PropTypes.string,
    thumbnail: PropTypes.string,
  }),
  description: PropTypes.string,
  isOrganizer: PropTypes.bool,
  endTime: PropTypes.instanceOf(DateTime),
  routes: PropTypes.object,
  rsvp: PropTypes.string,
};

export default EventDescriptionCard;
<|endoftext|>