<commit_before>var assert = require("chai").assert,
	async = require("async"),
	_ = require("underscore"),
	ObjectId = require("mongoose").Types.ObjectId;

var CitationController = require("../../../controllers/CitationController"),
	ArticleModel = require("../../../models/ArticleModel"),
	ignorePmid = [24563719];

suite("CitationController", function(){

	var citationController;
	var pmid;

	setup(function(){

		citationController = new CitationController();
		pmid = 21743474;//10.1038/nature10158

	});

	teardown(function(){

	});

	test("has getPmid method", function(done){
		assert.isFunction(citationController.getPmid);
		done();
	})

	suite("#getPmid", function(){
		test("gets an object containing a pmid property", function(done){

			/* if there is a pmid to get that is. Check the conditions set
			*  in the getPmid query.
			*
			*  [24563719] is a pmid to ingore
			*
			*/

			citationController.getPmid([24563719], function(err, value){
				var expectedNumber = value;
				assert.isNumber(expectedNumber.pmid);
				assert.isNull(err);
				done();
			})

		});

	});

	suite("#fetchCitations", function(){
		test("makes request to eutils.elink", function(done){

			citationController.fetchCitations(pmid, function(err, response){

				assert.equal(response.statusCode, 200, "response failed");
				done();
			});

		});
	});

	suite("#citationsExist", function(){

		test("body from response contains pubmed_pubmed_citedin", function(done){
			citationController.fetchCitations(pmid, function(err, response){
				var data = response.body;
				citationController.citationsExist(data, function(err, exist){
					assert.isTrue(exist, "pubmed_pubmed_citedin not in response body");
					done();
				})

			});
		});

	});

	suite("#parseResponse", function(){
		test("is called if citations exist in response", function(done){

			async.waterfall([
				function(callback){
						citationController.fetchCitations(pmid, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){
					if(exist ===false){
						callback(true);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}], function(err, result){

					assert.ok(result, "what's gone wrong here?");
					done();
				});
		});

		test("is not called if citations in response do not exist", function(done){

			async.waterfall([function(callback){
				/** dbPmid is a mock object and works as long as
				*   no one ever cites this article.
				* 	How's that for a dependency?
				*/
				dbPmid = {"pmid": 24277739};
				citationController.fetchCitations(dbPmid["pmid"], callback);

			}, function(response, callback){
				var data = response.body;

				citationController.citationsExist(data, callback);

			}, function(exist, citationLinkSet, callback){

				if(exist === false){
					callback(null, "no citations");//confusing?
				}else{
					citationController.parseResponse(citationLinkSet, callback);
				}
			}], function(err, result){

				assert.equal(result, "no citations", "#parseResponse called in error");
				done();
			});

		})

		test.only("extracts pmids from pubmed_pubmed_citedin section to an array", function(done){

				async.waterfall([
				function(callback){
						citationController.fetchCitations(pmid, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){
					if(exist ===false){
						callback(true);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}], function(err, result){

					assert.isArray(result, "not an array");
					done();
				});

		});

	});

	suite("#checkPmids", function(){

		var steps;

		setup(function(){//here I set up a function to to save repeating myself in the tests.
			steps = function(callback){

				async.waterfall([
				function(callback){
						citationController.fetchCitations(pmid, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){
					if(exist ===false){
						callback(true);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}], function(err, results){
					if(err){
						callback(err);
					}else{
						callback(results);
					}
				});
		}

		});

		test("do these pmids already exist in database?", function(done){

			steps(function(pmidArray){

				var pmids = pmidArray;
				citationController.existingPmids(pmids, function(err, result){

					assert.ok(result, "something wrong");
					done();
				});
			});

		});
	});

	suite("#sortPmids", function(){

		var stepsNeededBeforeSort;

		setup(function(){

			stepsNeededBeforeSort = function(callback){

				async.waterfall([
				function(callback){

					citationController.fetchCitations(pmid, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}

				], function(err, result){

					callback(result);//assuming there are no errors.

				});

			}

		});

		test("exists", function(done){

			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){
					assert.ok(newPmids, "not ok");

					done();
				});

			});
		});

		test("will pass back an array", function(done){

			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){

						assert.isArray(newPmids);
						done();

				})
			});

		});

		test("sorts newPmids from existingPmids", function(done){
			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){
					//25007843 exists in database already.
					assert.notInclude(newPmids, existingPmids[4]);
					done();
				});

			});
		})

	});

	suite("#addNewPmidsToDb", function(){

		var stepsBeforeAddingPmids;

		var seedPmid;

		var seedPmidObjectId;

		var newlyAddedPmids;

		setup(function(){

			seedPmid = 24431589//has an empty is_ref_of field, has two citations not in db

			seedPmidObjectId = ObjectId("53c27cec432e687019cc6f93");

			stepsBeforeAddingPmids = function(callback){

				async.waterfall([
				function(callback){

					citationController.fetchCitations(seedPmid, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}, function(pmidArray, callback){

					citationController.sortPmids(pmidArray, callback);

				}

				], function(err, newPmids, existingPmids){

					newlyAddedPmids = newPmids;

					callback(newPmids, existingPmids);

				});

			};

		});

		teardown(function(){//remove pmids just added. Not yet populating is_ref_of field so is ok to just remove new pmids
			ArticleModel.remove({pmid:{$in: newlyAddedPmids}}, function(err, result){
				if(err){
					console.log(err);
				}else{
					console.log("newlyAddedPmids removed status: "+ result);
				}
			});

		});

		test("adds new pmids with seedPmid ObjectId in references field", function(done){

			stepsBeforeAddingPmids(function(newPmids, existingPmids){
				citationController.addNewPmidsToDb(newPmids, seedPmidObjectId, function(err, result){

					//then check that seedPmidObjectId is in references field of a newPmid

					ArticleModel.find({references: seedPmidObjectId}, function(err, results){

						var expectedReferenceValue = results[0]["references"].pop().toString();
						assert.equal(seedPmidObjectId, expectedReferenceValue);
						done();
					});

				});
			});

		});

	});

	suite("#updateExistingPmids", function(){
		//23537139 has existing citations in db and a range in pubmed

		var pmidWithExistingCitations;

		var pmidWithExistingCitationsObjectId;

		var stepsBeforeUpdatingExistingPmids;

		setup(function(){

			pmidWithExistingCitations = 23537139;

			pmidWithExistingCitationsObjectId = ObjectId("53c2954da98ffe281c5122f4");

			stepsBeforeUpdatingExistingPmids = function(callback){
				async.waterfall([
				function(callback){

					citationController.fetchCitations(pmidWithExistingCitations, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}, function(pmidArray, callback){

					citationController.sortPmids(pmidArray, callback);

				}

				], function(err, newPmids, existingPmids){

					newlyAddedPmids = newPmids;

					callback(newPmids, existingPmids);

				});
			};

		});

		teardown(function(){
			//remove seedPmidObjectId from references field

			//five out of six pmids in database already have the seedObjectId in references field,
			// so I want to find the one that doesn;t have and use that as my test
			// $pull seedPmidObjectId from that pmid
			ArticleModel.update({pmid: 24575121}, {$pull:{references: pmidWithExistingCitationsObjectId}}, function(err, result){
				if(err){
					console.log(err);
				}else{
			 		console.log(result);
			 	}
			 });

		});

		test("is defined", function(){
			assert.isDefined(citationController.updateExistingPmids);
		});

		test("pushes seedPmidObjectId to references field of an existing pmid", function(done){

			stepsBeforeUpdatingExistingPmids(function(newPmids, existingPmids){

				citationController.updateExistingPmids(existingPmids, pmidWithExistingCitationsObjectId, function(err, results, objectIdToTest){
					if(!err){
						//check results appears in existingPmids
						//console.log("result from update is "+ results)
						var expectedValueInExistingPmidsReferenceField = objectIdToTest // which is actually just pmidWithExistingCitationsObjectId

						ArticleModel.find({references: expectedValueInExistingPmidsReferenceField}, "pmid", function(err, expectedResults){

							var expectedPmidToBeUpdated = 24575121; //24575121 should now be in expectedResults if its references field has been updated with pmidWithExistingCitationsObjectId

							var expectedPmids = _.pluck(expectedResults, "pmid"); // need to extract all pmids from here.

							assert.include(expectedPmids, expectedPmidToBeUpdated, "pmid's references field has not been updaed with pmidWithExistingCitationsObjectId");
							done();
						});

				}

				});

			});

		});

	});

	suite("count_citation field is updated", function(){
		var pmidWithExistingCitationsObjectId = ObjectId("53c2954da98ffe281c5122f4");
		test("citation_count field is updated after populateCitations has finished", function(done){

			ArticleModel.populateCitations(pmidWithExistingCitationsObjectId, function(result){
				console.log(result)
				assert.ok(result);
				done();
			})

		 });//might be off by +/- but should be acceptable margin of error.

	});

	suite("#upsertDocs", function(){

		var steps, pmidWithExistingCitations, pmidWithOneNewCitation, existingPmidObjectId, newPmidObjecetId;
		//after #parseResponse take the array of pmids and upsert on the array. Follow #existingPmids format.
		setup(function(){

			pmidWithExistingCitations = 23537139;
			existingPmidObjectId = ObjectId("53c2954da98ffe281c5122f4");

			pmidWithOneNewCitation = 24699266;

			steps = function(callback){
				async.waterfall([function(callback){
					citationController.fetchCitations(pmidWithExistingCitations, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){

					citationController.parseResponse(citationLinkSet, callback);//gettin' lazy

				}], function(err, pmids){
					if(err){
						callback(err);
					}else{
						console.log(pmids)
						callback(pmids);
					}
				});
		}
		});

		test("method adds new pmid", function(done){
			steps(function(pmids){

				citationController.upsertDocs(pmids, existingPmidObjectId, function(err, results){
					console.log(results)
					assert.ok(results);
					done();

				});
			});

		});

		test.skip("it also updates existing pmids", function(done){

		});

	});

});<commit_msg>Deleted test for checking #existingPmids as method had been removed from CitationsController.<commit_after>var assert = require("chai").assert,
	async = require("async"),
	_ = require("underscore"),
	ObjectId = require("mongoose").Types.ObjectId;

var CitationController = require("../../../controllers/CitationController"),
	ArticleModel = require("../../../models/ArticleModel"),
	ignorePmid = [24563719];

suite("CitationController", function(){

	var citationController;
	var pmid;

	setup(function(){

		citationController = new CitationController();
		pmid = 21743474;//10.1038/nature10158

	});

	teardown(function(){

	});

	test("has getPmid method", function(done){
		assert.isFunction(citationController.getPmid);
		done();
	})

	suite("#getPmid", function(){
		test("gets an object containing a pmid property", function(done){

			/* if there is a pmid to get that is. Check the conditions set
			*  in the getPmid query.
			*
			*  [24563719] is a pmid to ingore
			*
			*/

			citationController.getPmid([24563719], function(err, value){
				var expectedNumber = value;
				assert.isNumber(expectedNumber.pmid);
				assert.isNull(err);
				done();
			})

		});

	});

	suite("#fetchCitations", function(){
		test("makes request to eutils.elink", function(done){

			citationController.fetchCitations(pmid, function(err, response){

				assert.equal(response.statusCode, 200, "response failed");
				done();
			});

		});
	});

	suite("#citationsExist", function(){

		test("body from response contains pubmed_pubmed_citedin", function(done){
			citationController.fetchCitations(pmid, function(err, response){
				var data = response.body;
				citationController.citationsExist(data, function(err, exist){
					assert.isTrue(exist, "pubmed_pubmed_citedin not in response body");
					done();
				})

			});
		});

	});

	suite("#parseResponse", function(){
		test("is called if citations exist in response", function(done){

			async.waterfall([
				function(callback){
						citationController.fetchCitations(pmid, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){
					if(exist ===false){
						callback(true);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}], function(err, result){

					assert.ok(result, "what's gone wrong here?");
					done();
				});
		});

		test("is not called if citations in response do not exist", function(done){

			async.waterfall([function(callback){
				/** dbPmid is a mock object and works as long as
				*   no one ever cites this article.
				* 	How's that for a dependency?
				*/
				dbPmid = {"pmid": 24277739};
				citationController.fetchCitations(dbPmid["pmid"], callback);

			}, function(response, callback){
				var data = response.body;

				citationController.citationsExist(data, callback);

			}, function(exist, citationLinkSet, callback){

				if(exist === false){
					callback(null, "no citations");//confusing?
				}else{
					citationController.parseResponse(citationLinkSet, callback);
				}
			}], function(err, result){

				assert.equal(result, "no citations", "#parseResponse called in error");
				done();
			});

		})

		test("extracts pmids from pubmed_pubmed_citedin section to an array", function(done){

				async.waterfall([
				function(callback){
						citationController.fetchCitations(pmid, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){
					if(exist ===false){
						callback(true);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}], function(err, result){

					assert.isArray(result, "not an array");
					done();
				});

		});

	});

	suite("#sortPmids", function(){

		var stepsNeededBeforeSort;

		setup(function(){

			stepsNeededBeforeSort = function(callback){

				async.waterfall([
				function(callback){

					citationController.fetchCitations(pmid, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}

				], function(err, result){

					callback(result);//assuming there are no errors.

				});

			}

		});

		test("exists", function(done){

			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){
					assert.ok(newPmids, "not ok");

					done();
				});

			});
		});

		test("will pass back an array", function(done){

			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){

						assert.isArray(newPmids);
						done();

				})
			});

		});

		test("sorts newPmids from existingPmids", function(done){
			stepsNeededBeforeSort(function(pmidArray){

				citationController.sortPmids(pmidArray, function(err, newPmids, existingPmids){
					//25007843 exists in database already.
					assert.notInclude(newPmids, existingPmids[4]);
					done();
				});

			});
		})

	});

	suite("#addNewPmidsToDb", function(){

		var stepsBeforeAddingPmids;

		var seedPmid;

		var seedPmidObjectId;

		var newlyAddedPmids;

		setup(function(){

			seedPmid = 24431589//has an empty is_ref_of field, has two citations not in db

			seedPmidObjectId = ObjectId("53c27cec432e687019cc6f93");

			stepsBeforeAddingPmids = function(callback){

				async.waterfall([
				function(callback){

					citationController.fetchCitations(seedPmid, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}, function(pmidArray, callback){

					citationController.sortPmids(pmidArray, callback);

				}

				], function(err, newPmids, existingPmids){

					newlyAddedPmids = newPmids;

					callback(newPmids, existingPmids);

				});

			};

		});

		teardown(function(){//remove pmids just added. Not yet populating is_ref_of field so is ok to just remove new pmids
			ArticleModel.remove({pmid:{$in: newlyAddedPmids}}, function(err, result){
				if(err){
					console.log(err);
				}else{
					console.log("newlyAddedPmids removed status: "+ result);
				}
			});

		});

		test("adds new pmids with seedPmid ObjectId in references field", function(done){

			stepsBeforeAddingPmids(function(newPmids, existingPmids){
				citationController.addNewPmidsToDb(newPmids, seedPmidObjectId, function(err, result){

					//then check that seedPmidObjectId is in references field of a newPmid

					ArticleModel.find({references: seedPmidObjectId}, function(err, results){

						var expectedReferenceValue = results[0]["references"].pop().toString();
						assert.equal(seedPmidObjectId, expectedReferenceValue);
						done();
					});

				});
			});

		});

	});

	suite("#updateExistingPmids", function(){
		//23537139 has existing citations in db and a range in pubmed

		var pmidWithExistingCitations;

		var pmidWithExistingCitationsObjectId;

		var stepsBeforeUpdatingExistingPmids;

		setup(function(){

			pmidWithExistingCitations = 23537139;

			pmidWithExistingCitationsObjectId = ObjectId("53c2954da98ffe281c5122f4");

			stepsBeforeUpdatingExistingPmids = function(callback){
				async.waterfall([
				function(callback){

					citationController.fetchCitations(pmidWithExistingCitations, callback);

				}, function(response, callback){

					var data = response.body;

					citationController.citationsExist(data, callback);

				}, function(exist, citationLinkSet, callback){
					if(exist === false){
						callback(true, exist);
					}else{
						citationController.parseResponse(citationLinkSet, callback);
					}
				}, function(pmidArray, callback){

					citationController.sortPmids(pmidArray, callback);

				}

				], function(err, newPmids, existingPmids){

					newlyAddedPmids = newPmids;

					callback(newPmids, existingPmids);

				});
			};

		});

		teardown(function(){
			//remove seedPmidObjectId from references field

			//five out of six pmids in database already have the seedObjectId in references field,
			// so I want to find the one that doesn;t have and use that as my test
			// $pull seedPmidObjectId from that pmid
			ArticleModel.update({pmid: 24575121}, {$pull:{references: pmidWithExistingCitationsObjectId}}, function(err, result){
				if(err){
					console.log(err);
				}else{
			 		console.log(result);
			 	}
			 });

		});

		test("is defined", function(){
			assert.isDefined(citationController.updateExistingPmids);
		});

		test("pushes seedPmidObjectId to references field of an existing pmid", function(done){

			stepsBeforeUpdatingExistingPmids(function(newPmids, existingPmids){

				citationController.updateExistingPmids(existingPmids, pmidWithExistingCitationsObjectId, function(err, results, objectIdToTest){
					if(!err){
						//check results appears in existingPmids
						//console.log("result from update is "+ results)
						var expectedValueInExistingPmidsReferenceField = objectIdToTest // which is actually just pmidWithExistingCitationsObjectId

						ArticleModel.find({references: expectedValueInExistingPmidsReferenceField}, "pmid", function(err, expectedResults){

							var expectedPmidToBeUpdated = 24575121; //24575121 should now be in expectedResults if its references field has been updated with pmidWithExistingCitationsObjectId

							var expectedPmids = _.pluck(expectedResults, "pmid"); // need to extract all pmids from here.

							assert.include(expectedPmids, expectedPmidToBeUpdated, "pmid's references field has not been updaed with pmidWithExistingCitationsObjectId");
							done();
						});

				}

				});

			});

		});

	});

	suite("count_citation field is updated", function(){
		var pmidWithExistingCitationsObjectId = ObjectId("53c2954da98ffe281c5122f4");
		test("citation_count field is updated after populateCitations has finished", function(done){

			ArticleModel.populateCitations(pmidWithExistingCitationsObjectId, function(result){
				console.log(result)
				assert.ok(result);
				done();
			})

		 });//might be off by +/- but should be acceptable margin of error.

	});

	suite("#upsertDocs", function(){

		var steps, pmidWithExistingCitations, pmidWithOneNewCitation, existingPmidObjectId, newPmidObjecetId;
		//after #parseResponse take the array of pmids and upsert on the array. Follow #existingPmids format.
		setup(function(){

			pmidWithExistingCitations = 23537139;
			existingPmidObjectId = ObjectId("53c2954da98ffe281c5122f4");

			pmidWithOneNewCitation = 24699266;

			steps = function(callback){
				async.waterfall([function(callback){
					citationController.fetchCitations(pmidWithExistingCitations, callback);
				}, function(response, callback){
					var data = response.body;
					citationController.citationsExist(data, callback);
				}, function(exist, citationLinkSet, callback){

					citationController.parseResponse(citationLinkSet, callback);//gettin' lazy

				}], function(err, pmids){
					if(err){
						callback(err);
					}else{
						console.log(pmids)
						callback(pmids);
					}
				});
		}
		});

		test("method adds new pmid", function(done){
			steps(function(pmids){

				citationController.upsertDocs(pmids, existingPmidObjectId, function(err, results){
					console.log(results)
					assert.ok(results);
					done();

				});
			});

		});

		test.skip("it also updates existing pmids", function(done){

		});

	});

});<|endoftext|>


