code stringlengths 2 1.05M |
|---|
import { EntityInstance, SelectionState, ContentState } from 'draft-js';
import Immutable from 'immutable';
export default class EntityState extends Immutable.Record({
entity: null,
entityKey: null,
entitySelection: null
}) {
/**
* Create a new state from EditorState
*
* @param {ContentState} contentState
* @param {SelectionState} selectionState
* @return {EntityState}
*/
static create(contentState, selectionState) {
// Find active entity
const blockKey = selectionState.getStartKey();
const block = contentState.getBlockForKey(blockKey);
const entityKey = selectionState.isCollapsed()
? block.getEntityAt(selectionState.getStartOffset() - 1)
: block.getEntityAt(selectionState.getStartOffset());
const entity = entityKey
? contentState.getEntity(entityKey)
: null;
// Create selection around entity
let entitySelection = null;
block.findEntityRanges(
(character) => character.getEntity() === entityKey,
(start, end) => {
entitySelection = new SelectionState({
anchorKey: blockKey,
anchorOffset: start,
focusKey: blockKey,
focusOffset: end
});
}
);
// Create instance
return new EntityState({
entity,
entityKey,
entitySelection
});
}
/**
* Get active entity instance
*
* @return {EntityInstance|null}
*/
getEntity() {
return this.entity;
}
/**
* Get active entity key
*
* @return {string|null}
*/
getEntityKey() {
return this.entityKey;
}
/**
* Get selection around active entity
*
* @return {SelectionState|null}
*/
getEntitySelection() {
return this.entitySelection;
}
/**
* Check that the active entity's type is matching with the passed parameter
*
* @param {string} type
* @return {boolean}
*/
isEntityType(type) {
return this.entity && this.entity.getType() === type ? true : false;
}
}
|
'use strict';
angular.module('exploreAroundApp.util', []);
|
export const create = (el)=>{
el = el || 'div';
const holder = document.createElement(el);
const obj = {
addId: (id)=>{
holder.id = id;
return obj;
}
, addAttribute: (attrs)=>{
if (attrs){
for (let a in attrs){
if (attrs[a]){
holder[a] = attrs[a];
}
}
}
return obj;
}
, append: (path)=>{
path = path || document.body;
path.appendChild(holder);
return obj;
}
, get: ()=>{
return holder;
}
, remove: ()=>{
holder.parentNode.removeChild(holder);
}
};
return obj;
};
export const createHolder = (id, path, el)=>{
el = el || 'div';
path = path || document.body;
const holder = document.createElement(el);
holder.id = id;
path.appendChild(holder);
return holder;
};
export const createElement = (path, attrs, el)=>{
el = el || 'div';
const holder = document.createElement(el);
if (attrs){
for (let a in attrs){
if (attrs[a]){
holder[a] = attrs[a];
}
}
}
if (path){
path.appendChild(holder);
}
return holder;
};
export const removeElement = (el)=>{
el.parentNode.removeChild(el);
};
|
module.exports = function(LocationSchema) {
const read = require('read-file');
const path = require('path');
const pathToInput = path.join(__dirname, '/input.json');
const inputLocations = JSON.parse(read.sync(pathToInput));
inputLocations.forEach(function(loc) {
LocationSchema.findOneAndUpdate(
{originalId: loc.id},
loc,
{upsert: true},
function(error) {
if (error) {
console.log(error);
}
}
);
});
};
|
;'use strict';
angular.module('app')
.controller('AdminController', ['$rootScope','$scope', '$window', 'Hospital', 'hospital', 'departments', function($rootScope,$scope,$window,Hospital,hospital,departments){
var scope = this;
scope.status = {};
scope.hospital = hospital;
scope.departments = departments;
console.log(scope);
scope.updateHospitalProfile = function(){
var postDate = {};
postDate.hospital = {};
if(scope.hospital.level) postDate.hospital.level = scope.hospital.level;
if(scope.hospital.type) postDate.hospital.type = scope.hospital.type;
if(scope.hospital.description) postDate.hospital.description = scope.hospital.description;
if(scope.hospital.phone) postDate.hospital.phone = scope.hospital.phone;
if(scope.hospital.website) postDate.hospital.website = scope.hospital.website;
if(scope.hospital.location) postDate.hospital.location = scope.hospital.location;
if(scope.hospital.picture) postDate.hospital.picture = scope.hospital.picture;
if(scope.hospital.rule) postDate.hospital.rule = scope.hospital.rule;
Hospital.update({
hid: $window.sessionStorage.hid
},postDate,function(h){
$window.alert('跟新医院信息成功');
},function(e){
});
};
/////////////////////////////////////////////////////////////////////////////
/// adminController event handler
/////////////////////////////////////////////////////////////////////////////
}]); |
var assert = require('assert');
var helpers = require('../lib/helpers')
, doc = require('../lib/doc.json');
describe('Helper', function() {
describe('safeGet()', function() {
const clanState = {
name_info: {
clan_name: "foo",
other: {
secret: "value"
},
members: [ "bar" ],
nothing: [],
deep: {
sea: "foobar"
}
},
user_counts: {
chatting: 5
}
};
const emptyState = {
user_counts: {
chatting: 5
}
};
it('should return value on valid keys', function() {
const res = helpers.safeGet(clanState, 'name_info', 'clan_name');
assert.strictEqual(res, "foo");
});
it('should return nested objects', function() {
const res = helpers.safeGet(clanState, 'name_info', 'other');
assert.deepStrictEqual(res, { secret: "value" });
});
it('should return arrays', function() {
const res = helpers.safeGet(clanState, 'name_info', 'members');
assert.deepStrictEqual(res, [ "bar" ]);
});
it('should return empty arrays', function() {
const res = helpers.safeGet(clanState, 'name_info', 'nothing');
assert.deepStrictEqual(res, []);
});
it('should return deeply nested values', function() {
const res = helpers.safeGet(clanState, 'name_info', 'deep', 'sea');
assert.strictEqual(res, "foobar");
});
it('should return undefined on invalid key', function() {
const res = helpers.safeGet(emptyState, 'name_info', 'clan_name');
assert.strictEqual(res, undefined);
});
it('should return undefined when object is undefined', function() {
const res = helpers.safeGet(undefined, 'name_info', 'clan_name');
assert.strictEqual(res, undefined);
});
});
describe('replaceString()', function() {
it('should replace string with one argument', function() {
const res = helpers.replaceString(doc.act.youKicked, "foo");
assert.strictEqual(res, doc.act.youKicked.replace("%s", "foo"));
});
it('should replace string with two arguments', function() {
const res = helpers.replaceString(doc.act.userBanned, "foo", "bar");
assert.strictEqual(res, doc.act.userBanned
.replace("%s", "foo").replace("%s", "bar"));
});
});
});
|
import _ from 'lodash'
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts()
}
renderPosts(){
return _.map(this.props.posts, post => {
return(
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">Add a Post +</Link>
</div>
<h3>Posts:</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts }) (PostsIndex);
|
/* globals $ */
/*
Create a function that takes a selector and COUNT, then generates inside a UL with COUNT LIs:
* The UL must have a class `items-list`
* Each of the LIs must:
* have a class `list-item`
* content "List item #INDEX"
* The indices are zero-based
* If the provided selector does not selects anything, do nothing
* Throws if
* COUNT is a `Number`, but is less than 1
* COUNT is **missing**, or **not convertible** to `Number`
* _Example:_
* Valid COUNT values:
* 1, 2, 3, '1', '4', '1123'
* Invalid COUNT values:
* '123px' 'John', {}, []
*/
function solve() {
return function (selector, count) {
var i,
list = $('<ul />').addClass('items-list');
if (!selector || typeof selector !== 'string') {
throw {
name: 'Invalid argument error',
message: 'Selector should be a string'
}
}
if (!count || isNaN(count) || count < 1) {
throw {
name: 'Invalid argument error',
message: 'Number should be bigger than 0'
}
}
for (i = 0; i < count; i += 1) {
$('<li />').appendTo(list).text('List item #' + i).addClass('list-item');
}
$(selector).append(list);
};
};
module.exports = solve; |
window.ForgeWebComponents = window.ForgeWebComponents || {};
window.ForgeWebComponents.Settings = window.ForgeWebComponents.Settings || {};
window.ForgeWebComponents.Settings.RootUrl = "/api-mock/"
window.ForgeWebComponents.Config = {
"deltatre.forge.main": {
"WebComponentsConfiguration": {
"SiteRoot": "//cdn.rawgit.com/deltatre-webplu/forge-webcomponents/2.0.1/",
"Endpoints": [{
"Name": "forge-core-style",
"Url": "custom-styles/forge-core-style.html",
"Permission": null
}, {
"Name": "forge-array-input",
"Url": "forge-array-input/forge-array-input.html",
"Permission": null
}, {
"Name": "forge-youtube-video-input",
"Url": "forge-youtube-video-input/forge-youtube-video-input.html",
"Permission": null
}, {
"Name": "forge-tags-suggestion",
"Url": "samples/forge-tags-suggestion.html",
"Permission": null
}, {
"Name": "forge-performance-dashboard",
"Url": "forge-dashboards/forge-performance-dashboard.html",
"Permission": null
}, {
"Name": "forge-diva-video",
"Url": "http://localhost:60194/webcomponent/forge-diva-video.html",
"Permission": null
}, {
"Name": "forge-story-behavior-sample",
"Url": "samples/forge-story-behavior-sample.html",
"Permission": null
}, {
"Name": "forge-table-input",
"Url": "forge-story-parts/forge-table-input.html",
"Permission": null
}, {
"Name": "forge-empty-field",
"Url": "samples/forge-empty-field.html",
"Permission": null
}],
"DashboardEndpoints": [{
"Name": "forge-status-dashboard",
"Url": "forge-dashboards/forge-status-dashboard.html",
"Permission": null
}, {
"Name": "forge-commands-dashboard",
"Url": "forge-dashboards/forge-commands-dashboard.html",
"Permission": "AdministrationAccess"
}, {
"Name": "forge-editorial-dashboard",
"Url": "forge-dashboards/forge-editorial-dashboard.html",
"Permission": "Wcm.BasicAccess"
}, {
"Name": "forge-big-numbers-dashboard",
"Url": "forge-dashboards/forge-big-numbers-dashboard.html",
"Permission": "Wcm.BasicAccess"
}, {
"Name": "forge-workflow-dashboard",
"Url": "forge-dashboards/forge-workflow-dashboard.html",
"Permission": "Wcm.BasicAccess"
}, {
"Name": "forge-diva-dashboard",
"Url": "http://localhost:60194/webcomponent/forge-diva-dashboard.html",
"Permission": null
}]
},
"LogStoreConfiguration": {
"LogStoreType": "MongoDb"
}
},
"deltatre.forge.vsm": {
"AccessControlListConfiguration": {
"Permissions": [{
"Name": "TestAcl",
"Description": "ACL for E2E tests"
}, {
"Name": "TestAcl2",
"Description": "ACL for E2E tests"
}, {
"Name": "Story Writers",
"Description": "The guys in charge of writing stories"
}]
},
"FrontEndSiteConfiguration": {
"AllSites": [{
"Culture": "en-US",
"Environment": "Dev",
"Platform": "default",
"OriginUrl": "http://localhost:54787"
}, {
"Culture": "it-IT",
"Environment": "Dev",
"Platform": "default",
"OriginUrl": "http://www.google.it"
}, {
"Culture": "fr-FR",
"Environment": "Dev",
"Platform": "default",
"OriginUrl": "http://www.google.fr"
}, {
"Culture": "ru-RU",
"Environment": "Dev",
"Platform": "default",
"OriginUrl": "http://www.google.ru"
}, {
"Culture": "ar-QA",
"Environment": "Dev",
"Platform": "default",
"OriginUrl": "http://www.aljazeera.com"
}],
"SiteAssetsUrl": "http://localhost:54787"
}
},
"deltatre.forge.wcm": {
"PhotoConfiguration": {
"StorageType": "cloudinary",
"Formats": [{
"Name": "thumbnail",
"Instructions": "t_thumbnail",
"AspectRatio": "3:2",
"Extension": ".jpg"
}, {
"Name": "wide",
"Instructions": "t_wide",
"AspectRatio": "16:9",
"Extension": ".jpg"
}, {
"Name": "detail",
"Instructions": "t_detail",
"AspectRatio": "6:5",
"Extension": ".jpg"
}, {
"Name": "thumb-face",
"Instructions": "t_thumbface",
"AspectRatio": null,
"Extension": ".jpg"
}, {
"Name": "thumb-face-preset",
"Instructions": "t_thumbfacepreset",
"AspectRatio": null,
"Extension": ".jpg"
}, {
"Name": "sponsor-logo",
"Instructions": "t_sponsorlogo",
"AspectRatio": "2:1",
"Extension": ".jpg"
}, {
"Name": "story-header",
"Instructions": "t_storyheader",
"AspectRatio": "192:55",
"Extension": ".jpg"
}, {
"Name": "story-wide",
"Instructions": "t_storywide",
"AspectRatio": "192:50",
"Extension": ".jpg"
}, {
"Name": "list-card",
"Instructions": "t_listcard",
"AspectRatio": "16:9",
"Extension": ".jpg"
}, {
"Name": "featured-big",
"Instructions": "t_featuredbig",
"AspectRatio": "1270:846",
"Extension": ".jpg"
}, {
"Name": "featured-small",
"Instructions": "t_featuredsmall",
"AspectRatio": "979:652",
"Extension": ".jpg"
}, {
"Name": "Vertical banner",
"Instructions": "t_verticalbanner",
"AspectRatio": "1:2",
"Extension": ".jpg"
}],
"SmartCrop": true
},
"CustomEntitiesConfiguration": {
"Definitions": [{
"Code": "player",
"Name": "Player",
"MenuLabel": "Players",
"Icon": "accessibility",
"DistributionCode": "players",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "team",
"Name": "Team",
"MenuLabel": "Team menu",
"Icon": "android",
"DistributionCode": "teams",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "drivers",
"Name": "drivers",
"MenuLabel": "Drivers",
"Icon": "face",
"DistributionCode": "drivers",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": true,
"ShowAsStoryParts": true,
"DisableCreation": false
}, {
"Code": "youtube",
"Name": "YouTube",
"MenuLabel": "YouTube Videos",
"Icon": "ondemand_video",
"DistributionCode": "youtubeVideos",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "test",
"Name": "TestName",
"MenuLabel": "TestLabel",
"Icon": "accessible",
"DistributionCode": "TestAPICode",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "test2",
"Name": "test2",
"MenuLabel": "test2",
"Icon": null,
"DistributionCode": "test2",
"Enabled": false,
"UsableForTagging": false,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "suggest",
"Name": "Suggest",
"MenuLabel": "suggest",
"Icon": null,
"DistributionCode": "suggests",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "Sample",
"Name": "Sample",
"MenuLabel": "Sample",
"Icon": "",
"DistributionCode": "Sample",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": true,
"ShowAsStoryParts": true,
"DisableCreation": false
}, {
"Code": "divavideo",
"Name": "Diva Video",
"MenuLabel": "Diva Video",
"Icon": "video_call",
"DistributionCode": "divavideos",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": true,
"ShowAsStoryParts": false,
"DisableCreation": true
}, {
"Code": "poll",
"Name": "Poll",
"MenuLabel": "Poll",
"Icon": "poll",
"DistributionCode": "polls",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": true,
"ShowAsStoryParts": true,
"DisableCreation": false
}, {
"Code": "author",
"Name": "Author",
"MenuLabel": "Authors",
"Icon": "create",
"DistributionCode": "authors",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": false,
"ShowAsStoryParts": true,
"DisableCreation": false
}, {
"Code": "TestEntity",
"Name": "Test entity",
"MenuLabel": "Test Entity",
"Icon": "backup",
"DistributionCode": "TestEntity",
"Enabled": true,
"UsableForTagging": true,
"ShowInCompactMenu": false,
"ShowAsStoryParts": false,
"DisableCreation": false
}, {
"Code": "youtube-video",
"Name": "Youtube Video",
"MenuLabel": "Youtube Videos",
"Icon": "ondemand_video",
"DistributionCode": "youtube-videos",
"Enabled": true,
"UsableForTagging": false,
"ShowInCompactMenu": true,
"ShowAsStoryParts": false,
"DisableCreation": false
}]
},
"ExtendedFieldsConfiguration": {
"Definitions": [{
"Scope": "story",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "The author of the story",
"filter": true
},
"copyright": {
"type": "string"
},
"showAdvertising": {
"description": "True to show advertising",
"title": "Show banners",
"type": "boolean"
},
"kind": {
"description": "Content kind",
"type": "string",
"enum": ["Live Coverage", "Editorial", "Biography"],
"filter": true
},
"integer": {
"description": "end2end integer field",
"type": "integer"
},
"number": {
"description": "end2end number field",
"type": "number"
},
"FieldNotCamelCase": {
"description": "end2end FieldNotCamelCase field",
"type": "string"
}
},
"indexes": {
"e2etests": {
"integer": 1
}
}
}
}, {
"Scope": "photo",
"JsonSchema": {
"type": "object",
"properties": {
"copyright": {
"description": "copyright (do not remove, used for tests)",
"type": "string",
"localized": true
},
"geoLocation": {
"description": "geojson coordinates",
"type": "object",
"properties": {
"type": {
"type": "string"
},
"coordinates": {
"type": "array",
"items": {
"type": "number"
}
}
}
}
},
"indexes": {
"geoIndex": {
"geoLocation": "GeoSpatial"
}
}
}
}, {
"Scope": "customentity.player",
"JsonSchema": {
"type": "object",
"description": "USED FOR E2E TESTS",
"properties": {
"firstName": {
"type": "string",
"localized": true,
"tagextradata": true
},
"lastName": {
"type": "string",
"localized": true,
"tagextradata": true
},
"biography": {
"type": "string",
"localized": true,
"extended-type": "rich-text",
"tagextradata": true
},
"score": {
"type": "number",
"tagextradata": true
},
"country": {
"type": "string",
"localized": true,
"tagextradata": true
},
"dateOfBirth": {
"type": "string",
"localized": true,
"extended-type": "forge-datepicker-input"
},
"career": {
"title": "Senior career",
"type": "array",
"extended-type": "forge-demo-career-input",
"items": {
"type": "object",
"properties": {
"startYear": {
"title": "Start Year",
"type": "number"
},
"endYear": {
"title": "End Year",
"type": "number"
},
"team": {
"title": "Team",
"type": "string"
},
"goals": {
"title": "Goals",
"type": "number"
}
}
}
}
},
"indexes": {
"scoreIndex": {
"score": -1
},
"careerIndex": {
"career.endYear": 1
}
}
}
}, {
"Scope": "tag",
"JsonSchema": {
"type": "object",
"properties": {
"label": {
"description": "Label style (do not remove, used for tests)",
"type": "string",
"enum": ["default", "primary", "success", "info", "warning", "danger"]
}
},
"required": []
}
}, {
"Scope": "album",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "The author of the album"
},
"copyright": {
"description": "copyright",
"type": "string"
},
"kind": {
"description": "Content kind",
"type": "string",
"localized": true,
"enum": ["Live Coverage", "Editorial", "Biography"]
}
},
"indexes": {
"kindIndexField": {
"kind": 1
}
}
}
}, {
"Scope": "storyparts.photo",
"JsonSchema": {
"type": "object",
"properties": {
"caption": {
"type": "string",
"description": "A custom caption for the photo"
},
"layoutPreference": {
"type": "string",
"enum": ["Left", "Left Stretched", "Middle", "Middle Stretched", "Big Title Picture", "Right", "Right Stretched"],
"description": "The position preference of the photo"
}
}
}
}, {
"Scope": "storyparts.markdown",
"JsonSchema": {
"type": "object",
"properties": {
"quote": {
"type": "boolean",
"description": "Indicates if this text has to be displayed as a quote"
},
"allowFloats": {
"type": "boolean",
"description": "Indicates if this text allows floating content (to its left or right)"
}
}
}
}, {
"Scope": "storyparts.album",
"JsonSchema": {
"type": "object",
"properties": {
"caption": {
"type": "string",
"description": "A custom caption for the album"
},
"layoutPreference": {
"type": "string",
"enum": ["Slideshow", "Slideshow Stretched"],
"description": "The layout preference for this album"
}
}
}
}, {
"Scope": "storyparts.cartoon-players",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "The author of the content"
},
"copyright": {
"type": "string"
},
"positionPreference": {
"type": "string",
"enum": ["Left", "Middle", "Right"],
"description": "The position preference of the content"
}
}
}
}, {
"Scope": "storyparts.customentity.player",
"JsonSchema": {
"type": "object",
"properties": {
"positionPreference": {
"type": "string",
"enum": ["FloatLeft", "Center", "FloatRight"],
"description": "The position preference of the content"
},
"someNumbers": {
"type": "array",
"items": {
"type": "integer"
},
"title": "Numbers!",
"description": "put some numbers please"
}
}
}
}, {
"Scope": "document",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "The author of the document (used by tests)!"
},
"arrayTest": {
"type": "array",
"title": "arrayTest",
"localized": true
}
}
}
}, {
"Scope": "customentity.team",
"JsonSchema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"title": "City",
"description": "The city of the team"
},
"country": {
"type": "string"
},
"showAdvertising": {
"description": "True to show advertising",
"title": "Show banners",
"type": "boolean"
},
"description": {
"type": "string",
"localized": true,
"extended-type": "rich-text"
},
"confederation": {
"description": "Confederation kind",
"type": "string",
"enum": ["Uefa", "Concacaf", "SeriaA"]
},
"polymerArrayEnum": {
"description": "polymer array enum",
"type": "array",
"items": {
"type": "string",
"enum": ["UEFA European Football Championship", "FIFA World Cup", "FIFA Confederations Cup", "CAF Africa Cup of Nations", "CONMEBOL Copa América", "CONCACAF Gold Cup", "UEFA Champions League", "FIFA Club World Cup", "CAF Champions League", "CONMEBOL Copa Libertadores", "Deutscher Pokal"]
}
},
"language": {
"description": "Language of the team",
"type": "string",
"enum": ["Ignorante", "Forbito", "Multi"]
},
"OfficialFanClubs": {
"description": "list all the official fanclubs",
"type": "array",
"items": {
"type": "string"
},
"localized": true
},
"OQWERTYUIOP": {
"description": "random",
"type": "array",
"items": {
"type": "string"
}
},
"cupsWon": {
"description": "list all the cups the team won",
"type": "array",
"items": {
"type": "string",
"enum": ["UEFA European Football Championship", "FIFA World Cup", "FIFA Confederations Cup", "CAF Africa Cup of Nations", "CONMEBOL Copa América", "CONCACAF Gold Cup", "UEFA Champions League", "FIFA Club World Cup", "CAF Champions League", "CONMEBOL Copa Libertadores", "Deutscher Pokal"]
}
}
},
"indexes": {
"countryIndex": {
"country": -1
},
"languageTestIndex": {
"language": 1
},
"fanClubsIndex": {
"OfficialFanClubs": 1
},
"OQWERTYUIOPIndex": {
"OQWERTYUIOP": 1
},
"cupsWonIndex": {
"cupsWon": 1
}
}
}
}, {
"Scope": "customentity.drivers",
"JsonSchema": {
"type": "object",
"properties": {
"countryCode": {
"type": "string",
"title": "Country Code",
"description": "The code of the country of the driver. E.g. ITA",
"tagextradata": true,
"filter": true
},
"team": {
"title": "Team",
"type": "string",
"enum": ["Mercedes", "Ferrari", "Williams", "Red Bull Racing", "Force India", "Toro Rosso", "Sauber", "Haas", "Manor Racing", "Renault"],
"tagextradata": true
},
"wins": {
"title": "Race victories",
"type": "number",
"description": "The total number of victories",
"tagextradata": true,
"filter": true
},
"points": {
"title": "Points in career",
"type": "number",
"description": "The total number of points",
"tagextradata": true
},
"dob": {
"title": "Date of Birth",
"type": "string",
"format": "date-time",
"filter": true
},
"bio": {
"title": "Brief Bio",
"type": "string",
"localized": true,
"extended-type": "rich-text",
"filter": true
},
"showAdvertising": {
"description": "True to show advertising",
"title": "Show banners",
"type": "boolean",
"tagextradata": true,
"filter": true
}
},
"system": {
"title": {
"title": "name"
}
},
"indexes": {
"pointsIndex": {
"points": -1
}
}
}
}, {
"Scope": "customentity.youtube",
"JsonSchema": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "The description of the video",
"title": "Description",
"extended-type": "rich-text",
"localized": true
},
"videoId": {
"type": "string",
"description": "The unique identifier of the video",
"title": "Video Id",
"localized": true,
"extended-type": "forge-youtube-video-input",
"tagextradata": true
}
}
}
}, {
"Scope": "storyparts.customentity.team",
"JsonSchema": {
"type": "object",
"properties": {
"adWords": {
"type": "array",
"items": {
"type": "string"
},
"title": "AdWords",
"description": "list all the adWords"
},
"myEnum": {
"type": "array",
"items": {
"type": "string",
"enum": ["Uan", "Four", "Five", "Jonatan"]
},
"description": "The position preference of the content"
}
}
}
}, {
"Scope": "customentity.test",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "Name and Surname of the author",
"tagextradata": true
},
"copyright": {
"type": "string",
"tagextradata": true,
"localized": true
},
"description": {
"title": "Description",
"type": "string",
"description": "A short introduction (100 words)",
"extended-type": "rich-text",
"localized": true
},
"showAdvertising": {
"title": "Show banners",
"description": "True to show advertising",
"type": "boolean"
},
"kind": {
"title": "Kind",
"type": "string",
"enum": ["Live Coverage", "Editorial", "Biography"],
"tagextradata": true
}
}
}
}, {
"Scope": "customentity.test2",
"JsonSchema": {
"type": "object",
"properties": {
"localizedArray": {
"description": "Localized Array",
"type": "array",
"localized": true,
"items": {
"type": "string",
"enum": ["UEFA European Football Championship", "FIFA World Cup", "FIFA Confederations Cup", "CAF Africa Cup of Nations", "CONMEBOL Copa América", "CONCACAF Gold Cup", "UEFA Champions League", "FIFA Club World Cup", "CAF Champions League", "CONMEBOL Copa Libertadores", "Deutscher Pokal"]
}
},
"kind": {
"title": "Kind",
"type": "string",
"enum": ["Live Coverage", "Editorial", "Biography"],
"tagextradata": true
}
}
}
}, {
"Scope": "customentity.suggest",
"JsonSchema": {
"type": "object",
"properties": {
"suggest": {
"type": "string",
"description": "The placeholder for suggested tags",
"title": "Suggest",
"extended-type": "forge-tags-suggestion"
}
}
}
}, {
"Scope": "customentity.test3",
"JsonSchema": {
"type": "object",
"properties": {
"description": {
"type": "string",
"title": "Brief description",
"description": "Brief description of the venue",
"localized": true,
"extended-type": "rich-text"
},
"history": {
"type": "string",
"localized": true,
"extended-type": "rich-text",
"tagextradata": true
},
"capacity": {
"type": "number",
"description": "Stadium "s capacity",
"tagextradata": true
},
"active": {
"type": "boolean",
"localized": true,
"tagextradata": true
},
"language": {
"type": "string"
},
"limit": {
"type": "string"
},
"size": {
"type": "string"
},
"aCtivs2": {
"type": "boolean",
"localized": true,
"tagExtraData": true
},
"datetime": {
"type": "string",
"format": "date-time",
"description": "The date//time of the entity"
},
"ListOfStringsExtended": {
"description": "A list of strings",
"type": "array",
"localized": true,
"format": "date-time",
"tagextradata": true,
"items": {
"type": "string"
}
},
"ListOfStringEnums": {
"description": "A list of strings",
"type": "array",
"items": {
"type": "string",
"enum": ["one", "two", "three", "four"]
}
},
"ListOfStringsEnumsExtended": {
"description": "A list of strings",
"type": "array",
"localized": true,
"format": "date-time",
"tagextradata": true,
"items": {
"type": "string",
"enum": ["Italy", "Uk", "France", "Germany"]
}
},
"ListOfNumbersEnums": {
"description": "A list of numbers as enum",
"type": "array",
"items": {
"type": "number",
"enum": [2, 3, 4, 5]
}
},
"ListOfNumbersEnumsExtended": {
"description": "A list of number as enum extended",
"type": "array",
"localized": true,
"format": "date-time",
"tagextradata": true,
"items": {
"type": "number",
"enum": [1, 2, 3, 4]
}
},
"ListOfIntegers": {
"description": "A list of Integers",
"type": "array",
"items": {
"type": "integer"
}
},
"ListOfIntegersExtended": {
"description": "A list of integers",
"type": "array",
"localized": true,
"tagextradata": true,
"items": {
"type": "integer"
}
},
"ListOfNumbers": {
"description": "A list of numbers",
"type": "array",
"items": {
"type": "number"
}
},
"ListOfNumbersExtended": {
"description": "A list of number",
"type": "array",
"localized": true,
"tagextradata": true,
"items": {
"type": "string"
}
},
"ListOfBooleans": {
"description": "A list of boolean",
"type": "array",
"items": {
"type": "boolean"
}
},
"ListOfBooleansExtended": {
"description": "A list of boolean",
"type": "array",
"localized": true,
"tagextradata": true,
"items": {
"type": "boolean"
}
},
"surface": {
"type": "string",
"localized": true,
"tagextradata": true,
"enum": ["Natural grass", "Latitude 36 Bermuda Grass", "Other"]
}
},
"indexes": {
"descriptionIndex": {
"description": 1
},
"capacityIndex": {
"capacity": 1
},
"ListOfStringsEnumIndex": {
"ListOfStringEnums": 1
},
"languageIndex": {
"language": 1
},
"limitIndex": {
"limit": 1
},
"sizeIndex": {
"size": 1
}
}
}
}, {
"Scope": "customentity.Sample",
"JsonSchema": {
"type": "object",
"properties": {
"author": {
"type": "string",
"title": "Author",
"description": "Name and Surname of the author",
"tagextradata": true
},
"copyright": {
"type": "string",
"tagextradata": true,
"localized": true
},
"description": {
"title": "Description",
"type": "string",
"description": "A short introduction (100 words)",
"extended-type": "rich-text",
"localized": true
},
"showAdvertising": {
"title": "Show banners",
"description": "True to show advertising",
"type": "boolean"
},
"kind": {
"title": "Kind",
"type": "string",
"enum": ["Live Coverage", "Editorial", "Biography"],
"tagextradata": true
}
}
}
}, {
"Scope": "customentity.divavideo",
"JsonSchema": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "The description of the video",
"title": "Description",
"localized": true,
"tagextradata": false,
"extended-type": "rich-text"
},
"videoId": {
"type": "string",
"description": "The unique identifier of the video inside the Diva platform",
"title": "Video Id",
"localized": true,
"extended-type": "forge-diva-video",
"tagextradata": true,
"filter": true
},
"videoStatus": {
"type": "string",
"description": "The status of the video inside the Diva platform",
"title": "Video Status",
"enum": ["Scheduled", "OnDemand", "Live"],
"tagextradata": true,
"filter": true,
"readonly": true
},
"videoDuration": {
"type": "string",
"description": "The duration of the video inside the Diva platform",
"title": "Video Duration",
"readonly": true
},
"videoTimeCodeIn": {
"type": "string",
"format": "date-time",
"description": "The time code in of the video inside the Diva platform",
"title": "Video Time Code In",
"readonly": true
}
},
"indexes": {
"videoIdIndex": {
"videoId": 1
},
"videoStatusIndex": {
"videoStatus": 1
}
}
}
}, {
"Scope": "customentity.poll",
"JsonSchema": {
"type": "object",
"properties": {
"description": {
"title": "Description",
"type": "string",
"extended-type": "rich-text",
"localized": true
}
}
}
}, {
"Scope": "customentity.author",
"JsonSchema": {
"type": "object",
"properties": {
"firstName": {
"title": "First name",
"type": "string",
"extended-type": "rich-text",
"localized": true
},
"lastName": {
"title": "Last name",
"type": "string",
"extended-type": "rich-text",
"localized": true
},
"bio": {
"title": "Brief Biography",
"type": "string",
"extended-type": "rich-text",
"localized": true
}
}
}
}, {
"Scope": "customentity.TestEntity",
"JsonSchema": {
"type": "object",
"properties": {
"besugo": {
"type": "string",
"enum": ["bar"],
"tagextradata": true
},
"noteditable": {
"type": "string",
"readonly": true
}
}
}
}, {
"Scope": "customentity.youtube-video",
"JsonSchema": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "The description of the video",
"title": "Description",
"localized": true,
"tagextradata": false,
"extended-type": "rich-text"
},
"videoId": {
"type": "string",
"description": "The unique identifier of the video",
"title": "Video Id",
"localized": true,
"tagextradata": true,
"extended-type": "forge-youtube-video-input"
}
},
"indexes": {
"videoIdIndex": {
"videoId": 1
}
}
}
}]
},
"DistributionIndexesConfiguration": {
"Definitions": [{
"Scope": "story",
"JsonSchema": {
"type": "object",
"indexes": {
"titleIndexFTS": {
"system.title": "text",
"system.headline": "text",
"system.summary": "text"
}
}
}
}]
},
"ReferenceFieldsConfiguration": {
"ReferenceFieldsDefinitions": [{
"Entity": "customentity.poll",
"FieldName": "options",
"Localizable": true,
"AllowedReferencedEntities": ["Story", "album", "document", "photo", "customentity.drivers"]
}, {
"Entity": "customentity.sample",
"FieldName": "samples",
"Localizable": true,
"AllowedReferencedEntities": ["story", "album", "document", "customentity.team", "customentity.drivers"]
}, {
"Entity": "customentity.sample",
"FieldName": "samples-global",
"Localizable": false,
"AllowedReferencedEntities": ["photo", "story"]
}, {
"Entity": "customentity.poll",
"FieldName": "test",
"Localizable": true,
"AllowedReferencedEntities": ["photo", "customentity.drivers"]
}, {
"Entity": "story",
"FieldName": "Test1",
"Localizable": true,
"AllowedReferencedEntities": ["story", "photo", "document", "album"]
}]
},
"CustomBehaviorsConfiguration": {
"CustomBehaviorDefinitions": [{
"Entity": "story",
"Name": "forge-story-behavior-sample",
"Enabled": true
}]
},
"ExternalStoryParts": [{
"Name": "OEmbed",
"Definition": {
"Icon": "share",
"Schema": {
"title": "Embed social content",
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "An url representing the content you wish to embed"
},
"maxwidth": {
"type": "integer",
"description": "The max width in pixel (optional)"
},
"maxheight": {
"type": "integer",
"description": "The max height in pixel (optional)"
}
}
},
"Search": "http://localhost:60191/deltatre.forge.wcm/api/storyparts/oembed/search"
}
}, {
"Name": "cartoon-players",
"Definition": {
"Icon": "http://m.img.brothersoft.com/android/79/795ae74b6b6a126c29be851665fb7157_icon.png",
"Schema": {
"title": "Holly & Benji players",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"isRegular": {
"description": "Is a regular player or is a bench warmer",
"type": "boolean"
},
"team": {
"description": "In which team does he play?",
"enum": ["New Team", "Muppet"]
}
},
"required": ["firstName", "lastName"]
},
"Search": "http://webplu-sample-externaldata.azurewebsites.net/parts/search"
}
}, {
"Name": "fifacom-players",
"Definition": {
"Icon": "account_box",
"Schema": {
"title": "FifaCom Players",
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": ["name"]
},
"Search": "http://webplu-sample-externaldata.azurewebsites.net/players/search"
}
}, {
"Name": "Sample Table",
"Definition": {
"Icon": "grid_on",
"Schema": {
"title": "Table with Polymer Components",
"type": "object",
"properties": {
"tableValue": {
"type": "polymer",
"extended-type": "forge-table-input"
}
}
},
"Search": "http://webplu-sample-externaldata.azurewebsites.net/table-input/search"
}
}],
"ExternalFeedsConfiguration": {
"ExternalFeedsEndpoints": [{
"TargetEntity": "story",
"Name": "FifaRss",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/fifa-rss",
"Permission": null
}, {
"TargetEntity": "photo",
"Name": "GettyPhotos",
"Url": "http://webplu-sample-gettyintegration.azurewebsites.net/feeds",
"Permission": null
}, {
"TargetEntity": "document",
"Name": "SampleDocuments",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/feeds/document",
"Permission": null
}, {
"TargetEntity": "album",
"Name": "SampleAlbums",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/feeds/album",
"Permission": null
}, {
"TargetEntity": "selection",
"Name": "SampleSelections",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/feeds/selection",
"Permission": null
}, {
"TargetEntity": "customEntity.player",
"Name": "SampleCEPlayers",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/feeds/customEntityPlayer",
"Permission": null
}, {
"TargetEntity": "story",
"Name": "StoriesWithError",
"Url": "http://webplu-sample-externaldata.azurewebsites.net/feeds/storiesImportError",
"Permission": null
}, {
"TargetEntity": "customEntity.youtube",
"Name": "Youtube",
"Url": "http://webplu-sample-youtubeintegration.azurewebsites.net/feeds/FIFATV",
"Permission": null
}, {
"TargetEntity": "customEntity.youtube-video",
"Name": "NBA",
"Url": "http://webplu-sample-youtubeintegration.azurewebsites.net/feeds/nba?entityName=youtube-video",
"Permission": null
}]
},
"SystemLanguagesConfiguration": {
"Languages": [{
"Culture": "en-US",
"Name": "English (United States)"
}, {
"Culture": "it-IT",
"Name": "Italian (Italy)"
}, {
"Culture": "ro-RO",
"Name": "Romanian (Romania)"
}, {
"Culture": "ru-RU",
"Name": "Russian (Russia)"
}, {
"Culture": "zh-CN",
"Name": "Chinese (Simplified, PRC)"
}, {
"Culture": "ar-QA",
"Name": "Arabic (Qatar)"
}]
}
}
}; |
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M18 11l5-5-5-5v3h-4v4h4v3zm2 4.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z' })
);
}; |
/* eslint-env node */
const { Listener } = require("discord-akairo");
const Table = require("cli-table");
const config = require("./../../config.json");
function exec() {
this.client.user.setGame(config.default_game.replace("{guildCount}", this.client.guilds.size).replace("{prefix}", config.prefix).replace("{botName}", this.client.user.username));
let table = new Table({
tableSize: [10, 20]
});
table.push(
["Guilds", this.client.guilds.size], ["Users", this.client.users.size], ["Prefix", config.prefix], ["Bot ID", this.client.user.id]
);
return console.log(table.toString());
}
module.exports = new Listener("ready", exec, {
emitter: "client"
, eventName: "ready"
, type: "once"
});
|
// app.js
// INICIANDO ==========================================
var express = require('express');
// cria nossa aplicação Express
var app = express();
// MONGODB ============================================
// mongoose for mongodb
var mongoose = require('mongoose');
// conectando ao mongodb no mLab, criando o banco de dados contato
var dbConfig = require('./db.js');
mongoose.connect(dbConfig.url);
var conn = mongoose.connection;
// solicitações para log no console (express4)
var logger = require('morgan');
// puxar informações por POST HTML (express4)
var bodyParser = require('body-parser');
// simular DELETE e PUT (express4)
var methodOverride = require('method-override');
// mongoose.connect('mongodb://localhost/contato');
conn.on('error', console.error.bind(console, 'connection error:'));
// Requisição ao arquivo que cria nosso model Contato
require('./models/Contato');
// DEFININDO A APLICAÇÃO ==============================
// definindo local de arquivos públicos
app.use(express.static(__dirname + '/public'));
// logando todas as requisições no console
app.use(logger('dev'));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({'extended':'true'}));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
// ROTAS ===============================================
// Incluindo nossas rotas definidas no arquivo routes/index.js
var index = require('./routes/index');
// definindo nossas rotas na aplicação
app.use('/', index);
// LISTEN (iniciando nossa aplicação em node) ==========
// Define a porta 8080 onde será executada nossa aplicação
app.listen(8080);
// Imprime uma mensagem no console
console.log("Aplicação executada na porta 8080"); |
"use strict";
var NameList = (function () {
function NameList() {
this.names = ['Dijkstra', 'Knuth', 'Turing', 'Hopper'];
}
NameList.prototype.get = function () {
return this.names;
};
NameList.prototype.add = function (value) {
this.names.push(value);
};
NameList.prototype.remove = function (index) {
this.names.splice(index, 1);
};
return NameList;
}());
exports.NameList = NameList;
//# sourceMappingURL=name_list.js.map |
import React, { Component, PropTypes } from 'react';
import { Button, Text } from 'native-base';
import { FormattedMessage, } from 'react-intl';
export default class ButtonComponent extends Component {
static propTypes = {
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]).isRequired,
}
render() {
const { label } = this.props;
return (
<Button>
{typeof label === 'string' &&
<Text>{label}</Text>
}
{label && typeof label === 'object' &&
<Text><FormattedMessage id={label.code} values={label.values} /></Text>
}
</Button>
);
}
}
|
/*global app, $, Lang */
'use strict';
require(['app'], function() {
/**
* Edit a language
* */
$('.edit-lang').click(function() {
var tag = $('#language-filter-form [name="tag"]').val();
app.dialog(app.getUri('edit-language', {tag : tag}));
});
/**
* Delete a language
*/
$('.delete-lang').click(function() {
if (confirm(Lang.get('language.confirm-delete-lang'))) {
var tag = $('#language-filter-form [name="tag"]').val();
$.get(app.getUri('delete-language', {tag : tag}), function() {
app.load(app.getUri('manage-languages'));
});
}
});
/**
* Edit a translation key
*/
$('#language-manage-page')
/**
* Delete a translation key
*/
.on('click', '.delete-translation', function() {
var tag = $('#language-filter-form [name="tag"]').val(),
data = $(this).data('key').split('.'),
plugin = data[0],
key = data[1];
$.get(app.getUri('delete-translation', {plugin : plugin, key : key, tag : tag}), function() {
app.lists['language-key-list'].refresh();
});
});
var form = app.forms['language-filter-form'];
form.submit = function() {
var data = this.toString();
$.cookie('languages-filters', data);
app.load(app.getUri('manage-languages'));
return false;
};
form.node
.on('change', '[name="tag"], [name="keys"], [name="selected"]', function() {
form.submit();
});
}); |
require.config({
paths: {
'jquery': '../vendor/jquery/dist/jquery',
'bootstrap': '../vendor/bootstrap/dist/js/bootstrap',
'validator': '../vendor/bootstrap-validator/dist/validator'
}
});
require(['jquery'], function ($) {
require(['validator', 'bootstrap', 'validator'], function (validator, bootstrap, validator) {
$(function () {
'use strict';
// Page show-up
$('#status').fadeOut();
$('#preloader').delay(150).fadeOut('slow');
$('body').delay(150).css({'overflow': 'visible'});
// target _blank to all external links
$('body a').each(function () {
if (this.href.indexOf(location.hostname) === -1) {
$(this).attr('target', '_blank');
}
});
// Form Validation
$('.form-group').append('<div class="help-block with-errors"></div>');
$('form').validator();
}());
});
}); |
function euler204() {
// Good luck!
return true
}
euler204()
|
ig.module(
'game.main'
)
.requires(
'impact.game',
'impact.font',
'plugins.camera',
'plugins.touch-button',
'plugins.impact-splash-loader',
'plugins.gamepad',
'game.entities.player',
'game.entities.blob',
'game.levels.title',
'game.levels.grasslands',
'game.levels.snowhills'
)
.defines(function(){
// Our Main Game class. This will load levels, host all entities and
// run the game.
MyGame = ig.Game.extend({
clearColor: "#d0f4f7",
gravity: 800, // All entities are affected by this
// Load a font
font: new ig.Font( 'media/fredoka-one.font.png' ),
// HUD icons
heartFull: new ig.Image( 'media/heart-full.png' ),
heartEmpty: new ig.Image( 'media/heart-empty.png' ),
coinIcon: new ig.Image( 'media/coin.png' ),
init: function() {
// We want the font's chars to slightly touch each other,
// so set the letter spacing to -2px.
this.font.letterSpacing = -2;
// Load the LevelGrasslands as required above ('game.level.grassland')
this.loadLevel( LevelGrasslands );
},
loadLevel: function( data ) {
// Remember the currently loaded level, so we can reload when
// the player dies.
this.currentLevel = data;
// Call the parent implemenation; this creates the background
// maps and entities.
this.parent( data );
this.setupCamera();
},
setupCamera: function() {
// Set up the camera. The camera's center is at a third of the screen
// size, i.e. somewhat shift left and up. Damping is set to 3px.
this.camera = new ig.Camera( ig.system.width/3, ig.system.height/3, 3 );
// The camera's trap (the deadzone in which the player can move with the
// camera staying fixed) is set to according to the screen size as well.
this.camera.trap.size.x = ig.system.width/10;
this.camera.trap.size.y = ig.system.height/3;
// The lookahead always shifts the camera in walking position; you can
// set it to 0 to disable.
this.camera.lookAhead.x = ig.system.width/6;
// Set camera's screen bounds and reposition the trap on the player
this.camera.max.x = this.collisionMap.pxWidth - ig.system.width;
this.camera.max.y = this.collisionMap.pxHeight - ig.system.height;
this.camera.set( this.player );
},
reloadLevel: function() {
this.loadLevelDeferred( this.currentLevel );
},
update: function() {
// Update all entities and BackgroundMaps
this.parent();
// Camera follows the player
this.camera.follow( this.player );
// Instead of using the camera plugin, we could also just center
// the screen on the player directly, like this:
// this.screen.x = this.player.pos.x - ig.system.width/2;
// this.screen.y = this.player.pos.y - ig.system.height/2;
},
draw: function() {
// Call the parent implementation to draw all Entities and BackgroundMaps
this.parent();
// Draw the heart and number of coins in the upper left corner.
// 'this.player' is set by the player's init method
if( this.player ) {
var x = 16,
y = 16;
for( var i = 0; i < this.player.maxHealth; i++ ) {
// Full or empty heart?
if( this.player.health > i ) {
this.heartFull.draw( x, y );
}
else {
this.heartEmpty.draw( x, y );
}
x += this.heartEmpty.width + 8;
}
// We only want to draw the 0th tile of coin sprite-sheet
x += 48;
this.coinIcon.drawTile( x, y+6, 0, 36 );
x += 42;
this.font.draw( 'x ' + this.player.coins, x, y+10 )
}
// Draw touch buttons, if we have any
if( window.myTouchButtons ) {
window.myTouchButtons.draw();
}
}
});
// The title screen is simply a Game Class itself; it loads the LevelTitle
// runs it and draws the title image on top.
MyTitle = ig.Game.extend({
clearColor: "#d0f4f7",
gravity: 800,
// The title image
title: new ig.Image( 'media/title.png' ),
// Load a font
font: new ig.Font( 'media/fredoka-one.font.png' ),
init: function() {
// Bind keys
ig.input.bind( ig.KEY.LEFT_ARROW, 'left' );
ig.input.bind( ig.KEY.RIGHT_ARROW, 'right' );
ig.input.bind( ig.KEY.X, 'jump' );
ig.input.bind( ig.KEY.C, 'shoot' );
ig.input.bind( ig.GAMEPAD.PAD_LEFT, 'left' );
ig.input.bind( ig.GAMEPAD.PAD_RIGHT, 'right' );
ig.input.bind( ig.GAMEPAD.FACE_1, 'jump' );
ig.input.bind( ig.GAMEPAD.FACE_2, 'shoot' );
ig.input.bind( ig.GAMEPAD.FACE_3, 'shoot' );
// Align touch buttons to the screen size, if we have any
if( window.myTouchButtons ) {
window.myTouchButtons.align();
}
// We want the font's chars to slightly touch each other,
// so set the letter spacing to -2px.
this.font.letterSpacing = -2;
this.loadLevel( LevelTitle );
this.maxY = this.backgroundMaps[0].pxHeight - ig.system.height;
},
update: function() {
// Check for buttons; start the game if pressed
if( ig.input.pressed('jump') || ig.input.pressed('shoot') ) {
ig.system.setGame( MyGame );
return;
}
this.parent();
// Scroll the screen down; apply some damping.
var move = this.maxY - this.screen.y;
if( move > 5 ) {
this.screen.y += move * ig.system.tick;
this.titleAlpha = this.screen.y / this.maxY;
}
this.screen.x = (this.backgroundMaps[0].pxWidth - ig.system.width)/2;
},
draw: function() {
this.parent();
var cx = ig.system.width/2;
this.title.draw( cx - this.title.width/2, 60 );
var startText = ig.ua.mobile
? 'Press Button to Play!'
: 'Press X or C to Play!';
this.font.draw( startText, cx, 420, ig.Font.ALIGN.CENTER);
// Draw touch buttons, if we have any
if( window.myTouchButtons ) {
window.myTouchButtons.draw();
}
}
});
if( ig.ua.mobile ) {
// Use the TouchButton Plugin to create a TouchButtonCollection that we
// can draw in our game classes.
// Touch buttons are anchored to either the left or right and top or bottom
// screen edge.
var buttonImage = new ig.Image( 'media/touch-buttons.png' );
myTouchButtons = new ig.TouchButtonCollection([
new ig.TouchButton( 'left', {left: 0, bottom: 0}, 128, 128, buttonImage, 0 ),
new ig.TouchButton( 'right', {left: 128, bottom: 0}, 128, 128, buttonImage, 1 ),
new ig.TouchButton( 'shoot', {right: 128, bottom: 0}, 128, 128, buttonImage, 2 ),
new ig.TouchButton( 'jump', {right: 0, bottom: 96}, 128, 128, buttonImage, 3 )
]);
}
// If our screen is smaller than 640px in width (that's CSS pixels), we scale the
// internal resolution of the canvas by 2. This gives us a larger viewport and
// also essentially enables retina resolution on the iPhone and other devices
// with small screens.
var scale = (window.innerWidth < 640) ? 2 : 1;
// We want to run the game in "fullscreen", so let's use the window's size
// directly as the canvas' style size.
var canvas = document.getElementById('canvas');
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
// Listen to the window's 'resize' event and set the canvas' size each time
// it changes.
window.addEventListener('resize', function(){
// If the game hasn't started yet, there's nothing to do here
if( !ig.system ) { return; }
// Resize the canvas style and tell Impact to resize the canvas itself;
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
ig.system.resize( window.innerWidth * scale, window.innerHeight * scale );
// Re-center the camera - it's dependend on the screen size.
if( ig.game && ig.game.setupCamera ) {
ig.game.setupCamera();
}
// Also repositon the touch buttons, if we have any
if( window.myTouchButtons ) {
window.myTouchButtons.align();
}
}, false);
// Finally, start the game into MyTitle and use the ImpactSplashLoader plugin
// as our loading screen
var width = window.innerWidth * scale,
height = window.innerHeight * scale;
ig.main( '#canvas', MyTitle, 60, width, height, 1, ig.ImpactSplashLoader );
});
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc1
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.card
*
* @description
* Card components.
*/
angular.module('material.components.card', [
'material.core'
])
.directive('mdCard', mdCardDirective);
/**
* @ngdoc directive
* @name mdCard
* @module material.components.card
*
* @restrict E
*
* @description
* The `<md-card>` directive is a container element used within `<md-content>` containers.
*
* An image included as a direct descendant will fill the card's width, while the `<md-card-content>`
* container will wrap text content and provide padding. An `<md-card-footer>` element can be
* optionally included to put content flush against the bottom edge of the card.
*
* Action buttons can be included in an `<md-card-actions>` element, similar to `<md-dialog-actions>`.
* You can then position buttons using layout attributes.
*
* Card is built with:
* * `<md-card-header>` - Header for the card, holds avatar, text and squared image
* - `<md-card-avatar>` - Card avatar
* - `md-user-avatar` - Class for user image
* - `<md-icon>`
* - `<md-card-header-text>` - Contains elements for the card description
* - `md-title` - Class for the card title
* - `md-subhead` - Class for the card sub header
* * `<img>` - Image for the card
* * `<md-card-title>` - Card content title
* - `<md-card-title-text>`
* - `md-headline` - Class for the card content title
* - `md-subhead` - Class for the card content sub header
* - `<md-card-title-media>` - Squared image within the title
* - `md-media-sm` - Class for small image
* - `md-media-md` - Class for medium image
* - `md-media-lg` - Class for large image
* * `<md-card-content>` - Card content
* - `md-media-xl` - Class for extra large image
* * `<md-card-actions>` - Card actions
* - `<md-card-icon-actions>` - Icon actions
*
* Cards have constant width and variable heights; where the maximum height is limited to what can
* fit within a single view on a platform, but it can temporarily expand as needed.
*
* @usage
* ### Card with optional footer
* <hljs lang="html">
* <md-card>
* <img src="card-image.png" class="md-card-image" alt="image caption">
* <md-card-content>
* <h2>Card headline</h2>
* <p>Card content</p>
* </md-card-content>
* <md-card-footer>
* Card footer
* </md-card-footer>
* </md-card>
* </hljs>
*
* ### Card with actions
* <hljs lang="html">
* <md-card>
* <img src="card-image.png" class="md-card-image" alt="image caption">
* <md-card-content>
* <h2>Card headline</h2>
* <p>Card content</p>
* </md-card-content>
* <md-card-actions layout="row" layout-align="end center">
* <md-button>Action 1</md-button>
* <md-button>Action 2</md-button>
* </md-card-actions>
* </md-card>
* </hljs>
*
* ### Card with header, image, title actions and content
* <hljs lang="html">
* <md-card>
* <md-card-header>
* <md-card-avatar>
* <img class="md-user-avatar" src="avatar.png"/>
* </md-card-avatar>
* <md-card-header-text>
* <span class="md-title">Title</span>
* <span class="md-subhead">Sub header</span>
* </md-card-header-text>
* </md-card-header>
* <img ng-src="card-image.png" class="md-card-image" alt="image caption">
* <md-card-title>
* <md-card-title-text>
* <span class="md-headline">Card headline</span>
* <span class="md-subhead">Card subheader</span>
* </md-card-title-text>
* </md-card-title>
* <md-card-actions layout="row" layout-align="start center">
* <md-button>Action 1</md-button>
* <md-button>Action 2</md-button>
* <md-card-icon-actions>
* <md-button class="md-icon-button" aria-label="icon">
* <md-icon md-svg-icon="icon"></md-icon>
* </md-button>
* </md-card-icon-actions>
* </md-card-actions>
* <md-card-content>
* <p>
* Card content
* </p>
* </md-card-content>
* </md-card>
* </hljs>
*/
function mdCardDirective($mdTheming) {
return {
restrict: 'E',
link: function ($scope, $element) {
$mdTheming($element);
}
};
}
mdCardDirective.$inject = ["$mdTheming"];
})(window, window.angular); |
//Change ifame size, so that the bot panel can be there
var frame = document.getElementById("game_frame");
if(frame)
{
$(frame).width((980 + 501) + "px");
//Force page to reload to try to counter the ban
setTimeout(function() {
location.reload();
}, 2*60*60*1000);
}
function setup_facebook() {
var a = document.getElementById("iframe_canvas");
if (a) {
for (a.style.width = "100%"; (a = a.parentNode) !== null;) {
if (a.tagName == "DIV") {
a.style.width = "100%";
}
}
$("rightCol").style.display = "none";
} else {
setTimeout(setup_facebook, 1000);
}
}
if (document.URL.search(/apps.facebook.com\/play_godfather/i) >= 0) {
setup_facebook();
}
|
#!/usr/bin/env node
'use strict';
/* eslint-disable no-console */
const spawnSync = require( 'child_process').spawnSync;
const fs = require('fs');
const temp = require('temp');
const { blue, green, gray } = require('chalk');
const path = require('path');
const glob = require('glob');
const cliBuilds = 'https://github.com/angular/cli-builds.git';
class Executor {
constructor(cwd) {
this._cwd = cwd;
}
execute(command, ...args) {
args = args.filter(x => x !== undefined);
console.log(blue(`Running \`${command} ${args.map(x => `"${x}"`).join(' ')}\`...`));
console.log(blue(`CWD: ${this._cwd}`));
const runCommand = spawnSync(command, args, { cwd: this._cwd });
if (runCommand.status === 0) {
console.log(gray(runCommand.stdout.toString()));
return runCommand.stdout.toString();
} else {
throw new Error(
`Command returned status ${runCommand.status}. Details:\n${runCommand.stderr}`);
}
}
git(...args) {
return this.execute('git', ...args);
}
npm(...args) {
return this.execute('npm', ...args);
}
rm(...args) {
return this.execute('rm', ...args);
}
glob(pattern, options) {
return glob.sync(pattern, Object.assign({}, options || {}, { cwd: this._cwd }));
}
cp(root, destRoot) {
function mkdirp(p) {
if (fs.existsSync(p)) {
return;
}
mkdirp(path.dirname(p));
fs.mkdirSync(p);
}
this.glob(path.join(root, '**/*'), { nodir: true })
.forEach(name => {
const src = name;
const dest = path.join(destRoot, src.substr(root.length));
mkdirp(path.dirname(dest));
fs.writeFileSync(dest, fs.readFileSync(src));
});
}
read(p) {
return fs.readFileSync(path.join(this._cwd, p), 'utf-8');
}
write(p, content) {
fs.writeFileSync(path.join(this._cwd, p), content);
}
updateVersion(hash) {
const packageJson = JSON.parse(this.read('package.json'));
packageJson.version = `${packageJson.version}-${hash}`;
this.write('package.json', JSON.stringify(packageJson, null, 2));
}
}
function main() {
const cliPath = process.cwd();
const cliExec = new Executor(cliPath);
const tempRoot = temp.mkdirSync('angular-cli-builds');
const tempExec = new Executor(tempRoot);
const branchName = process.env['TRAVIS_BRANCH'];
console.log(green('Cloning builds repos...\n'));
tempExec.git('clone', cliBuilds);
console.log(green('Building...'));
const cliBuildsRoot = path.join(tempRoot, 'cli-builds');
const cliBuildsExec = new Executor(cliBuildsRoot);
cliExec.npm('run', 'build');
const message = cliExec.git('log', '--format=%h %s', '-n', '1');
const hash = message.split(' ')[0];
console.log(green('Copying cli-builds dist'));
cliBuildsExec.git('checkout', '-B', branchName);
cliBuildsExec.rm('-rf', ...cliBuildsExec.glob('*'));
cliExec.cp('dist/@angular/cli', cliBuildsRoot);
console.log(green('Updating package.json version'));
cliBuildsExec.updateVersion(hash);
cliBuildsExec.git('add', '-A');
cliBuildsExec.git('commit', '-m', message);
cliBuildsExec.git('tag', hash);
cliBuildsExec.git('config', 'credential.helper', 'store --file=.git/credentials');
cliBuildsExec.write('.git/credentials',
`https://${process.env['GITHUB_ACCESS_TOKEN']}@github.com`);
console.log(green('Done. Pushing...'));
cliBuildsExec.git('push', '-f', 'origin', branchName);
cliBuildsExec.git('push', '--tags', 'origin', branchName);
}
main();
|
/*
* MainScene.js
* 2015/03/10
* @auther minimo
* This Program is MIT license.
*
*/
tm.define("tactics.MainScene", {
superClass: tm.app.Scene,
//マルチタッチ補助クラス
touches: null,
touchID: -1,
//タッチ情報
startX: 0,
startY: 0,
touchTime: 0,
moveX: 0,
moveY: 0,
beforeX: 0,
beforeY: 0,
//コントロール中フラグ
control: CTRL_NOTHING,
//経過時間
time: 1,
//遷移情報
exitGame: false,
//マップ情報
world: null,
//選択矢印
arrow: null,
//ラベル用パラメータ
labelParam: {fontFamily: "Orbitron", align: "left", baseline: "middle",outlineWidth: 3, fontWeight:700},
init: function() {
this.superInit();
this.background = "rgba(0, 0, 0, 0.0)";
//バックグラウンド
this.bg = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: appMain.bgColor, strokeStyle: appMain.bgColor})
.addChildTo(this)
.setPosition(SC_W*0.5, SC_H*0.5);
//マルチタッチ初期化
this.touches = tm.input.TouchesEx(this);
//レイヤー準備
this.lowerLayer = tm.app.Object2D().addChildTo(this);
this.mainLayer = tm.app.Object2D().addChildTo(this);
this.upperLayer = tm.app.Object2D().addChildTo(this);
//マップ
this.world = tactics.World()
.addChildTo(this.mainLayer);
//勢力天秤
this.balance = tactics.PowerBalance(this.world)
.addChildTo(this.mainLayer)
.setPosition(SC_W*0.05, SC_H*0.9);
this.test = tm.display.Label("x:0 y:0")
.addChildTo(this)
.setPosition(32, SC_H-60)
.setParam({fontFamily:"Orbitron", align: "left", baseline:"middle", outlineWidth:2 });
//目隠し
this.mask = tm.display.RectangleShape({width: SC_W, height: SC_H, fillStyle: "rgba(0, 0, 0, 1.0)", strokeStyle: "rgba(0, 0, 0, 1.0)"})
.addChildTo(this)
.setPosition(SC_W*0.5, SC_H*0.5);
this.mask.tweener.clear().fadeOut(200);
},
update: function() {
//スクリーンショット保存
var kb = appMain.keyboard;
if (kb.getKeyDown("s")) appMain.canvas.saveAsImage();
this.time++;
},
setupWorld: function() {
},
//タッチorクリック開始処理
ontouchesstart: function(e) {
if (this.touchID > 0)return;
this.touchID = e.ID;
var sx = this.startX = e.pointing.x;
var sy = this.startY = e.pointing.y;
this.moveX = 0;
this.moveY = 0;
this.beforeX = sx;
this.beforeY = sy;
this.touchTime = 0;
//砦の判定
var res = this.world.getFort(sx, sy);
if (res && res.distance < 32) {
res.fort.select = true;
if (res.fort.alignment == TYPE_PLAYER) {
this.control = CTRL_FORT;
this.arrow = tactics.Arrow(res.fort).addChildTo(this.world);
}
return;
}
var mp = this.world.screenToMap(sx, sy);
var x = mp.x*64+(mp.y%2?32:0)+32;
var y = mp.y*16;
this.pointer = tm.display.Sprite("mapobject", 32, 32)
.addChildTo(this.world.base)
.setFrameIndex(4)
.setScale(MAPCHIP_SCALE)
.setPosition(x, y)
.setAlpha(0.5);
},
//タッチorクリック移動処理
ontouchesmove: function(e) {
if (this.touchID != e.ID) return;
var sx = e.pointing.x;
var sy = e.pointing.y;
var moveX = Math.abs(sx - this.beforeX);
var moveY = Math.abs(sx - this.beforeY);
var mp = this.world.screenToMap(sx, sy);
var x = mp.x*64+(mp.y%2?32:0)+32;
var y = mp.y*16;
if (this.pointer) {
this.pointer.setPosition(x, y);
} else {
this.pointer = tm.display.Sprite("mapobject", 32, 32)
.addChildTo(this.world.base)
.setFrameIndex(4)
.setScale(MAPCHIP_SCALE)
.setPosition(x, y)
.setAlpha(0.5);
}
if (this.arrow) {
if (this.arrow.to instanceof tactics.Fort) {
} else {
this.arrow.to = {x:sx-32, y:sy-16, active:true};
}
}
//砦をタッチ
if (this.control == CTRL_FORT) {
var res = this.world.getFort(sx, sy);
if (res && res.fort != this.arrow.from) {
if (res.distance < 32) {
if (this.arrow.to instanceof tactics.Fort && this.arrow.to != res.fort) {
this.arrow.to.select = false;
}
this.arrow.to = res.fort;
res.fort.select = true;
this.pointer.remove();
this.pointer = null;
} else {
if (this.arrow.to instanceof tactics.Fort) {
var f = this.arrow.to;
f.select = false;
this.arrow.to = {x:sx-32, y:sy-16, active:true};
}
}
}
}
//デバッグ用
this.test.text = "x:"+mp.x+" y:"+mp.y;
this.touchTime++;
},
//タッチorクリック終了処理
ontouchesend: function(e) {
if (this.touchID != e.ID) return;
this.touchID = -1;
var sx = e.pointing.x;
var sy = e.pointing.y;
var moveX = Math.abs(sx - this.beforeX);
var moveY = Math.abs(sx - this.beforeY);
//砦操作
if (this.control == CTRL_FORT && this.arrow) {
var from = this.arrow.from;
var to = this.arrow.to;
//行き先が砦かユニットの場合は兵隊派遣
if (to instanceof tactics.Fort || to instanceof tactics.Unit) {
this.world.enterUnit(from, to);
}
}
this.world.selectFortGroup(TYPE_PLAYER, false);
this.world.selectFortGroup(TYPE_ENEMY, false);
this.world.selectFortGroup(TYPE_NEUTRAL, false);
if (this.pointer) {
this.pointer.remove();
this.pointer = null;
}
if (this.arrow) {
this.arrow.remove();
this.arrow = null;
}
this.control = CTRL_NOTHING;
},
});
|
import { Map, Record } from 'immutable';
import unitOfWorkMapping, {
cartMetadata,
} from '../__mocks__/unitOfWorkMapping';
import UnitOfWork from '../src/UnitOfWork';
let unitOfWork = null;
beforeEach(() => {
unitOfWork = new UnitOfWork(unitOfWorkMapping, true);
});
describe('UnitOfWork', () => {
test('register unit of work', () => {
const entity = { foo: 'bar' };
unitOfWork.registerClean(1, entity);
expect(unitOfWork.getDirtyEntity(1).foo).toBe('bar');
});
test('immutability of objects', () => {
const entity = { foo: 'bar' };
expect(unitOfWork.getDirtyEntity(1)).toBeUndefined();
unitOfWork.registerClean(1, entity);
entity.foo = 'baz';
expect(unitOfWork.getDirtyEntity(1).foo).toBe('bar');
});
test('immutability of immutable maps', () => {
let entity = new Map({ foo: 'bar' });
unitOfWork.registerClean(1, entity);
expect(unitOfWork.getDirtyEntity(1).get('foo')).toBe('bar');
entity = entity.set('foo', 'baz');
expect(entity.get('foo')).toBe('baz');
expect(unitOfWork.getDirtyEntity(1).get('foo')).toBe('bar');
});
test('immutability of immutable records', () => {
class Entity extends Record({ foo: null }) {}
let entity = new Entity({ foo: 'bar' });
unitOfWork.registerClean(1, entity);
expect(unitOfWork.getDirtyEntity(1).foo).toBe('bar');
entity = entity.set('foo', 'baz');
expect(entity.foo).toBe('baz');
expect(unitOfWork.getDirtyEntity(1).foo).toBe('bar');
});
test('clear', () => {
unitOfWork.registerClean(1, { foo: 'bar' });
expect(unitOfWork.getDirtyEntity(1).foo).toBe('bar');
unitOfWork.clear(1);
expect(unitOfWork.getDirtyEntity(1)).toBeUndefined();
});
test('get dirty data simple entity', () => {
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1' },
{ '@id': '/v12/carts/1' },
cartMetadata
)
).toEqual({});
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
status: 'payed',
order: '/v1/orders/1',
data: null,
},
{
'@id': '/v12/carts/1',
status: 'payed',
order: '/v1/orders/1',
data: null,
},
cartMetadata
)
).toEqual({});
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1', status: 'payed' },
{ '@id': '/v12/carts/1', status: 'waiting' },
cartMetadata
)
).toEqual({ status: 'payed' });
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1', status: null },
{ '@id': '/v12/carts/1', status: 'waiting' },
cartMetadata
)
).toEqual({ status: null });
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1', status: null },
{ '@id': '/v12/carts/1', data: { foo: 'bar' } },
cartMetadata
)
).toEqual({ status: null });
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/2', status: 'payed' },
{ '@id': '/v12/carts/1', status: 'waiting' },
cartMetadata
)
).toEqual({ '@id': '/v12/carts/2', status: 'payed' });
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
status: 'payed',
data: {
foo: 'bar',
loo: 'baz',
},
},
{
'@id': '/v12/carts/1',
status: 'payed',
data: {
foo: 'bar',
},
},
cartMetadata
)
).toEqual({ data: { foo: 'bar', loo: 'baz' } });
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
status: 'payed',
data: {
foo: 'bar',
bad: 'baz',
},
},
{
'@id': '/v12/carts/1',
status: 'payed',
data: {
foo: 'bar',
bad: 'baz',
},
},
cartMetadata
)
).toEqual({});
});
test('get dirty data with more data', () => {
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1' },
{ '@id': '/v12/carts/1', status: 'ok' },
cartMetadata
)
).toEqual({});
});
test('get dirty data many to one relation', () => {
// string relation ids
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1', order: '/v12/orders/2' },
{ '@id': '/v12/carts/1', order: { '@id': '/v12/orders/1' } },
cartMetadata
)
).toEqual({ order: '/v12/orders/2' });
// only order id changed
expect(
unitOfWork.getDirtyData(
{ '@id': '/v12/carts/1', order: { '@id': '/v12/orders/2' } },
{ '@id': '/v12/carts/1', order: '/v12/orders/1' },
cartMetadata
)
).toEqual({ order: { '@id': '/v12/orders/2' } });
// only order id changed
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
order: { '@id': '/v12/orders/2', status: 'payed' },
},
{
'@id': '/v12/carts/1',
order: { '@id': '/v12/orders/1', status: 'payed' },
},
cartMetadata
)
).toEqual({ order: { '@id': '/v12/orders/2' } });
// with data alteration in order status
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
order: { '@id': '/v12/orders/2', status: 'payed' },
},
{
'@id': '/v12/carts/1',
order: { '@id': '/v12/orders/1', status: 'waiting' },
},
cartMetadata
)
).toEqual({ order: { '@id': '/v12/orders/2', status: 'payed' } });
});
test('get dirty data many to one no changes', () => {
// only with id
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
},
cartMetadata
)
).toEqual({});
// id and quantity
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 1 },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 1 },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
},
cartMetadata
)
).toEqual({});
});
test('get dirty data many to one remove item', () => {
// only with id
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: ['/v12/cart_items/1', '/v12/cart_items/2'],
},
{
'@id': '/v12/carts/1',
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
},
cartMetadata
)
).toEqual({ cartItemList: ['/v12/cart_items/1', '/v12/cart_items/2'] });
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: ['/v12/cart_items/1', '/v12/cart_items/3'],
},
{
'@id': '/v12/carts/1',
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
},
cartMetadata
)
).toEqual({ cartItemList: ['/v12/cart_items/1', '/v12/cart_items/3'] });
// with object changes
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 2,
},
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 2,
},
{
'@id': '/v12/cart_items/2',
quantity: 1,
},
],
},
cartMetadata
)
).toEqual({ cartItemList: [{ '@id': '/v12/cart_items/1' }] });
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/2',
quantity: 1,
},
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 2,
},
{
'@id': '/v12/cart_items/2',
quantity: 1,
},
],
},
cartMetadata
)
).toEqual({ cartItemList: [{ '@id': '/v12/cart_items/2' }] });
// with quantity changes
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/2',
quantity: 2,
},
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 2,
},
{
'@id': '/v12/cart_items/2',
quantity: 1,
},
],
},
cartMetadata
)
).toEqual({ cartItemList: [{ '@id': '/v12/cart_items/2', quantity: 2 }] });
});
test('get dirty data many to one add item', () => {
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
},
{
'@id': '/v12/carts/1',
cartItemList: ['/v12/cart_items/1', '/v12/cart_items/2'],
},
cartMetadata
)
).toEqual({
cartItemList: [
'/v12/cart_items/1',
'/v12/cart_items/2',
'/v12/cart_items/3',
],
});
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 1 },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
},
{
'@id': '/v12/carts/1',
cartItemList: [{ '@id': '/v12/cart_items/1', quantity: 1 }],
},
cartMetadata
)
).toEqual({
cartItemList: [
{ '@id': '/v12/cart_items/1' },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
});
});
test('get dirty data many to one update item', () => {
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 2 },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
},
{
'@id': '/v12/carts/1',
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 1 },
{ '@id': '/v12/cart_items/2', quantity: 1 },
],
},
cartMetadata
)
).toEqual({
cartItemList: [
{ '@id': '/v12/cart_items/1', quantity: 2 },
{ '@id': '/v12/cart_items/2' },
],
});
});
test('get dirty data many to one recursive item', () => {
expect(
unitOfWork.getDirtyData(
{
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 1,
cartItemDetailList: [
{ '@id': '/v12/cart_item_details/1', name: '' },
],
},
{ '@id': '/v12/cart_items/2', quantity: 1 },
{
'@id': '/v12/cart_items/3',
quantity: 1,
cartItemDetailList: [
{ '@id': '/v12/cart_item_details/2', name: '' },
],
},
],
},
{
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 2,
cartItemDetailList: [
{ '@id': '/v12/cart_item_details/1', name: 'foo' },
],
},
{ '@id': '/v12/cart_items/3', quantity: 1 },
],
},
cartMetadata
)
).toEqual({
cartItemList: [
{
'@id': '/v12/cart_items/1',
quantity: 1,
cartItemDetailList: [{ '@id': '/v12/cart_item_details/1', name: '' }],
},
{ '@id': '/v12/cart_items/2', quantity: 1 },
{
'@id': '/v12/cart_items/3',
cartItemDetailList: [{ '@id': '/v12/cart_item_details/2', name: '' }],
},
],
});
});
test('get dirty data one to many update data', () => {
expect(
unitOfWork.getDirtyData(
{
'@id': '/v12/carts/1',
order: {
'@id': '/v12/orders/1',
customerPaidAmount: 1500,
status: 'awaiting_payment',
},
},
{
'@id': '/v12/carts/1',
order: {
'@id': '/v12/orders/1',
customerPaidAmount: 1000,
status: 'awaiting_payment',
},
},
cartMetadata
)
).toEqual({
order: {
'@id': '/v12/orders/1',
customerPaidAmount: 1500,
},
});
});
});
|
/**
* 使用正确的this指向
*/
var count = 1;
var container = document.getElementById('container');
function getUserAction() {
console.log(this)
container.innerHTML = count++;
};
container.onmousemove = debounce(getUserAction, 1000);
// 第二版
function debounce(func, wait) {
var timeout;
return function () {
var context = this;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context)
}, wait);
}
}
|
var time;
var test;
var tester; |
/*
* Copyright (c) 2016-present, Parse, LLC
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*/
import { center } from 'stylesheets/base.scss';
import Loader from 'components/Loader/Loader.react';
import PropTypes from 'lib/PropTypes';
import React from 'react';
import styles from 'components/LoaderContainer/LoaderContainer.scss';
//Loader wrapper component
//Wraps child component with a layer and <Loader/> centered
const LoaderContainer = ({ loading, hideAnimation, children, solid = true }) => (
<div className={styles.loaderContainer}>
<div className={styles.children}>
{children}
</div>
<div className={[styles.loaderParent, loading ? styles.visible : '', solid ? styles.solid : ''].join(' ')}>
{(hideAnimation || !loading) ? null : <Loader className={center}/>}
</div>
</div>
);
export default LoaderContainer;
LoaderContainer.propTypes = {
loading: PropTypes.bool.describe(
'State of the loader (true displays loader, false hides loader).'
),
hideAnimation: PropTypes.bool.describe(
'Whether to hide the animation within the container.'
),
solid: PropTypes.bool.describe(
'Optional flag to have an solid background. Defaults to true. If false an opacity of 70% is used.'
),
};
|
const fs = require('fs');
const data = require('./_data/products.json');
const allImagesUsedInProducts = {
primary: [],
secondary: []
};
data.forEach(obj => {
allImagesUsedInProducts.primary.push(obj.imgPrimary);
console.log(`Just pushed ${obj.imgPrimary} to primary!`);
obj.imgSecondarySet.forEach(img => {
allImagesUsedInProducts.secondary.push(img);
console.log(`Just pushed ${img} to secondary!`);
});
});
fs.writeFileSync(
'./allImagesUsedInProducts.json',
JSON.stringify(allImagesUsedInProducts, null, 2)
);
const primaryDupes = allImagesUsedInProducts.primary.filter(
img =>
allImagesUsedInProducts.primary.indexOf(img) !==
allImagesUsedInProducts.primary.lastIndexOf(img)
);
const secondaryDupes = allImagesUsedInProducts.secondary.filter(
img =>
allImagesUsedInProducts.secondary.indexOf(img) !==
allImagesUsedInProducts.secondary.lastIndexOf(img)
);
const crossDupes = allImagesUsedInProducts.primary.filter(img =>
allImagesUsedInProducts.secondary.includes(img)
);
console.log(`\n\nprimaryDupes === `, primaryDupes);
console.log('primaryDupes.length', primaryDupes.length);
console.log(`\n\nsecondaryDupes === `, secondaryDupes);
console.log('secondaryDupes.length', secondaryDupes.length);
console.log(`\n\ncrossDupes === `, crossDupes);
console.log('crossDupes.length', crossDupes.length);
|
console.log("Spirit Looks Server started");
var appSettings = {
ajaxMode:true,
gurus:[
{
keyword:"mevalana",
title:"MEVLANA CELALEDDİN RUMİ"
},
{
keyword:"mooji",
title:"MOOJİ"
},
{
keyword:"osho",
title:"OSHO"
},
{
keyword:"krishnamurti",
title:"JIDDU KRISHNAMURTI"
}
]
}
var port = 8083;
var express = require('express');
var fs = require('fs');
var mustache = require('mustache');
var modRewrite = require('connect-modrewrite');
var app = express();
var partials = new Object();
addPartial("init","views/init.mustache");
addPartial("main","views/main.mustache");
app.use(modRewrite([
'^/topic/(.*)$ /?q=$1&f=all&p=1 [L]',
]))
.use(express.static('public'));
var customTags = [ '<%', '%>' ];
mustache.tags = customTags;
function sendHomePage(vars,res){
var gurusSorted = appSettings.gurus.slice(0);
gurusSorted.sort(function(a,b) {
return a.title > b.title ? 1 : (a.title == b.title ? 0 : -1);
});
appSettings.gurusSorted = gurusSorted;
vars.appSettingsString = JSON.stringify(appSettings);
vars.appSettings = appSettings;
fs.readFile('views/home.mustache', 'utf8', function (err,data) {
var rendered = mustache.to_html(data, vars, partials);
res.send(rendered);
});
}
app.get('/', function (req, res) {
appSettings.ajaxMode = true;
if(Object.keys(req.query).length === 0){
var gurusLen = appSettings.gurus.length;
fStr = appSettings.gurus[0].keyword;
for(var i = 1; i < gurusLen; i++){
fStr += ','+ appSettings.gurus[i].keyword;
}
sendHomePage({"query":null,"filterStr":fStr},res);
}else{
if(typeof req.query.q == "undefined"){
var gurusLen = appSettings.gurus.length;
fStr = appSettings.gurus[0].keyword;
for(var i = 1; i < gurusLen; i++){
fStr += ','+ appSettings.gurus[i].keyword;
}
sendHomePage({"query":null,"filterStr":fStr},res);
}else{
if(req.query.p){
appSettings.ajaxMode = false;
}
var qStr = req.query.q.split('/')[0];
var fStr = req.query.f;
if(typeof req.query.f == "undefined" ){
res.redirect('/?q='+req.query.q+'&f=all&s=');
return;
}
if(fStr == "all"){
var gurusLen = appSettings.gurus.length;
fStr = appSettings.gurus[0].keyword;
for(var i = 1; i < gurusLen; i++){
fStr += ','+ appSettings.gurus[i].keyword;
}
}
if(appSettings.ajaxMode){
res.redirect('/#/'+qStr+'/'+fStr+'/'+req.query.s);
}else{
sendHomePage({"query":qStr,"filter":fStr,"solo":req.query.s,"result":JSON.stringify(search())},res);
}
}
}
});
app.get('/search', function(req,res){
var rv = new Object();
rv.result = search();
rv.error = 0;
res.send(rv);
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("Spirit Looks app listening at http://%s:%s", host, port)
})
function search(){
return [
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
},
{
"title":"Jiddu Krishnamurti - Kimim ben? ",
"abstract":"Try watching this video on www.youtube.com, or enable JavaScript if it is ... Hz. Mevlana ... Öfke, Kıskançlık ve Korkuyu Aşmak - Osho; Sevginin Kökleri ... Kitap / DNA'nın On İki Tabakası -; DNA ve Bilinçli Şifa - Sol Luckman ...",
"link":"kendimlekonusuyorum.blogspot.com/.../jiddu-krishnamurti-kimim-ben-turkce.html"
}
]
}
function addPartial(name,filepath){
var data = fs.readFileSync(filepath);
partials[name] = data.toString();
}
|
module.exports = {
url: 'http://api.giphy.com/v1/gifs/search',
api_key: 'dc6zaTOxFJmzC'
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M11 13h2v2h-2zm8-8H5v14h14V5zm-4 4h-4v2h2c1.1 0 2 .89 2 2v2c0 1.11-.9 2-2 2h-2c-1.1 0-2-.89-2-2V9c0-1.11.9-2 2-2h4v2z" opacity=".3" /><path d="M9 9v6c0 1.11.9 2 2 2h2c1.1 0 2-.89 2-2v-2c0-1.11-.9-2-2-2h-2V9h4V7h-4c-1.1 0-2 .89-2 2zm4 4v2h-2v-2h2zm-8 8h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2zM5 5h14v14H5V5z" /></React.Fragment>
, 'Looks6TwoTone');
|
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
const SMI_MAX = (1 << 30) - 1;
const SMI_MIN = -(1 << 30);
function testmulneg(a, b) {
var base = a * b;
assertEquals(-base, a * -b, "a * -b where a = " + a + ", b = " + b);
assertEquals(-base, -a * b, "-a * b where a = " + a + ", b = " + b);
assertEquals(base, -a * -b, "*-a * -b where a = " + a + ", b = " + b);
}
testmulneg(2, 3);
testmulneg(SMI_MAX, 3);
testmulneg(SMI_MIN, 3);
testmulneg(3.2, 2.3);
var x = { valueOf: function() { return 2; } };
var y = { valueOf: function() { return 3; } };
testmulneg(x, y);
// The test below depends on the correct evaluation order, which is not
// implemented by any of the known JS engines.
var z;
var v = { valueOf: function() { z+=2; return z; } };
var w = { valueOf: function() { z+=3; return z; } };
z = 0;
var base = v * w;
z = 0;
assertEquals(-base, -v * w);
z = 0;
assertEquals(base, -v * -w);
|
/**
* Created by Liara Anna Maria Rørvig on 24/07/2017.
*/
'use strict';
const Colours = require( '../../lib/colours.json' );
const Command = require( '../command.js' );
const dot = require( 'dot-object' );
const NAME = 'psn';
const HELP_SIMPLE = 'Get\'s a user from PSN';
const HELP_DETAILED = 'Get\'s and displays you information about a user you want to lookup';
const CAN_RUN = undefined;
class CommandPSN extends Command {
constructor() {
super( {
name : NAME,
help_simple : HELP_SIMPLE,
help_detailed : HELP_DETAILED,
can_run : CAN_RUN
} );
}
invoke( parameters, message, bot ) {
let command_handler = ( resolve, reject ) => {
let username = parameters[ 0 ];
bot.psn.getProfile( parameters[ 0 ], ( error, profile_data ) => {
if ( error ) {
console.log( error );
return reject( {
error : true,
message : error.toString()
} );
}
let onlineId = profile_data.onlineId;
let panelBgc = profile_data.panelBgc;
let colour = panelBgc ? parseInt( panelBgc.slice( panelBgc.length - 6 ), 16 ) : Colours.pink;
let reactions = [
{
emoji : '🏆',
data : {
action : 'GetTrophies',
data : username
}
}
];
let embed = {
title : onlineId + '\'s Profile',
description : profile_data.aboutMe,
color : colour,
fields : [
{
name : 'Region',
value : profile_data.region,
inline : true
},
{
name : 'PS Plus',
value : profile_data.plus === 1 ? 'Yes' : 'No',
inline : true
},
{
name : 'Level',
value : profile_data.trophySummary.level,
inline : true
},
{
name : 'Progress',
value : `${profile_data.trophySummary.progress}%`,
inline : true
},
{
name : 'Platinum', value : profile_data.trophySummary.earnedTrophies.platinum, inline : true
}, {
name : 'Gold', value : profile_data.trophySummary.earnedTrophies.gold, inline : true
}, {
name : 'Silver', value : profile_data.trophySummary.earnedTrophies.silver, inline : true
}, {
name : 'Bronze', value : profile_data.trophySummary.earnedTrophies.bronze, inline : true
}
],
author : {
name : 'PlayStation Network',
url : 'https://www.playstation.com/en-ca/network/',
icon_url : 'https://media.playstation.com/is/image/SCEA/navigation_home_ps-logo-us?$Icon$'
},
thumbnail : {
url : dot.pick( 'personalDetail.profilePictureUrl', profile_data ) || profile_data.avatarUrl
}
};
if ( profile_data.relation === 'friend' ) {
embed.fields.push( {
name : 'Friends', value : 'Yes', inline : true
} );
reactions.push( {
emoji : '➗',
data : {
action : 'RemoveFriend',
data : username
}
} );
} else if ( profile_data.relation === 'no relationship' || profile_data.relation === 'friend of friends' ) {
embed.fields.push( {
name : 'Friends', value : 'No', inline : true
} );
reactions.push( {
emoji : '➕',
data : {
action : 'AddFriend',
data : username
}
} );
}
if ( dot.pick( 'presence.primaryInfo.onlineStatus', profile_data ) === 'offline' ) {
embed.fields.push( {
name : 'Status', value : 'Offline', inline : true
} );
embed.fields.push( {
name : 'Last Seen',
value : new Date( profile_data.presence.primaryInfo.lastOnlineDate ).toUTCString(),
inline : true
} );
} else if ( dot.pick( 'presence.primaryInfo.onlineStatus', profile_data ) === 'online' ) {
embed.fields.push( {
name : 'Status', value : 'Online', inline : true
} );
}
if ( dot.pick( 'presence.primaryInfo.gameTitleInfo.titleName', profile_data ) ) {
embed.fields.push( {
name : 'Currently Playing',
value : dot.pick( 'presence.primaryInfo.gameTitleInfo.titleName', profile_data ),
inline : true
} );
}
let response = {
error : false,
message : {
embed : embed
},
reactions : reactions,
no_delete : true
};
return resolve( response );
} );
};
let promise = new Promise( command_handler );
return promise;
}
reactionRemoveGetTrophies( parameters, message, bot ) {
let username = parameters;
bot.psn.getUserTrophies( 0, 10, username, ( error, trophies ) => {
if ( error ) {
return message.channel.send( error.toString() );
}
trophies = trophies.trophyTitles;
trophies.forEach( trophy => {
let title = trophy.trophyTitleName;
let description = trophy.trophyTitleDetail;
let thumbnail = trophy.trophyTitleIconUrl;
let platform = trophy.trophyTitlePlatfrom || 'Unknown';
let colour = Colours.pink;
let embed = {
title : title,
description : description,
color : colour,
author : {
name : 'PlayStation Network',
url : 'https://www.playstation.com/en-ca/network/',
icon_url : 'https://media.playstation.com/is/image/SCEA/navigation_home_ps-logo-us?$Icon$'
},
thumbnail : {
url : thumbnail
},
fields : [
{
name : 'Platform',
value : platform,
inline : true
}
]
};
message.channel.send( {
embed : embed
} );
} );
} );
}
reactionRemoveAddFriend( parameters, message, bot ) {
let username = parameters;
bot.psn.sendFriendRequest( username, '', ( error ) => {
if ( error ) {
return message.channel.send( error.toString() );
}
message.channel.send( 'Asynchronous Bot> Friend Request Sent' );
} );
}
reactionRemoveRemoveFriend( parameters, message, bot ) {
let username = parameters;
bot.psn.removeFriend( username, ( error ) => {
if ( error ) {
return message.channel.send( error.toString() );
}
message.channel.send( 'Asynchronous Bot> Friend Removed' );
} );
}
}
module.exports = CommandPSN; |
/**
* Gets back data from json file
* This is called in index.html
*
* @author Loan Lassalle (loan.lassalle@heig-vd.ch)
* @since 13.09.2017
*/
/* eslint-disable semi */
// eslint-disable-next-line no-unused-vars
function Organization (xhttpResponse) {
this._login = xhttpResponse.login;
this._name = xhttpResponse.name === null ? this._login : xhttpResponse.name;
this._description = xhttpResponse.description === null ? '' : xhttpResponse.description;
const createdAt = new Date(xhttpResponse.created_at);
this._createdAt = (createdAt.getMonth() + 1) + '/' + createdAt.getDate() + '/' + createdAt.getFullYear();
/**
* Sorts by name
*/
const sortName = function (a, b) {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
};
/**
* Checks if value is unique
*/
const unique = function (value, index, self) {
return self.indexOf(value) === index
};
/**
* Repos sorted by name
*/
const repos = xhttpResponse.repos.sort(sortName);
/**
* Name of repos
*/
this._reposName = (function () {
const reposName = [];
for (const repo of repos) {
reposName.push(repo.name)
}
return reposName
}());
this._reposLength = repos.length;
/**
* Gets number of bytes for a repo and a language
*/
const getLanguagesBytes = function (repo, languageName) {
for (const language of repo.languages) {
if (languageName === language.name) {
return language.nbrBytes
}
}
};
/**
* Number of bytes by repos
*/
this._reposBytesSum = (function () {
const bytes = {};
for (const repoName of this._reposName) {
bytes[repoName] = 0
}
for (const repo of repos) {
for (const language of repo.languages) {
bytes[repo.name] += getLanguagesBytes(repo, language.name)
}
}
return bytes
}.call(this));
/**
* Biggest repo by number bytes
*/
this._repoBiggestBytes = (function () {
let repoBiggestBytes = {
name: '',
html_url: '',
created_at: '',
nbrBytes: 0
};
for (const repo of repos) {
if (this._reposBytesSum[repo.name] > repoBiggestBytes.nbrBytes) {
repoBiggestBytes = {
name: repo.name,
html_url: repo.html_url,
created_at: repo.created_at,
nbrBytes: this._reposBytesSum[repo.name]
}
}
}
return repoBiggestBytes
}.call(this));
/**
* Smallest repo by number bytes
*/
this._repoSmallestBytes = (function () {
let repoSmallestBytes = this._repoBiggestBytes;
for (const repo of repos) {
if (this._reposBytesSum[repo.name] < repoSmallestBytes.nbrBytes) {
repoSmallestBytes = {
name: repo.name,
html_url: repo.html_url,
created_at: repo.created_at,
nbrBytes: this._reposBytesSum[repo.name]
}
}
}
return repoSmallestBytes
}.call(this));
/**
* Languages sorted by name
*/
const languages = (function () {
const languages = [];
for (const repo of repos) {
for (const language of repo.languages) {
languages.push(language)
}
}
return languages.sort(sortName)
}());
/**
* Name of languages
*/
this._languagesName = (function () {
const languagesName = [];
for (const language of languages) {
languagesName.push(language.name)
}
return languagesName.filter(unique)
}.call(this));
this._languagesNameLength = this._languagesName.length;
/**
* Gets name of languages of a repo
*/
const getLanguagesName = function (repo) {
const languagesName = [];
for (const language of repo.languages) {
languagesName.push(language.name)
}
return languagesName.sort(sortName)
};
/**
* Number of bytes by repos and languages
*/
this._languagesBytes = (function () {
const bytes = {};
for (const languageName of this._languagesName) {
bytes[languageName] = []
}
for (const repo of repos) {
for (const languageName of this._languagesName) {
if (getLanguagesName(repo).contains(languageName)) {
bytes[languageName].push(getLanguagesBytes(repo, languageName))
} else {
bytes[languageName].push(0)
}
}
}
return bytes
}.call(this));
/**
* Number of bytes by languages
*/
this._languagesBytesSum = (function () {
const bytesSum = {};
for (const languageName of this._languagesName) {
bytesSum[languageName] = 0
}
for (const languageName of this._languagesName) {
for (const bytes of this._languagesBytes[languageName]) {
bytesSum[languageName] += bytes
}
}
return bytesSum
}.call(this));
/**
* Biggest language by number bytes
*/
this._languageBiggestBytes = (function () {
let languageBiggestBytes = {
name: '',
nbrBytes: 0
};
for (const languageName of this._languagesName) {
if (this._languagesBytesSum[languageName] > languageBiggestBytes.nbrBytes) {
languageBiggestBytes = {
name: languageName,
nbrBytes: this._languagesBytesSum[languageName]
}
}
}
return languageBiggestBytes
}.call(this));
/**
* Smallest language by number bytes
*/
this._languageSmallestBytes = (function () {
let languageSmallestMin = this._languageBiggestBytes;
for (const languageName of this._languagesName) {
if (this._languagesBytesSum[languageName] < languageSmallestMin.nbrBytes) {
languageSmallestMin = {
name: languageName,
nbrBytes: this._languagesBytesSum[languageName]
}
}
}
return languageSmallestMin
}.call(this));
this._summary = (function () {
const summary = {};
summary['Organization Name'] = this._name;
if (this._description.length > 0) {
summary['Description'] = this._description;
}
summary['Created at'] = this._createdAt;
summary['Number of repos'] = this._reposLength;
summary['Number of languages'] = this._languagesNameLength;
const minimumBytesFor = 'Minimum of bytes for ' + this._languageSmallestBytes.name;
summary[minimumBytesFor] = this._languagesNameLength;
const maximumBytesFor = 'Maximum of bytes for ' + this._languageSmallestBytes.name;
summary[maximumBytesFor] = this._languagesNameLength;
return summary;
}.call(this));
}
/**
* Checks if object is in array
*
* @param obj object to check
* @returns {boolean} true if object is in array, false otherwise
*/
// eslint-disable-next-line no-extend-native
Array.prototype.contains = function (obj) {
let i = this.length;
while (i--) {
if (this[i] === obj) {
return true
}
}
return false
};
|
export const ic_view_list_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none","opacity":".87"},"children":[]},{"name":"path","attribs":{"d":"M5 11h2v2H5zm0 4h2v2H5zm0-8h2v2H5zm4 0h9v2H9zm0 8h9v2H9zm0-4h9v2H9z","opacity":".3"},"children":[]},{"name":"path","attribs":{"d":"M3 5v14h17V5H3zm4 12H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V7h2v2zm11 8H9v-2h9v2zm0-4H9v-2h9v2zm0-4H9V7h9v2z"},"children":[]}]}; |
define(['directives/directives'], function (directives) {
'use strict';
directives.directive('enzoCounter', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
var maxlength = element.attr('maxlength') || 10;
var opts = angular.extend({
maxCharacters: maxlength,
statusText: I18n.t('enzo.maxlength.statusText'),
alertText: I18n.t('enzo.maxlength.alertText'),
slider: true,
events: ['keyup', 'focus'],
statusClass: 'counter-status',
}, scope.$eval(attr.enzoMaxlength));
$(element).maxlength(opts);
}
};
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:b6ef9ff092f2c9e0226f5c24743bd00cb60ef65406f09913c92493a140e05daa
size 5176
|
// エラーメッセージ
var M = require('../message');
// M.RP_BETWEEN_RT
// M.RP_POS
// rp ルビ対応しない場合のカッコを囲む
module.exports = {
autoClose: 'rb,rt,rtc,rp,/*',
parent: 'ruby',
contents: {
phrasing: true
},
rules: [
posRule
]
};
/**
* rt または rtc 要素の直前または直後のどちらかに
* いれなければいけません。
* rt 要素の間に入れることはできません。
* @method
* @param {Object} node
* @param {Function} e
* @return {Boolean} pass
*/
function posRule (node, e) {
var children = node.parent.children;
var idx = children.indexOf(node);
var before = children[idx - 1];
var after = children[idx + 1];
var bName = before && before.nodeType === 1 && before.tagName || null;
var aName = after && after.nodeType === 1 && after.tagName || null;
if (bName === 'rt' && aName === 'rt') {
e(M.RP_BETWEEN_RT);
return false;
} else if (bName === 'rt' || bName === 'rtc' || aName === 'rt' || aName === 'rt') {
return true;
} else {
e(M.RP_POS);
return false;
}
} |
import React from 'react'
import BaseLayout from 'client/components/layout/BaseLayout'
import TypesContainer from 'client/containers/TypesContainer'
import PropTypes from 'prop-types'
import {
Row,
Col,
SimpleSelect,
Typography
} from 'ui/admin'
import GenericForm from 'client/components/GenericForm'
import extensions from 'gen/extensions'
import compose from 'util/compose'
import {withKeyValues} from 'client/containers/generic/withKeyValues'
import {graphql} from '../../../client/middleware/graphql'
const TYPE = 'Word'
class WordContainer extends React.Component {
constructor(props) {
super(props)
this.state = props.keyValueMap.WordContainerState || {
currentPair: '',
currentCategory: ''
}
this.prepareTypeSetting()
this.typeContainer = React.createRef()
}
render() {
const startTime = (new Date()).getTime()
const {history, location, match, wordCategorys} = this.props
const {currentPair, currentCategory} = this.state
const selectFrom = [], selectTo = [], pairs = [], selectPairs = [], categoryPair = []
const a = currentPair.split('/'), fromSelected = a[0].trim(), toSelected = (a.length > 1 ? a[1].trim() : '')
extensions.word.options.types[0].fields.forEach((a) => {
if (a.name.length === 2) {
extensions.word.options.types[0].fields.forEach((b) => {
if (b.name.length === 2 && b.name !== a.name) {
const name = a.name + ' / ' + b.name
if (!pairs.includes(name) && !pairs.includes(b.name + ' / ' + a.name)) {
pairs.push(name)
selectPairs.push({value: name, name})
}
}
})
}
})
categoryPair.push({value: 'all', name: 'All'})
wordCategorys && wordCategorys.results.forEach(e => {
categoryPair.push({value: e._id, name: e.name})
})
const content = (
<BaseLayout>
<Typography variant="h3" component="h1" gutterBottom>Words</Typography>
<Row>
<Col md={6}>
<SimpleSelect
label="Language pair"
value={currentPair}
onChange={this.handlePairChange.bind(this)}
items={selectPairs}
/>
<SimpleSelect
label="Category"
value={currentCategory}
onChange={this.handleCategoryChange.bind(this)}
items={categoryPair}
/>
</Col>
<Col md={6}>
{fromSelected && toSelected && <GenericForm fields={{
[fromSelected]: {value: '', label: fromSelected},
[toSelected]: {value: '', label: toSelected}
}}
onValidate={this.handleAddValidate}
onClick={this.handleAddClick.bind(this)}/>}
</Col>
</Row>
<TypesContainer onRef={ref => (this.typeContainer = ref)}
baseUrl={location.pathname}
title={false}
noLayout={true}
fixType={ TYPE }
settings={this.settings}
baseFilter={currentCategory && currentCategory !== 'all' ? 'categories:' + currentCategory : ''}
history={history} location={location} match={match}/>
</BaseLayout>
)
console.info(`render ${this.constructor.name} in ${(new Date()).getTime() - startTime}ms`)
return content
}
handleAddValidate(e) {
for (const k of Object.keys(e)) {
if (e[k] === '') return {isValid:false}
}
return {isValid:true}
}
handleAddClick(e) {
const {wordCategorys} = this.props
const {currentCategory} = this.state
let cat = null
if (currentCategory && wordCategorys.results)
cat = wordCategorys.results.filter(f => f._id === currentCategory)
const submitData = Object.assign({}, e, {categories: cat && cat.length ? cat[0]._id : null})
extensions.word.options.types[0].fields.forEach((a) => {
if (submitData[a.name] === undefined) {
submitData[a.name] = null
}
})
const optimisticData = Object.assign({}, submitData)
optimisticData.categories = cat
this.typeContainer.createData(submitData, optimisticData)
}
prepareTypeSetting() {
const {currentPair} = this.state
const settings = {[TYPE]: {columns: {}}}
const a = currentPair.split('/'), fromSelected = a[0].trim(), toSelected = (a.length > 1 ? a[1].trim() : '')
extensions.word.options.types[0].fields.forEach((a) => {
if (a.name.length === 2) {
settings[TYPE].columns[a.name] = false
}
})
if (fromSelected) {
settings[TYPE].columns[fromSelected] = true
}
if (toSelected) {
settings[TYPE].columns[toSelected] = true
}
this.settings = settings
}
refrehTypeSetting() {
this.props.setKeyValue({key: 'WordContainerState', value: this.state})
this.prepareTypeSetting()
}
handlePairChange(e) {
const o = {currentPair: e.target.value}
this.setState(o, this.refrehTypeSetting)
}
handleCategoryChange(e) {
const o = {currentCategory: e.target.value}
this.setState(o, this.refrehTypeSetting)
}
}
WordContainer.propTypes = {
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
match: PropTypes.object.isRequired,
/* To get and set settings */
setKeyValue: PropTypes.func.isRequired,
keyValueMap: PropTypes.object
}
const WordContainerWithGql = compose(
graphql(`query{wordCategorys{results{_id name}}}`, {
props: ({data: {wordCategorys}}) => ({
wordCategorys
})
})
)(WordContainer)
export default withKeyValues(WordContainerWithGql, ['WordContainerState'])
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Timeline = mongoose.model('Timeline'),
_ = require('lodash');
/**
* Create a Timeline
*/
exports.createTimeline = function(req, res) {
var timeline = new Timeline({});
timeline.owner = req.user;
timeline.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(timeline);
}
});
};
/**
* Show the current Timeline
*/
exports.read = function(req, res) {
res.jsonp(req.timeline);
};
/**
* Update a Timeline
*/
exports.updateTimeline = function(req, res) {
var timeline = req.timeline ;
timeline = _.extend(timeline , req.body);
timeline.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(timeline);
}
});
};
/**
* Delete an Timeline
*/
exports.deleteTimeline = function(req, res) {
var timeline = req.timeline ;
timeline.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(timeline);
}
});
};
/**
* List of Timelines
*/
exports.listTimelines = function(req, res) {
Timeline.find().sort('-created').populate('owner', 'username').exec(function(err, timelines) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(timelines);
}
});
};
/**
* Timeline middleware
*/
exports.timelineByID = function(req, res, next, id) {
Timeline.findById(id).populate('owner', 'username').exec(function(err, timeline) {
if (err) return next(err);
if (! timeline) return next(new Error('Failed to load Timeline ' + id));
req.timeline = timeline ;
next();
});
};
/**
* Timeline authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.timeline.owner.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
'use strict';
//Setting up route
angular.module('categories').config(['$stateProvider',
function($stateProvider) {
// Categories state routing
$stateProvider.
// CREATE
state('createCategory', {
url: '/categories/create',
templateUrl: 'modules/categories/views/create-category.client.view.html'
}).
// READ Categories
state('listCategories', {
url: '/categories',
templateUrl: 'modules/categories/views/categories.client.view.html'
}).
// READ Single Category
state('viewCategory', {
url: '/categories/:categoryId',
templateUrl: 'modules/categories/views/view-category.client.view.html'
}).
// EDIT Single Category
state('editCategory', {
url: '/categories/:categoryId/edit',
templateUrl: 'modules/categories/views/edit-category.client.view.html'
});
}
]);
|
//[Skin Customization]
webix.skin.flat.barHeight=45;webix.skin.flat.tabbarHeight=45;webix.skin.flat.rowHeight=34;webix.skin.flat.listItemHeight=34;webix.skin.flat.inputHeight=38;webix.skin.flat.layoutMargin.wide=10;webix.skin.flat.layoutMargin.space=10;webix.skin.flat.layoutPadding.space=10;
webix.skin.set('flat') |
/*
* Clearest Framework
* Provided under MIT License.
* Copyright (c) 2012-2015 Illya Kokshenev <sou@illya.com.br>
*/
"use strict";
var commons = require("./commons"),
inside = commons.inside,
isValue = commons.is.value,
promise = commons.promise;
/**
* Subscribes an observer on event key (k) of object (o).
* Event key commons.constant.ANY means any event of object o.
*
* @param o object
* @param k event key (string),
* @param observer = function(o, k, eventData)
* @returns {boolean} true: if observer subscribed, false: if observer already subscribed to that object, and undefined if subscription were not possible
*/
var NULL_VALUE = null, ANY = commons.constant.ANY;
function subscribe(o, k, observer) {
// ensure the object is not null or value type
if (o === undefined ||
o === null ||
isValue(o))
return;
var h_ = inside(observer),
o_ = inside(o), // get clearest objects inside handler and o
obs = h_.obs = h_.obs || [], // list observables
sub = o_.sub = o_.sub || {}; // subscribers by key
k = k || ANY;
var subk = sub[k],
exist = false,
index = -1;
if (!subk && !sub[ANY]) {
// new subscriber
sub[k] = [observer];
index = 0;
}
else {
// subscriber exists
if (sub[ANY]) { // first, check if there is already ANY subscription
index = sub[ANY].indexOf(observer);
if (index >= 0) {
exist = true;
k = ANY; // switch to ANY record
}
}
if (!exist) {
// check for subk
if (!subk) {
// new key
sub[k] = [observer];
index = 0;
}
else {
index = subk.indexOf(observer);
if (index < 0) {
// try to reuse memory
index = subk.indexOf(NULL_VALUE);
if (index < 0)
index = subk.push(observer) - 1; // new element
else
subk[index] = observer; // reused index
}
else
exist = true; // subscription already exists
}
}
}
// create new record in observer if needed
if (!exist) {
obs.push({
k: k,
o: o,
idx: index
});
return true;
}
else
return false;
}
/**
* Removes observer from all observable objects
* @param observer
*/
function unsubscribe(observer) {
if (!observer || !observer.__clearest__)
return; //nothing to do, not an observe
var obs = observer.__clearest__.obs;
if (obs === undefined)
return;
obs.forEach(
function (record) {
// clean up references
record.o.__clearest__.sub[record.k][record.idx] = NULL_VALUE;
});
// drop reference to observables
delete observer.__clearest__.obs;
}
/**
* Notifies all observers of object (o) with event (k) and event data (eventData)
*
* @param o observable object
* @param k event key string or (commons.constant.ANY)
* @param event data argument passed to observer
* @returns {*} count of notifications sent or false
*/
function notify(o, k, event) {
var count = 0;
if (o === undefined ||
o === null || o.__clearest__ === undefined)
return false; //cannot have subscribers
var sub = o.__clearest__.sub;
if (!sub) return false;
function _notifyInternal(subscribers, exclude) {
var count = 0;
if (subscribers !== undefined) {
subscribers.forEach(function (handler) {
// call observer
if (handler === NULL_VALUE ||
(exclude !== undefined && exclude.indexOf(handler) >= 0))
return; // skip
handler(event, o, k);
count++;
});
}
return count;
}
var anyKeySubscribers = sub[ANY];
//first, notify subscribers for ANY key
if (anyKeySubscribers) {
count += _notifyInternal(anyKeySubscribers);
}
if (k !== ANY) {
// notify subscribers for key k != ANY
count += _notifyInternal(sub[k], anyKeySubscribers);
}
else {
// k == ANY: notify everyone esle, except anyKeySubscribers (thet were already notified)
for (var k in sub) {
count += _notifyInternal(sub[k], anyKeySubscribers);
}
}
return count;
}
/**
* Sugar function that does two things:
*
* 1) assigns fields of (o) to corresponing key/values
* 2) notifies o with the corresponding events and data
*
* Foe example:
*
* send(o, {foo:42,bar:true})
*
* is equivalent to
*
* o.foo = 42; notify(o,'foo',42);
* o.bar = true; notify(o,'bar',true);
*
* send(o, {foo:42,bar:true}, 'changed')
*
* is equivalent to
* o.foo = 42; notify(o,'foo','changed');
* o.bar = true; notify(o,'bar','changed');
*
* @param o
* @param values
* @param a optional data argument
*/
function send(o, values, a, b) {
if (typeof values === 'string') {
// field notation
o[values] = a;
notify(o, values, b === undefined ? a : b);
}
else {
// object notation
for (var k in values) {
var v = o[k] = values[k];
notify(o, k, a === undefined ? v : a);
}
}
}
module.exports = {
subscribe: subscribe,
unsubscribe: unsubscribe,
notify: notify,
send: send
}
|
/**
* @file Group.js
* @author TalesM
*
*/
import Item from './Item';
//Defining subclass.
Group.prototype = Object.create(Item.prototype);
Group.prototype.constructor = Group;
/**
* The group class
* @constructor
* @base Item
* @param {Array} id
* @param {String} name
* @param {String} description
* @param {Boolean} closed
* @param {Item[]} dependencies
* @param {Item[]} children
*/
function Group(id, name, description, closed, dependencies, children) {
Item.call(this, id, null, name, description, dependencies);
this.subTasks = [];
this.closed = closed;
if(children){
children.forEach(function(kid) {
if(kid.parent || kid.hasDependency(this) || this.hasDependency(kid))
return;//continue
kid.parent = this;
this.subTasks.push(kid);
}, this);
}
}
Group.prototype.hasDependent = function(task){
return Item.prototype.hasDependent.call(this, task) || (this.parent && this.parent.hasDependent(task));
};
Group.prototype.isClosed = function() {
return this.closed || this.subTasks.every(function(kid){
return kid.isClosed();
});
};
/**
* Add a kid to group.
* @param {Item} task - The item to add.
* @return {Boolean} whether it was successful.
*/
Group.prototype.addKid = function(task){
if(!task || task.parent || task.hasDependency(this) || task.hasDependency(task))
return false;
task.parent = this;
let nextId = 1;
if(this.subTasks.length > 0){
nextId = this.subTasks[this.subTasks.length-1].id+1;
}
task.id = nextId;
this.subTasks.push(task);
return true;
};
/**
* Remove a kid from group.
* @param {Item} item.
* @return {Boolean} whether it was successful.
*/
Group.prototype.removeKid = function(task){
var subTasks = this.subTasks;
var pos=subTasks.indexOf(task);
if(pos === -1)
return false;
task.parent = null;
subTasks[pos] = null; //Soft delete.
subTasks.splice(pos, 1);
return true;
};
/**
* Removes a kid an puts another in its place.
* @param {Item} kid
* @param {Item} fosterKid
*
* @b Important! It do not reasing ids, you have to do it on your own.
*/
Group.prototype.swap = function(kid, fosterKid){
var ind = this.subTasks.indexOf(kid);
if(ind===-1)
throw Error('Swapping the kid of another person.');
if(fosterKid.parent)
throw Error('Foster kid already has a parent.');
kid.parent = null;
fosterKid.parent = this;
this.subTasks[ind] = fosterKid;
};
/**
* Get the number of children
* @returns {Number}
*/
Group.prototype.size = function(){
return this.subTasks.length;
};
/**
* Get the regular spent time (not overdue).
* @returns {Number}
*/
Group.prototype.spentReg = function() {
return this.subTasks.reduce(function(previous, task) {
return previous+task.spentReg();
}, 0);
};
/**
* Get the remaining time.
* @returns {Number}
*/
Group.prototype.remaining = function() {
return this.subTasks.reduce(function(previous, task) {
return previous+task.remaining();
}, 0);
};
/**
* Get the overdue time.
* @returns {Number}
*/
Group.prototype.overdue = function() {
return this.subTasks.reduce(function(previous, task) {
return previous+task.overdue();
}, 0);
};
/**
* Get the leftover time
* @returns {Number}
*/
Group.prototype.leftover = function() {
return this.subTasks.reduce(function(previous, task) {
return previous+task.leftover();
}, 0);
};
/**
* Get time you can't you use but have to wait anyway.
* It happens when a group have a 'hole' inside: a period of time
* where no subTask can be active, having some finished before and
* others starting later.
* @returns {Number}
*/
Group.prototype.unreachable = function(){
return this.end() - Item.prototype.end.call(this);
};
Group.prototype.end = function() {
var betterEnd = Item.prototype.end.call(this);
var kidsEnd = this.subTasks.reduce(function(larger, task){
return Math.max(larger, task.end());
}, 0);
return Math.max(betterEnd, kidsEnd);
};
Group.prototype.toArray = function () {
return this.subTasks;
}
export default Group;
|
const electron = require('electron')
const ipcRenderer = electron.ipcRenderer
let lastMsgId = 0
window.quitAndInstall = function () {
electron.remote.autoUpdater.quitAndInstall()
}
ipcRenderer.on('console', (event, consoleMsg) => {
console.log(consoleMsg)
})
ipcRenderer.on('message', (event, data) => {
showMessage(data.msg, data.hide, data.replaceAll)
})
function showMessage(message, hide = true, replaceAll = false) {
const messagesContainer = document.querySelector('.messages-container')
const msgId = lastMsgId++ + 1
const msgTemplate = `<div id="${msgId}" class="alert alert-info alert-info-message animated fadeIn">${message}</div>`
if (replaceAll) {
messagesContainer.innerHTML = msgTemplate
} else {
messagesContainer.insertAdjacentHTML('afterbegin', msgTemplate)
}
if (hide) {
setTimeout(() => {
const msgEl = document.getElementById(msgId)
msgEl.classList.remove('fadeIn')
msgEl.classList.add('fadeOut')
}, 4000)
}
}
|
import React from 'react';
import EventEmitter from 'events';
import PlugBoardWiring from './PlugBoard/PlugBoardWiring';
import NewPlugBoardWiring from './PlugBoard/NewPlugBoardWiring';
import Well from 'react-bootstrap/lib/Well';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import ListGroup from 'react-bootstrap/lib/ListGroup';
import ListGroupItem from 'react-bootstrap/lib/ListGroupItem';
export const PLUGBOARD_MAX_SIZE = 10;
export default class PlugBoard extends React.Component {
constructor (props) {
super(props);
this.state = {
isAdding: false
};
}
render () {
let wirings = this.props.wirings.map((wiring) => {
let key = wiring.join('');
return (
<ListGroupItem key={key}>
<PlugBoardWiring wiring={wiring} index={key} eventManager={this.props.eventManager} />
</ListGroupItem>
);
});
let addWiring;
if(this.props.wirings.length < PLUGBOARD_MAX_SIZE) {
addWiring = (
<Well className="plugBoardAddWiring">
<ControlLabel>New Wiring</ControlLabel>
<NewPlugBoardWiring wirings={this.props.wirings} eventManager={this.props.eventManager} />
</Well>
);
}
return (
<div className="enigmaPlugBoard">
<ListGroup className="enigmaPlugBoardWirings">
{wirings}
</ListGroup>
{addWiring}
</div>
);
}
}
PlugBoard.propTypes = {
wirings: React.PropTypes.array.isRequired,
eventManager: React.PropTypes.instanceOf(EventEmitter)
};
PlugBoard.defaultProps = {
wirings: []
};
|
var webpack = require('webpack');
module.exports = {
entry: './demo.js',
output: {
filename: './demo.bundle.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
drop_console: false,
}})
]
} |
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
var DEFAULT_VALUE = Object.freeze([".js", ".json", ".node"])
/**
* Gets `tryExtensions` property from a given option object.
*
* @param {object|undefined} option - An option object to get.
* @returns {string[]|null} The `tryExtensions` value, or `null`.
*/
function get(option) {
if (option && option.tryExtensions && Array.isArray(option.tryExtensions)) {
return option.tryExtensions.map(String)
}
return null
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Gets "tryExtensions" setting.
*
* 1. This checks `options` property, then returns it if exists.
* 2. This checks `settings.node` property, then returns it if exists.
* 3. This returns `[".js", ".json", ".node"]`.
*
* @param {RuleContext} context - The rule context.
* @returns {string[]} A list of extensions.
*/
module.exports = function getTryExtensions(context) {
return (
get(context.options && context.options[0]) ||
get(context.settings && context.settings.node) ||
DEFAULT_VALUE
)
}
|
var SubmitB = React.createClass({displayName: "SubmitB",
getInitialState: function(){
return{value: '', text: false, para: '', position: [], keywords: []};
},
handleClick : function(e){
this.setState({value: this.refs['a'].state.text,
text: this.refs['b'].state.text,
para: this.refs['c'].state.value,
position: this.refs['d'].state.position,
keywords: this.refs['e'].state.keywords
}, function () {
console.log(this.state.value);
console.log(this.state.text);
console.log(this.state.para);
console.log(this.state.position);
console.log(this.state.keywords);
});
},
render : function(){
var value = this.state.value;
var text = this.state.text;
var para = this.state.para;
var position = this.state.position;
return (
React.createElement("div", null,
React.createElement(TextImage, {ref: "b", value: text}),
React.createElement(TextV, {ref: "c", value: para}),
React.createElement(FontSize, {ref: "a", value: value}),
React.createElement(Imagepos, {ref: "d", value: position}),
React.createElement(Keywords, {ref: "e", value: this.state.keywords}),
React.createElement("button", {onClick: this.handleClick, id: "button"}, "Submit")
)
);
}
});
var Imagepos = React.createClass({displayName: "Imagepos",
getInitialState: function(){
return {position: this.props.value, clicks: 0};
},
handleChange: function(event){
var OFFSET_X = 606;
var OFFSET_Y = 75 ;
var pos_x = event.clientX?(event.clientX):event.pageX;
var pos_y = event.clientY?(event.clientY):event.pageY;
if(this.state.clicks == 0){
this.setState({clicks: this.state.clicks + 1 , position: [pos_x-OFFSET_X, pos_y-OFFSET_Y]}, function(){
console.log(this.state.position);
});
}
else if(this.state.clicks == 1){
this.setState({clicks: this.state.clicks + 1 , position: [this.state.position[0], this.state.position[1], pos_x-OFFSET_X, pos_y-OFFSET_Y]}, function(){
console.log(this.state.position);
});
}
else{
document.getElementById("cross").onclick = function() { return false; } ;
}
},
render:function(){
return(
React.createElement("form", {name: "pointform", method: "post"},
React.createElement("div", {id: "pointer_div"},
React.createElement("img", {src: "test.png", id: "cross", onClick: this.handleChange})
)
)
);
}
});
var TextV = React.createClass({displayName: "TextV",
getInitialState: function(){
return {value: this.props.value};
},
handleChange : function(e){
this.setState({value: e.target.value});
},
render: function () {
var value = this.state.value;
return(React.createElement("div", {className: "form-group", id: "textV"},
React.createElement("label", {className: "col-sm-1 control-label"}, "Text"),
React.createElement("div", {className: "col-sm-4"},
React.createElement("textarea", {className: "form-control", rows: "10", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.state.value})
)
)
);
}
});
var TextImage = React.createClass({displayName: "TextImage",
getInitialState: function(){
return {text: this.props.value};
},
itsText: function(e){
this.setState({text: true});
},
itsImage: function(e){
this.setState({text: false});
},
render: function(){
return(
React.createElement("div", {className: "radio", id: "TextOrImage"},
React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsText}), "Text"),
React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsImage}), "Image")
)
);
}
});
var FontSize = React.createClass({displayName: "FontSize",
getInitialState: function(){
return {text: this.props.value};
},
handleChange : function(e){
this.setState({text: e.target.value});
},
render: function () {
return(React.createElement("div", {className: "form-group", id: "fontSize"},
React.createElement("label", {className: "col-sm-1 control-label"}, "FontSize"),
React.createElement("div", {className: "col-sm-1"},
React.createElement("textarea", {className: "form-control", rows: "1", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.text})
)
)
);
}
});
var FinalKeywords = React.createClass({displayName: "FinalKeywords",
render: function() {
var createItem = function(itemText, index) {
return React.createElement("li", {key: index + itemText}, itemText);
};
return (React.createElement("div", {id: "display"},
React.createElement("ul", null, this.props.items.map(createItem))));
}
});
var Keywords = React.createClass({displayName: "Keywords",
getInitialState: function() {
return {keywords: [], text: ''};
},
onChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var nextkeywords = this.state.keywords.concat([this.state.text]);
var nextText = '';
this.setState({keywords: nextkeywords, text: nextText});
},
render: function() {
return (
React.createElement("div", {id: "keywords"},
React.createElement("label", {className: "col-sm-1 control-label"}, "Keywords"),
React.createElement(FinalKeywords, {items: this.state.keywords}),
React.createElement("form", {onSubmit: this.handleSubmit},
React.createElement("input", {onChange: this.onChange, value: this.state.text}),
React.createElement("button", null, "Add")
)
)
);
}
});
React.render(React.createElement(SubmitB, null) , document.getElementById('main'));
|
/**
* @author dforrer / https://github.com/dforrer
* Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch)
*/
/**
* @param object THREE.Object3D
* @constructor
*/
var RemoveObjectCommand = function ( object ) {
Command.call( this );
this.type = 'RemoveObjectCommand';
this.name = 'Remove Object';
this.object = object;
this.parent = ( object !== undefined ) ? object.parent : undefined;
if ( this.parent !== undefined ) {
this.index = this.parent.children.indexOf( this.object );
}
};
RemoveObjectCommand.prototype = {
execute: function () {
var scope = this.editor;
this.object.traverse( function ( child ) {
scope.removeHelper( child );
} );
this.parent.remove( this.object );
this.editor.select( this.parent );
this.object.traverse((object) => {
delete this.editor.animations[object.uuid];
if (object.geometry) {
delete this.editor.animations[object.geometry.uuid];
delete this.editor.geometryData[object.geometry.uuid];
}
});
this.editor.signals.objectRemoved.dispatch( this.object );
this.editor.signals.sceneGraphChanged.dispatch();
},
undo: function () {
var scope = this.editor;
this.object.traverse( function ( child ) {
if ( child.geometry !== undefined ) scope.addGeometry( child.geometry );
if ( child.material !== undefined ) scope.addMaterial( child.material );
scope.addHelper( child );
} );
this.parent.children.splice( this.index, 0, this.object );
this.object.parent = this.parent;
this.editor.select( this.object );
this.editor.signals.objectAdded.dispatch( this.object );
this.editor.signals.sceneGraphChanged.dispatch();
},
toJSON: function () {
var output = Command.prototype.toJSON.call( this );
output.object = this.object.toJSON();
output.index = this.index;
output.parentUuid = this.parent.uuid;
return output;
},
fromJSON: function ( json ) {
Command.prototype.fromJSON.call( this, json );
this.parent = this.editor.objectByUuid( json.parentUuid );
if ( this.parent === undefined ) {
this.parent = this.editor.scene;
}
this.index = json.index;
this.object = this.editor.objectByUuid( json.object.object.uuid );
if ( this.object === undefined ) {
var loader = new THREE.ObjectLoader();
this.object = loader.parse( json.object );
}
}
};
|
/**
* @license Angular v5.2.6
* (c) 2010-2018 Google, Inc. https://angular.io/
* License: MIT
*/
import { APP_ID, ApplicationRef, Inject, Injectable, InjectionToken, Injector, NgModule, NgZone, Optional, PLATFORM_ID, PLATFORM_INITIALIZER, RendererFactory2, Testability, Version, ViewEncapsulation, createPlatformFactory, platformCore, ɵALLOW_MULTIPLE_PLATFORMS } from '@angular/core';
import { BrowserModule, DOCUMENT, TransferState, ɵBrowserDomAdapter, ɵNAMESPACE_URIS, ɵSharedStylesHost, ɵTRANSITION_ID, ɵescapeHtml, ɵflattenStyles, ɵgetDOM, ɵsetRootDomAdapter, ɵshimContentAttribute, ɵshimHostAttribute } from '@angular/platform-browser';
import { __extends } from 'tslib';
import { ɵAnimationEngine } from '@angular/animations/browser';
import { PlatformLocation, ɵPLATFORM_SERVER_ID } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpBackend, HttpClientModule, HttpHandler, XhrFactory, ɵinterceptingHandler } from '@angular/common/http';
import { BrowserXhr, Http, HttpModule, ReadyState, RequestOptions, XHRBackend, XSRFStrategy } from '@angular/http';
import { ɵplatformCoreDynamic } from '@angular/platform-browser-dynamic';
import { NoopAnimationsModule, ɵAnimationRendererFactory } from '@angular/platform-browser/animations';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { parse } from 'url';
import { DomElementSchemaRegistry } from '@angular/compiler';
import { filter } from 'rxjs/operator/filter';
import { first } from 'rxjs/operator/first';
import { toPromise } from 'rxjs/operator/toPromise';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var domino = require('domino');
/**
* @param {?} methodName
* @return {?}
*/
function _notImplemented(methodName) {
return new Error('This method is not implemented in DominoAdapter: ' + methodName);
}
/**
* Parses a document string to a Document object.
* @param {?} html
* @param {?=} url
* @return {?}
*/
function parseDocument(html, url$$1) {
if (url$$1 === void 0) { url$$1 = '/'; }
var /** @type {?} */ window = domino.createWindow(html, url$$1);
var /** @type {?} */ doc = window.document;
return doc;
}
/**
* Serializes a document to string.
* @param {?} doc
* @return {?}
*/
function serializeDocument(doc) {
return (/** @type {?} */ (doc)).serialize();
}
/**
* DOM Adapter for the server platform based on https://github.com/fgnass/domino.
*/
var DominoAdapter = /** @class */ (function (_super) {
__extends(DominoAdapter, _super);
function DominoAdapter() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @return {?}
*/
DominoAdapter.makeCurrent = /**
* @return {?}
*/
function () { ɵsetRootDomAdapter(new DominoAdapter()); };
/**
* @param {?} error
* @return {?}
*/
DominoAdapter.prototype.logError = /**
* @param {?} error
* @return {?}
*/
function (error) { console.error(error); };
/**
* @param {?} error
* @return {?}
*/
DominoAdapter.prototype.log = /**
* @param {?} error
* @return {?}
*/
function (error) {
// tslint:disable-next-line:no-console
console.log(error);
};
/**
* @param {?} error
* @return {?}
*/
DominoAdapter.prototype.logGroup = /**
* @param {?} error
* @return {?}
*/
function (error) { console.error(error); };
/**
* @return {?}
*/
DominoAdapter.prototype.logGroupEnd = /**
* @return {?}
*/
function () { };
/**
* @return {?}
*/
DominoAdapter.prototype.supportsDOMEvents = /**
* @return {?}
*/
function () { return false; };
/**
* @return {?}
*/
DominoAdapter.prototype.supportsNativeShadowDOM = /**
* @return {?}
*/
function () { return false; };
/**
* @param {?} nodeA
* @param {?} nodeB
* @return {?}
*/
DominoAdapter.prototype.contains = /**
* @param {?} nodeA
* @param {?} nodeB
* @return {?}
*/
function (nodeA, nodeB) {
var /** @type {?} */ inner = nodeB;
while (inner) {
if (inner === nodeA)
return true;
inner = inner.parent;
}
return false;
};
/**
* @return {?}
*/
DominoAdapter.prototype.createHtmlDocument = /**
* @return {?}
*/
function () {
return parseDocument('<html><head><title>fakeTitle</title></head><body></body></html>');
};
/**
* @return {?}
*/
DominoAdapter.prototype.getDefaultDocument = /**
* @return {?}
*/
function () {
if (!DominoAdapter.defaultDoc) {
DominoAdapter.defaultDoc = domino.createDocument();
}
return DominoAdapter.defaultDoc;
};
/**
* @param {?} el
* @param {?=} doc
* @return {?}
*/
DominoAdapter.prototype.createShadowRoot = /**
* @param {?} el
* @param {?=} doc
* @return {?}
*/
function (el, doc) {
if (doc === void 0) { doc = document; }
el.shadowRoot = doc.createDocumentFragment();
el.shadowRoot.parent = el;
return el.shadowRoot;
};
/**
* @param {?} el
* @return {?}
*/
DominoAdapter.prototype.getShadowRoot = /**
* @param {?} el
* @return {?}
*/
function (el) { return el.shadowRoot; };
/**
* @param {?} node
* @return {?}
*/
DominoAdapter.prototype.isTextNode = /**
* @param {?} node
* @return {?}
*/
function (node) { return node.nodeType === DominoAdapter.defaultDoc.TEXT_NODE; };
/**
* @param {?} node
* @return {?}
*/
DominoAdapter.prototype.isCommentNode = /**
* @param {?} node
* @return {?}
*/
function (node) {
return node.nodeType === DominoAdapter.defaultDoc.COMMENT_NODE;
};
/**
* @param {?} node
* @return {?}
*/
DominoAdapter.prototype.isElementNode = /**
* @param {?} node
* @return {?}
*/
function (node) {
return node ? node.nodeType === DominoAdapter.defaultDoc.ELEMENT_NODE : false;
};
/**
* @param {?} node
* @return {?}
*/
DominoAdapter.prototype.hasShadowRoot = /**
* @param {?} node
* @return {?}
*/
function (node) { return node.shadowRoot != null; };
/**
* @param {?} node
* @return {?}
*/
DominoAdapter.prototype.isShadowRoot = /**
* @param {?} node
* @return {?}
*/
function (node) { return this.getShadowRoot(node) == node; };
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DominoAdapter.prototype.getProperty = /**
* @param {?} el
* @param {?} name
* @return {?}
*/
function (el, name) {
if (name === 'href') {
// Domino tries tp resolve href-s which we do not want. Just return the
// atribute value.
return this.getAttribute(el, 'href');
}
else if (name === 'innerText') {
// Domino does not support innerText. Just map it to textContent.
return el.textContent;
}
return (/** @type {?} */ (el))[name];
};
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
DominoAdapter.prototype.setProperty = /**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
function (el, name, value) {
if (name === 'href') {
// Eventhough the server renderer reflects any properties to attributes
// map 'href' to atribute just to handle when setProperty is directly called.
this.setAttribute(el, 'href', value);
}
else if (name === 'innerText') {
// Domino does not support innerText. Just map it to textContent.
el.textContent = value;
}
(/** @type {?} */ (el))[name] = value;
};
/**
* @param {?} doc
* @param {?} target
* @return {?}
*/
DominoAdapter.prototype.getGlobalEventTarget = /**
* @param {?} doc
* @param {?} target
* @return {?}
*/
function (doc, target) {
if (target === 'window') {
return doc.defaultView;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
};
/**
* @param {?} doc
* @return {?}
*/
DominoAdapter.prototype.getBaseHref = /**
* @param {?} doc
* @return {?}
*/
function (doc) {
var /** @type {?} */ base = this.querySelector(doc.documentElement, 'base');
var /** @type {?} */ href = '';
if (base) {
href = this.getHref(base);
}
// TODO(alxhub): Need relative path logic from BrowserDomAdapter here?
return href;
};
/** @internal */
/**
* \@internal
* @param {?} element
* @return {?}
*/
DominoAdapter.prototype._readStyleAttribute = /**
* \@internal
* @param {?} element
* @return {?}
*/
function (element) {
var /** @type {?} */ styleMap = {};
var /** @type {?} */ styleAttribute = element.getAttribute('style');
if (styleAttribute) {
var /** @type {?} */ styleList = styleAttribute.split(/;+/g);
for (var /** @type {?} */ i = 0; i < styleList.length; i++) {
if (styleList[i].length > 0) {
var /** @type {?} */ style = /** @type {?} */ (styleList[i]);
var /** @type {?} */ colon = style.indexOf(':');
if (colon === -1) {
throw new Error("Invalid CSS style: " + style);
}
(/** @type {?} */ (styleMap))[style.substr(0, colon).trim()] = style.substr(colon + 1).trim();
}
}
}
return styleMap;
};
/** @internal */
/**
* \@internal
* @param {?} element
* @param {?} styleMap
* @return {?}
*/
DominoAdapter.prototype._writeStyleAttribute = /**
* \@internal
* @param {?} element
* @param {?} styleMap
* @return {?}
*/
function (element, styleMap) {
var /** @type {?} */ styleAttrValue = '';
for (var /** @type {?} */ key in styleMap) {
var /** @type {?} */ newValue = styleMap[key];
if (newValue) {
styleAttrValue += key + ':' + styleMap[key] + ';';
}
}
element.setAttribute('style', styleAttrValue);
};
/**
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
DominoAdapter.prototype.setStyle = /**
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
function (element, styleName, styleValue) {
var /** @type {?} */ styleMap = this._readStyleAttribute(element);
(/** @type {?} */ (styleMap))[styleName] = styleValue;
this._writeStyleAttribute(element, styleMap);
};
/**
* @param {?} element
* @param {?} styleName
* @return {?}
*/
DominoAdapter.prototype.removeStyle = /**
* @param {?} element
* @param {?} styleName
* @return {?}
*/
function (element, styleName) { this.setStyle(element, styleName, null); };
/**
* @param {?} element
* @param {?} styleName
* @return {?}
*/
DominoAdapter.prototype.getStyle = /**
* @param {?} element
* @param {?} styleName
* @return {?}
*/
function (element, styleName) {
var /** @type {?} */ styleMap = this._readStyleAttribute(element);
return styleMap.hasOwnProperty(styleName) ? (/** @type {?} */ (styleMap))[styleName] : '';
};
/**
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
DominoAdapter.prototype.hasStyle = /**
* @param {?} element
* @param {?} styleName
* @param {?=} styleValue
* @return {?}
*/
function (element, styleName, styleValue) {
var /** @type {?} */ value = this.getStyle(element, styleName) || '';
return styleValue ? value == styleValue : value.length > 0;
};
/**
* @param {?} el
* @param {?} evt
* @return {?}
*/
DominoAdapter.prototype.dispatchEvent = /**
* @param {?} el
* @param {?} evt
* @return {?}
*/
function (el, evt) {
el.dispatchEvent(evt);
// Dispatch the event to the window also.
var /** @type {?} */ doc = el.ownerDocument || el;
var /** @type {?} */ win = (/** @type {?} */ (doc)).defaultView;
if (win) {
win.dispatchEvent(evt);
}
};
/**
* @return {?}
*/
DominoAdapter.prototype.getHistory = /**
* @return {?}
*/
function () { throw _notImplemented('getHistory'); };
/**
* @return {?}
*/
DominoAdapter.prototype.getLocation = /**
* @return {?}
*/
function () { throw _notImplemented('getLocation'); };
/**
* @return {?}
*/
DominoAdapter.prototype.getUserAgent = /**
* @return {?}
*/
function () { return 'Fake user agent'; };
/**
* @return {?}
*/
DominoAdapter.prototype.supportsWebAnimation = /**
* @return {?}
*/
function () { return false; };
/**
* @return {?}
*/
DominoAdapter.prototype.performanceNow = /**
* @return {?}
*/
function () { return Date.now(); };
/**
* @return {?}
*/
DominoAdapter.prototype.getAnimationPrefix = /**
* @return {?}
*/
function () { return ''; };
/**
* @return {?}
*/
DominoAdapter.prototype.getTransitionEnd = /**
* @return {?}
*/
function () { return 'transitionend'; };
/**
* @return {?}
*/
DominoAdapter.prototype.supportsAnimation = /**
* @return {?}
*/
function () { return true; };
/**
* @param {?} el
* @return {?}
*/
DominoAdapter.prototype.getDistributedNodes = /**
* @param {?} el
* @return {?}
*/
function (el) { throw _notImplemented('getDistributedNodes'); };
/**
* @return {?}
*/
DominoAdapter.prototype.supportsCookies = /**
* @return {?}
*/
function () { return false; };
/**
* @param {?} name
* @return {?}
*/
DominoAdapter.prototype.getCookie = /**
* @param {?} name
* @return {?}
*/
function (name) { throw _notImplemented('getCookie'); };
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
DominoAdapter.prototype.setCookie = /**
* @param {?} name
* @param {?} value
* @return {?}
*/
function (name, value) { throw _notImplemented('setCookie'); };
return DominoAdapter;
}(ɵBrowserDomAdapter));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Representation of the current platform state.
*
* \@experimental
*/
var PlatformState = /** @class */ (function () {
function PlatformState(_doc) {
this._doc = _doc;
}
/**
* Renders the current state of the platform to string.
*/
/**
* Renders the current state of the platform to string.
* @return {?}
*/
PlatformState.prototype.renderToString = /**
* Renders the current state of the platform to string.
* @return {?}
*/
function () { return serializeDocument(this._doc); };
/**
* Returns the current DOM state.
*/
/**
* Returns the current DOM state.
* @return {?}
*/
PlatformState.prototype.getDocument = /**
* Returns the current DOM state.
* @return {?}
*/
function () { return this._doc; };
PlatformState.decorators = [
{ type: Injectable },
];
/** @nocollapse */
PlatformState.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
]; };
return PlatformState;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var xhr2 = require('xhr2');
var isAbsoluteUrl = /^[a-zA-Z\-\+.]+:\/\//;
/**
* @param {?} url
* @return {?}
*/
function validateRequestUrl(url$$1) {
if (!isAbsoluteUrl.test(url$$1)) {
throw new Error("URLs requested via Http on the server must be absolute. URL: " + url$$1);
}
}
var ServerXhr = /** @class */ (function () {
function ServerXhr() {
}
/**
* @return {?}
*/
ServerXhr.prototype.build = /**
* @return {?}
*/
function () { return new xhr2.XMLHttpRequest(); };
ServerXhr.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ServerXhr.ctorParameters = function () { return []; };
return ServerXhr;
}());
var ServerXsrfStrategy = /** @class */ (function () {
function ServerXsrfStrategy() {
}
/**
* @param {?} req
* @return {?}
*/
ServerXsrfStrategy.prototype.configureRequest = /**
* @param {?} req
* @return {?}
*/
function (req) { };
ServerXsrfStrategy.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ServerXsrfStrategy.ctorParameters = function () { return []; };
return ServerXsrfStrategy;
}());
/**
* @abstract
*/
var ZoneMacroTaskWrapper = /** @class */ (function () {
function ZoneMacroTaskWrapper() {
}
/**
* @param {?} request
* @return {?}
*/
ZoneMacroTaskWrapper.prototype.wrap = /**
* @param {?} request
* @return {?}
*/
function (request) {
var _this = this;
return new Observable(function (observer) {
var /** @type {?} */ task = /** @type {?} */ ((null));
var /** @type {?} */ scheduled = false;
var /** @type {?} */ sub = null;
var /** @type {?} */ savedResult = null;
var /** @type {?} */ savedError = null;
var /** @type {?} */ scheduleTask = function (_task) {
task = _task;
scheduled = true;
var /** @type {?} */ delegate = _this.delegate(request);
sub = delegate.subscribe(function (res) { return savedResult = res; }, function (err) {
if (!scheduled) {
throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.');
}
savedError = err;
scheduled = false;
task.invoke();
}, function () {
if (!scheduled) {
throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.');
}
scheduled = false;
task.invoke();
});
};
var /** @type {?} */ cancelTask = function (_task) {
if (!scheduled) {
return;
}
scheduled = false;
if (sub) {
sub.unsubscribe();
sub = null;
}
};
var /** @type {?} */ onComplete = function () {
if (savedError !== null) {
observer.error(savedError);
}
else {
observer.next(savedResult);
observer.complete();
}
};
// MockBackend for Http is synchronous, which means that if scheduleTask is by
// scheduleMacroTask, the request will hit MockBackend and the response will be
// sent, causing task.invoke() to be called.
var /** @type {?} */ _task = Zone.current.scheduleMacroTask('ZoneMacroTaskWrapper.subscribe', onComplete, {}, function () { return null; }, cancelTask);
scheduleTask(_task);
return function () {
if (scheduled && task) {
task.zone.cancelTask(task);
scheduled = false;
}
if (sub) {
sub.unsubscribe();
sub = null;
}
};
});
};
return ZoneMacroTaskWrapper;
}());
var ZoneMacroTaskConnection = /** @class */ (function (_super) {
__extends(ZoneMacroTaskConnection, _super);
function ZoneMacroTaskConnection(request, backend) {
var _this = _super.call(this) || this;
_this.request = request;
_this.backend = backend;
validateRequestUrl(request.url);
_this.response = _this.wrap(request);
return _this;
}
/**
* @param {?} request
* @return {?}
*/
ZoneMacroTaskConnection.prototype.delegate = /**
* @param {?} request
* @return {?}
*/
function (request) {
this.lastConnection = this.backend.createConnection(request);
return /** @type {?} */ (this.lastConnection.response);
};
Object.defineProperty(ZoneMacroTaskConnection.prototype, "readyState", {
get: /**
* @return {?}
*/
function () {
return !!this.lastConnection ? this.lastConnection.readyState : ReadyState.Unsent;
},
enumerable: true,
configurable: true
});
return ZoneMacroTaskConnection;
}(ZoneMacroTaskWrapper));
var ZoneMacroTaskBackend = /** @class */ (function () {
function ZoneMacroTaskBackend(backend) {
this.backend = backend;
}
/**
* @param {?} request
* @return {?}
*/
ZoneMacroTaskBackend.prototype.createConnection = /**
* @param {?} request
* @return {?}
*/
function (request) {
return new ZoneMacroTaskConnection(request, this.backend);
};
return ZoneMacroTaskBackend;
}());
var ZoneClientBackend = /** @class */ (function (_super) {
__extends(ZoneClientBackend, _super);
function ZoneClientBackend(backend) {
var _this = _super.call(this) || this;
_this.backend = backend;
return _this;
}
/**
* @param {?} request
* @return {?}
*/
ZoneClientBackend.prototype.handle = /**
* @param {?} request
* @return {?}
*/
function (request) { return this.wrap(request); };
/**
* @param {?} request
* @return {?}
*/
ZoneClientBackend.prototype.delegate = /**
* @param {?} request
* @return {?}
*/
function (request) {
return this.backend.handle(request);
};
return ZoneClientBackend;
}(ZoneMacroTaskWrapper));
/**
* @param {?} xhrBackend
* @param {?} options
* @return {?}
*/
function httpFactory(xhrBackend, options) {
var /** @type {?} */ macroBackend = new ZoneMacroTaskBackend(xhrBackend);
return new Http(macroBackend, options);
}
/**
* @param {?} backend
* @param {?} interceptors
* @return {?}
*/
function zoneWrappedInterceptingHandler(backend, interceptors) {
var /** @type {?} */ realBackend = ɵinterceptingHandler(backend, interceptors);
return new ZoneClientBackend(realBackend);
}
var SERVER_HTTP_PROVIDERS = [
{ provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions] },
{ provide: BrowserXhr, useClass: ServerXhr }, { provide: XSRFStrategy, useClass: ServerXsrfStrategy },
{ provide: XhrFactory, useClass: ServerXhr }, {
provide: HttpHandler,
useFactory: zoneWrappedInterceptingHandler,
deps: [HttpBackend, [new Optional(), HTTP_INTERCEPTORS]]
}
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Config object passed to initialize the platform.
*
* \@experimental
* @record
*/
/**
* The DI token for setting the initial config for the platform.
*
* \@experimental
*/
var INITIAL_CONFIG = new InjectionToken('Server.INITIAL_CONFIG');
/**
* A function that will be executed when calling `renderModuleFactory` or `renderModule` just
* before current platform state is rendered to string.
*
* \@experimental
*/
var BEFORE_APP_SERIALIZED = new InjectionToken('Server.RENDER_MODULE_HOOK');
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} urlStr
* @return {?}
*/
function parseUrl(urlStr) {
var /** @type {?} */ parsedUrl = parse(urlStr);
return {
pathname: parsedUrl.pathname || '',
search: parsedUrl.search || '',
hash: parsedUrl.hash || '',
};
}
/**
* Server-side implementation of URL state. Implements `pathname`, `search`, and `hash`
* but not the state stack.
*/
var ServerPlatformLocation = /** @class */ (function () {
function ServerPlatformLocation(_doc, _config) {
this._doc = _doc;
this.pathname = '/';
this.search = '';
this.hash = '';
this._hashUpdate = new Subject();
var /** @type {?} */ config = /** @type {?} */ (_config);
if (!!config && !!config.url) {
var /** @type {?} */ parsedUrl = parseUrl(config.url);
this.pathname = parsedUrl.pathname;
this.search = parsedUrl.search;
this.hash = parsedUrl.hash;
}
}
/**
* @return {?}
*/
ServerPlatformLocation.prototype.getBaseHrefFromDOM = /**
* @return {?}
*/
function () { return /** @type {?} */ ((ɵgetDOM().getBaseHref(this._doc))); };
/**
* @param {?} fn
* @return {?}
*/
ServerPlatformLocation.prototype.onPopState = /**
* @param {?} fn
* @return {?}
*/
function (fn) {
// No-op: a state stack is not implemented, so
// no events will ever come.
};
/**
* @param {?} fn
* @return {?}
*/
ServerPlatformLocation.prototype.onHashChange = /**
* @param {?} fn
* @return {?}
*/
function (fn) { this._hashUpdate.subscribe(fn); };
Object.defineProperty(ServerPlatformLocation.prototype, "url", {
get: /**
* @return {?}
*/
function () { return "" + this.pathname + this.search + this.hash; },
enumerable: true,
configurable: true
});
/**
* @param {?} value
* @param {?} oldUrl
* @return {?}
*/
ServerPlatformLocation.prototype.setHash = /**
* @param {?} value
* @param {?} oldUrl
* @return {?}
*/
function (value, oldUrl) {
var _this = this;
if (this.hash === value) {
// Don't fire events if the hash has not changed.
return;
}
(/** @type {?} */ (this)).hash = value;
var /** @type {?} */ newUrl = this.url;
scheduleMicroTask(function () { return _this._hashUpdate.next(/** @type {?} */ ({ type: 'hashchange', oldUrl: oldUrl, newUrl: newUrl })); });
};
/**
* @param {?} state
* @param {?} title
* @param {?} newUrl
* @return {?}
*/
ServerPlatformLocation.prototype.replaceState = /**
* @param {?} state
* @param {?} title
* @param {?} newUrl
* @return {?}
*/
function (state, title, newUrl) {
var /** @type {?} */ oldUrl = this.url;
var /** @type {?} */ parsedUrl = parseUrl(newUrl);
(/** @type {?} */ (this)).pathname = parsedUrl.pathname;
(/** @type {?} */ (this)).search = parsedUrl.search;
this.setHash(parsedUrl.hash, oldUrl);
};
/**
* @param {?} state
* @param {?} title
* @param {?} newUrl
* @return {?}
*/
ServerPlatformLocation.prototype.pushState = /**
* @param {?} state
* @param {?} title
* @param {?} newUrl
* @return {?}
*/
function (state, title, newUrl) {
this.replaceState(state, title, newUrl);
};
/**
* @return {?}
*/
ServerPlatformLocation.prototype.forward = /**
* @return {?}
*/
function () { throw new Error('Not implemented'); };
/**
* @return {?}
*/
ServerPlatformLocation.prototype.back = /**
* @return {?}
*/
function () { throw new Error('Not implemented'); };
ServerPlatformLocation.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ServerPlatformLocation.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [INITIAL_CONFIG,] },] },
]; };
return ServerPlatformLocation;
}());
/**
* @param {?} fn
* @return {?}
*/
function scheduleMicroTask(fn) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var EMPTY_ARRAY = [];
var ServerRendererFactory2 = /** @class */ (function () {
function ServerRendererFactory2(ngZone, document, sharedStylesHost) {
this.ngZone = ngZone;
this.document = document;
this.sharedStylesHost = sharedStylesHost;
this.rendererByCompId = new Map();
this.schema = new DomElementSchemaRegistry();
this.defaultRenderer = new DefaultServerRenderer2(document, ngZone, this.schema);
}
/**
* @param {?} element
* @param {?} type
* @return {?}
*/
ServerRendererFactory2.prototype.createRenderer = /**
* @param {?} element
* @param {?} type
* @return {?}
*/
function (element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
switch (type.encapsulation) {
case ViewEncapsulation.Native:
case ViewEncapsulation.Emulated: {
var /** @type {?} */ renderer = this.rendererByCompId.get(type.id);
if (!renderer) {
renderer = new EmulatedEncapsulationServerRenderer2(this.document, this.ngZone, this.sharedStylesHost, this.schema, type);
this.rendererByCompId.set(type.id, renderer);
}
(/** @type {?} */ (renderer)).applyToHost(element);
return renderer;
}
case ViewEncapsulation.Native:
throw new Error('Native encapsulation is not supported on the server!');
default: {
if (!this.rendererByCompId.has(type.id)) {
var /** @type {?} */ styles = ɵflattenStyles(type.id, type.styles, []);
this.sharedStylesHost.addStyles(styles);
this.rendererByCompId.set(type.id, this.defaultRenderer);
}
return this.defaultRenderer;
}
}
};
/**
* @return {?}
*/
ServerRendererFactory2.prototype.begin = /**
* @return {?}
*/
function () { };
/**
* @return {?}
*/
ServerRendererFactory2.prototype.end = /**
* @return {?}
*/
function () { };
ServerRendererFactory2.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ServerRendererFactory2.ctorParameters = function () { return [
{ type: NgZone, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: ɵSharedStylesHost, },
]; };
return ServerRendererFactory2;
}());
var DefaultServerRenderer2 = /** @class */ (function () {
function DefaultServerRenderer2(document, ngZone, schema) {
this.document = document;
this.ngZone = ngZone;
this.schema = schema;
this.data = Object.create(null);
}
/**
* @return {?}
*/
DefaultServerRenderer2.prototype.destroy = /**
* @return {?}
*/
function () { };
/**
* @param {?} name
* @param {?=} namespace
* @param {?=} debugInfo
* @return {?}
*/
DefaultServerRenderer2.prototype.createElement = /**
* @param {?} name
* @param {?=} namespace
* @param {?=} debugInfo
* @return {?}
*/
function (name, namespace, debugInfo) {
if (namespace) {
return ɵgetDOM().createElementNS(ɵNAMESPACE_URIS[namespace], name);
}
return ɵgetDOM().createElement(name);
};
/**
* @param {?} value
* @param {?=} debugInfo
* @return {?}
*/
DefaultServerRenderer2.prototype.createComment = /**
* @param {?} value
* @param {?=} debugInfo
* @return {?}
*/
function (value, debugInfo) { return ɵgetDOM().createComment(value); };
/**
* @param {?} value
* @param {?=} debugInfo
* @return {?}
*/
DefaultServerRenderer2.prototype.createText = /**
* @param {?} value
* @param {?=} debugInfo
* @return {?}
*/
function (value, debugInfo) { return ɵgetDOM().createTextNode(value); };
/**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
DefaultServerRenderer2.prototype.appendChild = /**
* @param {?} parent
* @param {?} newChild
* @return {?}
*/
function (parent, newChild) { ɵgetDOM().appendChild(parent, newChild); };
/**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
DefaultServerRenderer2.prototype.insertBefore = /**
* @param {?} parent
* @param {?} newChild
* @param {?} refChild
* @return {?}
*/
function (parent, newChild, refChild) {
if (parent) {
ɵgetDOM().insertBefore(parent, refChild, newChild);
}
};
/**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
DefaultServerRenderer2.prototype.removeChild = /**
* @param {?} parent
* @param {?} oldChild
* @return {?}
*/
function (parent, oldChild) {
if (parent) {
ɵgetDOM().removeChild(parent, oldChild);
}
};
/**
* @param {?} selectorOrNode
* @param {?=} debugInfo
* @return {?}
*/
DefaultServerRenderer2.prototype.selectRootElement = /**
* @param {?} selectorOrNode
* @param {?=} debugInfo
* @return {?}
*/
function (selectorOrNode, debugInfo) {
var /** @type {?} */ el;
if (typeof selectorOrNode === 'string') {
el = ɵgetDOM().querySelector(this.document, selectorOrNode);
if (!el) {
throw new Error("The selector \"" + selectorOrNode + "\" did not match any elements");
}
}
else {
el = selectorOrNode;
}
ɵgetDOM().clearNodes(el);
return el;
};
/**
* @param {?} node
* @return {?}
*/
DefaultServerRenderer2.prototype.parentNode = /**
* @param {?} node
* @return {?}
*/
function (node) { return ɵgetDOM().parentElement(node); };
/**
* @param {?} node
* @return {?}
*/
DefaultServerRenderer2.prototype.nextSibling = /**
* @param {?} node
* @return {?}
*/
function (node) { return ɵgetDOM().nextSibling(node); };
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
DefaultServerRenderer2.prototype.setAttribute = /**
* @param {?} el
* @param {?} name
* @param {?} value
* @param {?=} namespace
* @return {?}
*/
function (el, name, value, namespace) {
if (namespace) {
ɵgetDOM().setAttributeNS(el, ɵNAMESPACE_URIS[namespace], namespace + ':' + name, value);
}
else {
ɵgetDOM().setAttribute(el, name, value);
}
};
/**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
DefaultServerRenderer2.prototype.removeAttribute = /**
* @param {?} el
* @param {?} name
* @param {?=} namespace
* @return {?}
*/
function (el, name, namespace) {
if (namespace) {
ɵgetDOM().removeAttributeNS(el, ɵNAMESPACE_URIS[namespace], name);
}
else {
ɵgetDOM().removeAttribute(el, name);
}
};
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DefaultServerRenderer2.prototype.addClass = /**
* @param {?} el
* @param {?} name
* @return {?}
*/
function (el, name) { ɵgetDOM().addClass(el, name); };
/**
* @param {?} el
* @param {?} name
* @return {?}
*/
DefaultServerRenderer2.prototype.removeClass = /**
* @param {?} el
* @param {?} name
* @return {?}
*/
function (el, name) { ɵgetDOM().removeClass(el, name); };
/**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
DefaultServerRenderer2.prototype.setStyle = /**
* @param {?} el
* @param {?} style
* @param {?} value
* @param {?} flags
* @return {?}
*/
function (el, style, value, flags) {
ɵgetDOM().setStyle(el, style, value);
};
/**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
DefaultServerRenderer2.prototype.removeStyle = /**
* @param {?} el
* @param {?} style
* @param {?} flags
* @return {?}
*/
function (el, style, flags) {
ɵgetDOM().removeStyle(el, style);
};
/**
* @param {?} tagName
* @param {?} propertyName
* @return {?}
*/
DefaultServerRenderer2.prototype._isSafeToReflectProperty = /**
* @param {?} tagName
* @param {?} propertyName
* @return {?}
*/
function (tagName, propertyName) {
return this.schema.securityContext(tagName, propertyName, true) ===
this.schema.securityContext(tagName, propertyName, false);
};
/**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
DefaultServerRenderer2.prototype.setProperty = /**
* @param {?} el
* @param {?} name
* @param {?} value
* @return {?}
*/
function (el, name, value) {
checkNoSyntheticProp(name, 'property');
ɵgetDOM().setProperty(el, name, value);
// Mirror property values for known HTML element properties in the attributes.
var /** @type {?} */ tagName = (/** @type {?} */ (el.tagName)).toLowerCase();
if (value != null && (typeof value === 'number' || typeof value == 'string') &&
this.schema.hasElement(tagName, EMPTY_ARRAY) &&
this.schema.hasProperty(tagName, name, EMPTY_ARRAY) &&
this._isSafeToReflectProperty(tagName, name)) {
this.setAttribute(el, name, value.toString());
}
};
/**
* @param {?} node
* @param {?} value
* @return {?}
*/
DefaultServerRenderer2.prototype.setValue = /**
* @param {?} node
* @param {?} value
* @return {?}
*/
function (node, value) { ɵgetDOM().setText(node, value); };
/**
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
DefaultServerRenderer2.prototype.listen = /**
* @param {?} target
* @param {?} eventName
* @param {?} callback
* @return {?}
*/
function (target, eventName, callback) {
var _this = this;
// Note: We are not using the EventsPlugin here as this is not needed
// to run our tests.
checkNoSyntheticProp(eventName, 'listener');
var /** @type {?} */ el = typeof target === 'string' ? ɵgetDOM().getGlobalEventTarget(this.document, target) : target;
var /** @type {?} */ outsideHandler = function (event) { return _this.ngZone.runGuarded(function () { return callback(event); }); };
return this.ngZone.runOutsideAngular(function () { return (ɵgetDOM().onAndCancel(el, eventName, outsideHandler)); });
};
return DefaultServerRenderer2;
}());
var AT_CHARCODE = '@'.charCodeAt(0);
/**
* @param {?} name
* @param {?} nameKind
* @return {?}
*/
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error("Found the synthetic " + nameKind + " " + name + ". Please include either \"BrowserAnimationsModule\" or \"NoopAnimationsModule\" in your application.");
}
}
var EmulatedEncapsulationServerRenderer2 = /** @class */ (function (_super) {
__extends(EmulatedEncapsulationServerRenderer2, _super);
function EmulatedEncapsulationServerRenderer2(document, ngZone, sharedStylesHost, schema, component) {
var _this = _super.call(this, document, ngZone, schema) || this;
_this.component = component;
var /** @type {?} */ styles = ɵflattenStyles(component.id, component.styles, []);
sharedStylesHost.addStyles(styles);
_this.contentAttr = ɵshimContentAttribute(component.id);
_this.hostAttr = ɵshimHostAttribute(component.id);
return _this;
}
/**
* @param {?} element
* @return {?}
*/
EmulatedEncapsulationServerRenderer2.prototype.applyToHost = /**
* @param {?} element
* @return {?}
*/
function (element) { _super.prototype.setAttribute.call(this, element, this.hostAttr, ''); };
/**
* @param {?} parent
* @param {?} name
* @return {?}
*/
EmulatedEncapsulationServerRenderer2.prototype.createElement = /**
* @param {?} parent
* @param {?} name
* @return {?}
*/
function (parent, name) {
var /** @type {?} */ el = _super.prototype.createElement.call(this, parent, name);
_super.prototype.setAttribute.call(this, el, this.contentAttr, '');
return el;
};
return EmulatedEncapsulationServerRenderer2;
}(DefaultServerRenderer2));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ServerStylesHost = /** @class */ (function (_super) {
__extends(ServerStylesHost, _super);
function ServerStylesHost(doc, transitionId) {
var _this = _super.call(this) || this;
_this.doc = doc;
_this.transitionId = transitionId;
_this.head = null;
_this.head = ɵgetDOM().getElementsByTagName(doc, 'head')[0];
return _this;
}
/**
* @param {?} style
* @return {?}
*/
ServerStylesHost.prototype._addStyle = /**
* @param {?} style
* @return {?}
*/
function (style) {
var /** @type {?} */ adapter = ɵgetDOM();
var /** @type {?} */ el = adapter.createElement('style');
adapter.setText(el, style);
if (!!this.transitionId) {
adapter.setAttribute(el, 'ng-transition', this.transitionId);
}
adapter.appendChild(this.head, el);
};
/**
* @param {?} additions
* @return {?}
*/
ServerStylesHost.prototype.onStylesAdded = /**
* @param {?} additions
* @return {?}
*/
function (additions) {
var _this = this;
additions.forEach(function (style) { return _this._addStyle(style); });
};
ServerStylesHost.decorators = [
{ type: Injectable },
];
/** @nocollapse */
ServerStylesHost.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [ɵTRANSITION_ID,] },] },
]; };
return ServerStylesHost;
}(ɵSharedStylesHost));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var INTERNAL_SERVER_PLATFORM_PROVIDERS = [
{ provide: DOCUMENT, useFactory: _document, deps: [Injector] },
{ provide: PLATFORM_ID, useValue: ɵPLATFORM_SERVER_ID },
{ provide: PLATFORM_INITIALIZER, useFactory: initDominoAdapter, multi: true, deps: [Injector] }, {
provide: PlatformLocation,
useClass: ServerPlatformLocation,
deps: [DOCUMENT, [Optional, INITIAL_CONFIG]]
},
{ provide: PlatformState, deps: [DOCUMENT] },
// Add special provider that allows multiple instances of platformServer* to be created.
{ provide: ɵALLOW_MULTIPLE_PLATFORMS, useValue: true }
];
/**
* @param {?} injector
* @return {?}
*/
function initDominoAdapter(injector) {
return function () { DominoAdapter.makeCurrent(); };
}
/**
* @param {?} renderer
* @param {?} engine
* @param {?} zone
* @return {?}
*/
function instantiateServerRendererFactory(renderer, engine, zone) {
return new ɵAnimationRendererFactory(renderer, engine, zone);
}
var SERVER_RENDER_PROVIDERS = [
ServerRendererFactory2,
{
provide: RendererFactory2,
useFactory: instantiateServerRendererFactory,
deps: [ServerRendererFactory2, ɵAnimationEngine, NgZone]
},
ServerStylesHost,
{ provide: ɵSharedStylesHost, useExisting: ServerStylesHost },
];
/**
* The ng module for the server.
*
* \@experimental
*/
var ServerModule = /** @class */ (function () {
function ServerModule() {
}
ServerModule.decorators = [
{ type: NgModule, args: [{
exports: [BrowserModule],
imports: [HttpModule, HttpClientModule, NoopAnimationsModule],
providers: [
SERVER_RENDER_PROVIDERS,
SERVER_HTTP_PROVIDERS,
{ provide: Testability, useValue: null },
],
},] },
];
/** @nocollapse */
ServerModule.ctorParameters = function () { return []; };
return ServerModule;
}());
/**
* @param {?} injector
* @return {?}
*/
function _document(injector) {
var /** @type {?} */ config = injector.get(INITIAL_CONFIG, null);
if (config && config.document) {
return parseDocument(config.document, config.url);
}
else {
return ɵgetDOM().createHtmlDocument();
}
}
/**
* \@experimental
*/
var platformServer = createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS);
/**
* The server platform that supports the runtime compiler.
*
* \@experimental
*/
var platformDynamicServer = createPlatformFactory(ɵplatformCoreDynamic, 'serverDynamic', INTERNAL_SERVER_PLATFORM_PROVIDERS);
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} doc
* @param {?} appId
* @param {?} transferStore
* @return {?}
*/
function serializeTransferStateFactory(doc, appId, transferStore) {
return function () {
var /** @type {?} */ script = doc.createElement('script');
script.id = appId + '-state';
script.setAttribute('type', 'application/json');
script.textContent = ɵescapeHtml(transferStore.toJson());
doc.body.appendChild(script);
};
}
/**
* NgModule to install on the server side while using the `TransferState` to transfer state from
* server to client.
*
* \@experimental
*/
var ServerTransferStateModule = /** @class */ (function () {
function ServerTransferStateModule() {
}
ServerTransferStateModule.decorators = [
{ type: NgModule, args: [{
providers: [
TransferState, {
provide: BEFORE_APP_SERIALIZED,
useFactory: serializeTransferStateFactory,
deps: [DOCUMENT, APP_ID, TransferState],
multi: true,
}
]
},] },
];
/** @nocollapse */
ServerTransferStateModule.ctorParameters = function () { return []; };
return ServerTransferStateModule;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} platformFactory
* @param {?} options
* @return {?}
*/
function _getPlatform(platformFactory, options) {
var /** @type {?} */ extraProviders = options.extraProviders ? options.extraProviders : [];
return platformFactory([
{ provide: INITIAL_CONFIG, useValue: { document: options.document, url: options.url } },
extraProviders
]);
}
/**
* @template T
* @param {?} platform
* @param {?} moduleRefPromise
* @return {?}
*/
function _render(platform, moduleRefPromise) {
return moduleRefPromise.then(function (moduleRef) {
var /** @type {?} */ transitionId = moduleRef.injector.get(ɵTRANSITION_ID, null);
if (!transitionId) {
throw new Error("renderModule[Factory]() requires the use of BrowserModule.withServerTransition() to ensure\nthe server-rendered app can be properly bootstrapped into a client app.");
}
var /** @type {?} */ applicationRef = moduleRef.injector.get(ApplicationRef);
return toPromise
.call(first.call(filter.call(applicationRef.isStable, function (isStable) { return isStable; })))
.then(function () {
var /** @type {?} */ platformState = platform.injector.get(PlatformState);
// Run any BEFORE_APP_SERIALIZED callbacks just before rendering to string.
var /** @type {?} */ callbacks = moduleRef.injector.get(BEFORE_APP_SERIALIZED, null);
if (callbacks) {
for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
var callback = callbacks_1[_i];
try {
callback();
}
catch (/** @type {?} */ e) {
// Ignore exceptions.
console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', e);
}
}
}
var /** @type {?} */ output = platformState.renderToString();
platform.destroy();
return output;
});
});
}
/**
* Renders a Module to string.
*
* `document` is the full document HTML of the page to render, as a string.
* `url` is the URL for the current render request.
* `extraProviders` are the platform level providers for the current render request.
*
* Do not use this in a production server environment. Use pre-compiled {\@link NgModuleFactory} with
* {\@link renderModuleFactory} instead.
*
* \@experimental
* @template T
* @param {?} module
* @param {?} options
* @return {?}
*/
function renderModule(module, options) {
var /** @type {?} */ platform = _getPlatform(platformDynamicServer, options);
return _render(platform, platform.bootstrapModule(module));
}
/**
* Renders a {\@link NgModuleFactory} to string.
*
* `document` is the full document HTML of the page to render, as a string.
* `url` is the URL for the current render request.
* `extraProviders` are the platform level providers for the current render request.
*
* \@experimental
* @template T
* @param {?} moduleFactory
* @param {?} options
* @return {?}
*/
function renderModuleFactory(moduleFactory, options) {
var /** @type {?} */ platform = _getPlatform(platformServer, options);
return _render(platform, platform.bootstrapModuleFactory(moduleFactory));
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@stable
*/
var VERSION = new Version('5.2.6');
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Generated bundle index. Do not edit.
*/
export { PlatformState, ServerModule, platformDynamicServer, platformServer, BEFORE_APP_SERIALIZED, INITIAL_CONFIG, ServerTransferStateModule, renderModule, renderModuleFactory, VERSION, INTERNAL_SERVER_PLATFORM_PROVIDERS as ɵINTERNAL_SERVER_PLATFORM_PROVIDERS, SERVER_RENDER_PROVIDERS as ɵSERVER_RENDER_PROVIDERS, ServerRendererFactory2 as ɵServerRendererFactory2, SERVER_HTTP_PROVIDERS as ɵh, ServerXhr as ɵd, ServerXsrfStrategy as ɵe, httpFactory as ɵf, zoneWrappedInterceptingHandler as ɵg, instantiateServerRendererFactory as ɵa, ServerStylesHost as ɵc, serializeTransferStateFactory as ɵb };
//# sourceMappingURL=platform-server.js.map
|
var renameNavLabelPlugin = require("./renameNavLabelPlugin");
var renameExternalModulePlugin = require("./renameExternalModulePlugin");
module.exports = function(PluginHost) {
var app = PluginHost.owner;
/**
* used like so:
* --navigation-label-globals "ui-router-ng2"
* or
* -nlg ui-router-ng2
*/
app.options.addDeclaration({ name: 'navigation-label-globals', short: 'nlg' });
/**
* used like so:
* --navigation-label-externals "UI-Router Internal API"
* or
* -nle "UI-Router Internal API"
*/
app.options.addDeclaration({ name: 'navigation-label-externals', short: 'nle'});
/**
* -nli "Public API"
*/
app.options.addDeclaration({ name: 'navigation-label-internals', short: 'nli'});
app.renderer.addComponent('RenameNavLabel', renameNavLabelPlugin.RenameNavLabelPlugin);
app.converter.addComponent('RenameExtModule', renameExternalModulePlugin.RenameExternalModulePlugin);
};
|
'use strict';
var fs = require('fs');
var testExistence = function (test, expectations) {
test.expect(expectations.length);
expectations.forEach(function (expectation) {
test.equal(fs.existsSync(expectation), true, expectation + ' should exist');
});
test.done();
};
exports.command = {
'app with asar': function (test) {
testExistence(test, [
'test/fixtures/out/footest.x86.rpm'
]);
},
'app without asar': function (test) {
testExistence(test, [
'test/fixtures/out/bartest.x86_64.rpm'
]);
}
};
|
#!/usr/bin/env node
/**
* Delivers your finished Pivotal tasks
*
* @package pivotal-deliver
* @author Gustav Rydstedt <gustav.rydstedt@gmail.com>
*/
var PivotalDeliver = require('./pivotal-deliver');
module.exports = PivotalDeliver;
if (require.main === module) {
// This module got invoked directly
var program = require('commander');
program
.version('0.0.1')
.option('-t, --token', 'Pivotal token')
.option('-i, --id', 'Pivotal project id')
.parse(process.argv);
var token = program.token || process.env.PIVOTAL_TOKEN;
var projectId = program.id || process.env.PIVOTAL_PROJECT_ID;
var pivotalDeliver = new PivotalDeliver(token, projectId);
pivotalDeliver.checkAndDeliver(function(err) {
if(err) {
console.error('Failed to check and deliver.');
console.error(err);
process.exit(1);
} else {
console.log('Done');
process.exit(0);
}
})
}; |
'use strict';
(function () {
angular
.module('estimates')
.config(EstimatesStates);
function EstimatesStates($stateProvider) {
$stateProvider
.state('root.estimates', {
url: 'estimates',
abstract: true,
resolve: {
readyCards: function(Trello) {
return Trello.estimateCards('556b2fa7e49b7bea50cc8303', {});
}
},
template: '<div ui-view="estimates"></div>',
}).state('root.estimates.list', {
url: '',
views: {
estimates: {
templateUrl: 'app/estimates/estimates.html',
controller: 'EstimatesController as vm',
}
},
}).state('root.estimates.detail', {
url: '/:shortLink',
resolve: {
card: function(Trello, $stateParams) {
return Trello.cardDetail($stateParams.shortLink, {});
},
checkLists: function(Trello, $stateParams) {
return Trello.get(cardApiPath('checklists', $stateParams));
},
comments: function(Trello, $stateParams) {
return Trello.get(cardApiPath('actions', $stateParams), {
filter: 'commentCard'
});
},
votes: function(Trello, $stateParams) {
return Trello.get(cardApiPath('membersVoted', $stateParams));
},
},
views: {
estimates: {
templateUrl: 'app/estimates/estimateCard.html',
controller: 'EstimateCardController as vm',
}
},
});
function cardApiPath(verb, $stateParams) {
return [
'cards/',
$stateParams.shortLink,
'/',
verb,
].join('');
}
}
})();
|
var test = require('tape'),
createTimePicker = require('../');
test('timePicker exists', function(t){
t.plan(2);
var timePicker = createTimePicker();
t.ok(timePicker, 'timePicker exists');
t.ok(timePicker.element, 'timePicker element exists');
});
test('set a valid time', function(t){
t.plan(5);
var timePicker = createTimePicker(),
testTime = '12:45:00 AM';
timePicker.time(testTime);
t.equal(timePicker.time(), '12:45:00 AM', 'Time set correctly');
t.equal(timePicker.hours(), 12, 'hours set correctly');
t.equal(timePicker.minutes(), 45, 'minutes set correctly');
t.equal(timePicker.seconds(), 0, 'seconds set correctly');
t.equal(timePicker.meridiem(), 'AM', 'meridiem set correctly');
});
test('set a standard valid time', function(t){
t.plan(10);
var timePicker = createTimePicker(),
testTime = new Date('1/1/2011 12:45:00').toTimeString();
timePicker.time(testTime);
t.equal(timePicker.time(), '12:45:00 AM', 'Time set correctly');
t.equal(timePicker.hours(), 12, 'hours set correctly');
t.equal(timePicker.minutes(), 45, 'minutes set correctly');
t.equal(timePicker.seconds(), 0, 'seconds set correctly');
t.equal(timePicker.meridiem(), 'AM', 'meridiem set correctly');
var testTime2 = new Date('1/1/2011 22:45:00').toTimeString();
timePicker.time(testTime2);
t.equal(timePicker.time(), '10:45:00 PM', 'Time set correctly');
t.equal(timePicker.hours(), 10, 'hours set correctly');
t.equal(timePicker.minutes(), 45, 'minutes set correctly');
t.equal(timePicker.seconds(), 0, 'seconds set correctly');
t.equal(timePicker.meridiem(), 'PM', 'meridiem set correctly');
});
test('set valid parts', function(t) {
t.plan(5);
var timePicker = createTimePicker(),
expectedTime = '10:30:20 PM';
timePicker.hours(10);
t.equal(timePicker.hours(), 10, 'hours set correctly');
timePicker.minutes(30);
t.equal(timePicker.minutes(), 30, 'minutes set correctly');
timePicker.seconds(20);
t.equal(timePicker.seconds(), 20, 'seconds set correctly');
timePicker.meridiem('PM');
t.equal(timePicker.meridiem(), 'PM', 'meridiem set correctly');
t.equal(timePicker.time(), expectedTime);
});
test('set single digit values', function(t) {
t.plan(5);
var timePicker = createTimePicker(),
expectedTime = '01:03:00 AM';
timePicker.hours(1);
t.equal(timePicker.hours(), 1, 'hours set correctly');
timePicker.minutes(3);
t.equal(timePicker.minutes(), 3, 'minutes set correctly');
timePicker.seconds(0);
t.equal(timePicker.seconds(), 0, 'seconds set correctly');
timePicker.meridiem('AM');
t.equal(timePicker.meridiem(), 'AM', 'meridiem set correctly');
t.equal(timePicker.time(), expectedTime);
});
|
// Load all required engine components
R.Engine.define({
"class":"BlockPlayer",
"requires":[
"R.objects.Object2D",
"R.math.Math2D"
]
});
var BlockPlayer = function () {
return R.objects.Object2D.extend({
velocity:null, // The velocity of our object
shape:null, // Our object's shape
constructor:function () {
// Call the base class to assign a name to this object
this.base("BlockPlayer");
// Pick a random position to start at
var start = R.math.Math2D.randomPoint(R.clone(Tutorial2.getFieldRect())
.shrink(25, 25).offset(25, 25));
// Pick a random velocity for each axis
this.velocity = R.math.Vector2D.create(1 + Math.floor(R.lang.Math2.random() * 3),
1 + Math.floor(R.lang.Math2.random() * 3));
// Set our object's shape
this.shape = R.math.Rectangle2D.create(0, 0, 50, 50);
// Position the object
this.setPosition(start);
},
/**
* Update the object within the rendering context. This calls the transform
* components to position the object on the playfield.
*
* @param renderContext {RenderContext} The rendering context
* @param time {Number} The engine time in milliseconds
* @param dt {Number} Delta time since last update
*/
update:function (renderContext, time, dt) {
renderContext.pushTransform();
// Call the "update" method of the super class
this.base(renderContext, time);
// Update the object's position
this.move();
// Draw the object on the render context
this.draw(renderContext);
renderContext.popTransform();
},
/**
* Calculate and perform a move for our object. We'll use
* the field dimensions from our playfield to determine when to
* "bounce".
*/
move:function () {
var pos = this.getPosition().add(this.velocity);
// Determine if we hit a "wall" of our playfield
var playfield = Tutorial2.getFieldRect();
if ((pos.x + 50 > playfield.r) || (pos.x < 0)) {
// Reverse the X velocity
this.velocity.setX(this.velocity.x * -1);
}
if ((pos.y + 50 > playfield.b) || (pos.y < 0)) {
// Reverse the Y velocity
this.velocity.setY(this.velocity.y * -1);
}
},
/**
* Draw our game object onto the specified render context.
* @param renderContext {RenderContext} The context to draw onto
*/
draw:function (renderContext) {
// Generate a rectangle to represent our object
var pos = this.getPosition();
// Set the color to draw with
renderContext.setFillStyle("#ffff00");
renderContext.drawFilledRectangle(this.shape);
}
}, { // Static
/**
* Get the class name of this object
* @return {String} The string MyObject
*/
getClassName:function () {
return "BlockPlayer";
}
});
}
|
app.directive('maslLogo', function () {
'use strict';
return {
restrict: 'E',
require: ['^logoColor', '^logoSize'],
scope: {
logoColor: '@',
logoSize: '@'
},
replace: true,
template: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ' +
'style="width: {{logoSize}}; height: {{logoSize}};" viewBox="-2 -5 105 100">' +
'<defs></defs>' +
'<g>' +
'<path d="M20.329,22.686c-0.734-2.246,0.492-4.662,2.737-5.397l16.881-5.521l-3.233-4.282c-1.423-1.885-4.105-2.261-5.991-0.836 L1.7,28.562c-1.885,1.424-2.259,4.107-0.835,5.993L36.31,81.501c1.424,1.885,2.064,3.039,3.951,1.612c0,0-0.967-2.449-1.643-4.52 L20.329,22.686z" transform="translate(0.5590000152587891,-5.225001335144043)" fill="{{logoColor}}"></path>' +
'<path d="M70.474,17.096l-1.799-5.5c-0.734-2.246-3.148-3.472-5.397-2.737L28.716,20.165c-2.245,0.735-3.47,3.15-2.737,5.396 l18.29,55.91c0.733,2.246,1.599,3.139,3.277,2.684c0,0,0.19-2.729,0.292-4.92l2.679-58.766c0.108-2.361,2.109-4.187,4.466-4.079 L70.474,17.096z" transform="translate(0.5590000152587891,-5.225001335144043)" fill="{{logoColor}}"></path>' +
'<path d="M95.917,23.335l-36.33-1.657c-2.356-0.107-4.357,1.718-4.465,4.08l-2.683,58.764c-0.108,2.359,1.72,4.359,4.078,4.467 l36.33,1.658c2.358,0.106,4.358-1.721,4.468-4.078l2.68-58.766C100.103,25.443,98.276,23.442,95.917,23.335z M82.318,57.349 l-0.205,13.374l-6.634-11.944L64.861,62.76l6.942-10.719L58.43,46.528l13.675-0.911l-1.424-15.475l8.37,12.914l9.7-4.798 l-6.839,11.332l11.892,7.81L82.318,57.349z" transform="translate(0.5590000152587891,-5.225001335144043)" fill="{{logoColor}}"></path>' +
'</g>' +
'</svg>'
};
});
app.directive('maslFooter', function () {
'use strict';
function link(scope, element, attrs) {
$('.footer-toggle').on('click', function(){
$(this).toggleClass('active');
});
}
return {
restrict: 'E',
scope: true,
replace: true,
link: link,
template: '<span class="footer-toggle">●</span>'
};
}); |
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
let vscode = require('vscode');
let path = require('path');
let open = require('open');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
let disposable = vscode.commands.registerCommand('extension.mxunit', function() {
let editor = vscode.window.activeTextEditor;
let config = vscode.workspace.getConfiguration('mxunit');
if(config){
if(!editor){
vscode.window.showWarningMessage('No Active MxUnit Test File!');
}
const ext = path.extname(editor.document.fileName);
const fullPath = editor.document.uri.fsPath;
if (/^\.(cfc)$/.test(ext)) {
let baseUrl = config.baseUrl;
let projectRoot = vscode.workspace.rootPath;
let relPath = replaceAll(fullPath,projectRoot,'/');
relPath = replaceAll(relPath,'\\','/');
let testName = getSelectedText(editor);
if(testName.length){
testName = '&testMethod=' + testName
}
let fullURL = baseUrl + relPath + '?method=runtestremote&output=html' + testName;
try {
open(decodeURIComponent(fullURL));
}
catch (error) {
vscode.window.showInformationMessage('Couldn\'t open test.');
console.error(error.stack);
}
} else {
vscode.window.showInformationMessage('Suppoorts cfc files only!');
}
} else {
vscode.window.showInformationMessage('Your Project needs to define mxunit settings!');
}
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
function getSelectedText(textEditor) {
return textEditor.document.getText(getSelectionRange(textEditor));
}
function getSelectionRange(textEditor) {
let
selection = textEditor.selection,
start = selection.start,
end = selection.end;
return new vscode.Range(start, end);
}
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
} |
var
gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
config = require('../config'),
consoleError = require('../utils/console_error');
function scriptsMin() {
return gulp.src( [config.paths.dist.scripts.all, '!'+config.paths.dist.scripts.all_minified] )
.pipe(
$.plumber({
errorHandler: consoleError
})
)
.pipe( $.uglify() )
.pipe(
$.rename( function(path) {
path.basename += '.min';
})
)
.pipe( gulp.dest( config.paths.dist.scripts.path ) );
};
module.exports = scriptsMin;
|
angular.module("appointmentModule")
.factory("appointmentService", appointmentService);
appointmentService.$inject = ['$http'];
function appointmentService($http) {
return {
getAllAppointmentSlots: function () {
return $http.get('/appointment/getAllAppointments');
},
getAllMakesByYear: function (year) {
console.log('year in service below');
console.log(year);
return $http.get('/vehicle/getAllMakesByYear/'+ year);
},
getAllVehicle: function() {
return $http.get('/vehicle/getAllVehicle');
},
getYears: function() {
return $http.get('/vehicle/getYears');
},
getAllModelsByYearAndMake: function(year, model) {
return $http.get('/vehicle/getAllModelsByYearAndMake/'+year+'/'+model);
},
getAvailableAppointmentDates: function () {
return $http.get('/appointment/getAvailableAppointmentDates');
},
getAvailableTimeSlotsForDate: function (date) {
return $http.get('/appointment/getAvailableTimeSlotsForDate/'+date);
},
getAvailableServices: function() {
return $http.get('/vehicle/getAvailableServices');
},
schedule: function (appointment) {
return $http.post('/appointment/schedule', {appointment});
},
createOwnerInformation: function(appointment) {
return $http.post('/appointment/createOwnerInformation',
{
first_name : appointment.first_name,
last_name : appointment.last_name,
email : appointment.email,
phone_number : appointment.phone_number
});
},
createAppointment: function(appointment) {
return $http.post('/appointment/createAppointment', appointment);
},
createServices: function(services, appointment_id) {
return $http.post('/appointment/createAppointmentServices', {services, appointment_id});
},
appointmentConfirmation: function(appointment_id) {
return $http.get('/appointment/confirmation/'+appointment_id);
},
cancelAppointment: function(id) {
return $http.post('/appointment/cancelAppointment',{id : id});
}
};
}
|
module.exports = {
_meta: {
id: "it-IT",
fallback: null,
language: "Italian",
country: "Italy",
countryCode: "IT"
},
names: require("./names"),
phone: require("./phone"),
address: require("./address"),
company: require("./company"),
internet: require("./internet")
}; |
// Dependencies
import builder from 'focus-core/component/builder';
import types from 'focus-core/component/types';
const React = require('react');
const {omit, keys} = require('lodash/object');
const {reduce} = require('lodash/collection');
// Table class.
const TABLE_CSS_CLASS = 'mdl-data-table mdl-js-data-table mdl-shadow--2dp ';
const TABLE_CELL_CLASS = 'mdl-data-table__cell--non-numeric';
// Mixins
const infiniteScrollMixin = require('../mixin/infinite-scroll').mixin;
const translationMixin = require('../../common/i18n').mixin;
const referenceMixin = require('../../common/mixin/reference-property');
const mdlBehaviour = require('../../common/mixin/mdl-behaviour');
// Components
const Button = require('../../common/button/action').component;
const tableMixin = {
/**
* React tag name.
*/
displayName: 'Table',
/**
* Mixin dependancies.
*/
mixins: [translationMixin, infiniteScrollMixin, referenceMixin, mdlBehaviour],
/** inheriteddoc */
getDefaultProps() {
return {
data: [],
idField: 'id',
isLoading: false,
operationList: [],
isSelectable: false
};
},
/** inheriteddoc */
proptypes: {
data: types('array'),
isSelectable: types('bool'),
onLineClick: types('func'),
idField: types('string'),
lineComponent: types('func').isRequired,
operationList: types('array'),
columns: types('object'),
sortColumn: types('func'),
isloading: types('bool'),
loader: types('func')
},
/**
* Render the table header.
* @return {Component} - Render the table header.
*/
_renderTableHeader() {
const {columns} = this.props;
return <thead><tr>{reduce(columns, this._renderColumnHeader, [])}</tr></thead>;
},
/**
* Build a function which is called when there is a click on a table column.
* @param {string} column - Column name.
* @param {string} order - The order config.
* @return {function} - The function to be called when there is a click on it.
*/
_sortColumnAction(column, order) {
let currentComponent = this;
return (event) => {
event.preventDefault();
currentComponent.props.sortColumn(column, order);
};
},
/**
* Render the column header.
* @param {array} accumulator - The array co,ntaining the accumulating component.
* @param {object} colProperties - The column properties.
* @param {string} name - The column name.
* @return {Component} - The component header.
*/
_renderColumnHeader(accumulator, colProperties, name) {
let sort;
if(!this.props.isEdit && !colProperties.noSort ) {
const order = colProperties.sort ? colProperties.sort : 'asc';
const iconName = 'asc' === order ? 'arrow_drop_up' : 'arrow_drop_down';
const icon = <i className='material-icons'>{iconName}</i>;
sort = <a className='sort' data-bypass data-name={name} href='#' onClick={this._sortColumnAction(name, ('asc' === order ? 'desc' : 'asc' ))}>{icon}</a>;
}
accumulator.push(<th className={TABLE_CELL_CLASS}>{this.i18n(colProperties.label)}{sort}</th>);
return accumulator;
},
/**
* Render the tbody tag and the content.
* @return {Component} - The component containing the tbody.
*/
_renderTableBody() {
const {data, LineComponent: TableLineComponent, idField} = this.props;
const reference = this._getReference();
return (
<tbody>
{data.map((line, index) => {
const otherLineProps = omit(this.props, 'data');
return <TableLineComponent className={TABLE_CELL_CLASS} data={line} key={line[idField]} ref={`line-${index}`} reference={reference} {...otherLineProps}/>;
})}
</tbody>
);
},
/**
* Render the loading table
* @return {Component} - The table in the loading mode.
*/
_renderLoading() {
const {isLoading, loader} = this.props;
if(isLoading) {
if(loader) {
return loader();
}
return (
<tbody className={'table-loading'}>
<tr>
<td>{`${this.i18n('list.loading')}`}</td>
</tr>
</tbody>
);
}
},
/**
* Render the manual fetch mode for the table.
* @return {Component} - The footer component when the mode is manual fetch , a show mode button is shown.
*/
_renderManualFetch() {
const {isManualFetch, hasMoreData} = this.props;
if(isManualFetch && hasMoreData) {
return (
<tfoot className="table-manual-fetch">
<tr>
<td colSpan={keys(this.props.columns).length}>
<Button handleOnClick={this.fetchNextPage} label="list.button.showMore" type="button" />
</td>
</tr>
</tfoot>
);
}
},
/**
* Render the list.
* @return {XML} the render of the table list.
*/
render() {
const SELECTABLE_CSS = this.props.isSelectable ? 'mdl-data-table--selectable' : '';
return (
<table className={`${TABLE_CSS_CLASS} ${SELECTABLE_CSS}`}>
{this._renderTableHeader()}
{this._renderTableBody()}
{this._renderLoading()}
{this._renderManualFetch()}
</table>
);
}
};
module.exports = builder(tableMixin);
|
const { PacketType, Decoder, Encoder } = require("..");
const expect = require("expect.js");
const helpers = require("./helpers.js");
const encoder = new Encoder();
describe("parser", () => {
it("encodes an ArrayBuffer", (done) => {
const packet = {
type: PacketType.EVENT,
data: ["a", new ArrayBuffer(2)],
id: 0,
nsp: "/",
};
helpers.test_bin(packet, done);
});
it("encodes a TypedArray", (done) => {
const array = new Uint8Array(5);
for (let i = 0; i < array.length; i++) array[i] = i;
const packet = {
type: PacketType.EVENT,
data: ["a", array],
id: 0,
nsp: "/",
};
helpers.test_bin(packet, done);
});
it("encodes ArrayBuffers deep in JSON", (done) => {
const packet = {
type: PacketType.EVENT,
data: [
"a",
{
a: "hi",
b: { why: new ArrayBuffer(3) },
c: { a: "bye", b: { a: new ArrayBuffer(6) } },
},
],
id: 999,
nsp: "/deep",
};
helpers.test_bin(packet, done);
});
it("encodes deep binary JSON with null values", (done) => {
const packet = {
type: PacketType.EVENT,
data: ["a", { a: "b", c: 4, e: { g: null }, h: new ArrayBuffer(9) }],
nsp: "/",
id: 600,
};
helpers.test_bin(packet, done);
});
it("cleans itself up on close", () => {
const packet = {
type: PacketType.EVENT,
data: ["a", new ArrayBuffer(2), new ArrayBuffer(3)],
id: 0,
nsp: "/",
};
const encodedPackets = encoder.encode(packet);
const decoder = new Decoder();
decoder.on("decoded", (packet) => {
throw new Error("received a packet when not all binary data was sent.");
});
decoder.add(encodedPackets[0]); // add metadata
decoder.add(encodedPackets[1]); // add first attachment
decoder.destroy(); // destroy before all data added
expect(decoder.reconstructor.buffers.length).to.be(0); // expect that buffer is clean
});
});
|
// Remove padding from a string.
function unpad(str) {
const lines = str.split('\n');
const m = lines[1] && lines[1].match(/^\s+/);
if (!m) {
return str;
}
const spaces = m[0].length;
return lines.map(
line => line.slice(spaces)
).join('\n').trim();
}
module.exports = unpad;
|
import Page from "./page"
class Search extends Page {
get foundPeopleTable() {
return browser.$("div#people #people-search-results")
}
get foundTaskTable() {
return browser.$("div#tasks #tasks-search-results")
}
linkOfPersonFound(name) {
return this.foundPeopleTable.$(`//tbody/tr//a[contains(text(), "${name}")]`)
}
linkOfTaskFound(name) {
return this.foundTaskTable.$(`//tbody/tr//a[contains(text(), "${name}")]`)
}
}
export default new Search()
|
//
// Queue class - A queue contains a list of items. Only one item can be active
// at a time, and when one is removed the next one is activated
//
// To use this class, first add() your item. A promise will be returned that gets resolved
// when your item is ready to be activated. Once your item is finished doing what it needs
// to do, remove() it. This will trigger the next item's promise.
//
// Example:
//
// var queue = new Queue();
//
// var msgbox = new Popup();
// queue.add(msgbox).then(() => {
// msgbox.show();
// msgbox.when('closed').then(() => queue.remove(msgbox));
// }
//
// var msgbox2 = new Popup();
// queue.add(msgbox2).then(() => {
// msgbox2.show();
// msgbox2.when('closed').then(() => queue.remove(msgbox2));
// }
//
//
// In the above example, only one message box would be visible at a time.
//
import EventSource from './event-source.js'
export default class Queue extends EventSource {
constructor() {
super();
// Setup vars
this.items = [];
this.current = null;
}
/** Adds a queue item, and returns a Promise. */
add(item) {
// Return a promise
return new Promise((onSuccess, onFail) => {
// Store item and handler at the end of the queue. When this item is ready to be activated, the handler will be called to resolve the promise.
this.items.push({
item: item,
activateHandler: onSuccess
});
// Emit event
this.emit("added", item);
// Check if we can activate this one now
setTimeout(this.checkActivated.bind(this), 1);
});
}
/** @private Checks if there a new item to be activated */
checkActivated() {
// Check if there's already an activated item
if (this.current)
return;
// Check if we have any items
if (this.items.length == 0) {
// No more items
this.emit("empty");
return;
}
// We can activate the next item now
this.current = this.items[0];
// Create promise resolve response. DO NOT directly pass a thenable, it won't work!
var resp = {
item: this.current.item
}
// Resolve promise
this.current.activateHandler && this.current.activateHandler(resp);
// Trigger event
this.emit("activated", resp);
}
/** Removes a queued item. If the item is the currently activated one, the next item in the queue will be activated. */
remove(item) {
// Remove item from queue
for (var i = 0 ; i < this.items.length ; i++)
if (this.items[i].item == item)
this.items.splice(i--, 1);
// Emit event
this.emit("removed", item);
// Check if this was the current item
if (this.current && this.current.item == item)
this.current = null;
// Possibly activate the next item
setTimeout(this.checkActivated.bind(this), 1);
}
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M4 9h10.5v3.5H4zm0 5.5h10.5V18H4zM16.5 9H20v9h-3.5z" opacity=".3" /><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5.5 14H4v-3.5h10.5V18zm0-5.5H4V9h10.5v3.5zM20 18h-3.5V9H20v9z" /></React.Fragment>
, 'WebTwoTone');
|
var ObjectRegistry = (function () {
function ObjectRegistry() {
this._objects = {};
}
ObjectRegistry.prototype.register = function (name, className) {
this._objects[name] = new className();
};
ObjectRegistry.prototype.invoke = function (name, method, params) {
try {
var instance = this._objects[name];
return instance[method](params);
}
catch (err) {
var msg = 'ObjectRegistry invoke fail on ' + name + '.' + method;
msg += (params) ? '(' + JSON.stringify(params) + ')' : '()';
throw (msg);
}
};
ObjectRegistry.prototype.get = function (name) {
return this._objects[name];
};
return ObjectRegistry;
})();
exports.ObjectRegistry = ObjectRegistry;
var ClassRegistry = (function () {
function ClassRegistry() {
this._classNames = {};
}
ClassRegistry.prototype.register = function (name, className) {
this._classNames[name] = className;
};
ClassRegistry.prototype.invoke = function (name, method, params) {
try {
var instance = new this._classNames[name];
return instance[method](params);
}
catch (err) {
var msg = 'ClassRegistry invoke fail on ' + name + '.' + method;
msg += (params) ? '(' + JSON.stringify(params) + ')' : '()';
throw (msg);
}
};
ClassRegistry.prototype.get = function (name) {
return this._classNames[name];
};
return ClassRegistry;
})();
exports.ClassRegistry = ClassRegistry;
var KeyRegistry = (function () {
function KeyRegistry(key, registry) {
this._objects = {};
this._key = key;
this._classRegistry = registry;
}
KeyRegistry.prototype.register = function (name, className) {
throw 'Register method should not be use on KeyRegistry';
};
KeyRegistry.prototype.invoke = function (name, method, params) {
try {
var instance = this._objects[this._key + ':' + name];
if (!instance) {
var className = this._classRegistry.get(name);
this._objects[this._key + ':' + name] = new className();
instance = this._objects[this._key + ':' + name];
}
return instance[method](params);
}
catch (err) {
var msg = 'KeyRegistry ' + this._key + ' invoke fail on ' + name + '.' + method;
msg += (params) ? '(' + JSON.stringify(params) + ')' : '()';
throw (msg);
}
};
KeyRegistry.prototype.key = function () {
return this._key;
};
KeyRegistry.prototype.get = function (name) {
return this._classRegistry.get(name);
};
return KeyRegistry;
})();
exports.KeyRegistry = KeyRegistry;
//# sourceMappingURL=Registry.js.map |
/**
* @license Angular v6.1.10
* (c) 2010-2018 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/core')) :
typeof define === 'function' && define.amd ? define('@angular/platform-browser', ['exports', '@angular/common', '@angular/core'], factory) :
(factory((global.ng = global.ng || {}, global.ng.platformBrowser = {}),global.ng.common,global.ng.core));
}(this, (function (exports,common,core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _DOM = null;
function getDOM() {
return _DOM;
}
function setRootDomAdapter(adapter) {
if (!_DOM) {
_DOM = adapter;
}
}
/* tslint:disable:requireParameterType */
/**
* Provides DOM operations in an environment-agnostic way.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
var DomAdapter = /** @class */ (function () {
function DomAdapter() {
this.resourceLoaderType = null;
}
Object.defineProperty(DomAdapter.prototype, "attrToPropMap", {
/**
* Maps attribute names to their corresponding property names for cases
* where attribute name doesn't match property name.
*/
get: function () { return this._attrToPropMap; },
set: function (value) { this._attrToPropMap = value; },
enumerable: true,
configurable: true
});
return DomAdapter;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Provides DOM operations in any browser environment.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
var GenericBrowserDomAdapter = /** @class */ (function (_super) {
__extends(GenericBrowserDomAdapter, _super);
function GenericBrowserDomAdapter() {
var _this = _super.call(this) || this;
_this._animationPrefix = null;
_this._transitionEnd = null;
try {
var element_1 = _this.createElement('div', document);
if (_this.getStyle(element_1, 'animationName') != null) {
_this._animationPrefix = '';
}
else {
var domPrefixes = ['Webkit', 'Moz', 'O', 'ms'];
for (var i = 0; i < domPrefixes.length; i++) {
if (_this.getStyle(element_1, domPrefixes[i] + 'AnimationName') != null) {
_this._animationPrefix = '-' + domPrefixes[i].toLowerCase() + '-';
break;
}
}
}
var transEndEventNames_1 = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
Object.keys(transEndEventNames_1).forEach(function (key) {
if (_this.getStyle(element_1, key) != null) {
_this._transitionEnd = transEndEventNames_1[key];
}
});
}
catch (e) {
_this._animationPrefix = null;
_this._transitionEnd = null;
}
return _this;
}
GenericBrowserDomAdapter.prototype.getDistributedNodes = function (el) { return el.getDistributedNodes(); };
GenericBrowserDomAdapter.prototype.resolveAndSetHref = function (el, baseUrl, href) {
el.href = href == null ? baseUrl : baseUrl + '/../' + href;
};
GenericBrowserDomAdapter.prototype.supportsDOMEvents = function () { return true; };
GenericBrowserDomAdapter.prototype.supportsNativeShadowDOM = function () {
return typeof document.body.createShadowRoot === 'function';
};
GenericBrowserDomAdapter.prototype.getAnimationPrefix = function () { return this._animationPrefix ? this._animationPrefix : ''; };
GenericBrowserDomAdapter.prototype.getTransitionEnd = function () { return this._transitionEnd ? this._transitionEnd : ''; };
GenericBrowserDomAdapter.prototype.supportsAnimation = function () {
return this._animationPrefix != null && this._transitionEnd != null;
};
return GenericBrowserDomAdapter;
}(DomAdapter));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _attrToPropMap = {
'class': 'className',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
var DOM_KEY_LOCATION_NUMPAD = 3;
// Map to convert some key or keyIdentifier values to what will be returned by getEventKey
var _keyMap = {
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf http://www.w3.org/TR/DOM-Level-3-Events-key/
'\b': 'Backspace',
'\t': 'Tab',
'\x7F': 'Delete',
'\x1B': 'Escape',
'Del': 'Delete',
'Esc': 'Escape',
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Up': 'ArrowUp',
'Down': 'ArrowDown',
'Menu': 'ContextMenu',
'Scroll': 'ScrollLock',
'Win': 'OS'
};
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
var _chromeNumKeyPadMap = {
'A': '1',
'B': '2',
'C': '3',
'D': '4',
'E': '5',
'F': '6',
'G': '7',
'H': '8',
'I': '9',
'J': '*',
'K': '+',
'M': '-',
'N': '.',
'O': '/',
'\x60': '0',
'\x90': 'NumLock'
};
var nodeContains;
if (core.ɵglobal['Node']) {
nodeContains = core.ɵglobal['Node'].prototype.contains || function (node) {
return !!(this.compareDocumentPosition(node) & 16);
};
}
/**
* A `DomAdapter` powered by full browser DOM APIs.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
/* tslint:disable:requireParameterType no-console */
var BrowserDomAdapter = /** @class */ (function (_super) {
__extends(BrowserDomAdapter, _super);
function BrowserDomAdapter() {
return _super !== null && _super.apply(this, arguments) || this;
}
BrowserDomAdapter.prototype.parse = function (templateHtml) { throw new Error('parse not implemented'); };
BrowserDomAdapter.makeCurrent = function () { setRootDomAdapter(new BrowserDomAdapter()); };
BrowserDomAdapter.prototype.hasProperty = function (element, name) { return name in element; };
BrowserDomAdapter.prototype.setProperty = function (el, name, value) { el[name] = value; };
BrowserDomAdapter.prototype.getProperty = function (el, name) { return el[name]; };
BrowserDomAdapter.prototype.invoke = function (el, methodName, args) {
var _a;
(_a = el)[methodName].apply(_a, __spread(args));
};
// TODO(tbosch): move this into a separate environment class once we have it
BrowserDomAdapter.prototype.logError = function (error) {
if (window.console) {
if (console.error) {
console.error(error);
}
else {
console.log(error);
}
}
};
BrowserDomAdapter.prototype.log = function (error) {
if (window.console) {
window.console.log && window.console.log(error);
}
};
BrowserDomAdapter.prototype.logGroup = function (error) {
if (window.console) {
window.console.group && window.console.group(error);
}
};
BrowserDomAdapter.prototype.logGroupEnd = function () {
if (window.console) {
window.console.groupEnd && window.console.groupEnd();
}
};
Object.defineProperty(BrowserDomAdapter.prototype, "attrToPropMap", {
get: function () { return _attrToPropMap; },
enumerable: true,
configurable: true
});
BrowserDomAdapter.prototype.contains = function (nodeA, nodeB) { return nodeContains.call(nodeA, nodeB); };
BrowserDomAdapter.prototype.querySelector = function (el, selector) { return el.querySelector(selector); };
BrowserDomAdapter.prototype.querySelectorAll = function (el, selector) { return el.querySelectorAll(selector); };
BrowserDomAdapter.prototype.on = function (el, evt, listener) { el.addEventListener(evt, listener, false); };
BrowserDomAdapter.prototype.onAndCancel = function (el, evt, listener) {
el.addEventListener(evt, listener, false);
// Needed to follow Dart's subscription semantic, until fix of
// https://code.google.com/p/dart/issues/detail?id=17406
return function () { el.removeEventListener(evt, listener, false); };
};
BrowserDomAdapter.prototype.dispatchEvent = function (el, evt) { el.dispatchEvent(evt); };
BrowserDomAdapter.prototype.createMouseEvent = function (eventType) {
var evt = this.getDefaultDocument().createEvent('MouseEvent');
evt.initEvent(eventType, true, true);
return evt;
};
BrowserDomAdapter.prototype.createEvent = function (eventType) {
var evt = this.getDefaultDocument().createEvent('Event');
evt.initEvent(eventType, true, true);
return evt;
};
BrowserDomAdapter.prototype.preventDefault = function (evt) {
evt.preventDefault();
evt.returnValue = false;
};
BrowserDomAdapter.prototype.isPrevented = function (evt) {
return evt.defaultPrevented || evt.returnValue != null && !evt.returnValue;
};
BrowserDomAdapter.prototype.getInnerHTML = function (el) { return el.innerHTML; };
BrowserDomAdapter.prototype.getTemplateContent = function (el) {
return 'content' in el && this.isTemplateElement(el) ? el.content : null;
};
BrowserDomAdapter.prototype.getOuterHTML = function (el) { return el.outerHTML; };
BrowserDomAdapter.prototype.nodeName = function (node) { return node.nodeName; };
BrowserDomAdapter.prototype.nodeValue = function (node) { return node.nodeValue; };
BrowserDomAdapter.prototype.type = function (node) { return node.type; };
BrowserDomAdapter.prototype.content = function (node) {
if (this.hasProperty(node, 'content')) {
return node.content;
}
else {
return node;
}
};
BrowserDomAdapter.prototype.firstChild = function (el) { return el.firstChild; };
BrowserDomAdapter.prototype.nextSibling = function (el) { return el.nextSibling; };
BrowserDomAdapter.prototype.parentElement = function (el) { return el.parentNode; };
BrowserDomAdapter.prototype.childNodes = function (el) { return el.childNodes; };
BrowserDomAdapter.prototype.childNodesAsList = function (el) {
var childNodes = el.childNodes;
var res = new Array(childNodes.length);
for (var i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}
return res;
};
BrowserDomAdapter.prototype.clearNodes = function (el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
};
BrowserDomAdapter.prototype.appendChild = function (el, node) { el.appendChild(node); };
BrowserDomAdapter.prototype.removeChild = function (el, node) { el.removeChild(node); };
BrowserDomAdapter.prototype.replaceChild = function (el, newChild, oldChild) { el.replaceChild(newChild, oldChild); };
BrowserDomAdapter.prototype.remove = function (node) {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
return node;
};
BrowserDomAdapter.prototype.insertBefore = function (parent, ref, node) { parent.insertBefore(node, ref); };
BrowserDomAdapter.prototype.insertAllBefore = function (parent, ref, nodes) {
nodes.forEach(function (n) { return parent.insertBefore(n, ref); });
};
BrowserDomAdapter.prototype.insertAfter = function (parent, ref, node) { parent.insertBefore(node, ref.nextSibling); };
BrowserDomAdapter.prototype.setInnerHTML = function (el, value) { el.innerHTML = value; };
BrowserDomAdapter.prototype.getText = function (el) { return el.textContent; };
BrowserDomAdapter.prototype.setText = function (el, value) { el.textContent = value; };
BrowserDomAdapter.prototype.getValue = function (el) { return el.value; };
BrowserDomAdapter.prototype.setValue = function (el, value) { el.value = value; };
BrowserDomAdapter.prototype.getChecked = function (el) { return el.checked; };
BrowserDomAdapter.prototype.setChecked = function (el, value) { el.checked = value; };
BrowserDomAdapter.prototype.createComment = function (text) { return this.getDefaultDocument().createComment(text); };
BrowserDomAdapter.prototype.createTemplate = function (html) {
var t = this.getDefaultDocument().createElement('template');
t.innerHTML = html;
return t;
};
BrowserDomAdapter.prototype.createElement = function (tagName, doc) {
doc = doc || this.getDefaultDocument();
return doc.createElement(tagName);
};
BrowserDomAdapter.prototype.createElementNS = function (ns, tagName, doc) {
doc = doc || this.getDefaultDocument();
return doc.createElementNS(ns, tagName);
};
BrowserDomAdapter.prototype.createTextNode = function (text, doc) {
doc = doc || this.getDefaultDocument();
return doc.createTextNode(text);
};
BrowserDomAdapter.prototype.createScriptTag = function (attrName, attrValue, doc) {
doc = doc || this.getDefaultDocument();
var el = doc.createElement('SCRIPT');
el.setAttribute(attrName, attrValue);
return el;
};
BrowserDomAdapter.prototype.createStyleElement = function (css, doc) {
doc = doc || this.getDefaultDocument();
var style = doc.createElement('style');
this.appendChild(style, this.createTextNode(css, doc));
return style;
};
BrowserDomAdapter.prototype.createShadowRoot = function (el) { return el.createShadowRoot(); };
BrowserDomAdapter.prototype.getShadowRoot = function (el) { return el.shadowRoot; };
BrowserDomAdapter.prototype.getHost = function (el) { return el.host; };
BrowserDomAdapter.prototype.clone = function (node) { return node.cloneNode(true); };
BrowserDomAdapter.prototype.getElementsByClassName = function (element, name) {
return element.getElementsByClassName(name);
};
BrowserDomAdapter.prototype.getElementsByTagName = function (element, name) {
return element.getElementsByTagName(name);
};
BrowserDomAdapter.prototype.classList = function (element) { return Array.prototype.slice.call(element.classList, 0); };
BrowserDomAdapter.prototype.addClass = function (element, className) { element.classList.add(className); };
BrowserDomAdapter.prototype.removeClass = function (element, className) { element.classList.remove(className); };
BrowserDomAdapter.prototype.hasClass = function (element, className) {
return element.classList.contains(className);
};
BrowserDomAdapter.prototype.setStyle = function (element, styleName, styleValue) {
element.style[styleName] = styleValue;
};
BrowserDomAdapter.prototype.removeStyle = function (element, stylename) {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
element.style[stylename] = '';
};
BrowserDomAdapter.prototype.getStyle = function (element, stylename) { return element.style[stylename]; };
BrowserDomAdapter.prototype.hasStyle = function (element, styleName, styleValue) {
var value = this.getStyle(element, styleName) || '';
return styleValue ? value == styleValue : value.length > 0;
};
BrowserDomAdapter.prototype.tagName = function (element) { return element.tagName; };
BrowserDomAdapter.prototype.attributeMap = function (element) {
var res = new Map();
var elAttrs = element.attributes;
for (var i = 0; i < elAttrs.length; i++) {
var attrib = elAttrs.item(i);
res.set(attrib.name, attrib.value);
}
return res;
};
BrowserDomAdapter.prototype.hasAttribute = function (element, attribute) {
return element.hasAttribute(attribute);
};
BrowserDomAdapter.prototype.hasAttributeNS = function (element, ns, attribute) {
return element.hasAttributeNS(ns, attribute);
};
BrowserDomAdapter.prototype.getAttribute = function (element, attribute) {
return element.getAttribute(attribute);
};
BrowserDomAdapter.prototype.getAttributeNS = function (element, ns, name) {
return element.getAttributeNS(ns, name);
};
BrowserDomAdapter.prototype.setAttribute = function (element, name, value) { element.setAttribute(name, value); };
BrowserDomAdapter.prototype.setAttributeNS = function (element, ns, name, value) {
element.setAttributeNS(ns, name, value);
};
BrowserDomAdapter.prototype.removeAttribute = function (element, attribute) { element.removeAttribute(attribute); };
BrowserDomAdapter.prototype.removeAttributeNS = function (element, ns, name) {
element.removeAttributeNS(ns, name);
};
BrowserDomAdapter.prototype.templateAwareRoot = function (el) { return this.isTemplateElement(el) ? this.content(el) : el; };
BrowserDomAdapter.prototype.createHtmlDocument = function () {
return document.implementation.createHTMLDocument('fakeTitle');
};
BrowserDomAdapter.prototype.getDefaultDocument = function () { return document; };
BrowserDomAdapter.prototype.getBoundingClientRect = function (el) {
try {
return el.getBoundingClientRect();
}
catch (e) {
return { top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0 };
}
};
BrowserDomAdapter.prototype.getTitle = function (doc) { return doc.title; };
BrowserDomAdapter.prototype.setTitle = function (doc, newTitle) { doc.title = newTitle || ''; };
BrowserDomAdapter.prototype.elementMatches = function (n, selector) {
if (this.isElementNode(n)) {
return n.matches && n.matches(selector) ||
n.msMatchesSelector && n.msMatchesSelector(selector) ||
n.webkitMatchesSelector && n.webkitMatchesSelector(selector);
}
return false;
};
BrowserDomAdapter.prototype.isTemplateElement = function (el) {
return this.isElementNode(el) && el.nodeName === 'TEMPLATE';
};
BrowserDomAdapter.prototype.isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
BrowserDomAdapter.prototype.isCommentNode = function (node) { return node.nodeType === Node.COMMENT_NODE; };
BrowserDomAdapter.prototype.isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
BrowserDomAdapter.prototype.hasShadowRoot = function (node) {
return node.shadowRoot != null && node instanceof HTMLElement;
};
BrowserDomAdapter.prototype.isShadowRoot = function (node) { return node instanceof DocumentFragment; };
BrowserDomAdapter.prototype.importIntoDoc = function (node) { return document.importNode(this.templateAwareRoot(node), true); };
BrowserDomAdapter.prototype.adoptNode = function (node) { return document.adoptNode(node); };
BrowserDomAdapter.prototype.getHref = function (el) { return el.getAttribute('href'); };
BrowserDomAdapter.prototype.getEventKey = function (event) {
var key = event.key;
if (key == null) {
key = event.keyIdentifier;
// keyIdentifier is defined in the old draft of DOM Level 3 Events implemented by Chrome and
// Safari cf
// http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/events.html#Events-KeyboardEvents-Interfaces
if (key == null) {
return 'Unidentified';
}
if (key.startsWith('U+')) {
key = String.fromCharCode(parseInt(key.substring(2), 16));
if (event.location === DOM_KEY_LOCATION_NUMPAD && _chromeNumKeyPadMap.hasOwnProperty(key)) {
// There is a bug in Chrome for numeric keypad keys:
// https://code.google.com/p/chromium/issues/detail?id=155654
// 1, 2, 3 ... are reported as A, B, C ...
key = _chromeNumKeyPadMap[key];
}
}
}
return _keyMap[key] || key;
};
BrowserDomAdapter.prototype.getGlobalEventTarget = function (doc, target) {
if (target === 'window') {
return window;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
};
BrowserDomAdapter.prototype.getHistory = function () { return window.history; };
BrowserDomAdapter.prototype.getLocation = function () { return window.location; };
BrowserDomAdapter.prototype.getBaseHref = function (doc) {
var href = getBaseElementHref();
return href == null ? null : relativePath(href);
};
BrowserDomAdapter.prototype.resetBaseElement = function () { baseElement = null; };
BrowserDomAdapter.prototype.getUserAgent = function () { return window.navigator.userAgent; };
BrowserDomAdapter.prototype.setData = function (element, name, value) {
this.setAttribute(element, 'data-' + name, value);
};
BrowserDomAdapter.prototype.getData = function (element, name) {
return this.getAttribute(element, 'data-' + name);
};
BrowserDomAdapter.prototype.getComputedStyle = function (element) { return getComputedStyle(element); };
// TODO(tbosch): move this into a separate environment class once we have it
BrowserDomAdapter.prototype.supportsWebAnimation = function () {
return typeof Element.prototype['animate'] === 'function';
};
BrowserDomAdapter.prototype.performanceNow = function () {
// performance.now() is not available in all browsers, see
// http://caniuse.com/#search=performance.now
return window.performance && window.performance.now ? window.performance.now() :
new Date().getTime();
};
BrowserDomAdapter.prototype.supportsCookies = function () { return true; };
BrowserDomAdapter.prototype.getCookie = function (name) { return common.ɵparseCookieValue(document.cookie, name); };
BrowserDomAdapter.prototype.setCookie = function (name, value) {
// document.cookie is magical, assigning into it assigns/overrides one cookie value, but does
// not clear other cookies.
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
};
return BrowserDomAdapter;
}(GenericBrowserDomAdapter));
var baseElement = null;
function getBaseElementHref() {
if (!baseElement) {
baseElement = document.querySelector('base');
if (!baseElement) {
return null;
}
}
return baseElement.getAttribute('href');
}
// based on urlUtils.js in AngularJS 1
var urlParsingNode;
function relativePath(url) {
if (!urlParsingNode) {
urlParsingNode = document.createElement('a');
}
urlParsingNode.setAttribute('href', url);
return (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname :
'/' + urlParsingNode.pathname;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A DI Token representing the main rendering context. In a browser this is the DOM Document.
*
* Note: Document might not be available in the Application Context when Application and Rendering
* Contexts are not the same (e.g. when running the application into a Web Worker).
*
* @deprecated import from `@angular/common` instead.
*/
var DOCUMENT = common.DOCUMENT;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function supportsState() {
return !!window.history.pushState;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* `PlatformLocation` encapsulates all of the direct calls to platform APIs.
* This class should not be used directly by an application developer. Instead, use
* {@link Location}.
*/
var BrowserPlatformLocation = /** @class */ (function (_super) {
__extends(BrowserPlatformLocation, _super);
function BrowserPlatformLocation(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
_this._init();
return _this;
}
// This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it
/** @internal */
BrowserPlatformLocation.prototype._init = function () {
this.location = getDOM().getLocation();
this._history = getDOM().getHistory();
};
BrowserPlatformLocation.prototype.getBaseHrefFromDOM = function () { return getDOM().getBaseHref(this._doc); };
BrowserPlatformLocation.prototype.onPopState = function (fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('popstate', fn, false);
};
BrowserPlatformLocation.prototype.onHashChange = function (fn) {
getDOM().getGlobalEventTarget(this._doc, 'window').addEventListener('hashchange', fn, false);
};
Object.defineProperty(BrowserPlatformLocation.prototype, "pathname", {
get: function () { return this.location.pathname; },
set: function (newPath) { this.location.pathname = newPath; },
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserPlatformLocation.prototype, "search", {
get: function () { return this.location.search; },
enumerable: true,
configurable: true
});
Object.defineProperty(BrowserPlatformLocation.prototype, "hash", {
get: function () { return this.location.hash; },
enumerable: true,
configurable: true
});
BrowserPlatformLocation.prototype.pushState = function (state, title, url) {
if (supportsState()) {
this._history.pushState(state, title, url);
}
else {
this.location.hash = url;
}
};
BrowserPlatformLocation.prototype.replaceState = function (state, title, url) {
if (supportsState()) {
this._history.replaceState(state, title, url);
}
else {
this.location.hash = url;
}
};
BrowserPlatformLocation.prototype.forward = function () { this._history.forward(); };
BrowserPlatformLocation.prototype.back = function () { this._history.back(); };
BrowserPlatformLocation = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], BrowserPlatformLocation);
return BrowserPlatformLocation;
}(common.PlatformLocation));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* An id that identifies a particular application being bootstrapped, that should
* match across the client/server boundary.
*/
var TRANSITION_ID = new core.InjectionToken('TRANSITION_ID');
function appInitializerFactory(transitionId, document, injector) {
return function () {
// Wait for all application initializers to be completed before removing the styles set by
// the server.
injector.get(core.ApplicationInitStatus).donePromise.then(function () {
var dom = getDOM();
var styles = Array.prototype.slice.apply(dom.querySelectorAll(document, "style[ng-transition]"));
styles.filter(function (el) { return dom.getAttribute(el, 'ng-transition') === transitionId; })
.forEach(function (el) { return dom.remove(el); });
});
};
}
var SERVER_TRANSITION_PROVIDERS = [
{
provide: core.APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [TRANSITION_ID, DOCUMENT, core.Injector],
multi: true
},
];
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var BrowserGetTestability = /** @class */ (function () {
function BrowserGetTestability() {
}
BrowserGetTestability.init = function () { core.setTestabilityGetter(new BrowserGetTestability()); };
BrowserGetTestability.prototype.addToWindow = function (registry) {
core.ɵglobal['getAngularTestability'] = function (elem, findInAncestors) {
if (findInAncestors === void 0) { findInAncestors = true; }
var testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new Error('Could not find testability for element.');
}
return testability;
};
core.ɵglobal['getAllAngularTestabilities'] = function () { return registry.getAllTestabilities(); };
core.ɵglobal['getAllAngularRootElements'] = function () { return registry.getAllRootElements(); };
var whenAllStable = function (callback /** TODO #9100 */) {
var testabilities = core.ɵglobal['getAllAngularTestabilities']();
var count = testabilities.length;
var didWork = false;
var decrement = function (didWork_ /** TODO #9100 */) {
didWork = didWork || didWork_;
count--;
if (count == 0) {
callback(didWork);
}
};
testabilities.forEach(function (testability /** TODO #9100 */) {
testability.whenStable(decrement);
});
};
if (!core.ɵglobal['frameworkStabilizers']) {
core.ɵglobal['frameworkStabilizers'] = [];
}
core.ɵglobal['frameworkStabilizers'].push(whenAllStable);
};
BrowserGetTestability.prototype.findTestabilityInTree = function (registry, elem, findInAncestors) {
if (elem == null) {
return null;
}
var t = registry.getTestability(elem);
if (t != null) {
return t;
}
else if (!findInAncestors) {
return null;
}
if (getDOM().isShadowRoot(elem)) {
return this.findTestabilityInTree(registry, getDOM().getHost(elem), true);
}
return this.findTestabilityInTree(registry, getDOM().parentElement(elem), true);
};
return BrowserGetTestability;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Exports the value under a given `name` in the global property `ng`. For example `ng.probe` if
* `name` is `'probe'`.
* @param name Name under which it will be exported. Keep in mind this will be a property of the
* global `ng` object.
* @param value The value to export.
*/
function exportNgVar(name, value) {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for angularJS (via `goog.provide('ng....')`).
var ng = core.ɵglobal['ng'] = core.ɵglobal['ng'] || {};
ng[name] = value;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var CORE_TOKENS = {
'ApplicationRef': core.ApplicationRef,
'NgZone': core.NgZone,
};
var INSPECT_GLOBAL_NAME = 'probe';
var CORE_TOKENS_GLOBAL_NAME = 'coreTokens';
/**
* Returns a {@link DebugElement} for the given native DOM element, or
* null if the given native element does not have an Angular view associated
* with it.
*/
function inspectNativeElement(element) {
return core.getDebugNode(element);
}
function _createNgProbe(coreTokens) {
exportNgVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
exportNgVar(CORE_TOKENS_GLOBAL_NAME, __assign({}, CORE_TOKENS, _ngProbeTokensToMap(coreTokens || [])));
return function () { return inspectNativeElement; };
}
function _ngProbeTokensToMap(tokens) {
return tokens.reduce(function (prev, t) { return (prev[t.name] = t.token, prev); }, {});
}
/**
* Providers which support debugging Angular applications (e.g. via `ng.probe`).
*/
var ELEMENT_PROBE_PROVIDERS = [
{
provide: core.APP_INITIALIZER,
useFactory: _createNgProbe,
deps: [
[core.NgProbeToken, new core.Optional()],
],
multi: true,
},
];
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* The injection token for the event-manager plug-in service.
*/
var EVENT_MANAGER_PLUGINS = new core.InjectionToken('EventManagerPlugins');
/**
* An injectable service that provides event management for Angular
* through a browser plug-in.
*/
var EventManager = /** @class */ (function () {
/**
* Initializes an instance of the event-manager service.
*/
function EventManager(plugins, _zone) {
var _this = this;
this._zone = _zone;
this._eventNameToPlugin = new Map();
plugins.forEach(function (p) { return p.manager = _this; });
this._plugins = plugins.slice().reverse();
}
/**
* Registers a handler for a specific element and event.
*
* @param element The HTML element to receive event notifications.
* @param eventName The name of the event to listen for.
* @param handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @returns A callback function that can be used to remove the handler.
*/
EventManager.prototype.addEventListener = function (element, eventName, handler) {
var plugin = this._findPluginFor(eventName);
return plugin.addEventListener(element, eventName, handler);
};
/**
* Registers a global handler for an event in a target view.
*
* @param target A target for global event notifications. One of "window", "document", or "body".
* @param eventName The name of the event to listen for.
* @param handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @returns A callback function that can be used to remove the handler.
*/
EventManager.prototype.addGlobalEventListener = function (target, eventName, handler) {
var plugin = this._findPluginFor(eventName);
return plugin.addGlobalEventListener(target, eventName, handler);
};
/**
* Retrieves the compilation zone in which event listeners are registered.
*/
EventManager.prototype.getZone = function () { return this._zone; };
/** @internal */
EventManager.prototype._findPluginFor = function (eventName) {
var plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
var plugins = this._plugins;
for (var i = 0; i < plugins.length; i++) {
var plugin_1 = plugins[i];
if (plugin_1.supports(eventName)) {
this._eventNameToPlugin.set(eventName, plugin_1);
return plugin_1;
}
}
throw new Error("No event manager plugin found for event " + eventName);
};
EventManager = __decorate([
core.Injectable(),
__param(0, core.Inject(EVENT_MANAGER_PLUGINS)),
__metadata("design:paramtypes", [Array, core.NgZone])
], EventManager);
return EventManager;
}());
var EventManagerPlugin = /** @class */ (function () {
function EventManagerPlugin(_doc) {
this._doc = _doc;
}
EventManagerPlugin.prototype.addGlobalEventListener = function (element, eventName, handler) {
var target = getDOM().getGlobalEventTarget(this._doc, element);
if (!target) {
throw new Error("Unsupported event target " + target + " for event " + eventName);
}
return this.addEventListener(target, eventName, handler);
};
return EventManagerPlugin;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var SharedStylesHost = /** @class */ (function () {
function SharedStylesHost() {
/** @internal */
this._stylesSet = new Set();
}
SharedStylesHost.prototype.addStyles = function (styles) {
var _this = this;
var additions = new Set();
styles.forEach(function (style) {
if (!_this._stylesSet.has(style)) {
_this._stylesSet.add(style);
additions.add(style);
}
});
this.onStylesAdded(additions);
};
SharedStylesHost.prototype.onStylesAdded = function (additions) { };
SharedStylesHost.prototype.getAllStyles = function () { return Array.from(this._stylesSet); };
SharedStylesHost = __decorate([
core.Injectable()
], SharedStylesHost);
return SharedStylesHost;
}());
var DomSharedStylesHost = /** @class */ (function (_super) {
__extends(DomSharedStylesHost, _super);
function DomSharedStylesHost(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
_this._hostNodes = new Set();
_this._styleNodes = new Set();
_this._hostNodes.add(_doc.head);
return _this;
}
DomSharedStylesHost.prototype._addStylesToHost = function (styles, host) {
var _this = this;
styles.forEach(function (style) {
var styleEl = _this._doc.createElement('style');
styleEl.textContent = style;
_this._styleNodes.add(host.appendChild(styleEl));
});
};
DomSharedStylesHost.prototype.addHost = function (hostNode) {
this._addStylesToHost(this._stylesSet, hostNode);
this._hostNodes.add(hostNode);
};
DomSharedStylesHost.prototype.removeHost = function (hostNode) { this._hostNodes.delete(hostNode); };
DomSharedStylesHost.prototype.onStylesAdded = function (additions) {
var _this = this;
this._hostNodes.forEach(function (hostNode) { return _this._addStylesToHost(additions, hostNode); });
};
DomSharedStylesHost.prototype.ngOnDestroy = function () { this._styleNodes.forEach(function (styleNode) { return getDOM().remove(styleNode); }); };
DomSharedStylesHost = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], DomSharedStylesHost);
return DomSharedStylesHost;
}(SharedStylesHost));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var NAMESPACE_URIS = {
'svg': 'http://www.w3.org/2000/svg',
'xhtml': 'http://www.w3.org/1999/xhtml',
'xlink': 'http://www.w3.org/1999/xlink',
'xml': 'http://www.w3.org/XML/1998/namespace',
'xmlns': 'http://www.w3.org/2000/xmlns/',
};
var COMPONENT_REGEX = /%COMP%/g;
var COMPONENT_VARIABLE = '%COMP%';
var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
function shimContentAttribute(componentShortId) {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function shimHostAttribute(componentShortId) {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
function flattenStyles(compId, styles, target) {
for (var i = 0; i < styles.length; i++) {
var style = styles[i];
if (Array.isArray(style)) {
flattenStyles(compId, style, target);
}
else {
style = style.replace(COMPONENT_REGEX, compId);
target.push(style);
}
}
return target;
}
function decoratePreventDefault(eventHandler) {
return function (event) {
var allowDefaultBehavior = eventHandler(event);
if (allowDefaultBehavior === false) {
// TODO(tbosch): move preventDefault into event plugins...
event.preventDefault();
event.returnValue = false;
}
};
}
var DomRendererFactory2 = /** @class */ (function () {
function DomRendererFactory2(eventManager, sharedStylesHost) {
this.eventManager = eventManager;
this.sharedStylesHost = sharedStylesHost;
this.rendererByCompId = new Map();
this.defaultRenderer = new DefaultDomRenderer2(eventManager);
}
DomRendererFactory2.prototype.createRenderer = function (element, type) {
if (!element || !type) {
return this.defaultRenderer;
}
switch (type.encapsulation) {
case core.ViewEncapsulation.Emulated: {
var renderer = this.rendererByCompId.get(type.id);
if (!renderer) {
renderer =
new EmulatedEncapsulationDomRenderer2(this.eventManager, this.sharedStylesHost, type);
this.rendererByCompId.set(type.id, renderer);
}
renderer.applyToHost(element);
return renderer;
}
case core.ViewEncapsulation.Native:
case core.ViewEncapsulation.ShadowDom:
return new ShadowDomRenderer(this.eventManager, this.sharedStylesHost, element, type);
default: {
if (!this.rendererByCompId.has(type.id)) {
var styles = flattenStyles(type.id, type.styles, []);
this.sharedStylesHost.addStyles(styles);
this.rendererByCompId.set(type.id, this.defaultRenderer);
}
return this.defaultRenderer;
}
}
};
DomRendererFactory2.prototype.begin = function () { };
DomRendererFactory2.prototype.end = function () { };
DomRendererFactory2 = __decorate([
core.Injectable(),
__metadata("design:paramtypes", [EventManager, DomSharedStylesHost])
], DomRendererFactory2);
return DomRendererFactory2;
}());
var DefaultDomRenderer2 = /** @class */ (function () {
function DefaultDomRenderer2(eventManager) {
this.eventManager = eventManager;
this.data = Object.create(null);
}
DefaultDomRenderer2.prototype.destroy = function () { };
DefaultDomRenderer2.prototype.createElement = function (name, namespace) {
if (namespace) {
return document.createElementNS(NAMESPACE_URIS[namespace], name);
}
return document.createElement(name);
};
DefaultDomRenderer2.prototype.createComment = function (value) { return document.createComment(value); };
DefaultDomRenderer2.prototype.createText = function (value) { return document.createTextNode(value); };
DefaultDomRenderer2.prototype.appendChild = function (parent, newChild) { parent.appendChild(newChild); };
DefaultDomRenderer2.prototype.insertBefore = function (parent, newChild, refChild) {
if (parent) {
parent.insertBefore(newChild, refChild);
}
};
DefaultDomRenderer2.prototype.removeChild = function (parent, oldChild) {
if (parent) {
parent.removeChild(oldChild);
}
};
DefaultDomRenderer2.prototype.selectRootElement = function (selectorOrNode) {
var el = typeof selectorOrNode === 'string' ? document.querySelector(selectorOrNode) :
selectorOrNode;
if (!el) {
throw new Error("The selector \"" + selectorOrNode + "\" did not match any elements");
}
el.textContent = '';
return el;
};
DefaultDomRenderer2.prototype.parentNode = function (node) { return node.parentNode; };
DefaultDomRenderer2.prototype.nextSibling = function (node) { return node.nextSibling; };
DefaultDomRenderer2.prototype.setAttribute = function (el, name, value, namespace) {
if (namespace) {
name = namespace + ":" + name;
var namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
}
else {
el.setAttribute(name, value);
}
}
else {
el.setAttribute(name, value);
}
};
DefaultDomRenderer2.prototype.removeAttribute = function (el, name, namespace) {
if (namespace) {
var namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
}
else {
el.removeAttribute(namespace + ":" + name);
}
}
else {
el.removeAttribute(name);
}
};
DefaultDomRenderer2.prototype.addClass = function (el, name) { el.classList.add(name); };
DefaultDomRenderer2.prototype.removeClass = function (el, name) { el.classList.remove(name); };
DefaultDomRenderer2.prototype.setStyle = function (el, style, value, flags) {
if (flags & core.RendererStyleFlags2.DashCase) {
el.style.setProperty(style, value, !!(flags & core.RendererStyleFlags2.Important) ? 'important' : '');
}
else {
el.style[style] = value;
}
};
DefaultDomRenderer2.prototype.removeStyle = function (el, style, flags) {
if (flags & core.RendererStyleFlags2.DashCase) {
el.style.removeProperty(style);
}
else {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
el.style[style] = '';
}
};
DefaultDomRenderer2.prototype.setProperty = function (el, name, value) {
checkNoSyntheticProp(name, 'property');
el[name] = value;
};
DefaultDomRenderer2.prototype.setValue = function (node, value) { node.nodeValue = value; };
DefaultDomRenderer2.prototype.listen = function (target, event, callback) {
checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
return this.eventManager.addGlobalEventListener(target, event, decoratePreventDefault(callback));
}
return this.eventManager.addEventListener(target, event, decoratePreventDefault(callback));
};
return DefaultDomRenderer2;
}());
var AT_CHARCODE = '@'.charCodeAt(0);
function checkNoSyntheticProp(name, nameKind) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error("Found the synthetic " + nameKind + " " + name + ". Please include either \"BrowserAnimationsModule\" or \"NoopAnimationsModule\" in your application.");
}
}
var EmulatedEncapsulationDomRenderer2 = /** @class */ (function (_super) {
__extends(EmulatedEncapsulationDomRenderer2, _super);
function EmulatedEncapsulationDomRenderer2(eventManager, sharedStylesHost, component) {
var _this = _super.call(this, eventManager) || this;
_this.component = component;
var styles = flattenStyles(component.id, component.styles, []);
sharedStylesHost.addStyles(styles);
_this.contentAttr = shimContentAttribute(component.id);
_this.hostAttr = shimHostAttribute(component.id);
return _this;
}
EmulatedEncapsulationDomRenderer2.prototype.applyToHost = function (element) { _super.prototype.setAttribute.call(this, element, this.hostAttr, ''); };
EmulatedEncapsulationDomRenderer2.prototype.createElement = function (parent, name) {
var el = _super.prototype.createElement.call(this, parent, name);
_super.prototype.setAttribute.call(this, el, this.contentAttr, '');
return el;
};
return EmulatedEncapsulationDomRenderer2;
}(DefaultDomRenderer2));
var ShadowDomRenderer = /** @class */ (function (_super) {
__extends(ShadowDomRenderer, _super);
function ShadowDomRenderer(eventManager, sharedStylesHost, hostEl, component) {
var _this = _super.call(this, eventManager) || this;
_this.sharedStylesHost = sharedStylesHost;
_this.hostEl = hostEl;
_this.component = component;
if (component.encapsulation === core.ViewEncapsulation.ShadowDom) {
_this.shadowRoot = hostEl.attachShadow({ mode: 'open' });
}
else {
_this.shadowRoot = hostEl.createShadowRoot();
}
_this.sharedStylesHost.addHost(_this.shadowRoot);
var styles = flattenStyles(component.id, component.styles, []);
for (var i = 0; i < styles.length; i++) {
var styleEl = document.createElement('style');
styleEl.textContent = styles[i];
_this.shadowRoot.appendChild(styleEl);
}
return _this;
}
ShadowDomRenderer.prototype.nodeOrShadowRoot = function (node) { return node === this.hostEl ? this.shadowRoot : node; };
ShadowDomRenderer.prototype.destroy = function () { this.sharedStylesHost.removeHost(this.shadowRoot); };
ShadowDomRenderer.prototype.appendChild = function (parent, newChild) {
return _super.prototype.appendChild.call(this, this.nodeOrShadowRoot(parent), newChild);
};
ShadowDomRenderer.prototype.insertBefore = function (parent, newChild, refChild) {
return _super.prototype.insertBefore.call(this, this.nodeOrShadowRoot(parent), newChild, refChild);
};
ShadowDomRenderer.prototype.removeChild = function (parent, oldChild) {
return _super.prototype.removeChild.call(this, this.nodeOrShadowRoot(parent), oldChild);
};
ShadowDomRenderer.prototype.parentNode = function (node) {
return this.nodeOrShadowRoot(_super.prototype.parentNode.call(this, this.nodeOrShadowRoot(node)));
};
return ShadowDomRenderer;
}(DefaultDomRenderer2));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ɵ0 = function (v) {
return '__zone_symbol__' + v;
};
/**
* Detect if Zone is present. If it is then use simple zone aware 'addEventListener'
* since Angular can do much more
* efficient bookkeeping than Zone can, because we have additional information. This speeds up
* addEventListener by 3x.
*/
var __symbol__ = (typeof Zone !== 'undefined') && Zone['__symbol__'] || ɵ0;
var ADD_EVENT_LISTENER = __symbol__('addEventListener');
var REMOVE_EVENT_LISTENER = __symbol__('removeEventListener');
var symbolNames = {};
var FALSE = 'FALSE';
var ANGULAR = 'ANGULAR';
var NATIVE_ADD_LISTENER = 'addEventListener';
var NATIVE_REMOVE_LISTENER = 'removeEventListener';
// use the same symbol string which is used in zone.js
var stopSymbol = '__zone_symbol__propagationStopped';
var stopMethodSymbol = '__zone_symbol__stopImmediatePropagation';
var blackListedEvents = (typeof Zone !== 'undefined') && Zone[__symbol__('BLACK_LISTED_EVENTS')];
var blackListedMap;
if (blackListedEvents) {
blackListedMap = {};
blackListedEvents.forEach(function (eventName) { blackListedMap[eventName] = eventName; });
}
var isBlackListedEvent = function (eventName) {
if (!blackListedMap) {
return false;
}
return blackListedMap.hasOwnProperty(eventName);
};
// a global listener to handle all dom event,
// so we do not need to create a closure every time
var globalListener = function (event) {
var symbolName = symbolNames[event.type];
if (!symbolName) {
return;
}
var taskDatas = this[symbolName];
if (!taskDatas) {
return;
}
var args = [event];
if (taskDatas.length === 1) {
// if taskDatas only have one element, just invoke it
var taskData = taskDatas[0];
if (taskData.zone !== Zone.current) {
// only use Zone.run when Zone.current not equals to stored zone
return taskData.zone.run(taskData.handler, this, args);
}
else {
return taskData.handler.apply(this, args);
}
}
else {
// copy tasks as a snapshot to avoid event handlers remove
// itself or others
var copiedTasks = taskDatas.slice();
for (var i = 0; i < copiedTasks.length; i++) {
// if other listener call event.stopImmediatePropagation
// just break
if (event[stopSymbol] === true) {
break;
}
var taskData = copiedTasks[i];
if (taskData.zone !== Zone.current) {
// only use Zone.run when Zone.current not equals to stored zone
taskData.zone.run(taskData.handler, this, args);
}
else {
taskData.handler.apply(this, args);
}
}
}
};
var DomEventsPlugin = /** @class */ (function (_super) {
__extends(DomEventsPlugin, _super);
function DomEventsPlugin(doc, ngZone, platformId) {
var _this = _super.call(this, doc) || this;
_this.ngZone = ngZone;
if (!platformId || !common.isPlatformServer(platformId)) {
_this.patchEvent();
}
return _this;
}
DomEventsPlugin.prototype.patchEvent = function () {
if (typeof Event === 'undefined' || !Event || !Event.prototype) {
return;
}
if (Event.prototype[stopMethodSymbol]) {
// already patched by zone.js
return;
}
var delegate = Event.prototype[stopMethodSymbol] =
Event.prototype.stopImmediatePropagation;
Event.prototype.stopImmediatePropagation = function () {
if (this) {
this[stopSymbol] = true;
}
// should call native delegate in case
// in some environment part of the application
// will not use the patched Event
delegate && delegate.apply(this, arguments);
};
};
// This plugin should come last in the list of plugins, because it accepts all
// events.
DomEventsPlugin.prototype.supports = function (eventName) { return true; };
DomEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
var _this = this;
var zoneJsLoaded = element[ADD_EVENT_LISTENER];
var callback = handler;
// if zonejs is loaded and current zone is not ngZone
// we keep Zone.current on target for later restoration.
if (zoneJsLoaded && (!core.NgZone.isInAngularZone() || isBlackListedEvent(eventName))) {
var symbolName = symbolNames[eventName];
if (!symbolName) {
symbolName = symbolNames[eventName] = __symbol__(ANGULAR + eventName + FALSE);
}
var taskDatas = element[symbolName];
var globalListenerRegistered = taskDatas && taskDatas.length > 0;
if (!taskDatas) {
taskDatas = element[symbolName] = [];
}
var zone = isBlackListedEvent(eventName) ? Zone.root : Zone.current;
if (taskDatas.length === 0) {
taskDatas.push({ zone: zone, handler: callback });
}
else {
var callbackRegistered = false;
for (var i = 0; i < taskDatas.length; i++) {
if (taskDatas[i].handler === callback) {
callbackRegistered = true;
break;
}
}
if (!callbackRegistered) {
taskDatas.push({ zone: zone, handler: callback });
}
}
if (!globalListenerRegistered) {
element[ADD_EVENT_LISTENER](eventName, globalListener, false);
}
}
else {
element[NATIVE_ADD_LISTENER](eventName, callback, false);
}
return function () { return _this.removeEventListener(element, eventName, callback); };
};
DomEventsPlugin.prototype.removeEventListener = function (target, eventName, callback) {
var underlyingRemove = target[REMOVE_EVENT_LISTENER];
// zone.js not loaded, use native removeEventListener
if (!underlyingRemove) {
return target[NATIVE_REMOVE_LISTENER].apply(target, [eventName, callback, false]);
}
var symbolName = symbolNames[eventName];
var taskDatas = symbolName && target[symbolName];
if (!taskDatas) {
// addEventListener not using patched version
// just call native removeEventListener
return target[NATIVE_REMOVE_LISTENER].apply(target, [eventName, callback, false]);
}
// fix issue 20532, should be able to remove
// listener which was added inside of ngZone
var found = false;
for (var i = 0; i < taskDatas.length; i++) {
// remove listener from taskDatas if the callback equals
if (taskDatas[i].handler === callback) {
found = true;
taskDatas.splice(i, 1);
break;
}
}
if (found) {
if (taskDatas.length === 0) {
// all listeners are removed, we can remove the globalListener from target
underlyingRemove.apply(target, [eventName, globalListener, false]);
}
}
else {
// not found in taskDatas, the callback may be added inside of ngZone
// use native remove listener to remove the callback
target[NATIVE_REMOVE_LISTENER].apply(target, [eventName, callback, false]);
}
};
DomEventsPlugin = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__param(2, core.Optional()), __param(2, core.Inject(core.PLATFORM_ID)),
__metadata("design:paramtypes", [Object, core.NgZone, Object])
], DomEventsPlugin);
return DomEventsPlugin;
}(EventManagerPlugin));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Supported HammerJS recognizer event names.
*/
var EVENT_NAMES = {
// pan
'pan': true,
'panstart': true,
'panmove': true,
'panend': true,
'pancancel': true,
'panleft': true,
'panright': true,
'panup': true,
'pandown': true,
// pinch
'pinch': true,
'pinchstart': true,
'pinchmove': true,
'pinchend': true,
'pinchcancel': true,
'pinchin': true,
'pinchout': true,
// press
'press': true,
'pressup': true,
// rotate
'rotate': true,
'rotatestart': true,
'rotatemove': true,
'rotateend': true,
'rotatecancel': true,
// swipe
'swipe': true,
'swipeleft': true,
'swiperight': true,
'swipeup': true,
'swipedown': true,
// tap
'tap': true,
};
/**
* DI token for providing [HammerJS](http://hammerjs.github.io/) support to Angular.
* @see `HammerGestureConfig`
*
* @experimental
*/
var HAMMER_GESTURE_CONFIG = new core.InjectionToken('HammerGestureConfig');
/** Injection token used to provide a {@link HammerLoader} to Angular. */
var HAMMER_LOADER = new core.InjectionToken('HammerLoader');
/**
* An injectable [HammerJS Manager](http://hammerjs.github.io/api/#hammer.manager)
* for gesture recognition. Configures specific event recognition.
* @experimental
*/
var HammerGestureConfig = /** @class */ (function () {
function HammerGestureConfig() {
/**
* A set of supported event names for gestures to be used in Angular.
* Angular supports all built-in recognizers, as listed in
* [HammerJS documentation](http://hammerjs.github.io/).
*/
this.events = [];
/**
* Maps gesture event names to a set of configuration options
* that specify overrides to the default values for specific properties.
*
* The key is a supported event name to be configured,
* and the options object contains a set of properties, with override values
* to be applied to the named recognizer event.
* For example, to disable recognition of the rotate event, specify
* `{"rotate": {"enable": false}}`.
*
* Properties that are not present take the HammerJS default values.
* For information about which properties are supported for which events,
* and their allowed and default values, see
* [HammerJS documentation](http://hammerjs.github.io/).
*
*/
this.overrides = {};
}
/**
* Creates a [HammerJS Manager](http://hammerjs.github.io/api/#hammer.manager)
* and attaches it to a given HTML element.
* @param element The element that will recognize gestures.
* @returns A HammerJS event-manager object.
*/
HammerGestureConfig.prototype.buildHammer = function (element) {
var mc = new Hammer(element, this.options);
mc.get('pinch').set({ enable: true });
mc.get('rotate').set({ enable: true });
for (var eventName in this.overrides) {
mc.get(eventName).set(this.overrides[eventName]);
}
return mc;
};
HammerGestureConfig = __decorate([
core.Injectable()
], HammerGestureConfig);
return HammerGestureConfig;
}());
var HammerGesturesPlugin = /** @class */ (function (_super) {
__extends(HammerGesturesPlugin, _super);
function HammerGesturesPlugin(doc, _config, console, loader) {
var _this = _super.call(this, doc) || this;
_this._config = _config;
_this.console = console;
_this.loader = loader;
return _this;
}
HammerGesturesPlugin.prototype.supports = function (eventName) {
if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) {
return false;
}
if (!window.Hammer && !this.loader) {
this.console.warn("The \"" + eventName + "\" event cannot be bound because Hammer.JS is not " +
"loaded and no custom loader has been specified.");
return false;
}
return true;
};
HammerGesturesPlugin.prototype.addEventListener = function (element, eventName, handler) {
var _this = this;
var zone = this.manager.getZone();
eventName = eventName.toLowerCase();
// If Hammer is not present but a loader is specified, we defer adding the event listener
// until Hammer is loaded.
if (!window.Hammer && this.loader) {
// This `addEventListener` method returns a function to remove the added listener.
// Until Hammer is loaded, the returned function needs to *cancel* the registration rather
// than remove anything.
var cancelRegistration_1 = false;
var deregister_1 = function () { cancelRegistration_1 = true; };
this.loader()
.then(function () {
// If Hammer isn't actually loaded when the custom loader resolves, give up.
if (!window.Hammer) {
_this.console.warn("The custom HAMMER_LOADER completed, but Hammer.JS is not present.");
deregister_1 = function () { };
return;
}
if (!cancelRegistration_1) {
// Now that Hammer is loaded and the listener is being loaded for real,
// the deregistration function changes from canceling registration to removal.
deregister_1 = _this.addEventListener(element, eventName, handler);
}
})
.catch(function () {
_this.console.warn("The \"" + eventName + "\" event cannot be bound because the custom " +
"Hammer.JS loader failed.");
deregister_1 = function () { };
});
// Return a function that *executes* `deregister` (and not `deregister` itself) so that we
// can change the behavior of `deregister` once the listener is added. Using a closure in
// this way allows us to avoid any additional data structures to track listener removal.
return function () { deregister_1(); };
}
return zone.runOutsideAngular(function () {
// Creating the manager bind events, must be done outside of angular
var mc = _this._config.buildHammer(element);
var callback = function (eventObj) {
zone.runGuarded(function () { handler(eventObj); });
};
mc.on(eventName, callback);
return function () {
mc.off(eventName, callback);
// destroy mc to prevent memory leak
if (typeof mc.destroy === 'function') {
mc.destroy();
}
};
});
};
HammerGesturesPlugin.prototype.isCustomEvent = function (eventName) { return this._config.events.indexOf(eventName) > -1; };
HammerGesturesPlugin = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__param(1, core.Inject(HAMMER_GESTURE_CONFIG)),
__param(3, core.Optional()), __param(3, core.Inject(HAMMER_LOADER)),
__metadata("design:paramtypes", [Object, HammerGestureConfig, core.ɵConsole, Object])
], HammerGesturesPlugin);
return HammerGesturesPlugin;
}(EventManagerPlugin));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Defines supported modifiers for key events.
*/
var MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
var ɵ0$1 = function (event) { return event.altKey; }, ɵ1$1 = function (event) { return event.ctrlKey; }, ɵ2$1 = function (event) { return event.metaKey; }, ɵ3 = function (event) { return event.shiftKey; };
/**
* Retrieves modifiers from key-event objects.
*/
var MODIFIER_KEY_GETTERS = {
'alt': ɵ0$1,
'control': ɵ1$1,
'meta': ɵ2$1,
'shift': ɵ3
};
/**
* @experimental
* A browser plug-in that provides support for handling of key events in Angular.
*/
var KeyEventsPlugin = /** @class */ (function (_super) {
__extends(KeyEventsPlugin, _super);
/**
* Initializes an instance of the browser plug-in.
* @param doc The document in which key events will be detected.
*/
function KeyEventsPlugin(doc) {
return _super.call(this, doc) || this;
}
KeyEventsPlugin_1 = KeyEventsPlugin;
/**
* Reports whether a named key event is supported.
* @param eventName The event name to query.
* @return True if the named key event is supported.
*/
KeyEventsPlugin.prototype.supports = function (eventName) { return KeyEventsPlugin_1.parseEventName(eventName) != null; };
/**
* Registers a handler for a specific element and key event.
* @param element The HTML element to receive event notifications.
* @param eventName The name of the key event to listen for.
* @param handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @returns The key event that was registered.
*/
KeyEventsPlugin.prototype.addEventListener = function (element, eventName, handler) {
var parsedEvent = KeyEventsPlugin_1.parseEventName(eventName);
var outsideHandler = KeyEventsPlugin_1.eventCallback(parsedEvent['fullKey'], handler, this.manager.getZone());
return this.manager.getZone().runOutsideAngular(function () {
return getDOM().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
});
};
KeyEventsPlugin.parseEventName = function (eventName) {
var parts = eventName.toLowerCase().split('.');
var domEventName = parts.shift();
if ((parts.length === 0) || !(domEventName === 'keydown' || domEventName === 'keyup')) {
return null;
}
var key = KeyEventsPlugin_1._normalizeKey(parts.pop());
var fullKey = '';
MODIFIER_KEYS.forEach(function (modifierName) {
var index = parts.indexOf(modifierName);
if (index > -1) {
parts.splice(index, 1);
fullKey += modifierName + '.';
}
});
fullKey += key;
if (parts.length != 0 || key.length === 0) {
// returning null instead of throwing to let another plugin process the event
return null;
}
var result = {};
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
};
KeyEventsPlugin.getEventFullKey = function (event) {
var fullKey = '';
var key = getDOM().getEventKey(event);
key = key.toLowerCase();
if (key === ' ') {
key = 'space'; // for readability
}
else if (key === '.') {
key = 'dot'; // because '.' is used as a separator in event names
}
MODIFIER_KEYS.forEach(function (modifierName) {
if (modifierName != key) {
var modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
if (modifierGetter(event)) {
fullKey += modifierName + '.';
}
}
});
fullKey += key;
return fullKey;
};
/**
* Configures a handler callback for a key event.
* @param fullKey The event name that combines all simultaneous keystrokes.
* @param handler The function that responds to the key event.
* @param zone The zone in which the event occurred.
* @returns A callback function.
*/
KeyEventsPlugin.eventCallback = function (fullKey, handler, zone) {
return function (event /** TODO #9100 */) {
if (KeyEventsPlugin_1.getEventFullKey(event) === fullKey) {
zone.runGuarded(function () { return handler(event); });
}
};
};
/** @internal */
KeyEventsPlugin._normalizeKey = function (keyName) {
// TODO: switch to a Map if the mapping grows too much
switch (keyName) {
case 'esc':
return 'escape';
default:
return keyName;
}
};
var KeyEventsPlugin_1;
KeyEventsPlugin = KeyEventsPlugin_1 = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], KeyEventsPlugin);
return KeyEventsPlugin;
}(EventManagerPlugin));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing
* values to be safe to use in the different DOM contexts.
*
* For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be
* sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on
* the website.
*
* In specific situations, it might be necessary to disable sanitization, for example if the
* application genuinely needs to produce a `javascript:` style link with a dynamic value in it.
* Users can bypass security by constructing a value with one of the `bypassSecurityTrust...`
* methods, and then binding to that value from the template.
*
* These situations should be very rare, and extraordinary care must be taken to avoid creating a
* Cross Site Scripting (XSS) security bug!
*
* When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as
* close as possible to the source of the value, to make it easy to verify no security bug is
* created by its use.
*
* It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that
* does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous
* code. The sanitizer leaves safe values intact.
*
* @security Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in
* sanitization for the value passed in. Carefully check and audit all values and code paths going
* into this call. Make sure any user data is appropriately escaped for this security context.
* For more detail, see the [Security Guide](http://g.co/ng/security).
*
*
*/
var DomSanitizer = /** @class */ (function () {
function DomSanitizer() {
}
return DomSanitizer;
}());
var DomSanitizerImpl = /** @class */ (function (_super) {
__extends(DomSanitizerImpl, _super);
function DomSanitizerImpl(_doc) {
var _this = _super.call(this) || this;
_this._doc = _doc;
return _this;
}
DomSanitizerImpl.prototype.sanitize = function (ctx, value) {
if (value == null)
return null;
switch (ctx) {
case core.SecurityContext.NONE:
return value;
case core.SecurityContext.HTML:
if (value instanceof SafeHtmlImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'HTML');
return core.ɵ_sanitizeHtml(this._doc, String(value));
case core.SecurityContext.STYLE:
if (value instanceof SafeStyleImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'Style');
return core.ɵ_sanitizeStyle(value);
case core.SecurityContext.SCRIPT:
if (value instanceof SafeScriptImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value, 'Script');
throw new Error('unsafe value used in a script context');
case core.SecurityContext.URL:
if (value instanceof SafeResourceUrlImpl || value instanceof SafeUrlImpl) {
// Allow resource URLs in URL contexts, they are strictly more trusted.
return value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value, 'URL');
return core.ɵ_sanitizeUrl(String(value));
case core.SecurityContext.RESOURCE_URL:
if (value instanceof SafeResourceUrlImpl) {
return value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value, 'ResourceURL');
throw new Error('unsafe value used in a resource URL context (see http://g.co/ng/security#xss)');
default:
throw new Error("Unexpected SecurityContext " + ctx + " (see http://g.co/ng/security#xss)");
}
};
DomSanitizerImpl.prototype.checkNotSafeValue = function (value, expectedType) {
if (value instanceof SafeValueImpl) {
throw new Error("Required a safe " + expectedType + ", got a " + value.getTypeName() + " " +
"(see http://g.co/ng/security#xss)");
}
};
DomSanitizerImpl.prototype.bypassSecurityTrustHtml = function (value) { return new SafeHtmlImpl(value); };
DomSanitizerImpl.prototype.bypassSecurityTrustStyle = function (value) { return new SafeStyleImpl(value); };
DomSanitizerImpl.prototype.bypassSecurityTrustScript = function (value) { return new SafeScriptImpl(value); };
DomSanitizerImpl.prototype.bypassSecurityTrustUrl = function (value) { return new SafeUrlImpl(value); };
DomSanitizerImpl.prototype.bypassSecurityTrustResourceUrl = function (value) {
return new SafeResourceUrlImpl(value);
};
DomSanitizerImpl = __decorate([
core.Injectable(),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], DomSanitizerImpl);
return DomSanitizerImpl;
}(DomSanitizer));
var SafeValueImpl = /** @class */ (function () {
function SafeValueImpl(changingThisBreaksApplicationSecurity) {
this.changingThisBreaksApplicationSecurity = changingThisBreaksApplicationSecurity;
// empty
}
SafeValueImpl.prototype.toString = function () {
return "SafeValue must use [property]=binding: " + this.changingThisBreaksApplicationSecurity +
" (see http://g.co/ng/security#xss)";
};
return SafeValueImpl;
}());
var SafeHtmlImpl = /** @class */ (function (_super) {
__extends(SafeHtmlImpl, _super);
function SafeHtmlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
SafeHtmlImpl.prototype.getTypeName = function () { return 'HTML'; };
return SafeHtmlImpl;
}(SafeValueImpl));
var SafeStyleImpl = /** @class */ (function (_super) {
__extends(SafeStyleImpl, _super);
function SafeStyleImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
SafeStyleImpl.prototype.getTypeName = function () { return 'Style'; };
return SafeStyleImpl;
}(SafeValueImpl));
var SafeScriptImpl = /** @class */ (function (_super) {
__extends(SafeScriptImpl, _super);
function SafeScriptImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
SafeScriptImpl.prototype.getTypeName = function () { return 'Script'; };
return SafeScriptImpl;
}(SafeValueImpl));
var SafeUrlImpl = /** @class */ (function (_super) {
__extends(SafeUrlImpl, _super);
function SafeUrlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
SafeUrlImpl.prototype.getTypeName = function () { return 'URL'; };
return SafeUrlImpl;
}(SafeValueImpl));
var SafeResourceUrlImpl = /** @class */ (function (_super) {
__extends(SafeResourceUrlImpl, _super);
function SafeResourceUrlImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
SafeResourceUrlImpl.prototype.getTypeName = function () { return 'ResourceURL'; };
return SafeResourceUrlImpl;
}(SafeValueImpl));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var INTERNAL_BROWSER_PLATFORM_PROVIDERS = [
{ provide: core.PLATFORM_ID, useValue: common.ɵPLATFORM_BROWSER_ID },
{ provide: core.PLATFORM_INITIALIZER, useValue: initDomAdapter, multi: true },
{ provide: common.PlatformLocation, useClass: BrowserPlatformLocation, deps: [DOCUMENT] },
{ provide: DOCUMENT, useFactory: _document, deps: [] },
];
/**
* @security Replacing built-in sanitization providers exposes the application to XSS risks.
* Attacker-controlled data introduced by an unsanitized provider could expose your
* application to XSS risks. For more detail, see the [Security Guide](http://g.co/ng/security).
* @experimental
*/
var BROWSER_SANITIZATION_PROVIDERS = [
{ provide: core.Sanitizer, useExisting: DomSanitizer },
{ provide: DomSanitizer, useClass: DomSanitizerImpl, deps: [DOCUMENT] },
];
var platformBrowser = core.createPlatformFactory(core.platformCore, 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
BrowserGetTestability.init();
}
function errorHandler() {
return new core.ErrorHandler();
}
function _document() {
return document;
}
var BROWSER_MODULE_PROVIDERS = [
BROWSER_SANITIZATION_PROVIDERS,
{ provide: core.ɵAPP_ROOT, useValue: true },
{ provide: core.ErrorHandler, useFactory: errorHandler, deps: [] },
{
provide: EVENT_MANAGER_PLUGINS,
useClass: DomEventsPlugin,
multi: true,
deps: [DOCUMENT, core.NgZone, core.PLATFORM_ID]
},
{ provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true, deps: [DOCUMENT] },
{
provide: EVENT_MANAGER_PLUGINS,
useClass: HammerGesturesPlugin,
multi: true,
deps: [DOCUMENT, HAMMER_GESTURE_CONFIG, core.ɵConsole, [new core.Optional(), HAMMER_LOADER]]
},
{ provide: HAMMER_GESTURE_CONFIG, useClass: HammerGestureConfig, deps: [] },
{
provide: DomRendererFactory2,
useClass: DomRendererFactory2,
deps: [EventManager, DomSharedStylesHost]
},
{ provide: core.RendererFactory2, useExisting: DomRendererFactory2 },
{ provide: SharedStylesHost, useExisting: DomSharedStylesHost },
{ provide: DomSharedStylesHost, useClass: DomSharedStylesHost, deps: [DOCUMENT] },
{ provide: core.Testability, useClass: core.Testability, deps: [core.NgZone] },
{ provide: EventManager, useClass: EventManager, deps: [EVENT_MANAGER_PLUGINS, core.NgZone] },
ELEMENT_PROBE_PROVIDERS,
];
/**
* Exports required infrastructure for all Angular apps.
* Included by defaults in all Angular apps created with the CLI
* `new` command.
* Re-exports `CommonModule` and `ApplicationModule`, making their
* exports and providers available to all apps.
*
*
*/
var BrowserModule = /** @class */ (function () {
function BrowserModule(parentModule) {
if (parentModule) {
throw new Error("BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.");
}
}
BrowserModule_1 = BrowserModule;
/**
* Configures a browser-based app to transition from a server-rendered app, if
* one is present on the page.
*
* @param params An object containing an identifier for the app to transition.
* The ID must match between the client and server versions of the app.
* @returns The reconfigured `BrowserModule` to import into the app's root `AppModule`.
*
* @experimental
*/
BrowserModule.withServerTransition = function (params) {
return {
ngModule: BrowserModule_1,
providers: [
{ provide: core.APP_ID, useValue: params.appId },
{ provide: TRANSITION_ID, useExisting: core.APP_ID },
SERVER_TRANSITION_PROVIDERS,
],
};
};
var BrowserModule_1;
BrowserModule = BrowserModule_1 = __decorate([
core.NgModule({ providers: BROWSER_MODULE_PROVIDERS, exports: [common.CommonModule, core.ApplicationModule] }),
__param(0, core.Optional()), __param(0, core.SkipSelf()), __param(0, core.Inject(BrowserModule_1)),
__metadata("design:paramtypes", [Object])
], BrowserModule);
return BrowserModule;
}());
/**
* Factory to create Meta service.
*/
function createMeta() {
return new Meta(core.inject(DOCUMENT));
}
/**
* A service that can be used to get and add meta tags.
*
* @experimental
*/
var Meta = /** @class */ (function () {
function Meta(_doc) {
this._doc = _doc;
this._dom = getDOM();
}
Meta.prototype.addTag = function (tag, forceCreation) {
if (forceCreation === void 0) { forceCreation = false; }
if (!tag)
return null;
return this._getOrCreateElement(tag, forceCreation);
};
Meta.prototype.addTags = function (tags, forceCreation) {
var _this = this;
if (forceCreation === void 0) { forceCreation = false; }
if (!tags)
return [];
return tags.reduce(function (result, tag) {
if (tag) {
result.push(_this._getOrCreateElement(tag, forceCreation));
}
return result;
}, []);
};
Meta.prototype.getTag = function (attrSelector) {
if (!attrSelector)
return null;
return this._dom.querySelector(this._doc, "meta[" + attrSelector + "]") || null;
};
Meta.prototype.getTags = function (attrSelector) {
if (!attrSelector)
return [];
var list /*NodeList*/ = this._dom.querySelectorAll(this._doc, "meta[" + attrSelector + "]");
return list ? [].slice.call(list) : [];
};
Meta.prototype.updateTag = function (tag, selector) {
if (!tag)
return null;
selector = selector || this._parseSelector(tag);
var meta = this.getTag(selector);
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
};
Meta.prototype.removeTag = function (attrSelector) { this.removeTagElement(this.getTag(attrSelector)); };
Meta.prototype.removeTagElement = function (meta) {
if (meta) {
this._dom.remove(meta);
}
};
Meta.prototype._getOrCreateElement = function (meta, forceCreation) {
if (forceCreation === void 0) { forceCreation = false; }
if (!forceCreation) {
var selector = this._parseSelector(meta);
var elem = this.getTag(selector);
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
if (elem && this._containsAttributes(meta, elem))
return elem;
}
var element = this._dom.createElement('meta');
this._setMetaElementAttributes(meta, element);
var head = this._dom.getElementsByTagName(this._doc, 'head')[0];
this._dom.appendChild(head, element);
return element;
};
Meta.prototype._setMetaElementAttributes = function (tag, el) {
var _this = this;
Object.keys(tag).forEach(function (prop) { return _this._dom.setAttribute(el, prop, tag[prop]); });
return el;
};
Meta.prototype._parseSelector = function (tag) {
var attr = tag.name ? 'name' : 'property';
return attr + "=\"" + tag[attr] + "\"";
};
Meta.prototype._containsAttributes = function (tag, elem) {
var _this = this;
return Object.keys(tag).every(function (key) { return _this._dom.getAttribute(elem, key) === tag[key]; });
};
Meta.ngInjectableDef = core.defineInjectable({ factory: createMeta, token: Meta, providedIn: "root" });
Meta = __decorate([
core.Injectable({ providedIn: 'root', useFactory: createMeta, deps: [] }),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], Meta);
return Meta;
}());
/**
* Factory to create Title service.
*/
function createTitle() {
return new Title(core.inject(DOCUMENT));
}
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*
* @experimental
*/
var Title = /** @class */ (function () {
function Title(_doc) {
this._doc = _doc;
}
/**
* Get the title of the current HTML document.
*/
Title.prototype.getTitle = function () { return getDOM().getTitle(this._doc); };
/**
* Set the title of the current HTML document.
* @param newTitle
*/
Title.prototype.setTitle = function (newTitle) { getDOM().setTitle(this._doc, newTitle); };
Title.ngInjectableDef = core.defineInjectable({ factory: createTitle, token: Title, providedIn: "root" });
Title = __decorate([
core.Injectable({ providedIn: 'root', useFactory: createTitle, deps: [] }),
__param(0, core.Inject(DOCUMENT)),
__metadata("design:paramtypes", [Object])
], Title);
return Title;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var win = typeof window !== 'undefined' && window || {};
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ChangeDetectionPerfRecord = /** @class */ (function () {
function ChangeDetectionPerfRecord(msPerTick, numTicks) {
this.msPerTick = msPerTick;
this.numTicks = numTicks;
}
return ChangeDetectionPerfRecord;
}());
/**
* Entry point for all Angular profiling-related debug tools. This object
* corresponds to the `ng.profiler` in the dev console.
*/
var AngularProfiler = /** @class */ (function () {
function AngularProfiler(ref) {
this.appRef = ref.injector.get(core.ApplicationRef);
}
// tslint:disable:no-console
/**
* Exercises change detection in a loop and then prints the average amount of
* time in milliseconds how long a single round of change detection takes for
* the current state of the UI. It runs a minimum of 5 rounds for a minimum
* of 500 milliseconds.
*
* Optionally, a user may pass a `config` parameter containing a map of
* options. Supported options are:
*
* `record` (boolean) - causes the profiler to record a CPU profile while
* it exercises the change detector. Example:
*
* ```
* ng.profiler.timeChangeDetection({record: true})
* ```
*/
AngularProfiler.prototype.timeChangeDetection = function (config) {
var record = config && config['record'];
var profileName = 'Change Detection';
// Profiler is not available in Android browsers, nor in IE 9 without dev tools opened
var isProfilerAvailable = win.console.profile != null;
if (record && isProfilerAvailable) {
win.console.profile(profileName);
}
var start = getDOM().performanceNow();
var numTicks = 0;
while (numTicks < 5 || (getDOM().performanceNow() - start) < 500) {
this.appRef.tick();
numTicks++;
}
var end = getDOM().performanceNow();
if (record && isProfilerAvailable) {
// need to cast to <any> because type checker thinks there's no argument
// while in fact there is:
//
// https://developer.mozilla.org/en-US/docs/Web/API/Console/profileEnd
win.console.profileEnd(profileName);
}
var msPerTick = (end - start) / numTicks;
win.console.log("ran " + numTicks + " change detection cycles");
win.console.log(msPerTick.toFixed(2) + " ms per check");
return new ChangeDetectionPerfRecord(msPerTick, numTicks);
};
return AngularProfiler;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var PROFILER_GLOBAL_NAME = 'profiler';
/**
* Enabled Angular debug tools that are accessible via your browser's
* developer console.
*
* Usage:
*
* 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
* 1. Type `ng.` (usually the console will show auto-complete suggestion)
* 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
* then hit Enter.
*
* @experimental All debugging apis are currently experimental.
*/
function enableDebugTools(ref) {
exportNgVar(PROFILER_GLOBAL_NAME, new AngularProfiler(ref));
return ref;
}
/**
* Disables Angular tools.
*
* @experimental All debugging apis are currently experimental.
*/
function disableDebugTools() {
exportNgVar(PROFILER_GLOBAL_NAME, null);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function escapeHtml(text) {
var escapedText = {
'&': '&a;',
'"': '&q;',
'\'': '&s;',
'<': '&l;',
'>': '&g;',
};
return text.replace(/[&"'<>]/g, function (s) { return escapedText[s]; });
}
function unescapeHtml(text) {
var unescapedText = {
'&a;': '&',
'&q;': '"',
'&s;': '\'',
'&l;': '<',
'&g;': '>',
};
return text.replace(/&[^;]+;/g, function (s) { return unescapedText[s]; });
}
/**
* Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* @experimental
*/
function makeStateKey(key) {
return key;
}
/**
* A key value store that is transferred from the application on the server side to the application
* on the client side.
*
* `TransferState` will be available as an injectable token. To use it import
* `ServerTransferStateModule` on the server and `BrowserTransferStateModule` on the client.
*
* The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
* boolean, number, string, null and non-class objects will be serialized and deserialzied in a
* non-lossy manner.
*
* @experimental
*/
var TransferState = /** @class */ (function () {
function TransferState() {
this.store = {};
this.onSerializeCallbacks = {};
}
TransferState_1 = TransferState;
/** @internal */
TransferState.init = function (initState) {
var transferState = new TransferState_1();
transferState.store = initState;
return transferState;
};
/**
* Get the value corresponding to a key. Return `defaultValue` if key is not found.
*/
TransferState.prototype.get = function (key, defaultValue) {
return this.store[key] !== undefined ? this.store[key] : defaultValue;
};
/**
* Set the value corresponding to a key.
*/
TransferState.prototype.set = function (key, value) { this.store[key] = value; };
/**
* Remove a key from the store.
*/
TransferState.prototype.remove = function (key) { delete this.store[key]; };
/**
* Test whether a key exists in the store.
*/
TransferState.prototype.hasKey = function (key) { return this.store.hasOwnProperty(key); };
/**
* Register a callback to provide the value for a key when `toJson` is called.
*/
TransferState.prototype.onSerialize = function (key, callback) {
this.onSerializeCallbacks[key] = callback;
};
/**
* Serialize the current state of the store to JSON.
*/
TransferState.prototype.toJson = function () {
// Call the onSerialize callbacks and put those values into the store.
for (var key in this.onSerializeCallbacks) {
if (this.onSerializeCallbacks.hasOwnProperty(key)) {
try {
this.store[key] = this.onSerializeCallbacks[key]();
}
catch (e) {
console.warn('Exception in onSerialize callback: ', e);
}
}
}
return JSON.stringify(this.store);
};
var TransferState_1;
TransferState = TransferState_1 = __decorate([
core.Injectable()
], TransferState);
return TransferState;
}());
function initTransferState(doc, appId) {
// Locate the script tag with the JSON data transferred from the server.
// The id of the script tag is set to the Angular appId + 'state'.
var script = doc.getElementById(appId + '-state');
var initialState = {};
if (script && script.textContent) {
try {
initialState = JSON.parse(unescapeHtml(script.textContent));
}
catch (e) {
console.warn('Exception while restoring TransferState for app ' + appId, e);
}
}
return TransferState.init(initialState);
}
/**
* NgModule to install on the client side while using the `TransferState` to transfer state from
* server to client.
*
* @experimental
*/
var BrowserTransferStateModule = /** @class */ (function () {
function BrowserTransferStateModule() {
}
BrowserTransferStateModule = __decorate([
core.NgModule({
providers: [{ provide: TransferState, useFactory: initTransferState, deps: [DOCUMENT, core.APP_ID] }],
})
], BrowserTransferStateModule);
return BrowserTransferStateModule;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Predicates for use with {@link DebugElement}'s query functions.
*
* @experimental All debugging apis are currently experimental.
*/
var By = /** @class */ (function () {
function By() {
}
/**
* Match all elements.
*
* @usageNotes
* ### Example
*
* {@example platform-browser/dom/debug/ts/by/by.ts region='by_all'}
*/
By.all = function () { return function (debugElement) { return true; }; };
/**
* Match elements by the given CSS selector.
*
* @usageNotes
* ### Example
*
* {@example platform-browser/dom/debug/ts/by/by.ts region='by_css'}
*/
By.css = function (selector) {
return function (debugElement) {
return debugElement.nativeElement != null ?
getDOM().elementMatches(debugElement.nativeElement, selector) :
false;
};
};
/**
* Match elements that have the given directive present.
*
* @usageNotes
* ### Example
*
* {@example platform-browser/dom/debug/ts/by/by.ts region='by_directive'}
*/
By.directive = function (type) {
return function (debugElement) { return debugElement.providerTokens.indexOf(type) !== -1; };
};
return By;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var VERSION = new core.Version('6.1.10');
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
exports.ɵangular_packages_platform_browser_platform_browser_c = BROWSER_MODULE_PROVIDERS;
exports.ɵangular_packages_platform_browser_platform_browser_b = _document;
exports.ɵangular_packages_platform_browser_platform_browser_a = errorHandler;
exports.ɵangular_packages_platform_browser_platform_browser_k = GenericBrowserDomAdapter;
exports.ɵangular_packages_platform_browser_platform_browser_d = createMeta;
exports.ɵangular_packages_platform_browser_platform_browser_i = SERVER_TRANSITION_PROVIDERS;
exports.ɵangular_packages_platform_browser_platform_browser_h = appInitializerFactory;
exports.ɵangular_packages_platform_browser_platform_browser_e = createTitle;
exports.ɵangular_packages_platform_browser_platform_browser_f = initTransferState;
exports.ɵangular_packages_platform_browser_platform_browser_j = _createNgProbe;
exports.ɵangular_packages_platform_browser_platform_browser_g = EventManagerPlugin;
exports.BrowserModule = BrowserModule;
exports.platformBrowser = platformBrowser;
exports.Meta = Meta;
exports.Title = Title;
exports.disableDebugTools = disableDebugTools;
exports.enableDebugTools = enableDebugTools;
exports.BrowserTransferStateModule = BrowserTransferStateModule;
exports.TransferState = TransferState;
exports.makeStateKey = makeStateKey;
exports.By = By;
exports.DOCUMENT = DOCUMENT;
exports.EVENT_MANAGER_PLUGINS = EVENT_MANAGER_PLUGINS;
exports.EventManager = EventManager;
exports.HAMMER_GESTURE_CONFIG = HAMMER_GESTURE_CONFIG;
exports.HAMMER_LOADER = HAMMER_LOADER;
exports.HammerGestureConfig = HammerGestureConfig;
exports.DomSanitizer = DomSanitizer;
exports.VERSION = VERSION;
exports.ɵBROWSER_SANITIZATION_PROVIDERS = BROWSER_SANITIZATION_PROVIDERS;
exports.ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS = INTERNAL_BROWSER_PLATFORM_PROVIDERS;
exports.ɵinitDomAdapter = initDomAdapter;
exports.ɵBrowserDomAdapter = BrowserDomAdapter;
exports.ɵBrowserPlatformLocation = BrowserPlatformLocation;
exports.ɵTRANSITION_ID = TRANSITION_ID;
exports.ɵBrowserGetTestability = BrowserGetTestability;
exports.ɵescapeHtml = escapeHtml;
exports.ɵELEMENT_PROBE_PROVIDERS = ELEMENT_PROBE_PROVIDERS;
exports.ɵDomAdapter = DomAdapter;
exports.ɵgetDOM = getDOM;
exports.ɵsetRootDomAdapter = setRootDomAdapter;
exports.ɵDomRendererFactory2 = DomRendererFactory2;
exports.ɵNAMESPACE_URIS = NAMESPACE_URIS;
exports.ɵflattenStyles = flattenStyles;
exports.ɵshimContentAttribute = shimContentAttribute;
exports.ɵshimHostAttribute = shimHostAttribute;
exports.ɵDomEventsPlugin = DomEventsPlugin;
exports.ɵHammerGesturesPlugin = HammerGesturesPlugin;
exports.ɵKeyEventsPlugin = KeyEventsPlugin;
exports.ɵDomSharedStylesHost = DomSharedStylesHost;
exports.ɵSharedStylesHost = SharedStylesHost;
exports.ɵDomSanitizerImpl = DomSanitizerImpl;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=platform-browser.umd.js.map
|
import React, {Component} from 'react'
import Snackbar from 'material-ui/Snackbar';
import {connect} from 'react-redux';
import {issueSnackbarMessage} from '../../model/actions/actions';
import {DEBUG} from '../../settings';
class SnackbarContainer extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
componentWillUpdate(nextProps /*, nextState*/) {
if (nextProps.snackbarMessage && (nextProps.snackbarMessage !== this.props.snackbarMessage)) {
this.setState({
open: true,
});
}
}
handleRequestClose = () => {
this.setState({
open: false,
});
this.props.dispatch(issueSnackbarMessage(null));
};
render() {
const style = {
content: {
color: "white",
textAlign: "center",
}
};
DEBUG && console.log("SnackbarContainer render this.state.open: ", this.state.open);
let message = "";
if (this.props.snackbarMessage) {
message = this.props.snackbarMessage;
}
return (
<div>
<Snackbar
open={this.state.open}
message={message}
contentStyle={style.content}
autoHideDuration={4000}
onRequestClose={this.handleRequestClose}
/>
</div>
);
}
}
const mapStateToProps = (state/*, props*/) => {
return {
snackbarMessage: state.actionReducer.snackbarMessage,
}
};
const ConnectedSnackbarContainer = connect(mapStateToProps)(SnackbarContainer);
export default ConnectedSnackbarContainer;
|
'use strict';
module.exports = props => `<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>${props.title}</title>
${props.fonts || ''}
<style type="text/css">
${props.style}
</style>
</head>
<body>
<div class="container">
${props.front}
<div id="content">
${props.body}
</div>
</div>
<script>
${props.script}
</script>
</body>
</html>
`;
|
/* eslint no-unused-expressions: 0 */
import React from 'react';
import { shallow } from 'enzyme';
import Undo from '../index';
import sinon from 'sinon';
import chai, { expect } from 'chai';
import sinonChai from 'sinon-chai';
import { EditorState, Modifier } from 'draft-js';
chai.use(sinonChai);
describe('UndoButton', () => {
const onChange = () => sinon.spy();
let editorState;
let store = {
getEditorState: () => editorState,
setEditorState: onChange,
};
beforeEach(() => {
editorState = EditorState.createEmpty();
});
it('applies the className based on the theme property `undo`', () => {
const theme = { undo: 'custom-class-name' };
const result = shallow(
<Undo
store={ store }
theme={ theme }
children={ 'undo' }
/>
);
expect(result).to.have.prop('className', 'custom-class-name');
});
it('renders the passed in children', () => {
const result = shallow(
<Undo
store={ store }
children="undo"
/>
);
expect(result).to.have.prop('children', 'undo');
});
it('applies a custom className as well as the theme', () => {
const theme = { undo: 'custom-class-name' };
const result = shallow(
<Undo
store={ store }
theme={ theme }
className="undo"
children="undo"
/>
);
expect(result).to.have.prop('className').to.contain('undo');
expect(result).to.have.prop('className').to.contain('custom-class-name');
});
it('adds disabled attribute to button if the getUndoStack is empty', () => {
const result = shallow(
<Undo
store={ store }
children="redo"
/>
);
expect(result.find('button')).prop('disabled').to.equal(true);
});
it('removes disabled attribute from button if the getUndoStack is not empty', () => {
const contentState = editorState.getCurrentContent();
const SelectionState = editorState.getSelection();
const newContent = Modifier.insertText(
contentState,
SelectionState,
'hello'
);
const newEditorState = EditorState.push(editorState, newContent, 'insert-text');
store = {
getEditorState: () => newEditorState,
setEditorState: onChange,
};
const result = shallow(
<Undo
store={ store }
children="redo"
/>
);
expect(result.find('button')).prop('disabled').to.equal(false);
});
it('triggers an update with undo when the button is clicked', () => {
const result = shallow(
<Undo
store={ store }
children="redo"
/>
);
result.find('button').simulate('click');
expect(onChange).to.have.been.calledOnce;
});
});
|
function Ui() {
'use strict';
return;
}
(function strict() { // strict mode wrapper
'use strict';
Ui.prototype = {
/**
* Template manager object.
*
* @public
* @type {TemplateManager}
*/
templateManager: null,
/**
* UI module initialization.
*
* @param {App} app
* @public
*/
init: function UI_init(app) {
this.app = app;
this.templateManager = new TemplateManager();
$(document).ready(this.domInit.bind(this));
// init inner objects
this.splash.context = this;
this.auth.context = this;
this.registration.context = this;
this.login.context = this;
this.home.context = this;
this.new_treatment.context = this;
this.profile.context = this;
this.options.context = this;
this.location.context = this;
this.time.context = this;
this.sensors.context = this;
this.sound.context = this;
this.led.context = this;
this.system.context = this;
this.radio.context = this;
this.alarm.context = this;
this.battery.context = this;
this.video.context = this;
this.health.context = this;
this.addressbook.context = this;
},
/**
* When DOM is ready, initializes it.
*
* @private
*/
domInit: function UI_domInit() {
this.templateManager.loadToCache(
[
'treatment'
],
this.initPages.bind(this)
);
$.mobile.tizen.disableSelection(document);
},
/**
* Appends pages to the body and initializes them.
*
* @private
*/
initPages: function UI_initPages() {
this.splash.init();
this.auth.init();
this.registration.init();
this.login.init();
this.home.init();
this.new_treatment.init();
this.profile.init();
this.options.init();
this.location.init();
this.time.init();
this.sensors.init();
this.sound.init();
this.led.init();
this.system.init();
this.radio.init();
this.alarm.init();
this.battery.init();
this.video.init();
this.addressbook.init();
this.health.init();
window.addEventListener('tizenhwkey', function onTizenHwKey(e) {
var activePageId = tau.activePage.id;
if (e.keyName === 'back') {
if (activePageId === 'splash') {
app.exit();
} else {
history.back();
}
}
});
},
/**
* Contains methods related to the splash page.
*
* @public
* @type {object}
*/
splash: {
/**
* Initializes splash page.
*
* @public
*/
init: function UI_splash_init() {
this.addEvents();
},
/**
* Binds events to the splash page.
*
* @public
*/
addEvents: function addEvents() {
$('.button_action_start').click(function () {
if (localStorage.getItem('ApiKey')) {
$('#main .text').text('API Key = ' + localStorage.getItem('ApiKey'));
tau.changePage("#home");
} else {
tau.changePage("#auth");
}
});
$('.button_action_clear').on('click', function () {
localStorage.clear();
});
}
},
/**
* Contains methods related to the auth page.
*
* @public
* @type {object}
*/
auth: {
/**
* Initializes auth page.
*
* @public
*/
init: function UI_auth_init() {
}
},
/**
* Contains methods related to the registration page.
*
* @public
* @type {object}
*/
registration: {
/**
* Initializes registration page.
*
* @public
*/
init: function UI_registration_init() {
$('.form_action_register').initForm(function (result) {
localStorage.setItem('ApiKey', result['ApiKey']);
tau.changePage("#home");
}, function (result) {
console.log(result['Message']);
});
}
},
/**
* Contains methods related to the login page.
*
* @public
* @type {object}
*/
login: {
/**
* Initializes login page.
*
* @public
*/
init: function UI_login_init() {
}
},
/**
* Contains methods related to the home page.
*
* @public
* @type {object}
*/
home: {
/**
* Initializes home page.
*
* @public
*/
init: function UI_home_init() {
}
},
/**
* Contains methods related to the new_treatment page.
*
* @public
* @type {object}
*/
new_treatment: {
/**
* Initializes new_treatment page.
*
* @public
*/
init: function UI_new_treatment_init() {
this.addEvents();
},
/**
* Binds events to the new_treatment page.
*
* @public
*/
addEvents: function addEvents() {
$('#issueFiles').on('change', function readSelectedFiles() {
var html = '',
displaySection = document.getElementById('selectedFilesList'),
files = document.getElementById('issueFiles').files;
if (files.length === 0) {
return;
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
/* Check whether the file is an image */
if (!file.type.match('image.*')) {
continue;
}
reader.onload = (function (e) {
var fileItem = document.createElement('div');
fileItem.className = 'file-list__item';
var img = '<img class="img" src="' + e.target.result + '" title="' + escape(file.name) + '"/>';
fileItem.innerHTML = img + '<div class="file-list__inner"><strong>File name: </strong>' + escape(file.name) + '<br />' +
'type: ' + file.type + '<br />' +
'size: ' + file.size + 'bytes<br />' +
'lastModifiedDate: ' + (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : '') +
'<br /></div>';
displaySection.appendChild(fileItem);
});
reader.readAsDataURL(file);
}
});
}
},
/**
* Contains methods related to the profile page.
*
* @public
* @type {object}
*/
profile: {
/**
* Initializes profile page.
*
* @public
*/
init: function UI_profile_init() {
this.addEvents();
},
/**
* Handles pageshow event on the profile page.
*
* @private
*/
onShow: function onShow() {
this.displayList();
},
/**
* Binds events to the profile page.
*
* @public
*/
addEvents: function addEvents() {
$('#profile').on('pageshow', this.onShow.bind(this));
},
/**
* Builds profile info HTML list and adds it to page.
*
* @private
*/
displayList: function displayList() {
var list = '',
infoList = document.getElementById('profile_info');
$.ajax({
type: 'get',
url: app.config.get('profileRequest'),
contentType: 'application/json',
dataType: 'json',
beforeSend: function (request) {
localStorage.getItem('ApiKey') && request.setRequestHeader('X-ApiKey', localStorage.getItem('ApiKey'));
},
success: function (result) {
if (result['Success']) {
list = '' +
'<li class="list__item">Last name: <span class="string profile__lname">' + result["PatientProfile"]["LastName"] + '</span></li>' +
'<li class="list__item">Name: <span class="string profile__name">' + result["PatientProfile"]["Name"] + '</span></li>' +
'<li class="list__item">Second name: <span class="string profile__sname">' + result["PatientProfile"]["SecondName"] + '</span></li>' +
'<li class="list__item">Date of birth: <span class="string profile__birthday">' + result["PatientProfile"]["BirthdayDate"] + '</span></li>' +
'<li class="list__item">Gender: <span class="string profile__gender">' + result["PatientProfile"]["Gender"] + '</span></li>' +
'<li class="list__item">Policy number: <span class="string profile__policy">' + result["PatientProfile"]["PolicyNumber"] + '</span></li>' +
'<li class="list__item">Phone number: <span class="string profile__phone">' + result["PatientProfile"]["PhoneNumber"] + '</span></li>' +
'<li class="list__item">Email: <span class="string profile__email">' + result["PatientProfile"]["Email"] + '</span></li>' +
'<li class="list__item">Registration date: <span class="string profile__ger">' + result["PatientProfile"]["RegisterDate"] + '</span></li>';
infoList.innerHTML = list;
tau.engine.createWidgets(infoList);
tau.widget.Listview(infoList).refresh();
} else {
console.log('no');
}
}
});
}
},
/**
* Contains methods related to the options page.
*
* @public
* @type {object}
*/
options: {
/**
* Initializes options page.
*
* @public
*/
init: function UI_options_init() {
}
},
/**
* Contains methods related to the location page.
*
* @public
* @type {object}
*/
location: {
/**
* Initializes location page.
*
* @public
*/
init: function UI_location_init() {
this.addEvents();
},
/**
* Binds events to the location page.
*
* @public
*/
addEvents: function addEvents() {
// Holds information that uniquely identifies a watch operation.
var watchId;
function successCallback(position) {
document.getElementById("locationInfo").innerHTML = "Latitude: " +
position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function errorCallback(error) {
var errorInfo = document.getElementById("locationInfo");
switch (error.code) {
case error.PERMISSION_DENIED:
errorInfo.innerHTML = "User denied the request for Geolocation."; break;
case error.POSITION_UNAVAILABLE:
errorInfo.innerHTML = "Location information is unavailable."; break;
case error.TIMEOUT:
errorInfo.innerHTML = "The request to get user location timed out."; break;
case error.UNKNOWN_ERROR:
errorInfo.innerHTML = "An unknown error occurred."; break;
}
}
$('#oneShot').on('click', function oneShotFunc() {
navigator.geolocation ?
navigator.geolocation.getCurrentPosition(successCallback, errorCallback) :
document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
});
$('#watchPos').on('click', function watchFunc() {
navigator.geolocation ?
watchId = navigator.geolocation.watchPosition(successCallback, errorCallback) :
document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
});
$('#stopWatchPos').on('click', function stopWatchFunc() {
navigator.geolocation ?
navigator.geolocation.clearWatch(watchId) :
document.getElementById("locationInfo").innerHTML = "Geolocation is not supported.";
});
}
},
/**
* Contains methods related to the time page.
*
* @public
* @type {object}
*/
time: {
/**
* Initializes time page.
*
* @public
*/
init: function UI_time_init() {
$('#currentTime').text(tizen.time.getCurrentDateTime().toLocaleString());
$('#currentZone').text(tizen.time.getLocalTimezone());
$('#zonesCount').text(tizen.time.getAvailableTimezones().length);
$('#dateFormat').text(tizen.time.getDateFormat());
$('#timeFormat').text(tizen.time.getTimeFormat());
}
},
/**
* Contains methods related to the sensors page.
*
* @public
* @type {object}
*/
sensors: {
/**
* Initializes sensors page.
*
* @public
*/
init: function UI_sensors_init() {
var sensorCapabilities = tizen.sensorservice.getAvailableSensors();
sensorCapabilities.forEach(function (item, i, arr) {
var sensor = tizen.sensorservice.getDefaultSensor(item);
var line = "<li class=\"list__item\"><p class=\"text\">" + item + " val: <span id=\"" + item + "-Value\"></span></p></li>";
$('#sensors-list').append(line);
sensor.setChangeListener(function (sensorData) {
if (typeof(sensorData.proximityState) !== 'undefined') {
$('#PROXIMITY-Value').text(sensorData.proximityState);
}
});
sensor.start(function () {
console.log(item + ' started');
});
})
},
addSensor: function addSensor(sensorType, sensor) {
console.log(sensorType);
console.log(sensor);
},
onSuccess: function onSuccess() {
console.log('Sensor started successfully');
}
},
/**
* Contains methods related to the sound page.
*
* @public
* @type {object}
*/
sound: {
/**
* Initializes sound page.
*
* @public
*/
init: function UI_sound_init() {
var SOUND_TYPES = ["SYSTEM", "NOTIFICATION", "ALARM", "MEDIA", "VOICE", "RINGTONE"];
SOUND_TYPES.forEach(function(item,i,arr){
var volume = tizen.sound.getVolume(item);
var line = '<li class="list__item"><p class="text">'+item+' type volume: <span id="'+ item+'-volume">'+volume+'</span>';
var slider = '<br /><input class="slider" id="'+item+'-slider" type="range" min="0" max="10" step="1" value="'+ volume*10 +'"/></p></li>';
$('#sound-info-list').append(line + slider);
var id = '#'+item+'-slider';
$(id).on('change',function(){
var type = '#' + item + '-slider';
var value = $(type).val();
tizen.sound.setVolume(item,value/10);
})
});
$('#currentSoundMode').text(tizen.sound.getSoundMode());
tizen.sound.setVolumeChangeListener(function (soundType, volume) {
var volumeId = '#'+soundType+'-volume';
$(volumeId).text(volume);
var sliderId = '#'+soundType+'-slider';
$(sliderId).attr("value", volume*10);
});
tizen.sound.setSoundModeChangeListener(function(soundMode){
$('#currentSoundMode').text(soundMode);
});
}
},
/**
* Contains methods related to the led page.
*
* @public
* @type {object}
*/
led: {
/**
* Initializes led page.
*
* @public
*/
init: function UI_led_init() {
this.addEvents();
},
/**
* Binds events to the led page.
*
* @public
*/
addEvents: function addEvents() {
$('.button_led_on').on('click', function() {
$(this).hide();
tizen.systeminfo.getPropertyValue("CAMERA_FLASH",
function (flash) {
try {
flash.setBrightness(1);
$('.button_led_off').show();
} catch (error) {
console.log("Setting flash brightness failed: " + error.message);
}
},
function (error) {
console.log("Error, name: " + error.name + ", message: " + error.message);
}
);
});
$('.button_led_off').on('click', function() {
$(this).hide();
tizen.systeminfo.getPropertyValue("CAMERA_FLASH",
function (flash) {
flash.setBrightness(0);
$('.button_led_on').show();
},
function (error) {
console.log("Error, name: " + error.name + ", message: " + error.message);
}
);
});
}
},
/**
* Contains methods related to the system page.
*
* @public
* @type {object}
*/
system: {
/**
* Initializes system page.
*
* @public
*/
init: function UI_system_init() {
function onPowerSuccessCallback(battery) { $('#batteryLevel').text((battery.level*100).toFixed(1) + '%'); }
function onDeviceOrientation(deviceOrientation) { $('#orientation').text(deviceOrientation.status); }
function onCPUSuccessCallback(cpu) { $('#cpu').text((cpu.load*100).toFixed(1) + '%'); }
tizen.systeminfo.getPropertyValue('BATTERY', onPowerSuccessCallback);
tizen.systeminfo.getPropertyValue('DEVICE_ORIENTATION', onDeviceOrientation);
tizen.systeminfo.getPropertyValue('CPU', onCPUSuccessCallback);
tizen.systeminfo.addPropertyValueChangeListener('BATTERY', onPowerSuccessCallback);
tizen.systeminfo.addPropertyValueChangeListener('DEVICE_ORIENTATION', onDeviceOrientation);
tizen.systeminfo.addPropertyValueChangeListener('CPU', onCPUSuccessCallback);
$('#totalMemory').text(tizen.systeminfo.getTotalMemory() + ' bytes.');
$('#availableMemory').text(tizen.systeminfo.getAvailableMemory() + ' bytes.');
}
},
/**
* Contains methods related to the radio page.
*
* @public
* @type {object}
*/
radio: {
/**
* Initializes radio page.
*
* @public
*/
init: function UI_radio_init() {
this.addEvents();
},
/**
* Binds events to the radio page.
*
* @public
*/
addEvents: function addEvents() {
$('.button_radio_on').on('click', function() {
startRadio();
});
$('.button_radio_off').on('click', function() {
stopRadio();
});
$('.button_radio_scan').on('click', function() {
if (tizen.fmradio.state === "PLAYING") {
tizen.fmradio.seekUp(successCallback);
}
});
if(tizen.fmradio.isAntennaConnected) {
$('#radioTitle').text('Turn on the Radio');
} else {
$('#radioTitle').text('Plug in a headset');
}
tizen.fmradio.setAntennaChangeListener(antennaCallback);
function antennaCallback(isAntennaConnected) {
if(!isAntennaConnected) {
stopRadio();
$('#radioTitle').text('Plug in a headset')
} else {
$('#radioTitle').text('Turn on the Radio');
}
}
function startRadio() {
var radioState = tizen.fmradio.state;
var frequencyToPlay = 92.3;
if ((radioState == "READY" || radioState == "PLAYING") && tizen.fmradio.isAntennaConnected) {
$('.button_radio_on').hide();
$('.button_radio_scan, .button_radio_off').show();
tizen.fmradio.start(frequencyToPlay);
$('#radioTitle').text('Playing ' + frequencyToPlay);
$('.fm-img').show();
}
}
function stopRadio() {
$('.button_radio_scan, .button_radio_off').hide();
$('.button_radio_on').show();
if (tizen.fmradio.state == "PLAYING") {
tizen.fmradio.stop();
$('#radioTitle').text('Turn on the Radio');
$('.fm-img').hide();
}
}
function successCallback() {
$('#radioTitle').text(tizen.fmradio.frequency);
}
}
},
/**
* Contains methods related to the alarm page.
*
* @public
* @type {object}
*/
alarm: {
/**
* Initializes alarm page.
*
* @public
*/
init: function UI_alarm_init() {
this.updateAlarmInfo();
this.addEvents(this);
},
/**
* Binds events to the alarm page.
*
* @public
*/
addEvents: function addEvents(alarm) {
$('.button_alarm_on').on('click', function() {
var input = $('#alarm_period');
if(alarm.validateInput()) {
var num = input.val();
var period = tizen.alarm.PERIOD_MINUTE;
var newAlarm = new tizen.AlarmRelative(num * period, num * period);
tizen.alarm.add(newAlarm, tizen.application.getCurrentApplication().appInfo.id);
input.val('');
alarm.updateAlarmInfo();
}
});
$('.button_alarm_off').on('click', function() {
tizen.alarm.removeAll();
alarm.updateAlarmInfo();
});
$('.button_alarm_update').on('click', function() {
alarm.updateAlarmInfo();
});
},
/**
* Update information about available alarms
*
* @public
*/
updateAlarmInfo: function updateAlarmInfo() {
var alarms = tizen.alarm.getAll();
$('#alarm_number').text(alarms.length);
},
/**
* Validate input for correct numeric value
*
* @public
*/
validateInput: function validateInput() {
var input = $('#alarm_period');
var period = input.val();
if (period >= 1 && period <=59) {
input.removeClass('input_error_yes');
return true;
} else {
input.addClass('input_error_yes');
return false;
}
}
},
/**
* Contains methods related to the battery page.
*
* @public
* @type {object}
*/
battery: {
/**
* Initializes battery page.
*
* @public
*/
init: function UI_battery_init() {
this.addEvents();
},
/**
* Binds events to the battery page.
*
* @public
*/
addEvents: function addEvents() {
var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
window.addEventListener('load', getBatteryState);
/* Detects changes in the battery charging status */
battery.addEventListener('chargingchange', getBatteryState);
/* Detects changes in the battery charging time */
battery.addEventListener('chargingtimechange', getBatteryState);
/* Detects changes in the battery discharging time */
battery.addEventListener('dischargingtimechange', getBatteryState);
/* Detects changes in the battery level */
battery.addEventListener('levelchange', getBatteryState);
function getBatteryState()
{
var message = "";
var charging = battery.charging;
var chargingTime = getTimeFormat(battery.chargingTime);
var dischargingTime = getTimeFormat(battery.dischargingTime);
var level = Math.floor(battery.level * 100);
if (charging == false && level < 100)
{
/* Not charging */
message = dischargingTime.hour + ":" + dischargingTime.minute + " remained.";
if (battery.dischargingTime == "Infinity")
{
message = "";
}
}
else if (charging && level < 100)
{
/* Charging */
message = "Charging is complete after "
+ chargingTime.hour + ":" + chargingTime.minute;
if (battery.chargingTime == "Infinity")
{
message = "";
}
}
else if (level == 100)
{
message = "Charging is completed";
}
if (charging) {
document.querySelector('#charging').textContent = 'charging...';
} else if (!charging && level <= 90) {
document.querySelector('#charging').textContent = 'Please connect the charger';
} else if (!charging && level > 90) {
document.querySelector('#charging').textContent = 'You do not need the charger';
}
document.querySelector('#level').textContent = level + "%";
document.querySelector('#progress').value = level;
document.querySelector('#message').textContent = message;
}
/* Time is received in seconds, converted to hours and minutes, and returned */
function getTimeFormat(time)
{
/* Time parameter is second */
var tempMinute = time / 60;
var hour = parseInt(tempMinute / 60, 10);
var minute = parseInt(tempMinute % 60, 10);
minute = minute < 10 ? "0" + minute : minute;
return {"hour": hour, "minute": minute};
}
}
},
/**
* Contains methods related to the video page.
*
* @public
* @type {object}
*/
video: {
/**
* Initializes video page.
*
* @public
*/
init: function UI_video_init() {
this.addEvents();
},
/**
* Binds events to the video page.
*
* @public
*/
addEvents: function addEvents() {
$('.video-input').on('change', function readSelectedFiles() {
var URL = window.URL || window.webkitURL;
var files = document.getElementById('videoFile').files,
displaySection = document.getElementById('video-container');
if (files.length === 0) {
return;
} else {
displaySection.innerHTML = '<video class="video-player" id="video-p" src="' + URL.createObjectURL(files[0]) + '" poster="" preload="auto" controls muted></video>';
}
});
}
},
/**
* Contains methods related to the addressbook page.
*
* @public
* @type {object}
*/
addressbook: {
/**
* Initializes addressbook page.
*
* @public
*/
init: function UI_addressbook_init() {
var myAddressbook = tizen.contact.getDefaultAddressBook();
console.log(myAddressbook);
var filter = new tizen.AttributeFilter("name.firstName", "CONTAINS", "n");
var sortMode = new tizen.SortMode("name.lastName", "ASC");
// try {
// myAddressbook.find(contactsFoundCB, null, filter, sortMode);
// }
//
// /* Define the event success callback */
// function contactsFoundCB(contacts)
// {
// contacts[0].name.firstName = "Christopher";
// myAddressbook.update(contacts[0]);
//
// console.log(contacts[0].name.firstName);
// for(var i = 0; i < contacts.length; i++) {
// console.log(contacts[i].name.firstName);
// }
// }
this.addEvents();
},
/**
* Binds events to the addressbook page.
*
* @public
*/
addEvents: function addEvents() {
}
},
/**
* Contains methods related to the health page.
*
* @public
* @type {object}
*/
health: {
/**
* Initializes health page.
*
* @public
*/
init: function UI_health_init() {
this.addEvents();
},
/**
* Binds events to the health page.
*
* @public
*/
addEvents: function addEvents() {
}
}
};
/**
* Creates and displays popup widget.
*
* @public
* @param {string} text Text information.
* @param {object} buttons Buttons template object.
*/
Ui.prototype.popup = function showPopup(text, buttons) {
var i = 0,
popupNumber = Object.keys(buttons).length,
popup = document.getElementById('popup'),
popupButtons = $('#popupButtons'),
popupText = document.getElementById('popupText'),
tauPopup = tau.widget.Popup(popup),
buttonsCount = 0;
// if buttons template wasn't add, use default template
if (!buttons) {
buttons = {
'OK': function ok() {
tauPopup.close();
}
};
}
// clear popup
popupButtons.empty();
popup.className = popup.className.replace(/\bcenter_basic.*?\b/g, '');
popup.classList.add('center_basic_' + popupNumber + 'btn');
// adds buttons to popup HTML element
for (i in buttons) {
if (buttons.hasOwnProperty(i)) {
buttonsCount += 1;
if (buttons[i]) {
$('<a/>').text(i).attr({
'data-inline': 'true'
}).addClass('ui-btn').bind('click', buttons[i]).appendTo(
popupButtons
);
}
}
}
if (buttonsCount === 2) {
popupButtons.addClass('ui-grid-col-2');
} else {
popupButtons.removeClass('ui-grid-col-2');
}
// adds text to popup HTML element
popupText.innerHTML = '<p>' + text + '</p>';
tau.engine.createWidgets(popup);
tau.widget.Popup(popup).open();
};
}());
|
var QuoteScanner = function QuoteScanner(data) {
this.data = data;
};
var findQuoteEnd = function (data, matched, cursor, oldCursor) {
var commentStartMark = '/*';
var commentEndMark = '*/';
var escapeMark = '\\';
var blockEndMark = '}';
var dataPrefix = data.substring(oldCursor, cursor);
var commentEndedAt = dataPrefix.lastIndexOf(commentEndMark, cursor);
var commentStartedAt = dataPrefix.lastIndexOf(commentStartMark, cursor);
var commentStarted = false;
if (commentEndedAt >= cursor && commentStartedAt > -1)
commentStarted = true;
if (commentStartedAt < cursor && commentStartedAt > commentEndedAt)
commentStarted = true;
if (commentStarted) {
var commentEndsAt = data.indexOf(commentEndMark, cursor);
if (commentEndsAt > -1)
return commentEndsAt;
commentEndsAt = data.indexOf(blockEndMark, cursor);
return commentEndsAt > -1 ? commentEndsAt - 1 : data.length;
}
while (true) {
if (data[cursor] === undefined)
break;
if (data[cursor] == matched && (data[cursor - 1] != escapeMark || data[cursor - 2] == escapeMark))
break;
cursor++;
}
return cursor;
};
QuoteScanner.prototype.each = function (callback) {
var data = this.data;
var tempData = [];
var nextStart = 0;
var nextEnd = 0;
var cursor = 0;
var matchedMark = null;
var singleMark = '\'';
var doubleMark = '"';
var dataLength = data.length;
for (; nextEnd < data.length;) {
var nextStartSingle = data.indexOf(singleMark, nextEnd + 1);
var nextStartDouble = data.indexOf(doubleMark, nextEnd + 1);
if (nextStartSingle == -1)
nextStartSingle = dataLength;
if (nextStartDouble == -1)
nextStartDouble = dataLength;
if (nextStartSingle < nextStartDouble) {
nextStart = nextStartSingle;
matchedMark = singleMark;
} else {
nextStart = nextStartDouble;
matchedMark = doubleMark;
}
if (nextStart == -1)
break;
nextEnd = findQuoteEnd(data, matchedMark, nextStart + 1, cursor);
if (nextEnd == -1)
break;
var text = data.substring(nextStart, nextEnd + 1);
tempData.push(data.substring(cursor, nextStart));
if (text.length > 0)
callback(text, tempData, nextStart);
cursor = nextEnd + 1;
}
return tempData.length > 0 ?
tempData.join('') + data.substring(cursor, data.length) :
data;
};
module.exports = QuoteScanner;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unibeautify_1 = require("unibeautify");
const src_1 = require("../../src");
test("should successfully beautify JSX text", () => {
const unibeautify = unibeautify_1.newUnibeautify();
unibeautify.loadBeautifier(src_1.default);
const text = `export default class TestCase extends React.Component {
render() {
return ( <div className={this.props.className} someAttr>
<div>Smth</div>
</div> );
}
}`;
const beautifierResult = `export default class TestCase extends React.Component {
render() {
return (<div className={this.props.className} someAttr>
<div>Smth</div>
</div>);
}
}`;
return unibeautify
.beautify({
languageName: "JSX",
options: {
JSX: {
indent_char: " ",
indent_size: 2
}
},
text
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
test("should successfully beautify JSX text with wrap_line_length", () => {
const unibeautify = unibeautify_1.newUnibeautify();
unibeautify.loadBeautifier(src_1.default);
const text = `export default class TestCase extends React.Component {
render() {
return ( <div className={this.props.className} someAttr>
<div>Smth</div>
</div> );
}
}`;
const beautifierResult = `export default class TestCase extends React
.Component {
render() {
return (
<div className={this.props.className} someAttr>
<div>Smth</div>
</div>
);
}
}`;
return unibeautify
.beautify({
languageName: "JSX",
options: {
JSX: {
indent_char: " ",
indent_size: 2,
wrap_line_length: 40
}
},
text
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
//# sourceMappingURL=JSX.spec.js.map |
import React from "react";
export default class ProductCategoryRow extends React.Component {
render() {
return (
<tr>
<th colSpan="2">{this.props.category}</th>
</tr>
);
}
}; |
var Q = require('q'),
_ = require('lodash'),
request = require('request');
//private variables
var config = {};
//private functions
function genQuery(query) {
return query ? '?'+ query : '';
}
function requestP(method, uri, data) {
return Q.Promise(function (resolve, reject) {
var reqOptions = {
method: method,
uri: config.baseUrl + uri,
headers: config.headers,
json: true
};
if (data) {
reqOptions['body'] = data;
}
request(reqOptions, function (err, res, body) {
if (err) {
return reject(err);
}
var statusCode = res.toJSON().statusCode;
if (statusCode >= 200 && statusCode <= 299) {
resolve(body);
} else {
reject({ statusCode: statusCode, err: body });
}
});
});
}
function restify(fn, arg) {
return function () {
return fn(genResourceIdPath(_.toArray(arguments)));
};
}
function restifyWithData(fn) {
return function () {
var args = _.toArray(arguments),
resourcesAndIds = _.initial(args),
obj = _.last(args);
return fn(genResourceIdPath(resourcesAndIds), obj);
};
}
function generate(fn) {
return function () {
var args = _.toArray(arguments);
args.unshift(fn);
return _.partial.apply(null, args);
};
}
//Public Functions
var get = _.partial(requestP, 'GET'),
post = _.partial(requestP, 'POST'),
put = _.partial(requestP, 'PUT'),
del = _.partial(requestP, 'DELETE');
function genResourceIdPath (resourcesAndIds) {
var half = Math.ceil(resourcesAndIds.length/2),
resources = resourcesAndIds.slice(0, half),
ids = resourcesAndIds.slice(half, resourcesAndIds.length),
concatArray = [];
for (var i = 0; i < ids.length; i++) {
concatArray.push(resources[i]);
concatArray.push(ids[i]);
}
if (resources.length > ids.length) {
concatArray.push(resources[resources.length-1]);
}
return concatArray.join('/');
}
function listObjects (/*resources, ids, query*/) {
var args = _.toArray(arguments);
//one resource, query
if (args.length == 2) {
return get(args[0] + genQuery(args[1]));
}
//multiple resources and ids, no query
if (args.length % 2 == 1) {
return get(genResourceIdPath(args));
}
//multiple resources and ids, query
var query = genQuery(args[args.length - 1]),
pathArgs = args.slice(0, args.length-1);
return get(genResourceIdPath(pathArgs) + query);
}
//brckt definition
module.exports = brckt = function (baseUrl, headers) {
config.baseUrl = baseUrl.slice(-1) == '/' ? baseUrl : baseUrl + '/';
config.headers = headers;
return {
buildGetFn: generate(restify(get)),
buildListFn: generate(listObjects),
buildCreateFn: generate(restifyWithData(post)),
buildUpdateFn: generate(restifyWithData(put)),
buildRemoveFn: generate(restify(del)),
getObject: restify(get),
listObjects: listObjects,
createObject: restifyWithData(post),
updateObject: restifyWithData(put),
removeObject: restify(del),
get: get,
post: post,
put: put,
delete: del,
};
};
|
// # Ghost Configuration
// Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments).
// Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
var mailgunApiTransport = require('nodemailer-mailgunapi-transport');
var auth = {
auth: {
api_key: 'SMTP_PASSWORD',
domain: 'MAIN_DOMAIN'
}
}
config = {
// ### Production
// When running Ghost in the wild, use the production environment.
// Configure your URL and mail settings here
production: {
url: 'http://MAIN_DOMAIN',
mail: {
from: 'SMTP_USER',
transport: mailgunApiTransport(auth),
},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
host: '127.0.0.1',
port: '2368'
}
},
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
// Change this to your Ghost blog's published URL.
url: 'http://localhost:2368',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
// ```
// mail: {
// transport: 'SMTP',
// options: {
// service: 'Mailgun',
// auth: {
// user: '', // mailgun username
// pass: '' // mailgun password
// }
// }
// },
// ```
// #### Database
// Ghost supports sqlite3 (default), MySQL & PostgreSQL
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
// #### Server
// Can be host & port (default), or socket
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
},
// #### Paths
// Specify where your content directory lives
paths: {
contentPath: path.join(__dirname, '/content/')
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
},
pool: {
afterCreate: function (conn, done) {
conn.run('PRAGMA synchronous=OFF;' +
'PRAGMA journal_mode=MEMORY;' +
'PRAGMA locking_mode=EXCLUSIVE;' +
'BEGIN EXCLUSIVE; COMMIT;', done);
}
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
module.exports = config;
|
// Scripts go in here. This is an example script to test the api.
import http from 'http'
const options = {
hostname: 'localhost',
port: 3000,
path: '/api/thing',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
const req = http.request(options, (res) => {
let resBody = []
res.on('data', (chunk) => {
resBody.push(chunk)
})
res.on('end', () => {
console.log(`Response body: ${resBody.join('')}`)
})
})
req.on('error', (err) => {
console.log(err)
})
req.write(JSON.stringify({ name: 'foo' }))
req.end()
|
// Regular expression that matches all symbols in the Halfwidth and Fullwidth Forms block as per Unicode v4.0.1:
/[\uFF00-\uFFEF]/; |
'use strict';
exports.register = function(plugin, options, next) {
const Controllers = {
editor: {
info: require('../controllers/editor/info'),
share: require('../controllers/editor/share'),
editor: require('../controllers/editor/editor'),
steps: require('../controllers/editor/steps')
}
};
plugin.route([
// Editor info
{
method: 'GET',
path: '/editor/info',
config: Controllers.editor.info.show
},
// Editor data
{
method: 'GET',
path: '/editor/data',
config: Controllers.editor.editor.getData
},
// Editor data update
{
method: 'POST',
path: '/editor/data',
config: Controllers.editor.editor.updateData
},
// Share
{
method: 'GET',
path: '/editor/share',
config: Controllers.editor.share.show
},
// Share
{
method: 'POST',
path: '/editor/share',
config: Controllers.editor.share.postShareForm
},
// T + 2
{
method: 'GET',
path: '/editor/t2',
config: Controllers.editor.steps.showStep
},
// T + 5
{
method: 'GET',
path: '/editor/t5',
config: Controllers.editor.steps.showStep
},
// T + 6
{
method: 'GET',
path: '/editor/t6',
config: Controllers.editor.steps.showStep
},
// T + 7
{
method: 'GET',
path: '/editor/t7',
config: Controllers.editor.steps.showStep
},
// T + 8
{
method: 'GET',
path: '/editor/t8',
config: Controllers.editor.steps.showStep
}
]);
next();
};
exports.register.attributes = {
name: 'editor_routes',
version: require('../../package.json').version
};
|
import React from 'react';
import Icon from '../Icon';
export default class Crop75Icon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M38 14H10c-2.21 0-4 1.79-4 4v12c0 2.21 1.79 4 4 4h28c2.21 0 4-1.79 4-4V18c0-2.21-1.79-4-4-4zm0 16H10V18h28v12z"/></svg>;}
}; |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('angular2/core');
var router_1 = require('angular2/router');
var common_1 = require('angular2/common');
var title_1 = require('./providers/title');
var x_large_1 = require('./directives/x-large');
var home_1 = require('./home/home');
var folders_1 = require('./folders/folders');
var files_1 = require('./files/files');
var App = (function () {
function App(title) {
this.title = title;
this.url = 'https://twitter.com/thevivekwisdom';
}
App = __decorate([
core_1.Component({
selector: 'app',
providers: common_1.FORM_PROVIDERS.concat([title_1.Title]),
directives: router_1.ROUTER_DIRECTIVES.concat([x_large_1.XLarge]),
pipes: [],
styles: ['app.css'],
template: 'app.html'
}),
router_1.RouteConfig([
{ path: '/', component: home_1.Home, name: 'Home' },
{ path: '/folders', component: folders_1.Folders, name: 'Folders' },
{ path: '/files', component: files_1.Files, name: 'Files' }
]),
__metadata('design:paramtypes', [title_1.Title])
], App);
return App;
})();
exports.App = App;
//# sourceMappingURL=app.js.map |
var mongoose = require('mongoose');
var Org = require('./models/model.orgs.js');
var moment = require('moment');
var jwt = require('jsonwebtoken');
var randtoken = require('rand-token');
var Mailgun = require('mailgun-js');
var helpers = require('./helpers.js');
var port = process.env.PORT || 3000;
var APP_URL = process.env.APP_URL;
var MONGOLAB_URI = process.env.MONGOLAB_URI;
var MAILGUN_API = process.env.MAILGUN_API;
var MAILGUN_DOMAIN = process.env.MAILGUN_DOMAIN;
var TOKEN_SECRET = process.env.TOKEN_SECRET;
module.exports = function(app) {
app.post('/API/org/create', function(req, res) {
Org.findOne({name: req.body.name}, function(err, existingOrg) {
if (existingOrg) {
return res.status(401).send({ message: 'There is already a organization with that name' });
}
var org = new Org({
name: req.body.name,
regkey: req.body.regkey,
createdby: req.user,
});
org.save(function(err, result) {
if (err) {
return res.status(409).send({message: 'There was an error creating the organization: ' + err});
}
res.send({message: 'New organization created', result: result});
});
});
});
app.get('/api/orgs', function(req, res) {
Org.find({}, function(err, orgs) {
if (err) {
return res.status(409).send({message: 'There was an error retrieving organizations ' + err});
}
res.send(orgs);
});
});
};
|
import * as Utils from './utils';
const getNextDirection = (mesh) => {
if (mesh.position.z >= 170 && mesh.userData.animDirection === 'left') {
return 'right';
}
if (mesh.position.z <= -170 && mesh.userData.animDirection === 'right') {
return 'left';
}
return mesh.userData.animDirection;
}
export const animateCatcher = (mesh, dt) => {
mesh.userData.animDirection = getNextDirection(mesh);
if (mesh.userData.animDirection === 'left') {
mesh.position.z += mesh.userData.animRate * dt;
}
if (mesh.userData.animDirection === 'right') {
mesh.position.z -= mesh.userData.animRate * dt;
}
}
export const getAnimatableIds = (scene, animations, removal) => {
return animations.filter(id => {
if (removal.includes(id)) {
const object = scene.getObjectById(id);
scene.remove(object);
return false;
}
return true;
});
}
export const animateCubeFromId = (id, dt, catcher, scene, removalArray) => {
const object = scene.getObjectById(id);
if (object.position.y >= 320) {
return;
}
if (object.position.x >= 170) {
object.position.y += object.userData.animRate * dt;
if (Utils.isInside(catcher, object)) {
removalArray.push(object.id);
}
return;
}
object.position.x += object.userData.animRate * dt;
}
|
asc.component('demo', function () {
this.templateSrc = 'demo/template.html';
}); |
// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license
(function($) {
function maybeCall(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
};
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = true;
this.fixTitle();
};
Tipsy.prototype = {
show: function() {
var title = this.getTitle();
if (title && this.enabled) {
var $tip = this.tip();
$tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
$tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
$tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
if (this.options.className) {
$tip.addClass(maybeCall(this.options.className, this.$element[0]));
}
var that = this;
function tipOver() {
that.hoverTooltip = true;
}
function tipOut() {
if (that.hoverState == 'in') return; // If field is still focused.
that.hoverTooltip = false;
if (that.options.trigger != 'manual') {
var eventOut = that.options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy';
that.$element.trigger(eventOut);
}
}
if (this.options.hoverable) {
$tip.hover(tipOver, tipOut);
}
var pos = $.extend({}, this.$element.offset(), {
width: this.$element[0].offsetWidth,
height: this.$element[0].offsetHeight
});
var actualWidth = $tip[0].offsetWidth,
actualHeight = $tip[0].offsetHeight,
gravity = maybeCall(this.options.gravity, this.$element[0]);
var tp;
switch (gravity.charAt(0)) {
case 'n':
tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 's':
tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'e':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
break;
case 'w':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
break;
}
if (gravity.length == 2) {
if (gravity.charAt(1) == 'w') {
tp.left = pos.left + pos.width / 2 - 15;
} else {
tp.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
$tip.css(tp).addClass('tipsy-' + gravity);
$tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
if (this.options.fade) {
$tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
} else {
$tip.css({visibility: 'visible', opacity: this.options.opacity});
}
// if there's a callback, run it
if( $.isFunction(this.options.afterShow) ) this.options.afterShow.apply(self);
}
},
hide: function() {
if (this.options.fade) {
this.tip().stop().fadeOut(function() { $(this).remove(); });
} else {
this.tip().remove();
}
},
fixTitle: function() {
var $e = this.$element;
if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
$e.attr('original-title', $e.attr('title') || '').removeAttr('title');
}
},
getTitle: function() {
var title, $e = this.$element, o = this.options;
this.fixTitle();
var title, o = this.options;
if (typeof o.title == 'string') {
title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
} else if (typeof o.title == 'function') {
title = o.title.call($e[0]);
}
title = ('' + title).replace(/(^\s*|\s*$)/, "");
return title || o.fallback;
},
tip: function() {
if (!this.$tip) {
this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
}
return this.$tip;
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide();
this.$element = null;
this.options = null;
}
},
enable: function() { this.enabled = true; },
disable: function() { this.enabled = false; },
toggleEnabled: function() { this.enabled = !this.enabled; }
};
$.fn.tipsy = function(options) {
if (options === true) {
return this.data('tipsy');
} else if (typeof options == 'string') {
var tipsy = this.data('tipsy');
if (tipsy) tipsy[options]();
return this;
}
options = $.extend({}, $.fn.tipsy.defaults, options);
if (options.hoverable) {
options.delayOut = options.delayOut || 200;
}
function get(ele) {
var tipsy = $.data(ele, 'tipsy');
if (!tipsy) {
tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
$.data(ele, 'tipsy', tipsy);
}
return tipsy;
}
function enter() {
var tipsy = get(this);
if( options.activeTip === undefined ){
tipsy.hoverState = 'in';
if (options.delayIn == 0) {
tipsy.show();
} else {
tipsy.fixTitle();
setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
}
}
};
function leave() {
var tipsy = get(this);
if( tipsy.clickState !== 'on' ){
tipsy.hoverState = 'out';
if (options.delayOut == 0) {
tipsy.hide();
} else {
setTimeout(function() { if (tipsy.hoverState == 'out' && !tipsy.hoverTooltip) tipsy.hide(); }, options.delayOut);
}
}
};
function sticky() {
var tipsy = get(this),
activeTip,
show = (tipsy.clickState === 'on') ? false : true;
handleClose();
if( show ){
tipsy.show();
tipsy.clickState = 'on';
options.activeTip = this;
$(this).addClass('tipsy-sticky-click');
options.stickyClick(this, tipsy.clickState);
}
}
function handleScroll(event) {
var target = $(event.target);
if( !(target.parents().hasClass('tipsy-inner')) ){
if( options.activeTip ){
options.activeTip.clickState = 'off';
options.stickyClick(options.activeTip, 'off');
get(options.activeTip).hide();
options.activeTip = undefined;
}
}
}
function closeAll(){
var elements = $('.tipsy');
elements.remove();
}
function handleClose(){
var elements = $('.tipsy-sticky-click'),
i, length, tipsy, node;
for(i=0, length = elements.length; i < length; i += 1){
node = elements[i];
$(node).removeClass('tipsy-sticky-click');
tipsy = get(node);
tipsy.clickState = 'off';
tipsy.hide();
options.stickyClick(node, tipsy.clickState);
}
options.activeTip = undefined;
}
if (!options.live) this.each(function() { get(this); });
if (options.trigger != 'manual') {
var binder = options.live ? 'live' : 'bind',
eventIn = options.trigger == 'hover' ? 'mouseenter.tipsy' : 'focus.tipsy',
eventOut = options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy';
this[binder](eventIn, enter)[binder](eventOut, leave);
}
if (options.stickyClick) {
this['live']('click', sticky);
$(document).bind('scroll', handleScroll);
$(document).bind('close.tipsy', handleClose);
}
$(document).bind('close.tipsy', function(){
closeAll();
});
return this;
};
$.fn.tipsy.defaults = {
className: null,
delayIn: 0,
delayOut: 0,
fade: false,
fallback: '',
gravity: 'n',
html: false,
live: false,
hoverable: false,
stickyClick: false,
offset: 0,
opacity: 0.8,
title: 'title',
trigger: 'hover',
afterShow: null //call back after the tip is shown
};
// Overwrite this method to provide options on a per-element basis.
// For example, you could store the gravity in a 'tipsy-gravity' attribute:
// return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
// (remember - do not modify 'options' in place!)
$.fn.tipsy.elementOptions = function(ele, options) {
return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
};
$.fn.tipsy.autoNS = function() {
return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
};
$.fn.tipsy.autoWE = function() {
return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
};
/**
* yields a closure of the supplied parameters, producing a function that takes
* no arguments and is suitable for use as an autogravity function like so:
*
* @param margin (int) - distance from the viewable region edge that an
* element should be before setting its tooltip's gravity to be away
* from that edge.
* @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
* if there are no viewable region edges effecting the tooltip's
* gravity. It will try to vary from this minimally, for example,
* if 'sw' is preferred and an element is near the right viewable
* region edge, but not the top edge, it will set the gravity for
* that element's tooltip to be 'se', preserving the southern
* component.
*/
$.fn.tipsy.autoBounds = function(margin, prefer) {
return function() {
var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
boundTop = $(document).scrollTop() + margin,
boundLeft = $(document).scrollLeft() + margin,
$this = $(this);
if ($this.offset().top < boundTop) dir.ns = 'n';
if ($this.offset().left < boundLeft) dir.ew = 'w';
if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
return dir.ns + (dir.ew ? dir.ew : '');
}
};
})(jQuery);
|
// <editor-fold desc="Dependencies">
var gulp = require('gulp');
var path = require('path');
var argv = require('yargs').argv;
var webpackStream = require('webpack-stream');
var openBrowser = require('gulp-open');
var Env = require('./gulp/Env');
var Log = require('./gulp/Log');
var WebpackConfig = require('./gulp/WebpackConfig');
// </editor-fold> Dependencies
// <editor-fold desc="Environment Settings">
// BUILD
var buildConfig = require('./env/build.default');
try{
buildConfig = Env.combine(buildConfig, require('./env/build'));
}catch(e){}
// DEMO
var demoEnv = require('./env/demo.example');
try{
demoEnv = require('./env/demo');
}catch(e){
Log.yellow("Warning: No demo.js exists. Running with demo.example.js.");
}
// OAUTH
var oauthEnv = {};
try{
oauthEnv = require('./env/oauth');
}catch(e){
Log.yellow(
"Warning: No oauth.js exists.\n"+
"You'll be unable to build an app that requires users to login with OAuth.\n"+
"Create an empty file to suppress this warning."
);
}
// </editor-fold> Environment Settings
// <editor-fold desc="Common Tasks">
gulp.task('default', ['build']);
// </editor-fold> Common Settings
// <editor-fold desc="Build Tasks">
gulp.task('build', ['build:web', 'build:node']);
/**
* Build with the web entry point and settings
*/
gulp.task('build:web', function(){
return gulp.src('').pipe(
webpackStream(
WebpackConfig.makeWeb('web-full.js', 'playerme-core.js')
)
).pipe(
gulp.dest('dist/web')
);
});
/**
* Build with the node entry point and settings
*/
gulp.task('build:node', function(){
return gulp.src('').pipe(
webpackStream(
WebpackConfig.makeNode('node.js', 'playerme-core.node.js')
)
).pipe(
gulp.dest('dist/node')
);
});
/**
* Pass a custom entry point to webpack with custom output settings
* Takes an entry flag and an output flag
* @example gulp build:custom --entry example.js --output playerme-core.example.js --libraryTarget var --target web
* TODO Prompt for input if required flags haven't been set
*/
gulp.task('build:custom', function(){
var entryFileName = argv.entry || argv.E || false;
var outputFileName = argv.output || argv.O || false;
var target = argv.target || argv.T || 'web';
var libraryTarget = argv.libraryTarget || argv.L || 'var';
var example = "(e.g. `" +
"gulp build:custom" +
" --entry example.js" +
" --output playerme-core.example.js" +
" --libraryTarget var" +
" --target web" +
"`)";
if (!entryFileName){
Log.red('Please pass an entry file name. '+example);
return;
}
if (!outputFileName){
Log.red('Please pass an output file name. '+example);
return;
}
var config = WebpackConfig.makeWeb(
path.resolve('./entry', entryFileName),
path.resolve(outputFileName)
);
config.target = target;
config.output.libraryTarget = libraryTarget;
config.output.umdNamedDefine = true;
return gulp.src('').pipe(
webpackStream(config)
).pipe(
gulp.dest('./')
);
});
/**
* Pass a custom entry point to webpack.
* Takes an entry flag and an output flag
* @example gulp build:custom --entry example.js --output playerme-core.example.js
* TODO Prompt for input if required flags haven't been set
*/
gulp.task('build:custom:web', function(){
var entryFileName = argv.entry || argv.E || false;
var outputFileName = argv.output || argv.O || 'playerme-core.custom.js';
var example = "(e.g. `gulp build:custom --entry example.js --output playerme-core.example.js`)";
if (!entryFileName){
Log.red('Please pass an entry file name. '+example);
return;
}
return gulp.src('').pipe(
webpackStream(
WebpackConfig.makeWeb(
path.resolve('./entry', entryFileName),
path.resolve(outputFileName)
)
)
).pipe(
gulp.dest('dist/web')
);
});
/**
* Pass a custom entry point to webpack.
* Takes an entry flag and an output flag
* @example gulp build:custom --entry example.js --output playerme-core.example.js
* TODO Prompt for input if required flags haven't been set
*/
gulp.task('build:custom:node', function(){
var entryFileName = argv.entry || argv.E || false;
var outputFileName = argv.output || argv.O || 'playerme-core.custom.js';
var example = "(e.g. `gulp build:custom --entry example.js --output playerme-core.example.js`)";
if (!entryFileName){
Log.red('Please pass an entry file name. '+example);
return;
}
return gulp.src('').pipe(
webpackStream(
WebpackConfig.makeNode(
path.resolve('./entry', entryFileName),
path.resolve(outputFileName)
)
)
).pipe(
gulp.dest('dist/web')
);
});
// </editor-fold> Build Tasks
// <editor-fold desc="Demo Web Tasks">
gulp.task('demo:web', function(){
return gulp.src(
'./demo/web/TestPage/index.html'
).pipe(
openBrowser()
);
});
// </editor-fold>
// <editor-fold desc="Demo Node Tasks">
gulp.task('demo:node:auth', function(done){
demoNode('auth/index.js', done);
});
gulp.task('demo:node:user', function(done){
demoNode('user/index.js', done);
});
gulp.task('demo:node:realtime', function(done){
demoNode('realtime/index.js', done);
});
function demoNode(indexFile, callback){
var spawn = require('child_process').spawn;
var joinedPath = path.join('demo/node', indexFile);
var absolutePath = path.resolve(joinedPath);
var spawned = spawn(buildConfig.NODE_COMMAND, [
absolutePath
],{
cwd: __dirname,
env: Env.combine(demoEnv)
});
spawned.stdout.on('data', function (data) {
Log.magenta(data.toString());
});
spawned.stderr.on('data', function (data) {
Log.red(data.toString());
});
spawned.on('exit', function (code) {
Log.cyan('Demo exited with return code ' + code.toString());
callback();
});
}
// </editor-fold> |
import MagnonElement from "../../src/magnon-element.js";
import { css } from "../../src/literals.js";
import "../magnon-styles/magnon-styles.js";
const style = css`
:host {
display: inline-block;
position: relative;
width: var(--magnon-spinner-size, 32px);
height: var(--magnon-spinner-size, 32px);
}
.ball {
display: block;
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
background: var(--magnon-spinner-color, var(--magnon-black));
border-radius: 50%;
width: calc(var(--magnon-spinner-size, 32px) / 3);
height: calc(var(--magnon-spinner-size, 32px) / 3);
transform-origin: center;
}
`;
const pi2 = Math.PI * 2;
export class MagnonSpinner extends MagnonElement {
constructor(options = {
balls: 3, ballScale: 1, ballOffset: 1 / 3, spinSpeed: 3,
minRadius: 0, maxRadius: 100
}) {
super({ content: `<div id="container"></div>` + style });
this._balls = [];
this._initOptions = options;
this._timer = 0;
requestAnimationFrame(() => this._animate());
}
static get elementName() {
return "magnon-spinner";
}
static get propertyAttributes() {
return {
bool: ["alternate"],
number: [
"balls", "ball-scale", "ball-offset",
"spin-speed", "min-radius", "max-radius"
]
};
}
connectedCallback() {
const options = this._initOptions;
this.balls = options.balls;
this.ballScale = options.ballScale;
this.ballOffset = options.ballOffset;
this.alternate = options.alternate;
this.spinSpeed = options.spinSpeed;
this.minRadius = options.minRadius;
this.maxRadius = options.maxRadius;
}
propertySet(property, old, value) {
if (property === "balls") {
const container = this.root.querySelector("#container");
let child = container.firstChild;
while (child) {
container.removeChild(child);
child = container.firstChild;
}
this._balls = [];
for (let i = 0; i < value; i++) {
const ball = document.createElement("span");
ball.className = "ball";
container.appendChild(ball);
this._balls[i] = ball;
}
}
}
_animate() {
this._timer += 0.05;
if (this._timer >= pi2) this._timer -= pi2;
const radiusMin = parseInt(this.minRadius);
const radiusMax = parseInt(this.maxRadius);
const radiusTotal = radiusMax - radiusMin;
this._balls.forEach((ball, i) => {
const rotation = pi2 * this.ballOffset * i + this._timer * this.spinSpeed;
const fromMiddle = (Math.sin(this._timer / 2) * radiusTotal) + radiusMin;
ball.style.transform = `
rotate(${rotation}rad)
translate(${fromMiddle}%)
scale(${this.ballScale})
`;
});
requestAnimationFrame(() => this._animate());
}
}
MagnonSpinner.init();
|
/**
* Created by smichaels on 6/23/17.
*/
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import {sendWebsocketMessage} from '../actions/index';
class WsSendButton extends Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(event) {
event.preventDefault();
this.props.sendWebsocketMessage();
}
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group pull-right">
<button type="submit" className="btn btn-primary">Send Websocket Message</button>
</form>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({sendWebsocketMessage}, dispatch);
}
export default connect(null, mapDispatchToProps)(WsSendButton); |
//----------------------------------------------------------------------
$(document).ready(function()
{
//----------------------------------------------------------------------
function limit_finished_jobs(limit)
{
if (limit < 0)
$finished_table.ajax.url("/get_all_finished_jobs");
else
$finished_table.ajax.url("/get_all_finished_jobs?limit="+String(limit));
}
//----------------------------------------------------------------------
//--------------------------- gen functions ----------------------------
//----------------------------------------------------------------------
function check_heartbeat_timestamp(aData)
{
var $red_bk_color = "#F78181"; //red
var $bk_color = "#F78181"; //red
//sample format
//'2015-10-26 11:23:47.325000'
if (aData.Status === "Offline")
{
return $bk_color;
}
else
{
var $date_arr = aData.Heartbeat.split(" ");
if ($date_arr.length > 1)
{
if (aData.Status === "Idle")
$bk_color = "#9FF781"; //green
else
$bk_color = "#F3F781"; // yellow
var $mDate = $date_arr[0].split("-");
if ($mDate.length < 3)
return $red_bk_color;
var $mTime = $date_arr[1].split(":");
if ($mTime.length < 3)
return $red_bk_color;
// Get the current date and check it to heartbeat
var $now = new Date();
if ($now.getFullYear() !== parseInt($mDate[0]))
return $red_bk_color;
if ($now.getMonth() + 1 !== parseInt($mDate[1]))
return $red_bk_color;
if ($now.getDate() !== parseInt($mDate[2]))
return $red_bk_color;
var $hourDiff = $now.getHours() - parseInt($mTime[0]);
var $minDiff = $now.getMinutes() - parseInt($mTime[1]);
if ($hourDiff > 1)
return $red_bk_color;
if ($minDiff > 10)
return $red_bk_color;
}
}
return $bk_color;
}
//----------------------------------------------------------------------
function convert_procmask_number_to_string(aData)
{
var $str = "";
if(aData.Experiment === 'XRF-Maps' || aData.Experiment === 'MapsPy')
{
if( (aData.Args.ProcMask & 1) === 1)
{
if(aData.Experiment === 'XRF-Maps')
{
$str += '(A) Analyze datasets using ROI and NNLS :: ';
}
else if (aData.Experiment === 'MapsPy')
{
$str += '(A) Analyze datasets using ROI and ROI+ :: ';
}
}
if( (aData.Args.ProcMask & 2) === 2)
{
$str += '(B) Extract integrated spectra from analyzed files and fit the spectra to optimize fit parameters :: ';
}
if( (aData.Args.ProcMask & 4) === 4)
{
if(aData.Experiment === 'XRF-Maps')
{
$str += '(C) Analyze datasets using ROI, NNLS and per pixel fitting :: ';
}
else if (aData.Experiment === 'MapsPy')
{
$str += '(C) Analyze datasets using ROI, ROI+ and per pixel fitting :: ';
}
}
if( (aData.Args.ProcMask & 8) === 8)
{
$str += '(D) :: ';
}
if( (aData.Args.ProcMask & 16) === 16)
{
$str += '(E) Add exchange information to analyzed files :: ';
}
if( (aData.Args.ProcMask & 32) === 32)
{
$str += '(F) Create hdf5 file from single line netcdf files for flyscan :: ';
}
if( (aData.Args.ProcMask & 64) === 64)
{
$str += '(G) Generate average .h5 from each detector :: ';
}
}
else
{
$str = aData.Experiment;
}
return $str;
}
//----------------------------------------------------------------------
function convert_status_number_to_string(aData)
{
var $str = "";
if(aData.Status === 0)
{
$str = 'Waiting';
}
else if(aData.Status === 1)
{
$str = 'Processing';
}
else if(aData.Status === 2)
{
$str = 'Completed';
}
else if(aData.Status === 3)
{
$str = 'Canceling';
}
else if(aData.Status === 4)
{
$str = 'Canceled';
}
else if(aData.Status > 4)
{
$str = 'Error Occured';
}
return $str;
}
//----------------------------------------------------------------------
function find_node_id_by_hostname(hostname)
{
var $id = -1;
$node_list = $pn_table.data();
$node_list.each( function (node)
{
if (node.Hostname === hostname)
{
$id = d.Process_Node_Id;
return;
}
});
return $id;
}
//----------------------------------------------------------------------
function find_hostname_by_node_id(node_id)
{
$node_list = $pn_table.data();
var $name = "N/A";
$node_list.each( function (node)
{
if (node.Id === node_id)
{
$name = node.ComputerName;
return;
}
});
return $name;
}
//----------------------------------------------------------------------
function create_job_data_table($id, $url)
{
return $($id).DataTable(
{
//"processing": true,
//"serverSide": true,
"ajax": $url,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull )
{
var $status = convert_status_number_to_string(aData);
$('td', nRow).eq(3).html($status);
var $procmask = convert_procmask_number_to_string(aData);
$('td', nRow).eq(4).html($procmask);
var $computer = find_hostname_by_node_id(aData.Process_Node_Id);
$('td', nRow).eq(5).html($computer);
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "Id" },
{ "data": "DataPath" },
{ "data": "Status" },
{ "data": "Args.ProcMask" },
{ "data": "Process_Node_Id" },
{
"class": "delete-control",
"orderable": false,
"data": null,
"defaultContent": ""
}
],
"order": [[1, 'desc']]
});
}
//----------------------------------------------------------------------
function format_job_details ( d )
{
var $host_and_port = '';
var $host_name = '';
$node_list = $pn_table.data();
$node_list.each( function (node)
{
if (node.Id === d.Process_Node_Id)
{
$host_and_port = node.Hostname+":"+node.Port;
$host_name = node.ComputerName;
}
});
var ret_str = 'Id: '+d.Id+'<br>'+
'Version: '+d.Version+'<br>'+
'Experiment: '+d.Experiment+'<br>'+
'DataPath: '+d.DataPath+'<br>'+
'Priority: '+d.Priority+'<br>'+
'BeamLine: '+d.BeamLine+'<br>'+
'StartProcTime: '+d.StartProcTime+'<br>'+
'FinishProcTime: '+d.FinishProcTime+'<br>'+
'Dataset Files To Process: ' + d.DatasetFilesToProc +'<br>'+
'Process Node: '+$host_name+'<br>'+
'Email Addresses: '+d.Emails+'<br>'+
'IsConcurrent: ' +d.IsConcurrent+'<br>'+
'<a href=http://'+$host_and_port+'/get_job_log?log_path='+d.Log_Path+'>Job Log</a><br>';
if(d.Experiment === 'XRF-Maps' || d.Experiment === 'MapsPy')
{
ret_str += 'Processing Type: '+convert_procmask_number_to_string(d)+'<br>'+
'Detector Elements: '+d.Args.DetectorElements+'<br>'+
'Detector To Start With: '+d.Args.DetectorToStartWith+'<br>'+
'Quick and Dirty: '+d.Args.QuickAndDirty+'<br>'+
//'NNLS: '+d.Args.NNLS+'<br>'+
'Lines processed in parrallel: '+d.Args.MaxLinesToProc+'<br>'+
'Files processed in parrallel: '+d.Args.MaxFilesToProc+'<br>'+
'Live Job: '+d.Args.Is_Live_Job+'<br>'+
'<a href=/get_output_list?job_path='+d.DataPath+'>Output Directory</a> (output_old) <br>'+
'<a href=/get_output_list?job_path='+d.DataPath+'&process_type=ORIG>Output Directory</a> (output)<br>'+
'<a href=/get_output_list?job_path='+d.DataPath+'&process_type=PER_PIXEL>Output Directory</a> (output.fits) Per Pixel Fitting<br>';
}
else if(d.Experiment === 'PtychoLib')
{
ret_str += 'N/A';
}
else
{
ret_str += d.Args;
}
return ret_str;
}
//----------------------------------------------------------------------
function format_pn_details ( d )
{
return 'Id: '+d.Id+'<br>'+
'Computer Name: '+d.ComputerName+'<br>'+
'Status: '+d.Status+'<br>'+
'NumThreads: '+d.NumThreads+'<br>'+
'Hostname: '+d.Hostname+'<br>'+
'Port: '+d.Port+'<br>'+
'Heartbeat: '+d.Heartbeat + '<br>'+
'Process Cpu Percent: '+d.ProcessCpuPercent + '%<br>'+
'Process Mem Percent: '+d.ProcessMemPercent + '%<br>'+
'System Cpu Percent: '+d.SystemCpuPercent + '%<br>'+
'System Mem Percent: '+d.SystemMemPercent + '%<br>'+
'System Swap Percent: '+d.SystemSwapPercent + '%<br>' +
'Supported Software: '+d.SupportedSoftware ;
}
//----------------------------------------------------------------------
function gen_job_mask()
{
var procMask = 0;
if ($('#analysis-type-a')[0].checked === true)
{
procMask += 1;
}
if ($('#analysis-type-b')[0].checked === true)
{
procMask += 2;
}
if ($('#analysis-type-c')[0].checked === true)
{
procMask += 4;
}
/*
if ($('#analysis-type-d')[0].checked === true)
{
procMask += 8;
}
*/
if ($('#analysis-type-e')[0].checked === true)
{
procMask += 16;
}
/*
if ($('#analysis-type-f')[0].checked === true)
{
procMask += 32;
}
*/
if ($('#analysis-type-g')[0].checked === true)
{
procMask += 64;
}
return procMask;
}
//----------------------------------------------------------------------
function get_check_value(name)
{
if( $(name)[0].checked)
{
return 1;
}
return 0;
}
//----------------------------------------------------------------------
function populate_datasets_list(str_datapath_id, str_dataset_list_id)
{
$.ajax(
{
type: 'POST',
url:"/get_mda_list",
data: {'job_path': $(str_datapath_id).val()},
datatype: "json",
success: function(data)
{
//$.notify("Got dataset list", "success");
var $datasets = $.parseJSON(data);
$.notify("Got dataset list ", "success");
$(str_dataset_list_id).html("");
$datasets.mda_files.sort();
for (i = 0; i < $datasets.mda_files.length; i++)
{
var node = $datasets.mda_files[i];
node = node.replace(/\\/g, "/");
var $shortname = node.split("/");
var $total = $shortname.length;
//var $option = "<option value=\""+$datasets.mda_files[i]+"\">"+$shortname[$total-1]+"</option>";
var $option = "<option value=\""+$shortname[$total-1]+"\">"+$shortname[$total-1]+"</option>";
$(str_dataset_list_id).append($option);
}
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText,
{
autoHide: false,
clickToHide: true
});
}
});
}
function submit_new_xrf_job(is_xrf_maps_job)
{
var $procMask = gen_job_mask();
var $quickNdirty = get_check_value('#option-quick-and-dirty');
var $xrfbin = 0; // get_check_value('#option-xrf-bin');
var $xanes = is_xrf_maps_job; //0 = mapspy , 1 = xrf maps get_check_value('#option-xanes');
var $is_live_job = get_check_value('#option-is-live-job');
var $dataset_filenames = 'all';
var $pn_id = $( "#proc_node_option option:selected" ).attr('value');
if ( $("#chk_all_datasets")[0].checked === false )
{
$dataset_filenames = $('#datasets_list').val().join();
}
var $experiment = 'MapsPy';
if (is_xrf_maps_job)
$experiment = 'XRF-Maps';
if($procMask === 0)
{
$.notify("No analysis type selected! Select A, B, C, D, E, or F", "error");
return;
}
$.ajax(
{
type: 'POST',
url:"/job",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'Experiment': $experiment,
'BeamLine': '2-ID-E',
'DataPath': $("#DataPath").val(),
'Version': '9.00',
'Status': 0,
'Priority': parseInt($("#priority").val(), 10),
'StartProcTime': 0,
'FinishProcTime': 0,
'Log_Path': '',
'Emails': $("#option-emails").val(),
'Process_Node_Id': parseInt($pn_id, 10),
'DatasetFilesToProc': $dataset_filenames,
'IsConcurrent': $is_live_job,
'Args': {
'ProcMask': $procMask,
'Standards': 'maps_standardinfo.txt',
'XRF_Bin': $xrfbin,
'MaxLinesToProc': parseInt($("#option-proc-per-line").val(), 10),
'MaxFilesToProc': parseInt($("#option-proc-per-file").val(), 10),
'DetectorList': $("#option-detector-list"),
'XANES_Scan': $xanes,
'QuickAndDirty': $quickNdirty,
'Is_Live_Job': $is_live_job
}
}),
datatype: "json",
success: function(data)
{
$.notify("Queued Job: " + $("#DataPath").val(), "success");
$queued_table.ajax.reload();
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText,
{
autoHide: false,
clickToHide: true
});
}
});
}
function submit_new_pty_job()
{
var $calc_stxm = get_check_value('#pty-chk-calc-stxm');
var $alg_epie = get_check_value('#pty-chk-alg-epie');
var $alg_dm = get_check_value('#pty-chk-alg-dm');
var $det_dist = $("#pty-detector-dist").val();
var $pixel_size = $("#pty-dect-pix-size").val();
var $center_y = $("#pty-diff-center-y").val();
var $center_x = $("#pty-diff-center-x").val();
var $diff_size = $("#pty-diff-size").val();
var $rot = $( "#pty-rotate option:selected" ).attr('value');
var $probe_size = $("#pty-probe-size").val();
var $probe_modes = $("#pty-probe-modes").val();
var $threshold = $("#pty-threshold").val();
var $iter = $("#pty-iterations").val();
var $dataset_filenames = 'all';
var $gpu_id = $( "#pty-gpu-node option:selected" ).attr('value');
var $node_id = find_node_id_by_hostname('xrf1');
if ( $("#pty_chk_all_datasets")[0].checked === false )
{
$dataset_filenames = $('#pty_datasets_list').val().join();
}
$.ajax(
{
type: 'POST',
url:"/job",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'Experiment': 'PtychoLib',
'BeamLine': '2-ID-D',
'DataPath': $("#Pty-DataPath").val(),
'Version': '1.00',
'Status': 0,
'Priority': parseInt($("#pty-priority").val(), 10),
'StartProcTime': 0,
'FinishProcTime': 0,
'Log_Path': '',
'Emails': $("#pty-option-emails").val(),
'Process_Node_Id': $node_id,
'DatasetFilesToProc': $dataset_filenames,
'IsConcurrent': 1,
'Args': {
'CalcSTXM': $calc_stxm,
'AlgorithmEPIE': $alg_epie,
'AlgorithmDM': $alg_dm,
'DetectorDistance': $det_dist,
'PixelSize': $pixel_size,
'CenterY': $center_y,
'CenterX': $center_x,
'DiffractionSize': $diff_size,
'Rotation': $rot,
'GPU_ID': $gpu_id,
'ProbeSize': $probe_size,
'ProbeModes': $probe_modes,
'Threshold': $threshold,
'Iterations': $iter
}
}),
datatype: "json",
success: function(data)
{
$.notify("Queued Job: " + $("#Pty-DataPath").val(), "success");
$queued_table.ajax.reload();
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText,
{
autoHide: false,
clickToHide: true
});
}
});
}
//----------------------------------------------------------------------
//--------------------------- button clicks ----------------------------
//----------------------------------------------------------------------
$("#Btn-Submit-Job").click(function(e)
{
submit_new_xrf_job(0);
});
//----------------------------------------------------------------------
$("#Btn-Submit-Xrf-Maps-Job").click(function(e)
{
submit_new_xrf_job(1);
});
$("#Btn-Submit-Pty-Job").click(function(e)
{
submit_new_pty_job();
});
//----------------------------------------------------------------------
$('#Btn-Select-Dir').click(function(e)
{
$('.overlay').hide();
var $tree = $('#jstree').jstree(true);
var $sel = $tree.get_selected();
$('#DataPath').val( $sel[0] );
populate_datasets_list('#DataPath', '#datasets_list');
});
$('#Btn-Select-Pty-Dir').click(function(e)
{
$('.overlay').hide();
var $tree = $('#pty-jstree').jstree(true);
var $sel = $tree.get_selected();
$('#Pty-DataPath').val( $sel[0] );
populate_datasets_list('#Pty-DataPath', '#pty_datasets_list');
});
//----------------------------------------------------------------------
$("#Btn-Browse-verify").click(function(e)
{
$('.overlay').show();
$('#jstree').jstree(
{
'core':
{
'data' : function (obj, callback)
{
var me = this;
$.ajax(
{
type: 'POST',
url:"/get_dataset_dirs_list",
data: {'job_path': 'verify', 'depth': 2},
datatype: "json",
success: function(rdata)
{
callback.call(me, JSON.parse(rdata));
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText, {
autoHide: false,
clickToHide: true
});
}
});
}
},
"plugins" : [ "sort" ]
});
});
$("#Btn-Browse-production").click(function(e)
{
$('.overlay').show();
$('#jstree').jstree(
{
'core':
{
'data' : function (obj, callback)
{
var me = this;
$.ajax(
{
type: 'POST',
url:"/get_dataset_dirs_list",
data: {'job_path': 'production', 'depth': 2},
datatype: "json",
success: function(rdata)
{
callback.call(me, JSON.parse(rdata));
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText, {
autoHide: false,
clickToHide: true
});
}
});
}
},
"plugins" : [ "sort" ]
});
});
$("#Btn-Browse-production").click(function(e)
{
$('.overlay').show();
$('#jstree').jstree(
{
'core':
{
'data' : function (obj, callback)
{
var me = this;
$.ajax(
{
type: 'POST',
url:"/get_dataset_dirs_list",
data: {'job_path': 'production', 'depth': 2},
datatype: "json",
success: function(rdata)
{
callback.call(me, JSON.parse(rdata));
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText, {
autoHide: false,
clickToHide: true
});
}
});
}
},
"plugins" : [ "sort" ]
});
});
$("#Btn-Browse-micdata").click(function(e)
{
$('.overlay').show();
$('#jstree').jstree(
{
'core':
{
'data' : function (obj, callback)
{
var me = this;
$.ajax(
{
type: 'POST',
url:"/get_dataset_dirs_list",
data: {'job_path': 'micdata', 'depth': 2},
datatype: "json",
success: function(rdata)
{
callback.call(me, JSON.parse(rdata));
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText, {
autoHide: false,
clickToHide: true
});
}
});
}
},
"plugins" : [ "sort" ]
});
});
$("#Btn-Browse-Pty").click(function(e)
{
$('.overlay').show();
$('#pty-jstree').jstree(
{
'core':
{
'data' : function (obj, callback)
{
var me = this;
$.ajax(
{
type: 'POST',
url:"/get_dataset_dirs_list",
data: {'job_path': 'pty', 'depth': 1},
datatype: "json",
success: function(rdata)
{
callback.call(me, JSON.parse(rdata));
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText, {
autoHide: false,
clickToHide: true
});
}
});
}
},
"plugins" : [ "sort" ]
});
});
//----------------------------------------------------------------------
jQuery('.tabs .tab-links a').on('click', function(e)
{
var currentAttrValue = jQuery(this).attr('href');
// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
//----------------------------------------------------------------------
var $pn_table = $("#process_node_table").DataTable(
{
//"processing": true,
//"serverSide": true,
"ajax": "/process_node",
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull )
{
var $bk_color = check_heartbeat_timestamp(aData);
$('td', nRow).css('background-color', $bk_color);
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "ComputerName" },
{ "data": "Status" },
{ "data": "NumThreads" },
{ "data": "Heartbeat" },
{ "data": "SystemCpuPercent" },
{ "data": "SystemMemPercent" },
{ "data": "SystemSwapPercent" }
],
"order": [[1, 'asc']]
});
//-----------------------------------------------------------------------
$("#chk_all_datasets").change(function()
{
if(this.checked)
{
$("#datasets_list").hide();
}
else
{
$("#datasets_list").show();
}
});
$("#pty_chk_all_datasets").change(function()
{
if(this.checked)
{
$("#pty_datasets_list").hide();
}
else
{
$("#pty_datasets_list").show();
}
});
//----------------------------------------------------------------------
//--------------------------- init -------------------------------------
//----------------------------------------------------------------------
var $queued_table = create_job_data_table("#table_unprocessed_jobs", "/get_all_unprocessed_jobs");
var $processing_table = create_job_data_table("#table_processing_jobs", "/get_all_processing_jobs");
var $finished_table = create_job_data_table("#table_finished_jobs", "/get_all_finished_jobs?limit=100");
$("#priority").val(5);
$("#pty-priority").val(5);
$("#pty-rotate").val(0);
$("#chk_all_datasets").prop("checked", true);
$("#pty_chk_all_datasets").prop("checked", true);
$("#analysis-type-roi").prop("checked", true);
$("#analysis-type-svd").prop("checked", true);
$("#analysis-type-a").prop("checked", true);
$("#analysis-type-g").prop("checked", true);
$("#datasets_list").hide();
$("#pty_datasets_list").hide();
$('.overlay').hide();
var $detailPnRows = [];
var $detailJobRows = [];
var $detailPRJobRows = [];
var $detailQuJobRows = [];
$("#limit_100").checked = true;
$("#limit_100").on("click", function() { limit_finished_jobs(100); } );
$("#limit_500").on("click", function() { limit_finished_jobs(500); } );
$("#limit_1000").on("click", function() { limit_finished_jobs(1000); } );
$("#limit_All").on("click", function() { limit_finished_jobs(-1); } );
setInterval(function()
{
$queued_table.ajax.reload(null, false);
$processing_table.ajax.reload(null, false);
$pn_table.ajax.reload(null, false);
}, 4000);
setInterval(function()
{
$finished_table.ajax.reload(null, false);
}, 10000);
//----------------------------------------------------------------------
//$('#table_finished_jobs').on( 'click', 'tr td.details-control', function ()
$('.display_table').on( 'click', 'tr td.details-control', function ()
{
var tr = $(this).closest('tr');
var detail_id = 0;
var closest_table = tr.closest('table');
var row = -1;
var idx;
if (closest_table[0].id === 'process_node_table')
{
row = $pn_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailPnRows );
detail_id = 1;
}
else if(closest_table[0].id === 'table_unprocessed_jobs')
{
row = $queued_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailQuJobRows );
detail_id = 2;
}
else if(closest_table[0].id === 'table_processing_jobs')
{
row = $processing_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailPRJobRows );
detail_id = 3;
}
else if(closest_table[0].id === 'table_finished_jobs')
{
row = $finished_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailJobRows );
detail_id = 4;
}
else
return;
//var row = $finished_table.row( tr );
//var idx = $.inArray( tr.attr('id'), $detailJobRows );
if ( row.child.isShown() )
{
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
//$detailJobRows.splice( idx, 1 );
if (detail_id === 1)
$detailPnRows.splice( idx, 1 )
else if (detail_id === 2)
$detailQuJobRows.splice( idx, 1 )
else if (detail_id === 3)
$detailPRJobRows.splice( idx, 1 )
else if (detail_id === 4)
$detailJobRows.splice( idx, 1 )
}
else
{
tr.addClass( 'details' );
if (detail_id === 1)
row.child( format_pn_details( row.data() ) ).show();
else
row.child( format_job_details( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 )
{
if (detail_id === 1)
$detailPnRows.push( row );
else if (detail_id === 2)
$detailQuJobRows.push( row );
else if (detail_id === 3)
$detailPRJobRows.push( row );
else if (detail_id === 4)
$detailJobRows.push( row );
}
}
});
$('.display_table').on( 'click', 'tr td.delete-control', function ()
{
var tr = $(this).closest('tr');
var detail_id = 0;
var closest_table = tr.closest('table');
var row = -1;
var idx = -1;
if(closest_table[0].id === 'table_unprocessed_jobs')
{
row = $queued_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailQuJobRows );
detail_id = 2;
}
else if(closest_table[0].id === 'table_processing_jobs')
{
row = $processing_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailPRJobRows );
detail_id = 3;
}
else if(closest_table[0].id === 'table_finished_jobs')
{
row = $finished_table.row( tr );
idx = $.inArray( tr.attr('id'), $detailJobRows );
detail_id = 4;
}
else
return;
if (confirm("Are you sure you want to cancel this job?") == true)
{
//send
$.ajax(
{
type: 'DELETE',
url:"/job",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(row.data()),
datatype: "json",
success: function(data)
{
$.notify("Canceling Job: " + row.data().Id, "success");
},
error: function(xhr, textStatus, errorThrown)
{
$.notify(xhr.responseText,
{
autoHide: false,
clickToHide: true
});
}
});
}
});
//----------------------------------------------------------------------
$pn_table.on( 'draw', function ()
{
$.each( $detailPnRows, function ( i, row )
{
row.child( format_pn_details( row.data() ) ).show();
});
var $node_list1 = $pn_table.data();
//$node_list1.sort();
$node_list1.each( function (node)
{
if ( $("#proc_node_option option[value='"+node.Id+"']").length < 1 )
{
$('#proc_node_option').append( $("<option></option>").attr('value',node.Id).text(node.ComputerName));
}
});
});
//----------------------------------------------------------------------
$queued_table.on( 'draw', function ()
{
$.each( $detailQuJobRows, function ( i, row )
{
row.child( format_job_details( row.data() ) ).show();
});
});
//----------------------------------------------------------------------
$processing_table.on( 'draw', function ()
{
$.each( $detailPRJobRows, function ( i, row )
{
row.child( format_job_details( row.data() ) ).show();
});
});
//----------------------------------------------------------------------
$finished_table.on( 'draw', function ()
{
$.each( $detailJobRows, function ( i, row )
{
row.child( format_job_details( row.data() ) ).show();
});
});
//----------------------------------------------------------------------
});
|
/* jshint expr:true */
import { expect } from 'chai';
import {
describeModule,
it
} from 'ember-mocha';
describeModule(
'serializer:proposal',
'ProposalSerializer',
{
// Specify the other units that are required for this test.
// needs: ['serializer:foo']
},
function() {
// Replace this with your real tests.
it('exists', function() {
var serializer = this.subject();
expect(serializer).to.be.ok;
});
}
);
|
var searchData=
[
['image',['image',['../classlfgui_1_1image.html',1,'lfgui']]]
];
|
/* ____________________________________________________________________ */
/* ____________________________________________________________________ */
/* __________________________--_________________(((((((( __________ */
/* ____p________t_________--___________________))))))))) () -----)-)__ */
/* ____A_____g___h_______--___________________(((((((((( ))))) )__ */
/* ____G______h___e______--________________ )))))))))) )___ */
/* ____E_______o__________--______________ WWWWWWWWWW (____ */
/* ________o____s_________D------________ )___ */
/* ____D____f____t_______------__________ (___ */
/* ____O_________________------__________Cc )___ */
/* ____G_________________-----_________________ (_____ */
/* ________________________--- _______________ _D )_________ */
/* __ ____________________-----___________ ___ (_________ */
/* _ (____________________________________ ___ k______ */
/* __ ____j________ */
/* _______free_to_do_whatever____BUT PLEASE PRESERVE THE SEAL__________ */
/* __________________________________^______^____________^_____________ */
/* _______DOMLESS___mangoRoom.com______________________________________ */
PAGE.add("Constructors.Domless", function (options) {
var o = options = options || {}
o.getRandom = o.getRandom || function() { return String(Math.random()).replace(".","") }
o.name = o.name || "domless" + o.getRandom()
o.refreshSpeed = o.refreshSpeed = 60
o.refresh = o.refresh || false
var Legend = function() {
return {
s : undefined // CSSStyleSheet
, DOMObj : undefined // DOM ELEMENT
, rules : { /* HASH HERE ONE RULE PER TARGET */ }
, rulesCount : 0
, lastRulesCount : 0
, addStyle : function(target, text) { return this }
, getStyle : function(target) { return this }
, removeStyle : function(target) { return this }
, regenerate : function() { return this }
, style : ""
, cat : undefined
, Legend : Legend
}
}
var dog = Legend()
var cat = dog.cat = {
generateStyle : function(rules) { return this }
, options : options
, prospect : ""
}
function initiateStyleSheet(callback) {
var style = dog.DOMObj = document.createElement("style")
document.head.appendChild(style)
dog.s = document.styleSheets[document.styleSheets.length-1]
return dog
}
var addStyle = dog.addStyle = function(target, style) {
removeStyle(target).rules[target] = style
dog.rulesCount ++
return dog
}
var removeStyle = dog.removeStyle = function(target) {
if (!dog.rules[target]) return dog
delete dog.rules[target]
dog.rulesCount --
return dog
}
dog.getStyle = function(target) {
return dog.s[target]
}
function timer(func, time) {
setInterval(function() {
func()
}, time)
}
function generateHelper(rule, text) {
var style = ""
style += rule
style += text
return style
}
cat.generateStyle = function(rules) {
rules = rules || dog.rules
cat.prospect = ""
for (var rule in rules) cat.prospect += generateHelper(rule, rules[rule])
return dog
}
cat.terminateThenReplace = function (replaceCallback) {
if (cat.prospect === dog.style) return dog
dog.DOMObj.innerText = dog.style = cat.prospect
return dog
}
dog.regenerate = function() {
if (dog.rulesCount) {
cat.generateStyle().cat.terminateThenReplace()
}
return dog
}
function init() {
initiateStyleSheet()
if (o.refresh) {
timer(function() {
dog.regenerate()
}, options.refreshSpeed)
}
}
init()
return dog
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:c39d9996ad184c6c80b0b4e7e519dcc4b25e40dee1e453ff61ac687b1e942743
size 3933
|
import React from 'react';
import PropTypes from 'prop-types';
import { Card, CardActions, CardTitle, CardText } from 'material-ui/Card';
import DeleteButton from './DeleteButton';
import EditButton from './EditButton';
const buttonStyle = {
margin: '0.5em',
};
const cardStyle = {
marginTop: '1em',
marginBottom: '1em',
};
/* eslint-disable react/prefer-stateless-function */
/* eslint-disable react/jsx-boolean-value */
class CategoryCard extends React.Component {
constructor() {
super();
this.state = { edit: false, shadow: 1 };
this.onMouseOut = this.onMouseOut.bind(this);
this.onMouseOut = this.onMouseOut.bind(this);
}
onMouseOver = () => { this.setState({ shadow: 3 }); }
onMouseOut = () => { this.setState({ shadow: 1 }); }
render() {
const { item } = this.props;
return (
<Card
style={cardStyle}
zDepth={this.state.shadow}
onMouseOver={this.onMouseOver}
onFocus={this.onMouseOver}
onMouseOut={this.onMouseOut}
onBlur={this.onMouseOut}
>
<CardTitle
title={item.name}
actAsExpander={true}
showExpandableButton={true}
/>
<CardText expandable={true}>
{item.description}
</CardText>
<CardActions expandable={true}>
<EditButton style={buttonStyle} edit={this.props.edit} post={item}>
Edit
</EditButton>
<DeleteButton
style={buttonStyle}
delete={this.props.delete}
post={item}
/>
</CardActions>
</Card>
);
}
}
CategoryCard.propTypes = {
delete: PropTypes.func.isRequired,
edit: PropTypes.func.isRequired,
item: PropTypes.object.isRequired,
};
export default CategoryCard;
|
(() => {
const {_, $} = window
const taskUploadTableIds = new Promise((resolve, reject) => {
const tableIds = _.fromPairs(
KC3Database.con.tables.map(table =>
[table.name, table.schema.primKey.name]
)
)
const postData = {
raw: JSON.stringify(tableIds),
}
const jqXhr = $.post(
`http://localhost:19721/post-table-ids/${name}`,
postData,
'text'
)
jqXhr.done(resp => {
if (resp !== 'ok') {
const errMsg = `unexpected response: ${resp}`
console.error(errMsg)
return reject(errMsg)
} else {
return resolve('ok')
}
}).fail(e => {
console.error(e)
return reject(e)
})
})
const tableTasks = KC3Database.con.tables.map(async table => {
const {name} = table
const xs = await table.toArray()
const dataChunks = _.chunk(xs,2000)
const chunkTasks = dataChunks.map((chunk, ind) => new Promise((resolve, reject) => {
const postData = {
time: Number(new Date()),
raw: JSON.stringify(chunk),
}
const jqXhr = $.post(
`http://localhost:19721/post/${name}`,
postData,
'text'
)
jqXhr.done(resp => {
if (resp !== 'ok') {
const errMsg = `unexpected response: ${resp}`
console.error(errMsg)
return reject(errMsg)
} else {
return resolve('ok')
}
}).fail(e => {
console.error(e)
return reject(e)
})
}))
return Promise.all(chunkTasks)
})
Promise.all([taskUploadTableIds, ...tableTasks]).then(() =>
console.log('all done')
)
})()
|
import angular from 'angular';
import ServiceInjector from 'utils/ServiceInjector';
export default class Controller extends ServiceInjector {
constructor(...args) {
super(...args);
this.form = {
flag: '',
};
}
async doSubmitFlag() {
if (this.form.flag) {
const data = (await this.Contest.submitFlag(this.data.cc._id, this.form.flag)).data;
if (!data.success) {
this.dialogs.error(
this.$translate.instant('ui.page.ajax.postFailMsg'),
this.$translate.instant('ui.page.challenge.detail.wrongFlag'),
{ size: 'sm' }
);
return;
} else {
this.$uibModalInstance.close(data);
}
}
}
doCancel() {
this.$uibModalInstance.dismiss('Canceled');
}
}
Controller.$inject = ['$uibModalInstance', 'data', 'Contest', 'dialogs', '$translate'];
angular
.module('dummyctf.dashboard')
.controller('publicChallengeDetailController', Controller);
|
#!/usr/bin/env node
"use strict";
var child_process_1 = require('child_process');
var path_1 = require('path');
var args = [path_1.join(__dirname, '_bin.js')];
for (var i = 2; i < process.argv.length; i++) {
var arg = process.argv[i];
var flag = arg.split('=')[0];
switch (flag) {
case '-d':
args.unshift('--debug');
break;
case 'debug':
case '--debug':
case '--debug-brk':
args.unshift(arg);
break;
case '-gc':
case '--expose-gc':
args.unshift('--expose-gc');
break;
case '--gc-global':
case '--es_staging':
case '--no-deprecation':
case '--prof':
case '--log-timer-events':
case '--throw-deprecation':
case '--trace-deprecation':
case '--use_strict':
case '--allow-natives-syntax':
case '--perf-basic-prof':
args.unshift(arg);
break;
default:
if (/^--(?:harmony|trace|icu-data-dir|max-old-space-size)/.test(arg)) {
args.unshift(arg);
}
break;
}
if (/^[^-]/.test(arg)) {
break;
}
}
var proc = child_process_1.spawn(process.execPath, args.concat(process.argv.slice(2)), { stdio: 'inherit' });
proc.on('exit', function (code, signal) {
process.on('exit', function () {
if (signal) {
process.kill(process.pid, signal);
}
else {
process.exit(code);
}
});
});
//# sourceMappingURL=bin.js.map |
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import './style/index.less';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.