<commit_before>import React from 'react'
import Section from '../components/Section'

// require('../../build/fonts/sawarabigothic/SawarabiGothic-Regular.ttf')

class SpecimenSawarabi extends React.Component {
  render () {
    return (

どうやらアトモスフェアの高い位置まで到達したようだった。空は真っ暗で、星の瞬きもなくなっていた。丘の上では彼方に広がる水平線が同じ高さに見えるのと同じ錯覚によって、眼下に真っ暗な雲が広がり、車は巨大な暗い空間の真ん中に浮いているように見えた。その空間の上半分は銀色にきらめいていた。

依然として速度を増しながら進むにつれて、夜と日中の切り替わりが曖昧になり、一続きの灰色になった。空は深い青色で夕暮れ時のような明るい光で照らされている。急に現れる太陽はきらめく円弧の形をした光の筋となった。月はおぼろげに揺らぐ帯となり、星は見えなかった。ただ、時折青い空に明るく瞬く円が見えた。

    )
  }
}

export default SpecimenSawarabi
<commit_msg>Adds initial SVG motion to Sawarabi section<commit_after>import React from 'react'
import Section from '../components/Section'

// require('../../build/fonts/sawarabigothic/SawarabiGothic-Regular.ttf')

class SpecimenSawarabi extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      eventPageX: 0,
      eventPageY: 0,
      offsetTop: 0,
      offsetLeft: 0,
      r: 200
    }

    this.handleOnMouseMove = this.handleOnMouseMove.bind(this)
    this.handleOnTouchMove = this.handleOnTouchMove.bind(this)
  }

  componentDidMount () {
    const self = this
    const container = self._container

    self.setState({
      offsetTop: container.offsetLeft,
      offsetLeft: container.offsetLeft
    })

  }

  handleOnMouseMove (e) {
    e.persist()
    const self = this
    const eventPageX = e.pageX
    const eventPageY = e.pageY
    const container = self._container

    self.setState({
      eventPageX: eventPageX,
      eventPageY: eventPageY,
      offsetTop: container.offsetTop,
      offsetLeft: container.offsetLeft
    })
  }

  handleOnTouchMove (e) {
    e.persist()
    const self = this
    const touch = e.touches[0]
    const eventPageX = touch.clientX
    const eventPageY = touch.clientY

    self.setState({
      eventPageX: eventPageX,
      eventPageY: eventPageY,
      offsetTop: 0,
      offsetLeft: 0
    })
  }

  render () {
    const state = this.state
    const cx = ((state.eventPageX) - (state.offsetLeft - (state.r / 2) ))
    const cy = (state.eventPageY - (state.offsetTop - (state.r / 2) ))

    return (

 this._container = c}>
          <svg width="100%"
               height="100%"
               viewBox={'0 0 1122 705'}
               version="1.1"
               xmlns="http://www.w3.org/2000/svg"
               style={{ fillRule: 'evenodd', clipRule: 'evenodd', strokeLinejoin: 'round', strokeMiterlimit: 1.41421 }}>
             <g>
               <circle cx={ 500 - cx } cy={ cy * 0.2 }  r={ state.r / 5 } className="fill-red" />
               <circle cx={ cx + 100 * 0.2 } cy={ 300 - cy * 1.1  } r={ state.r / 3 }  className="fill-red" />
               <circle cx={ cx * 0.1 } cy={ cy * 0.2 }  r={ state.r * 0.12 } className="fill-maroon" />
               <circle cx={ cx * 1.3 } cy={ cy * 3 } r={ state.r * 1.2 }  className="fill-red" />
               <circle cx={ cx * 0.25} cy={ cy * 1.1 }  r={ state.r * 0.5}   className="fill-red" />
               <circle cx={ cx * 3 } cy={ cy * 0.2 }  r={ state.r * 0.6 }  className="fill-red" />
               <circle cx={ cx * 2 } cy={ cy * 3 }    r={ state.r * 1 }    className="fill-maroon" />
               <circle cx={ cx * 1 }   cy={ cy * 1 }        r={ state.r }        className="fill-maroon" />
             </g>
             <g>
             <g>
               <text x="200" y="200" className="wf-sawarabimincho h4 sm-h5 md-h3 lg-h2 line-height-4 fill-white">どうやらアトモスフェアの高い位置まで到達したようだった。空は真っ暗で、星の瞬きもなくなっていた。丘の上では彼方に広がる水平線が同じ高さに見えるのと同じ錯覚によって、眼下に真っ暗な雲が広がり、車は巨大な暗い空間の真ん中に浮いているように見えた。その空間の上半分は銀色にきらめいていた。</text>
               <text x="200" y="350" className="wf-sawarabigothic h4 sm-h5 md-h3 lg-h2 line-height-4 fill-white">依然として速度を増しながら進むにつれて、夜と日中の切り替わりが曖昧になり、一続きの灰色になった。空は深い青色で夕暮れ時のような明るい光で照らされている。急に現れる太陽はきらめく円弧の形をした光の筋となった。月はおぼろげに揺らぐ帯となり、星は見えなかった。ただ、時折青い空に明るく瞬く円が見えた。</text>
             </g>
             </g>
           </svg>

    )
  }
}

export default SpecimenSawarabi
<|endoftext|>


<commit_before>/*
 * ng-toolqit
 * https://github.com/matyax/ng-toolqit

 * Version: 1.0.1
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

angular.module('ngToolqit', ['ng']).

  filter('range', function() {
    return function(range, quantity) {
      if (typeof range != 'object') {
        throw new Error('Filter input must be an empty array.');
      }

      quantity = parseInt(quantity);

      for (var i = 0; i < quantity; i++) {
        range.push(i);
      }

      return range;
    };
  });

})(window, window.angular);<commit_msg>Implement format directive<commit_after>/*
 * ng-toolqit
 * https://github.com/matyax/ng-toolqit

 * Version: 1.0.1
 * License: MIT
 */
(function(window, angular, undefined) {'use strict';

  angular.module('ngToolqit', ['ng']).
    /**
     * @ngdoc filter
     * @name range
     *
     * @description
     * Creates a range of `quantity´ elements for an ng-repeat.
     */
    filter('range', function () {
      return function (range, quantity) {
        if (typeof range !== 'object') {
          throw new Error('Filter input must be an empty array.');
        }

        quantity = parseInt(quantity);

        for (var i = 0; i < quantity; i++) {
          range.push(i);
        }

        return range;
      };
    });

  angular.module('ngToolqit').
    /**
     * @ngdoc directive
     * @name format
     *
     * @description
     * Formats the input of an ngModel according to the given format rules.
     */
    directive('format', [function () {
      return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (! attr.formatRules) {
            throw new Error('Missing format rules.');
          }

          ngModel.$parsers.push(function (value) {
            value = applyFormatRules(value, attr.formatRules);

            element.val(value);

            return value;
          });
        }
      };

      /**
       * Apply a set of rules to a given string.
       *
       * @param {string} input Input string
       * @param {string} rules Rules
       * @return {string} Transformed string
       *
       * @example
       * Rules:
       * 9: [0-9]
       * a: [a-zA-Z]
       * *: [a-zA-Z0-9]
       *
       * E.g. ssn: 999-99-9999
       */
      function applyFormatRules(input, rules) {
        var rulesHash = {
              '9': '[0-9]',
              'a': '[a-zA-Z]',
              '\\*': '[a-zA-Z0-9]'
            },
            fullRegExp = rules, //Full pattern regular expression to test the entire input.
            output     = '';

        for (var rule in rulesHash) {
          fullRegExp = fullRegExp.replace(new RegExp(rule, 'g'), rulesHash[rule]);
        }

        input = input.substring(0, rules.length);

        if (input.match(fullRegExp)) {
          return input; //No need to keep testing the input
        }

        var inputChars = input.split(''),
            ruleChars  = rules.split('');

        inputChars.filter(function (value, i, inputChars) {
          if (! rulesHash[ruleChars[i]]) { //Literal string, insert and splice input value
            output += ruleChars[i];

            if (value === ruleChars[i]) {
              return true;
            }
          }

          if (value.match(rulesHash[ruleChars[i]])) {
            output += value;
            return true;
          }

          return false;
        });

        return output;
      }
  }]);
})(window, window.angular);<|endoftext|>


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

    angular
        .module('ng-duallist', [])
        .directive('duallist', ngDuallist)
        .run(templateCache)

    ngDuallist.$inject = ['$rootScope', '$filter'];
    templateCache.$inject = ['$templateCache'];

    /* @ngInject */
    function ngDuallist($rootScope, $filter) {
        // Usage:
        //
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'E',
            scope: {
                leftscope: '=',
                rightscope: '=',
                'duallistOption': '=',
                leftsearch: '='
            },
            bindToController: false,
            controller: Controller,
            controllerAs: 'vm',
            templateUrl: function (element, attrs) {
                return attrs.templateUrl || 'dual/duallist.html';
            },
            replace: true
        };
        return directive;

        function link(scope, element, attrs, controller) {

            if (scope.duallistOption.leftContainerScrollEnd) { // excecute the left container scroll end event
                $(element).find('.left-sub-container').bind('scroll', function () {
                     console.log($(this)[0].scrollHeight - $(this).scrollTop())
                             console.log($(this).outerHeight())
                    if ($(this)[0].scrollHeight - $(this).scrollTop() === $(this).height()) {

                        scope.$evalAsync(scope.duallistOption.leftContainerScrollEnd);
                    };
                });
            }

            if (scope.duallistOption.rightContainerScrollEnd) { // execute the righ contained scroll end event
                $(element).find('.right-sub-container').bind('scroll', function () {
                    if ($(this)[0].scrollHeight - $(this).scrollTop() === $(this).height()) {
                        scope.$evalAsync(scope.duallistOption.rightContainerScrollEnd);
                    };
                });
            }
            if (scope.duallistOption.leftContainerSearch) { //left seracg text chage
                $(element).find('#leftsearch').bind("change paste keyup", function () {
                    var value = $(this).val();
                    scope.$evalAsync(scope.duallistOption.leftContainerSearch(value));

                })
            }

            if (scope.duallistOption.rightContainerSearch) { //right serach text chage
                $(element).find('#rightsearch').bind("change paste keyup", function () {
                    var value = $(this).val();
                    scope.$evalAsync(scope.duallistOption.rightContainerSearch(value));

                })
            }

             if (scope.duallistOption.onMoveRight) { //right serach text chage
                $(element).find('#moveRightButton').bind("click", function () {

                    scope.$evalAsync(scope.duallistOption.onMoveRight)

                })
            }

             if (scope.duallistOption.onMoveLeft) { //right serach text chage
                $(element).find('#moveLeftButton').bind("click", function () {

                    scope.$evalAsync(scope.duallistOption.onMoveLeft);

                })
            }

        }

    }

    Controller.$inject = ['$scope'];

    /* @ngInject */
    function Controller($scope) {

        /**
         * @description move the selected item to the right
         */
        $scope.moveRight = function () {

            for (var i = 0; i < $scope.leftscope.length; i++) {
                if ($scope.leftscope[i].selected) {
                    $scope.leftscope[i].selected = false
                    $scope.rightscope.push($scope.leftscope[i]);
                    var index = $scope.leftscope.indexOf($scope.leftscope[i]);
                    $scope.leftscope.splice(index, 1)
                    i--
                }

            }

            $scope.leftSelectAll = false;

        };

        /**
         * @description move the selected item to the left
         */
        $scope.moveLeft = function () {
            //var leftSelectedValue=$filter()
            console.log($scope.rightscope)
            for (var i = 0; i < $scope.rightscope.length; i++) {
                console.log(i)
                if ($scope.rightscope[i].selected) {
                    $scope.rightscope[i].selected = false
                    $scope.leftscope.push($scope.rightscope[i]);
                    var index = $scope.rightscope.indexOf($scope.rightscope[i]);
                    // console.log(index)
                    $scope.rightscope.splice(index, 1)
                    i--
                }

            }
            $scope.rightSelectAll = false;
        };

        /**
         * @description select all left container
         */
        $scope.selectAllLeftContainer = function () {

            angular.forEach($scope.leftscope, function (val) {
                if ($scope.leftSelectAll) {
                    val.selected = true;
                } else {
                    val.selected = false;
                }
            })
        }

        /**
         * @description select all right container
         */
        $scope.selectAllRightContainer = function () {
            angular.forEach($scope.rightscope, function (val) {
                if ($scope.rightSelectAll) {
                    val.selected = true;
                } else {
                    val.selected = false;
                }
            });
        }

    }

    function templateCache($templateCache) {
        $templateCache.put('dual/duallist.html', '

 {{duallistOption.leftContainerLabel}}   0">Showing all{{leftscope.length}} Empty List  <form class="form-inline">

 <input type="text" class="form-control" id="leftsearch" placeholder="Search">
 <input title="toggle all" class="all pull-right" ng-model="leftSelectAll" ng-change="selectAllLeftContainer()" type="checkbox">

</form>

 {{data.name}}<input class="pull-right" ng-model="data.selected" type="checkbox">

 <button id="moveRightButton" ng-click="moveRight()" title="Send to list 2" class="btn btn-default center-block add"></button> <button id="moveLeftButton" ng-click="moveLeft()" title="Send to list 1" class="btn btn-default center-block remove"></button>

 {{duallistOption.rightContainerLabel}}   0">Showing all{{rightscope.length}} Empty List  <form class="form-inline">

 <input type="text" class="form-control" id="rightsearch" placeholder="Search">
 <input ng-model="rightSelectAll" ng-change="selectAllRightContainer()" title="toggle all" class="all pull-right" type="checkbox">

</form>

 {{data.name}}<input ng-model="data.selected" class="pull-right" type="checkbox">

');

    }

})();<commit_msg>Semi added<commit_after>(function () {
    'use strict';

    angular
        .module('ng-duallist', [])
        .directive('duallist', ngDuallist)
        .run(templateCache)

    ngDuallist.$inject = ['$rootScope', '$filter'];
    templateCache.$inject = ['$templateCache'];

    /* @ngInject */
    function ngDuallist($rootScope, $filter) {
        // Usage:
        //
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'E',
            scope: {
                leftscope: '=',
                rightscope: '=',
                'duallistOption': '=',
                leftsearch: '='
            },
            bindToController: false,
            controller: Controller,
            controllerAs: 'vm',
            templateUrl: function (element, attrs) {
                return attrs.templateUrl || 'dual/duallist.html';
            },
            replace: true
        };
        return directive;

        function link(scope, element, attrs, controller) {

            if (scope.duallistOption.leftContainerScrollEnd) { // excecute the left container scroll end event
                $(element).find('.left-sub-container').bind('scroll', function () {
                    console.log($(this)[0].scrollHeight - $(this).scrollTop())
                    console.log($(this).outerHeight())
                    if ($(this)[0].scrollHeight - $(this).scrollTop() === $(this).height()) {

                        scope.$evalAsync(scope.duallistOption.leftContainerScrollEnd);
                    };
                });
            }

            if (scope.duallistOption.rightContainerScrollEnd) { // execute the righ contained scroll end event
                $(element).find('.right-sub-container').bind('scroll', function () {
                    if ($(this)[0].scrollHeight - $(this).scrollTop() === $(this).height()) {
                        scope.$evalAsync(scope.duallistOption.rightContainerScrollEnd);
                    };
                });
            }
            if (scope.duallistOption.leftContainerSearch) { //left seracg text chage
                $(element).find('#leftsearch').bind("change paste keyup", function () {
                    var value = $(this).val();
                    scope.$evalAsync(scope.duallistOption.leftContainerSearch(value));

                })
            }

            if (scope.duallistOption.rightContainerSearch) { //right serach text chage
                $(element).find('#rightsearch').bind("change paste keyup", function () {
                    var value = $(this).val();
                    scope.$evalAsync(scope.duallistOption.rightContainerSearch(value));

                })
            }

            if (scope.duallistOption.onMoveRight) { //right serach text chage
                $(element).find('#moveRightButton').bind("click", function () {

                    scope.$evalAsync(scope.duallistOption.onMoveRight)

                })
            }

            if (scope.duallistOption.onMoveLeft) { //right serach text chage
                $(element).find('#moveLeftButton').bind("click", function () {

                    scope.$evalAsync(scope.duallistOption.onMoveLeft);

                })
            };

        }

    }

    Controller.$inject = ['$scope'];

    /* @ngInject */
    function Controller($scope) {

        /**
         * @description move the selected item to the right
         */
        $scope.moveRight = function () {

            for (var i = 0; i < $scope.leftscope.length; i++) {
                if ($scope.leftscope[i].selected) {
                    $scope.leftscope[i].selected = false
                    $scope.rightscope.push($scope.leftscope[i]);
                    var index = $scope.leftscope.indexOf($scope.leftscope[i]);
                    $scope.leftscope.splice(index, 1)
                    i--
                }

            }

            $scope.leftSelectAll = false;

        };

        /**
         * @description move the selected item to the left
         */
        $scope.moveLeft = function () {
            //var leftSelectedValue=$filter()
            console.log($scope.rightscope)
            for (var i = 0; i < $scope.rightscope.length; i++) {
                console.log(i)
                if ($scope.rightscope[i].selected) {
                    $scope.rightscope[i].selected = false
                    $scope.leftscope.push($scope.rightscope[i]);
                    var index = $scope.rightscope.indexOf($scope.rightscope[i]);
                    // console.log(index)
                    $scope.rightscope.splice(index, 1)
                    i--
                }

            }
            $scope.rightSelectAll = false;
        };

        /**
         * @description select all left container
         */
        $scope.selectAllLeftContainer = function () {

            angular.forEach($scope.leftscope, function (val) {
                if ($scope.leftSelectAll) {
                    val.selected = true;
                } else {
                    val.selected = false;
                }
            })
        }

        /**
         * @description select all right container
         */
        $scope.selectAllRightContainer = function () {
            angular.forEach($scope.rightscope, function (val) {
                if ($scope.rightSelectAll) {
                    val.selected = true;
                } else {
                    val.selected = false;
                }
            });
        }

    }

    function templateCache($templateCache) {
        $templateCache.put('dual/duallist.html', '

 {{duallistOption.leftContainerLabel}}   0">Showing all{{leftscope.length}} Empty List  <form class="form-inline">

 <input type="text" class="form-control" id="leftsearch" placeholder="Search">
 <input title="toggle all" class="all pull-right" ng-model="leftSelectAll" ng-change="selectAllLeftContainer()" type="checkbox">

</form>

 {{data.name}}<input class="pull-right" ng-model="data.selected" type="checkbox">

 <button id="moveRightButton" ng-click="moveRight()" title="Send to list 2" class="btn btn-default center-block add"></button> <button id="moveLeftButton" ng-click="moveLeft()" title="Send to list 1" class="btn btn-default center-block remove"></button>

 {{duallistOption.rightContainerLabel}}   0">Showing all{{rightscope.length}} Empty List  <form class="form-inline">

 <input type="text" class="form-control" id="rightsearch" placeholder="Search">
 <input ng-model="rightSelectAll" ng-change="selectAllRightContainer()" title="toggle all" class="all pull-right" type="checkbox">

</form>

 {{data.name}}<input ng-model="data.selected" class="pull-right" type="checkbox">

');

    }

})();<|endoftext|>


<commit_before>//  This file has our application code.
//  Complete this code so all QUnit tests pass.
//  We have defined an App object that interacts with the user.
//  It includes an example of many common programming constructs.

var App = {
  launch: function () {
    App.getFirstName();
    App.getLastName();
    App.getWidth();
    App.getLength();
    App.calculateArea();
    App.estimateCount();
    App.showExample();

  },
  getFirstName: function () {
    let answer = prompt("What is your first name?", "Awesome");
    if (answer != null) {
      document.getElementById("first").innerHTML = answer;
    }
  },
  getLastName: function () {
    let answer = prompt("What is your last name?", "Lilly");
    if (answer != null) {
      document.getElementById("last").innerHTML = answer;
    }
  },
  getWidth: function () {
    let answer = prompt("What is the width of your farm in miles?", 5);
    if (answer != null) {
      document.getElementById("width").innerHTML = answer;
    }
  },
  getLength: function () {
    let answer = prompt("What is the length of your farm in miles?", 5);
    if (answer != null) {
      document.getElementById("length").innerHTML = answer;
    }
  },
  calculateArea: function () {
    let inputWidth = parseFloat(document.getElementById("width").innerHTML);
    let inputLength = parseFloat(document.getElementById("length").innerHTML);
    if (inputWidth < 1) { inputWidth = 1; }
    if (inputLength < 1) { inputLength = 1; }
    if (inputWidth > 100) { inputWidth = 100; }
    if (inputLength > 100) { inputLength = 100; }
    let answer = inputWidth * inputLength;
    document.getElementById("area").innerHTML = answer;
    alert("You have about " + answer + " square miles.");
  },
  estimateCount: function () {
    let area = parseFloat(document.getElementById("area").innerHTML);
    let count;
    if (area < 1) { count = 0; }
    else { count = area }; // estimate 1 per square mile
    document.getElementById("count").innerHTML = count;
    alert("You could have about " + count + " sheep.");
  },
  showExample: function () {
    let totalCount = parseFloat(document.getElementById("count").innerHTML);
    for (var i = 0; i < totalCount; i++) {
      App.addImage(i);
    }
  },
  addImage: function (icount) {
    var imageElement = document.createElement("img");
    imageElement.id = "image" + icount;
    imageElement.class = "picture";
    imageElement.style.maxWidth = "90px";
    var displayElement = document.getElementById("displayPlace");
    displayElement.appendChild(imageElement);
    document.getElementById("image" + icount).src = "59-images-of-baby-lamb-clipart-you-can-use-these-free-cliparts-for-sEfudv-clipart.jpg";
  }
};

<commit_msg>resets display<commit_after>//  This file has our application code.
//  Complete this code so all QUnit tests pass.
//  We have defined an App object that interacts with the user.
//  It includes an example of many common programming constructs.

var App = {
  launch: function () {
    App.getFirstName();
    App.getLastName();
    App.getWidth();
    App.getLength();
    App.calculateArea();
    App.estimateCount();
    App.showExample();

  },
  getFirstName: function () {
    let answer = prompt("What is your first name?", "Awesome");
    if (answer != null) {
      document.getElementById("first").innerHTML = answer;
    }
  },
  getLastName: function () {
    let answer = prompt("What is your last name?", "Lilly");
    if (answer != null) {
      document.getElementById("last").innerHTML = answer;
    }
  },
  getWidth: function () {
    let answer = prompt("What is the width of your farm in miles?", 5);
    if (answer != null) {
      document.getElementById("width").innerHTML = answer;
    }
  },
  getLength: function () {
    let answer = prompt("What is the length of your farm in miles?", 5);
    if (answer != null) {
      document.getElementById("length").innerHTML = answer;
    }
  },
  calculateArea: function () {
    let inputWidth = parseFloat(document.getElementById("width").innerHTML);
    let inputLength = parseFloat(document.getElementById("length").innerHTML);
    if (inputWidth < 1) { inputWidth = 1; }
    if (inputLength < 1) { inputLength = 1; }
    if (inputWidth > 100) { inputWidth = 100; }
    if (inputLength > 100) { inputLength = 100; }
    let answer = inputWidth * inputLength;
    document.getElementById("area").innerHTML = answer;
    alert("You have about " + answer + " square miles.");
  },
  estimateCount: function () {
    let area = parseFloat(document.getElementById("area").innerHTML);
    let count;
    if (area < 1) { count = 0; }
    else { count = area }; // estimate 1 per square mile
    document.getElementById("count").innerHTML = count;
    alert("You could have about " + count + " sheep.");
  },
  showExample: function () {
    document.getElementById("displayPlace").innerHTML="";
    let totalCount = parseFloat(document.getElementById("count").innerHTML);
    for (var i = 0; i < totalCount; i++) {
      App.addImage(i);
    }
  },
  addImage: function (icount) {
    var imageElement = document.createElement("img");
    imageElement.id = "image" + icount;
    imageElement.class = "picture";
    imageElement.style.maxWidth = "90px";
    var displayElement = document.getElementById("displayPlace");
    displayElement.appendChild(imageElement);
    document.getElementById("image" + icount).src = "59-images-of-baby-lamb-clipart-you-can-use-these-free-cliparts-for-sEfudv-clipart.jpg";
  }
};

<|endoftext|>


<commit_before>console.log('DadaTube: userscript.js loaded');

// https://github.com/DVLP/localStorageDB#you-can-use-it-as-a-one-liner-in-your-js-code
!function(){function e(t,o){return n?void(n.transaction("s").objectStore("s").get(t).onsuccess=function(e){var t=e.target.result&&e.target.result.v||null;o(t)}):void setTimeout(function(){e(t,o)},100)}var t=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB;if(!t)return void console.error("indexDB not supported");var n,o={k:"",v:""},r=t.open("d2",1);r.onsuccess=function(e){n=this.result},r.onerror=function(e){console.error("indexedDB request error"),console.log(e)},r.onupgradeneeded=function(e){n=null;var t=e.target.result.createObjectStore("s",{keyPath:"k"});t.transaction.oncomplete=function(e){n=e.target.db}},window.ldb={get:e,set:function(e,t){o.k=e,o.v=t,n.transaction("s","readwrite").objectStore("s").put(o)}}}();

$(function() {
    'use strict';

    var options = {
        hiddenOpacity: 0.1,
        removeJunkStrategy: 'remove'
    };

    function addGlobalStyle(css) {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) {
            throw 'no head?!';
        }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    }

    var hiddenClass = 'dnthHidden';

    addGlobalStyle('.' + hiddenClass + ' { opacity: ' + options.hiddenOpacity + '; transition: opacity 0.2s ease-in-out; }');

    function removeJunk() {
        function doRemove($junk) {
            if ('remove' === options.removeJunkStrategy) {
                $junk.remove();
            } else if ('border' === options.removeJunkStrategy) {
                $junk.css('border', '2px solid red');
            } else {
                throw 'unknown removeJunkStrategy: ' + options.removeJunkStrategy;
            }
        }

        var $h3 = $('h3:contains("Related pages")');
        doRemove($h3.nextAll().css('border', '2px solid red'));
        doRemove($h3);

        var $footer = $('#footer');
        doRemove($footer.nextAll());
        doRemove($footer);

        doRemove($('iframe'));

        doRemove($('ul.tags'));
    }

    /**
     * Show/hide hidables in the view
     */
    var hidableView = {
        hide: function ($hidables, onComplete) {
            $hidables.addClass(hiddenClass);

            if (onComplete) {
                onComplete();
            }
        },
        show: function ($hidables, onComplete) {
            $hidables.removeClass(hiddenClass);

            if (onComplete) {
                onComplete();
            }
        }
    };

    var hidablesController = {
        showAll: function () {
            hidablesController.show($hidables);
        },
        hideAll: function () {
            hidablesController.hide($hidables);
        },
        show: function ($hidables) {
            $hidables.each(function () {
                hiddenHidablesStorage.remove(identifyHidable($(this)));
            });

            hidableView.show($hidables);
        },
        hide: function ($hidables) {
            $hidables.each(function () {
                hiddenHidablesStorage.add(identifyHidable($(this)));
            });

            hidableView.hide($hidables);
        },
        toggleVisibility: function ($hidable) {
            if ($hidable.hasClass(hiddenClass)) {
                hidablesController.show($hidable);
            } else {
                hidablesController.hide($hidable);
            }
        }
    };

    var HidablesStorage = function (storageDriver, prefix) {
        this.has = function (id, callback) {
            if (!id) {
                callback(false);
            }

            ldb.get(prefix + id, function (value) {
                console.log('HidablesStorage get', prefix + id, value);
                callback(value ? true : false);
            });
            // callback(storageDriver[prefix + id] ? true : false);
        };

        this.add = function (id) {
            console.log('HidablesStorage.add(' + id + ') called');

            ldb.set(prefix + id, (new Date()).toJSON());

            ldb.get(prefix + id, function (value) {
                console.log('value for "' + prefix + id + '" was set: "' + value + '"');
            });

            // storageDriver[prefix + id] = (new Date()).toJSON();
        };

        this.remove = function (id) {
            this.has(id, function (has) {
                if (has) {
                    ldb.set(prefix + id, null);
                    // storageDriver.removeItem(prefix + id);
                }
            });
        };
    }; // eo Storage

    /**
     * Hidables IDs storage helper.
     * Keys have prefix to avoid collisions and easily find items.
     * Key hold hidable IDs, values have the date they were hidden.
     */
    var hiddenHidablesStorage = new HidablesStorage(localStorage, 'dnthHiddenHidable_');

    /**
     * Gets hidable identifying data
     */
    var identifyHidable = function ($hidable) {
        return $hidable
            .find('a.glitem')
            .attr('href')
            .match('/pics/([a-zA-Z0-9\-\/_\.]+)')[1];
    };

    /**
     * Items to hide
     */
    var $hidables = $('ul#g').find('li:not([style])'); // te, co mają styl, to reklamy

    // $hidables.each(function () {
    //     console.log('hidable on start', identifyHidable($(this)));
    // });

    removeJunk();

    /**
     * Clicking on a table row (hidable), hides it.
     */
    $hidables.click(function () {
        console.log('hidable clicked');

        hidablesController.toggleVisibility($(this));
    });

    function selectHidablesFromStorage(returnResultCallback) {
        var selectedIds = [];

        var hidablesLength = $hidables.length;
        var hidablesProcessed = 0;

        $hidables.each(function (index, value) {
            var id = identifyHidable($(value));

            hiddenHidablesStorage.has(id, function (has) {
                hidablesProcessed++;

                if (has) {
                    selectedIds.push(id);
                }

                if (hidablesProcessed === hidablesLength) {
                    document.selectedIds = selectedIds;

                    document.hids = $hidables;

                    var $result = $hidables.filter(function () {
                        return !$.inArray(
                            identifyHidable($(this)),
                            selectedIds
                        );
                    });

                    returnResultCallback($result);
                }
            });
        });
    }

    /**
     * Page loaded: removing elements already hidden and saved to localStorage
     */
    selectHidablesFromStorage(function ($found) {
        console.log('found to remove on start', $found);

        hidableView.hide($found);
        // $found.remove();
    });

    /**
     * Hide/remove from storage when space is hit
     */
    var removedAfterSpace = false;
    $(document).keydown(function(evt) {
        if (32 == evt.keyCode) {
            console.log('space was hit');

            selectHidablesFromStorage(function ($found) {
                if (removedAfterSpace) {
                    hidableView.hide($found);
                } else {
                    hidableView.hide($found);
                    // $found.remove();

                    removedAfterSpace = true;
                }
            });
        }
    });

    $('<button>hide all and close</button>')
        .insertAfter('ul.gallery')
        .click(function () {
            hidablesController.hideAll();

            window.close();
        });
});
<commit_msg>hide all and close button styling and inserting<commit_after>console.log('DadaTube: userscript.js loaded');

// https://github.com/DVLP/localStorageDB#you-can-use-it-as-a-one-liner-in-your-js-code
!function(){function e(t,o){return n?void(n.transaction("s").objectStore("s").get(t).onsuccess=function(e){var t=e.target.result&&e.target.result.v||null;o(t)}):void setTimeout(function(){e(t,o)},100)}var t=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB;if(!t)return void console.error("indexDB not supported");var n,o={k:"",v:""},r=t.open("d2",1);r.onsuccess=function(e){n=this.result},r.onerror=function(e){console.error("indexedDB request error"),console.log(e)},r.onupgradeneeded=function(e){n=null;var t=e.target.result.createObjectStore("s",{keyPath:"k"});t.transaction.oncomplete=function(e){n=e.target.db}},window.ldb={get:e,set:function(e,t){o.k=e,o.v=t,n.transaction("s","readwrite").objectStore("s").put(o)}}}();

$(function() {
    'use strict';

    var options = {
        hiddenOpacity: 0.1,
        removeJunkStrategy: 'remove'
    };

    function addGlobalStyle(css) {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) {
            throw 'no head?!';
        }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    }

    var hiddenClass = 'dnthHidden';

    addGlobalStyle('.' + hiddenClass + ' { opacity: ' + options.hiddenOpacity + '; transition: opacity 0.2s ease-in-out; }');

    function removeJunk() {
        function doRemove($junk) {
            if ('remove' === options.removeJunkStrategy) {
                $junk.remove();
            } else if ('border' === options.removeJunkStrategy) {
                $junk.css('border', '2px solid red');
            } else {
                throw 'unknown removeJunkStrategy: ' + options.removeJunkStrategy;
            }
        }

        var $h3 = $('h3:contains("Related pages")');
        doRemove($h3.nextAll().css('border', '2px solid red'));
        doRemove($h3);

        var $footer = $('#footer');
        doRemove($footer.nextAll());
        doRemove($footer);

        doRemove($('iframe'));

        doRemove($('ul.tags'));
    }

    /**
     * Show/hide hidables in the view
     */
    var hidableView = {
        hide: function ($hidables, onComplete) {
            $hidables.addClass(hiddenClass);

            if (onComplete) {
                onComplete();
            }
        },
        show: function ($hidables, onComplete) {
            $hidables.removeClass(hiddenClass);

            if (onComplete) {
                onComplete();
            }
        }
    };

    var hidablesController = {
        showAll: function () {
            hidablesController.show($hidables);
        },
        hideAll: function () {
            hidablesController.hide($hidables);
        },
        show: function ($hidables) {
            $hidables.each(function () {
                hiddenHidablesStorage.remove(identifyHidable($(this)));
            });

            hidableView.show($hidables);
        },
        hide: function ($hidables) {
            $hidables.each(function () {
                hiddenHidablesStorage.add(identifyHidable($(this)));
            });

            hidableView.hide($hidables);
        },
        toggleVisibility: function ($hidable) {
            if ($hidable.hasClass(hiddenClass)) {
                hidablesController.show($hidable);
            } else {
                hidablesController.hide($hidable);
            }
        }
    };

    var HidablesStorage = function (storageDriver, prefix) {
        this.has = function (id, callback) {
            if (!id) {
                callback(false);
            }

            ldb.get(prefix + id, function (value) {
                console.log('HidablesStorage get', prefix + id, value);
                callback(value ? true : false);
            });
            // callback(storageDriver[prefix + id] ? true : false);
        };

        this.add = function (id) {
            console.log('HidablesStorage.add(' + id + ') called');

            ldb.set(prefix + id, (new Date()).toJSON());

            ldb.get(prefix + id, function (value) {
                console.log('value for "' + prefix + id + '" was set: "' + value + '"');
            });

            // storageDriver[prefix + id] = (new Date()).toJSON();
        };

        this.remove = function (id) {
            this.has(id, function (has) {
                if (has) {
                    ldb.set(prefix + id, null);
                    // storageDriver.removeItem(prefix + id);
                }
            });
        };
    }; // eo Storage

    /**
     * Hidables IDs storage helper.
     * Keys have prefix to avoid collisions and easily find items.
     * Key hold hidable IDs, values have the date they were hidden.
     */
    var hiddenHidablesStorage = new HidablesStorage(localStorage, 'dnthHiddenHidable_');

    /**
     * Gets hidable identifying data
     */
    var identifyHidable = function ($hidable) {
        return $hidable
            .find('a.glitem')
            .attr('href')
            .match('/pics/([a-zA-Z0-9\-\/_\.]+)')[1];
    };

    /**
     * Items to hide
     */
    var $hidables = $('ul#g').find('li:not([style])'); // te, co mają styl, to reklamy

    // $hidables.each(function () {
    //     console.log('hidable on start', identifyHidable($(this)));
    // });

    removeJunk();

    /**
     * Clicking on a table row (hidable), hides it.
     */
    $hidables.click(function () {
        console.log('hidable clicked');

        hidablesController.toggleVisibility($(this));
    });

    function selectHidablesFromStorage(returnResultCallback) {
        var selectedIds = [];

        var hidablesLength = $hidables.length;
        var hidablesProcessed = 0;

        $hidables.each(function (index, value) {
            var id = identifyHidable($(value));

            hiddenHidablesStorage.has(id, function (has) {
                hidablesProcessed++;

                if (has) {
                    selectedIds.push(id);
                }

                if (hidablesProcessed === hidablesLength) {
                    document.selectedIds = selectedIds;

                    document.hids = $hidables;

                    var $result = $hidables.filter(function () {
                        return !$.inArray(
                            identifyHidable($(this)),
                            selectedIds
                        );
                    });

                    returnResultCallback($result);
                }
            });
        });
    }

    /**
     * Page loaded: removing elements already hidden and saved to localStorage
     */
    selectHidablesFromStorage(function ($found) {
        console.log('found to remove on start', $found);

        hidableView.hide($found);
        // $found.remove();
    });

    /**
     * Hide/remove from storage when space is hit
     */
    var removedAfterSpace = false;
    $(document).keydown(function(evt) {
        if (32 == evt.keyCode) {
            console.log('space was hit');

            selectHidablesFromStorage(function ($found) {
                if (removedAfterSpace) {
                    hidableView.hide($found);
                } else {
                    hidableView.hide($found);
                    // $found.remove();

                    removedAfterSpace = true;
                }
            });
        }
    });

    $('<button>hide all and close</button>')
        .addClass('yt-uix-button yt-uix-button-size-default yt-uix-button-expander')
        .insertAfter('#watch-more-related-button')
        .click(function () {
            hidablesController.hideAll();

            window.close();
        });
});
<|endoftext|>


<commit_before>const Vinslider = function(target, custom) {
    if (target == undefined) return;
    /*  DEFAULT SETTINGS AND CUSTOM OPTIONS
    *
    */
    this.preset = {
        speed: 5000,
        pager: true,
        controller: true,
        auto: true,
        infinite: true,
        gutter: 0,
        percentGutter: false,
        startFrom: 0,
        direction: true,
        mode: 'fade',
        enableClass: 'active',
        amount: 1,
        scrollable: false,
        vertical: false,
        moveBy: 1,
    };
    this.custom = custom ? custom : this.preset;
    this.options = custom ? custom : this.preset;
    /*  DOM
    *
    */
    this.dot;
    this.controller;
    this.prevBtn;
    this.nextBtn;
    this.ul = target.children[0];
    this.list = this.ul.children;
    /*  HELPER
    *
    */
    this.mode = {
        fade: 'fade',
        slide: 'slide',
        multiple: 'multiple',
    }
    this.classname = ['vinmain', 'vincontroller', 'vinbullet'];
    this.direction = ['left', 'clientWidth', 'width'];
    this.timer;
    this.end;
    this.prevIndex;
    this.curIndex;
    this.nextIndex;
    this.prevLi;
    this.curLi;
    this.nextLi;
    this.itemNum = this.list.length;
    this.size;
    this.ifwrong = false;
    /*  START RUNNING
    *
    */
    this.init(target);
};

Vinslider.prototype = {
    init: function(target) {
        this.settingOptions();
        /*  CREATE DOM ELEMENT
        *
        */
        this.modeInit();
        this.responsive();
        this.buildBullet(target);
        this.buildController(target);
        /*  RUN VINSLIDER
        *
        */
        this.initFunction(this.options.startFrom);
        this.lifecircle();
        this.autoPlay(this.options.speed);
        this.userEvent();
    },

    modeInit: function() {
        /*  LI WIDTH CALCULATION
        *
        */
        this.ul.className = this.classname[0];
        if (this.options.vertical) {
            this.direction = ['top', 'clientHeight', 'height'];
        }
        for (e=0; e<this.itemNum; e++) {
            var li = this.list[e];
            var gut;

            if (this.options.mode == this.mode.multiple) {
                this.options.amount = (this.options.amount <= 1) ? 2 : this.options.amount;
                this.size = this.ul[this.direction[1]] / this.options.amount;
            }   else {
                this.size = this.ul[this.direction[1]];
            }

            if (this.options.percentGutter) {
                gut = this.size * this.options.gutter;
            }   else {
                gut = this.options.gutter;
            }

            var fix = (this.options.mode == this.mode.multiple) ? gut / (this.options.amount-1) : 1;

            this.size = this.size + fix;
            li.style[this.direction[2]] = this.size - gut + 'px';
        }
        /*  MODE INIT
        *
        */
        if ( this.options.mode == this.mode.slide ) {
            for (i=0; i<this.itemNum; i++) {
                var li = this.list[i];
                li.style.opacity = 1;
            }
        }

        if ( this.options.mode == this.mode.multiple ) {
            for (i=0; i<this.itemNum; i++) {
                var li = this.list[i];
                li.style.opacity = 1;
            }
            this.options.pager = false;
        }
    },

    responsive: function() {
        var timeout = false;
        /*  FOR REAL TIME RESPONSIVE
        *
        */
        var self = this;
        window.addEventListener('resize',function() {
            clearTimeout(timeout);
            timeout = setTimeout(reset, 300);
        });

        function reset() {
            self.modeInit();
            self.lifecircle();
        }
    },

    settingOptions: function() {
        /*  SET OPTIONS TO DEFAULT IF THERE IS NOT A CUSTOM ONE
        *
        */
        var self = this;
        (function(obj) {
            var ind = 0;
            var key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    self.options[key] = self.custom[key] !== undefined ? self.custom[key] : self.preset[key];
                }
            }
        })(this.preset);
    },

    buildController: function(target) {
        var ul = document.createElement('ul');
        ul.className = this.classname[1];
        target.appendChild(ul);

        for (i=0; i<2; i++) {
            var li = document.createElement('li');
            ul.appendChild(li);
        }

        this.controller = ul;
        this.prevBtn = this.controller.children[0];
        this.nextBtn = this.controller.children[1];

        if (this.options.controller == false) ul.style.display = 'none';
    },

    buildBullet: function(target) {
        var ul = document.createElement('ul');
        ul.className = this.classname[2];
        target.appendChild(ul);

        for (i=0; i<this.itemNum; i++) {
            var li = document.createElement('li');
            ul.appendChild(li);
        }

        this.dot = ul.children;
        if (this.options.pager == false) ul.style.display = 'none';
    },

    lifecircle: function() {
        /*  BASIC LIFECIRCLE OF A SLIDE
        *
        */
        for (i=0; i<this.itemNum; i++) {
            var li = this.list[i];
            var dot = this.dot[i];
            var status = li.className;

            li.className = '';
            dot.className = '';

            /*  ADD ACITVE CLASS
            *
            */
            if (status == this.options.enableClass) {
                li.className = this.options.enableClass;
                dot.className = this.options.enableClass;
                this.curIndex = i;
                this.curLi = this.list[this.curIndex];
            }
        }

        this.prevIndex = this.curIndex - 1;
        this.nextIndex = this.curIndex + 1;

        this.prevLi = this.list[this.curIndex-1];
        this.nextLi = this.list[this.curIndex+1];

        /*  OTHER MODE
        *
        */
        if ( this.options.mode == this.mode.slide || this.options.mode == this.mode.multiple ) {
            for (e=0; e<this.itemNum; e++) {
                var ind  = e - this.curIndex;
                this.list[e].style[this.direction[0]] = this.size * ind + 'px';
            }
        }
    },

    initFunction: function(ind) {
        /*  INITIALIZE THE FUNCTION
        *
        */
        if (ind < 0 || ind > this.itemNum ) {
            return;
        }   else {
            this.list[ind].className = this.options.enableClass;
        }
    },

    autoPlay: function(num) {
        var self = this;
        if ( this.options.auto ) {
            this.timer = setInterval(function() {
                if (self.options.direction) {
                    self.forward();
                }   else  {
                    self.backward();
                }
            }, num);
        }
    },

    resetAutoPlay: function() {
        clearTimeout(this.timer);
        this.autoPlay(this.options.speed);
    },

    userEvent: function() {
        /*  USER EVENT
        *
        */
        var self = this;
       /*  CONTROLLER NAVIGATION
        *
        */
        this.nextBtn.onclick = function() {
            self.forward();
            self.resetAutoPlay();
        }

        this.prevBtn.onclick = function() {
            self.backward();
            self.resetAutoPlay();
        }
       /*  SCROLL
        *
        */
        if (this.options.scrollable) {
            this.ul.onwheel = function(event) {
                event.preventDefault();
                if (event.deltaY > 0 || event.deltaX > 0) {
                    self.forward();
                    self.resetAutoPlay();
                }   else {
                    self.backward();
                    self.resetAutoPlay();
                }
            };
        }
       /*  PAGER NAVIGATION
        *
        */
        for (i=0; i<this.itemNum; i++) {
            this.dot[i].onclick = function () {
                var ind = Array.prototype.indexOf.call(self.dot, this);

                for (e=0; e<self.itemNum; e++) {
                    self.list[e].className = '';
                    self.dot[e].className = '';
                }

                self.list[ind].className = self.options.enableClass;
                self.lifecircle();
                self.resetAutoPlay();
            }
        }
    },

    ifStop: function() {
        this.end = parseInt(this.list[this.itemNum-1].style[this.direction[0]]) < this.ul[this.direction[1]];
    },

    /*  FUNCTIONS TO MANIPULATE THE SLIDER
    *
    */
    forward: function() {
        for (var i = 0; i < this.options.moveBy; i++) {
            this.ifStop();
            if ( this.options.mode !== this.mode.multiple ) {
                if ( this.nextIndex < this.itemNum ) {
                    this.curLi.className = '';
                    this.nextLi.className = this.options.enableClass;
                }   else {
                    if (this.options.infinite) {
                        this.curLi.className = '';
                        this.list[0].className = this.options.enableClass;
                    }
                }
            }   else {
                if ( !this.end ) {
                    this.curLi.className = '';
                    this.nextLi.className = this.options.enableClass;
                }   else {
                    if (this.options.infinite) {
                        this.curLi.className = '';
                        this.list[0].className = this.options.enableClass;
                    }
                }
            }
            this.lifecircle();
        }
    },

    backward: function() {
        for (var i = 0; i < this.options.moveBy; i++) {
            this.ifStop();
            if ( this.prevIndex >= 0 ) {
                this.curLi.className = '';
                this.prevLi.className = this.options.enableClass;
            }   else {
                if (this.options.infinite) {
                    if (this.options.mode == this.mode.multiple) {
                        this.curLi.className = '';
                        this.list[this.itemNum-this.options.amount].className = this.options.enableClass;
                    }   else {
                        this.curLi.className = '';
                        this.list[this.itemNum-1].className = this.options.enableClass;
                    }
                }
            }
            this.lifecircle();
        }
    },
};<commit_msg>target changed to selector<commit_after>const Vinslider = function(selector, custom) {
    if (selector == undefined) return;
    /*  DEFAULT SETTINGS AND CUSTOM OPTIONS
    *
    */
    this.preset = {
        speed: 5000,
        pager: true,
        controller: true,
        auto: true,
        infinite: true,
        gutter: 0,
        percentGutter: false,
        startFrom: 0,
        direction: true,
        mode: 'fade',
        enableClass: 'active',
        amount: 1,
        scrollable: false,
        vertical: false,
        moveBy: 1,
    };
    this.custom = custom ? custom : this.preset;
    this.options = custom ? custom : this.preset;
    /*  DOM
    *
    */
    this.dot;
    this.controller;
    this.prevBtn;
    this.nextBtn;
    this.ul = selector.children[0];
    this.list = this.ul.children;
    /*  HELPER
    *
    */
    this.mode = {
        fade: 'fade',
        slide: 'slide',
        multiple: 'multiple',
    }
    this.classname = ['vinmain', 'vincontroller', 'vinbullet'];
    this.direction = ['left', 'clientWidth', 'width'];
    this.timer;
    this.end;
    this.prevIndex;
    this.curIndex;
    this.nextIndex;
    this.prevLi;
    this.curLi;
    this.nextLi;
    this.itemNum = this.list.length;
    this.size;
    this.ifwrong = false;
    /*  START RUNNING
    *
    */
    this.init(selector);
};

Vinslider.prototype = {
    init: function(selector) {
        this.settingOptions();
        /*  CREATE DOM ELEMENT
        *
        */
        this.modeInit();
        this.responsive();
        this.buildBullet(selector);
        this.buildController(selector);
        /*  RUN VINSLIDER
        *
        */
        this.initFunction(this.options.startFrom);
        this.lifecircle();
        this.autoPlay(this.options.speed);
        this.userEvent();
    },

    modeInit: function() {
        /*  LI WIDTH CALCULATION
        *
        */
        this.ul.className = this.classname[0];
        if (this.options.vertical) {
            this.direction = ['top', 'clientHeight', 'height'];
        }
        for (e=0; e<this.itemNum; e++) {
            var li = this.list[e];
            var gut;

            if (this.options.mode == this.mode.multiple) {
                this.options.amount = (this.options.amount <= 1) ? 2 : this.options.amount;
                this.size = this.ul[this.direction[1]] / this.options.amount;
            }   else {
                this.size = this.ul[this.direction[1]];
            }

            if (this.options.percentGutter) {
                gut = this.size * this.options.gutter;
            }   else {
                gut = this.options.gutter;
            }

            var fix = (this.options.mode == this.mode.multiple) ? gut / (this.options.amount-1) : 1;

            this.size = this.size + fix;
            li.style[this.direction[2]] = this.size - gut + 'px';
        }
        /*  MODE INIT
        *
        */
        if ( this.options.mode == this.mode.slide ) {
            for (i=0; i<this.itemNum; i++) {
                var li = this.list[i];
                li.style.opacity = 1;
            }
        }

        if ( this.options.mode == this.mode.multiple ) {
            for (i=0; i<this.itemNum; i++) {
                var li = this.list[i];
                li.style.opacity = 1;
            }
            this.options.pager = false;
        }
    },

    responsive: function() {
        var timeout = false;
        /*  FOR REAL TIME RESPONSIVE
        *
        */
        var self = this;
        window.addEventListener('resize',function() {
            clearTimeout(timeout);
            timeout = setTimeout(reset, 300);
        });

        function reset() {
            self.modeInit();
            self.lifecircle();
        }
    },

    settingOptions: function() {
        /*  SET OPTIONS TO DEFAULT IF THERE IS NOT A CUSTOM ONE
        *
        */
        var self = this;
        (function(obj) {
            var ind = 0;
            var key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    self.options[key] = self.custom[key] !== undefined ? self.custom[key] : self.preset[key];
                }
            }
        })(this.preset);
    },

    buildController: function(selector) {
        var ul = document.createElement('ul');
        ul.className = this.classname[1];
        selector.appendChild(ul);

        for (i=0; i<2; i++) {
            var li = document.createElement('li');
            ul.appendChild(li);
        }

        this.controller = ul;
        this.prevBtn = this.controller.children[0];
        this.nextBtn = this.controller.children[1];

        if (this.options.controller == false) ul.style.display = 'none';
    },

    buildBullet: function(selector) {
        var ul = document.createElement('ul');
        ul.className = this.classname[2];
        selector.appendChild(ul);

        for (i=0; i<this.itemNum; i++) {
            var li = document.createElement('li');
            ul.appendChild(li);
        }

        this.dot = ul.children;
        if (this.options.pager == false) ul.style.display = 'none';
    },

    lifecircle: function() {
        /*  BASIC LIFECIRCLE OF A SLIDE
        *
        */
        for (i=0; i<this.itemNum; i++) {
            var li = this.list[i];
            var dot = this.dot[i];
            var status = li.className;

            li.className = '';
            dot.className = '';

            /*  ADD ACITVE CLASS
            *
            */
            if (status == this.options.enableClass) {
                li.className = this.options.enableClass;
                dot.className = this.options.enableClass;
                this.curIndex = i;
                this.curLi = this.list[this.curIndex];
            }
        }

        this.prevIndex = this.curIndex - 1;
        this.nextIndex = this.curIndex + 1;

        this.prevLi = this.list[this.curIndex-1];
        this.nextLi = this.list[this.curIndex+1];

        /*  OTHER MODE
        *
        */
        if ( this.options.mode == this.mode.slide || this.options.mode == this.mode.multiple ) {
            for (e=0; e<this.itemNum; e++) {
                var ind  = e - this.curIndex;
                this.list[e].style[this.direction[0]] = this.size * ind + 'px';
            }
        }
    },

    initFunction: function(ind) {
        /*  INITIALIZE THE FUNCTION
        *
        */
        if (ind < 0 || ind > this.itemNum ) {
            return;
        }   else {
            this.list[ind].className = this.options.enableClass;
        }
    },

    autoPlay: function(num) {
        var self = this;
        if ( this.options.auto ) {
            this.timer = setInterval(function() {
                if (self.options.direction) {
                    self.forward();
                }   else  {
                    self.backward();
                }
            }, num);
        }
    },

    resetAutoPlay: function() {
        clearTimeout(this.timer);
        this.autoPlay(this.options.speed);
    },

    userEvent: function() {
        /*  USER EVENT
        *
        */
        var self = this;
       /*  CONTROLLER NAVIGATION
        *
        */
        this.nextBtn.onclick = function() {
            self.forward();
            self.resetAutoPlay();
        }

        this.prevBtn.onclick = function() {
            self.backward();
            self.resetAutoPlay();
        }
       /*  SCROLL
        *
        */
        if (this.options.scrollable) {
            this.ul.onwheel = function(event) {
                event.preventDefault();
                if (event.deltaY > 0 || event.deltaX > 0) {
                    self.forward();
                    self.resetAutoPlay();
                }   else {
                    self.backward();
                    self.resetAutoPlay();
                }
            };
        }
       /*  PAGER NAVIGATION
        *
        */
        for (i=0; i<this.itemNum; i++) {
            this.dot[i].onclick = function () {
                var ind = Array.prototype.indexOf.call(self.dot, this);

                for (e=0; e<self.itemNum; e++) {
                    self.list[e].className = '';
                    self.dot[e].className = '';
                }

                self.list[ind].className = self.options.enableClass;
                self.lifecircle();
                self.resetAutoPlay();
            }
        }
    },

    ifStop: function() {
        this.end = parseInt(this.list[this.itemNum-1].style[this.direction[0]]) < this.ul[this.direction[1]];
    },

    /*  FUNCTIONS TO MANIPULATE THE SLIDER
    *
    */
    forward: function() {
        for (var i = 0; i < this.options.moveBy; i++) {
            this.ifStop();
            if ( this.options.mode !== this.mode.multiple ) {
                if ( this.nextIndex < this.itemNum ) {
                    this.curLi.className = '';
                    this.nextLi.className = this.options.enableClass;
                }   else {
                    if (this.options.infinite) {
                        this.curLi.className = '';
                        this.list[0].className = this.options.enableClass;
                    }
                }
            }   else {
                if ( !this.end ) {
                    this.curLi.className = '';
                    this.nextLi.className = this.options.enableClass;
                }   else {
                    if (this.options.infinite) {
                        this.curLi.className = '';
                        this.list[0].className = this.options.enableClass;
                    }
                }
            }
            this.lifecircle();
        }
    },

    backward: function() {
        for (var i = 0; i < this.options.moveBy; i++) {
            this.ifStop();
            if ( this.prevIndex >= 0 ) {
                this.curLi.className = '';
                this.prevLi.className = this.options.enableClass;
            }   else {
                if (this.options.infinite) {
                    if (this.options.mode == this.mode.multiple) {
                        this.curLi.className = '';
                        this.list[this.itemNum-this.options.amount].className = this.options.enableClass;
                    }   else {
                        this.curLi.className = '';
                        this.list[this.itemNum-1].className = this.options.enableClass;
                    }
                }
            }
            this.lifecircle();
        }
    },
};<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
 */

import { dispatch, dispatchAsync } from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, CallTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
import CallStore from '../stores/CallStore';

const HIDE_MODAL_AFTER = 3000;

export default {
  hide() {
    dispatch(ActionTypes.CALL_MODAL_HIDE);
  },

  handleCall(event) {
    const { id, type } = event;
    switch (type) {
      case CallTypes.STARTED:
        ActorClient.bindCall(id, this.setCall);
        dispatch(ActionTypes.CALL_MODAL_OPEN, { id });
        break;
      case CallTypes.ENDED:
        setTimeout(() => {
          ActorClient.unbindCall(id, this.setCall);
          if (CallStore.isOpen()) dispatch(ActionTypes.CALL_MODAL_HIDE);
        }, HIDE_MODAL_AFTER);
        break;
      default:
    }
  },

  makeCall(peerId) {
    dispatchAsync(ActorClient.makeCall(peerId), {
      request: ActionTypes.CALL,
      success: ActionTypes.CALL_SUCCESS,
      failure: ActionTypes.CALL_ERROR
    }, { peerId });
  },
  makeGroupCall(peerId) {
    dispatchAsync(ActorClient.makeGroupCall(peerId), {
      request: ActionTypes.CALL,
      success: ActionTypes.CALL_SUCCESS,
      failure: ActionTypes.CALL_ERROR
    }, { peerId });
  },

  setCall(call) {
    dispatch(ActionTypes.CALL_CHANGED, { call });
  },

  answerCall(id) {
    ActorClient.answerCall(id);
    dispatch(ActionTypes.CALL_ANSWER, { id })
  },

  endCall(id) {
    ActorClient.endCall(id);
    dispatch(ActionTypes.CALL_END, { id })
  }
}
<commit_msg>feat(web): add missing muteCall method<commit_after>/*
 * Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
 */

import { dispatch, dispatchAsync } from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, CallTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
import CallStore from '../stores/CallStore';

const HIDE_MODAL_AFTER = 3000;

export default {
  hide() {
    dispatch(ActionTypes.CALL_MODAL_HIDE);
  },

  handleCall(event) {
    const { id, type } = event;
    switch (type) {
      case CallTypes.STARTED:
        ActorClient.bindCall(id, this.setCall);
        dispatch(ActionTypes.CALL_MODAL_OPEN, { id });
        break;
      case CallTypes.ENDED:
        setTimeout(() => {
          ActorClient.unbindCall(id, this.setCall);
          if (CallStore.isOpen()) dispatch(ActionTypes.CALL_MODAL_HIDE);
        }, HIDE_MODAL_AFTER);
        break;
      default:
    }
  },

  muteCall(peerId) {
    console.info('mute', {peerId});
  },

  makeCall(peerId) {
    dispatchAsync(ActorClient.makeCall(peerId), {
      request: ActionTypes.CALL,
      success: ActionTypes.CALL_SUCCESS,
      failure: ActionTypes.CALL_ERROR
    }, { peerId });
  },

  makeGroupCall(peerId) {
    dispatchAsync(ActorClient.makeGroupCall(peerId), {
      request: ActionTypes.CALL,
      success: ActionTypes.CALL_SUCCESS,
      failure: ActionTypes.CALL_ERROR
    }, { peerId });
  },

  setCall(call) {
    dispatch(ActionTypes.CALL_CHANGED, { call });
  },

  answerCall(id) {
    ActorClient.answerCall(id);
    dispatch(ActionTypes.CALL_ANSWER, { id })
  },

  endCall(id) {
    ActorClient.endCall(id);
    dispatch(ActionTypes.CALL_END, { id })
  }
}
<|endoftext|>