code stringlengths 2 1.05M |
|---|
// ******************** Imports ********************
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import ListItem from './ListItem';
import {eventAttributePropTypes} from '../Event';
// ******************** Container ********************
class EventList extends React.Component {
/**
* @param {Object} props
* @param {Array.<{label: string, description: string}>} props.events
* @param {string} props.uuid
* @returns {XML}
* @constructor
*/
constructor(props) {
super(props);
this.state = {dragEnabled : false};
}
getNode() {
// eslint-disable-next-line react/no-find-dom-node
return ReactDOM.findDOMNode(this);
}
onStop(event, {item}) {
let eventNode;
let marker;
let position;
eventNode = item.get(0);
marker = eventNode.parentElement.parentElement.id;
position = Array.prototype.slice.call(this.getNode().children).indexOf(eventNode);
$(this.getNode()).sortable('cancel');
console.log('onStop');
this.props.onEventMoved({ event : item.get(0).dataset.uuid
, marker
, position});
}
// ***** React methods *****
componentDidMount() {
let sortableConfig;
sortableConfig = { axis : 'y'
, connectWith : '.timeline-event-list'
, cursorAt : { left: 5
, top : 0}
, forcePlaceholderSize : true
, handle : 'div.reorder'
, helper : 'clone'
, placeholder : 'ui-sortable-placeholder'
// Events jQuery
, deactivate : (event, ui) => {ui.item.attr('style', ''); }
, stop : this.onStop.bind(this)};
console.log('componentDidMount');
$(this.getNode()).sortable(sortableConfig);
}
componentWillUnmount() {
$(this.getNode()).sortable('destroy');
}
// Event listeners
render() {
let events;
events = this.props.events.map(function(event) {
return <ListItem event = {event}
key = {event.uuid}
onEventChange = {this.props.onEventChange}
onEventRemove = {this.props.onEventRemove}/>;
}.bind(this));
return (<ul className="timeline-event-list">
{events}
</ul>);
}
}
const eventsPropType = PropTypes.arrayOf(PropTypes.shape(eventAttributePropTypes)).isRequired;
EventList.propTypes = { events : eventsPropType
, onEventChange : PropTypes.func.isRequired
, onEventMoved : PropTypes.func.isRequired
, onEventRemove : PropTypes.func.isRequired};
// ******************** Export ********************
export default EventList;
export {eventsPropType};
|
{
const original = obj[name];
obj[name] = function devMatcher() {
try {
original.apply(this, arguments);
} catch (e) {
global.__hadDevFailures = e.stack;
}
};
}
|
'use strict';
import {RouteConfig, AbstractPage} from 'scaffi-ui-core'; // jshint unused: false
import template from './yo-scaffi-directive.html';
// export-params-start
const ROUTE = 'app.ui.yo-scaffi.directive';
const PARAMS = {
url: '/directive',
template: template,
resolve: {
},
ncyBreadcrumb: {
label: 'Directive'
}
};
// export-params-end
//start-non-standard
@RouteConfig(ROUTE, PARAMS)
//end-non-standard
class YoScaffiDirective extends AbstractPage {
constructor($state, $scope){
super($scope);
this.$state = $state;
this.$scope = $scope;
}
getCodeSample1(){
return `
<input type="text" ng-model="vm.formItem.Name" color-me />
`
}
}
export default YoScaffiDirective;
export {ROUTE, PARAMS}; |
exports.index = function (req, res) {
res.render('index', {});
} |
/**
* Created by hebao on 2017/5/27.
* this component's main job is to change LinearGradient in animated ,
* relay on two lib:
* 1 react-native-linear-gradient // realize linear gradient Git: https://github.com/react-native-community/react-native-linear-gradient
* Git: https://github.com/react-native-community/react-native-linear-gradient
* PS: need to link naive android or iOS
* 2 chroma-js // lib to manage color, use it to realize animation
* Git: https://github.com/gka/chroma.js/
* Doc: https://gka.github.io/chroma.js/
* install: npm install chroma-js --save
*/
import React, {Component} from 'react';
import {
StyleSheet
} from 'react-native';
import PropTypes from 'prop-types';
import LinearGradient from 'react-native-linear-gradient';
import Chroma from 'chroma-js';
import shallowCompare from 'react-addons-shallow-compare';
import Util from '../utility/util';
const debugKeyWord = '[AniLinearGradient]';
export default class AniLinearGradient extends Component {
_changeColorHandle = -1;
_gradientTime = 20;//every 20ms to change one gradient color
static propTypes = {
initColors: PropTypes.array,
targetColors: PropTypes.array,
aniDuration: PropTypes.number,
gradientStyle: PropTypes.any
};
static defaultProps = {
initColors: ['#ffce4d', '#ffa931'],
targetColors: ['#5adf70', '#39cb51'],
aniDuration: 500,
gradientStyle: {}
};
constructor(props) {
super(props);
let _gradientNum = Math.ceil(props.aniDuration / this._gradientTime);
this.state = {
startColors: Chroma.scale([props.initColors[0], props.targetColors[0]]).colors(_gradientNum),
endColors: Chroma.scale([props.initColors[1], props.targetColors[1]]).colors(_gradientNum),
gradientNum: _gradientNum,
colorIndex: 0
}
}
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
componentWillUnmount() {
clearTimeout(this._changeColorHandle);
}
/**
* this component's API
* to start gradient linear animation,
* have one or two argument
* if provide one argument, it will set to be the targetColors
* if provide two arguments, it will set to be the initColors and targetColors
*/
startChange() {
let _argArrLength = arguments.length;
let {initColors} = this.props;
let {gradientNum} = this.state;
if (_argArrLength == 1) {
this.state.startColors = Chroma.scale([initColors[0], arguments[0][0]]).colors(gradientNum);
this.state.endColors = Chroma.scale([initColors[1], arguments[0][1]]).colors(gradientNum);
}
else if (_argArrLength == 2) {
this.state.startColors = Chroma.scale([arguments[0][0], arguments[1][0]]).colors(gradientNum);
this.state.endColors = Chroma.scale([arguments[0][1], arguments[1][1]]).colors(gradientNum);
}
this.startAni();
}
startAni() {
let {colorIndex} = this.state;
colorIndex++;
this.setState({
colorIndex: colorIndex
}, () => {
clearTimeout(this._changeColorHandle);
if (colorIndex < this.state.gradientNum - 1) {
this._changeColorHandle = setTimeout(() => {
this.startAni();
}, this._gradientTime);
}
else {
this.state.colorIndex = 0;
}
});
}
render() {
Util.log(debugKeyWord + 'render!!!');
let {startColors, endColors, colorIndex} = this.state;
return (
<LinearGradient
start={{x: 0.0, y: 0.0}} end={{x: 1.0, y: 1.0}}
colors={[startColors[colorIndex], endColors[colorIndex]]}
style={[Styles.linearGradient, this.props.gradientStyle]}/>
);
}
}
const Styles = StyleSheet.create({
linearGradient: {
width: 79,
height: 79,
borderRadius: 40,
position: 'absolute',
top: 0,
left: 0,
}
}); |
/**
* HTTP Server Settings
* (sails.config.http)
*
* Configuration for the underlying HTTP server in Sails.
* Only applies to HTTP requests (not WebSockets)
*
* For more information on configuration, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html
*/
module.exports.http = {
/****************************************************************************
* *
* Express middleware to use for every Sails request. To add custom *
* middleware to the mix, add a function to the middleware config object and *
* add its key to the "order" array. The $custom key is reserved for *
* backwards-compatibility with Sails v0.9.x apps that use the *
* `customMiddleware` config option. *
* *
****************************************************************************/
middleware: {
// Passport Init
passportInit : require('passport').initialize(),
passportSession : require('passport').session(),
/***************************************************************************
* *
* The order in which middleware should be run for HTTP request. (the Sails *
* router is invoked by the "router" middleware below.) *
* *
***************************************************************************/
order: [
'startRequestTimer',
'cookieParser',
'session',
/* Passport */
'passportInit',
'passportSession',
/* Passport */
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'www',
'favicon',
'404',
'500'
],
/****************************************************************************
* *
* Example custom middleware; logs each request to the console. *
* *
****************************************************************************/
// myRequestLogger: function (req, res, next) {
// console.log("Requested :: ", req.method, req.url);
// return next();
// }
/***************************************************************************
* *
* The body parser that will handle incoming multipart HTTP requests. By *
* default as of v0.10, Sails uses *
* [skipper](http://github.com/balderdashy/skipper). See *
* http://www.senchalabs.org/connect/multipart.html for other options. *
* *
* Note that Sails uses an internal instance of Skipper by default; to *
* override it and specify more options, make sure to "npm install skipper" *
* in your project first. You can also specify a different body parser or *
* a custom function with req, res and next parameters (just like any other *
* middleware function). *
* *
***************************************************************************/
// bodyParser: require('skipper')({strict: true})
},
/***************************************************************************
* *
* The number of seconds to cache flat files on disk being served by *
* Express static middleware (by default, these files are in `.tmp/public`) *
* *
* The HTTP static cache is only active in a 'production' environment, *
* since that's the only time Express will cache flat-files. *
* *
***************************************************************************/
// cache: 31557600000
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose');
var User = require('./user.server.model.js');
var chalk = require('chalk');
var async = require('async');
var ObjectId = require('mongoose').Types.ObjectId;
/**
* Create User
*/
exports.create = function(req, res) {
console.log(chalk.blue('Creation of new user requested'));
var user = new User();
var error;
//make sure username was included
if( !req.body.username ){
error = new Error('Username Required');
console.log(chalk.red.bold(error));
return complete( error, null );
} else {
user.username = req.body.username;
}
//make sure passowrd was included
if( !req.body.password ){
error = new Error('Password Required');
console.log(chalk.red.bold(error));
return complete( error, null );
} else {
user.password = req.body.password;
}
if ( req.body.name ) user.name = req.body.name;
// only an admin can modify this attribute
if (req.body.admin && ( req.decoded.admin === true ) ) {
user.admin = req.body.admin;
}
user.save(function(err, user) {
if (err && err.code === 11000) {
error = new Error('Username already exists');
console.log(chalk.red.bold(error));
return complete(error, user );
}
complete( err, user );
});
function complete( err, user ){
var msg;
if (err){
msg = 'Failed to save new user';
console.log( err.err );
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
msg = 'Creation of ' + user.name + ' Successfull!';
console.log( chalk.green( msg ) );
return res.json({ success: true, message: msg });
}
};
/**
* Show User
*/
exports.read = function(req, res) {
console.log(chalk.blue('User Requested'));
var error;
var id;
// This is shared by the '/user/:user_id' route and the
// '/me' route. If there is no :user_id we assume its
// being used by '/me'.
if (!req.params.user_id) {
if( req.decoded._id ) id = req.decoded._id;
else {
error = new Error('No paramater');
return complete(error, null);
}
}
else id = req.params.user_id;
console.log(chalk.yellow('Searching for user with id ' + id));
User.findById(id)
.populate('show_history.show media_history.media queue.show')
.exec(function(err, user) {
if (!user){
error = new Error('User with that id does not exist.');
return complete( error, null );
}
complete( err, user );
});
function complete( err, user ){
var msg;
if (err){
msg = err.message;
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
msg = 'Search was Successfull!';
console.log( chalk.green( msg ) );
return res.json( user );
}
};
/**
* Update User
*/
exports.update = function(req, res) {
console.log(chalk.blue('Update for User Requested'));
var error;
var id;
// This is shared by the '/user/:user_id' route and the
// '/me' route. If there is no :user_id we assume that
// its being used by '/me'.
if (!req.params.user_id) {
if( req.decoded._id ) id = req.decoded._id;
else {
error = new Error('No paramater');
return complete(error, null);
}
}
else id = req.params.user_id;
console.log(chalk.yellow('Searching for user with id ' + id));
User.findById(id, function(err, user) {
if (!user) {
var error = new Error('User with that id does not exist.');
return complete( error, null );
}
// login information
if ( req.body.name ) user.name = req.body.name;
if ( req.body.username ) user.username = req.body.username;
if ( req.body.password ) user.password = req.body.password;
// update what shows user has watched
if ( req.body.show_history ) user.show_history = req.body.show_history.slice();
if ( req.body.media_history ) user.media_history = req.body.media_history.slice();
// only an admin can modify this attribute
if (req.body.admin && ( req.decoded.admin === true ) ) {
user.admin = req.body.admin;
}
complete( err, user );
});
function complete( err, user ){
var msg;
if (err){
msg = err.message;
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(chalk.yellow('Saving...') );
user.save( function(err) {
if ( err && err.code === 11000 ) {
msg ='Username already exists.';
return complete( error, null );
}else if (err){
msg = 'Failed to save new User';
console.log(err.err);
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(user);
msg = 'Update of ' + user.name + ' Successfull!';
console.log( chalk.green( msg ) );
return res.json({ success: true, message: msg });
});
}
};
/**
* Delete User
*/
exports.delete = function(req, res) {
console.log(chalk.blue('Deletion of User Requested'));
var error;
if (!req.params.user_id){
error = new Error('No paramater');
return complete(error, null);
}
console.log(chalk.yellow('Searching for user with id ' + req.params.user_id ) );
User.findOne({'_id': req.params.user_id}).exec(function(err, user){
if (!user) {
error = 'No user with that name exists.';
return complete(new Error(error), null );
}
console.log(chalk.blue('Found: ' + chalk.yellow(user.username) ) );
user.remove(complete);
});
function complete( err, user ){
var msg;
if (err){
msg = err.message;
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
msg = 'Deletion of ' + req.params.user_id + ' occured without error.';
console.log(chalk.green(msg));
res.json({ success: true, message: msg });
}
};
/**
* Reset User
*/
exports.reset = function(req, res) {
console.log(chalk.blue('User reset requested'));
var error;
var id;
// Only /me can access this at the moment. Leaving this
// statment for when I figure out how I want /users to
// get to this function in the future.
if (!req.params.user_id) {
if( req.decoded._id ) id = req.decoded._id;
else {
error = new Error('No paramater');
return complete(error, null);
}
}
else id = req.params.user_id;
console.log(chalk.yellow('Searching for user with id ' + id));
User.findById(id, function(err, user) {
if (!user) {
var error = new Error('User with that id does not exist.');
return complete( error, null );
}
user.name = '';
user.queue = [];
user.show_history = [];
user.media_history = [];
user.save( function(user, err){
complete( user, err );
});
});
function complete( err, user ){
var msg;
if (err){
msg = err.message;
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(chalk.yellow('Saving...') );
user.save( function(err) {
if (err){
msg = 'Failed to save User';
console.log(err.err);
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(user);
msg = 'Reset of ' + user.name + ' was Successfull!';
console.log( chalk.green( msg ) );
return res.json({ success: true, message: msg });
});
}
};
/**
* List of Users
*/
exports.list = function(req, res) {
console.log(chalk.blue('Listing all users.'));
User.find().exec(function(err, users) {
if (err) res.send(err);
res.json(users);
});
};
/**
* Push to User
*/
exports.push = function(req, res) {
console.log(chalk.blue('Data has been pushed to a User'));
var error;
var id;
// This is shared by the '/user/:user_id' route and the
// '/me' route. If there is no :user_id we assume that
// its being used by '/me'.
if (!req.params.user_id) {
if( req.decoded._id ) id = req.decoded._id;
else {
error = new Error('No paramater');
return complete(error, null);
}
}
else id = req.params.user_id;
console.log(chalk.yellow('Searching for user with id ' + id));
User.findById(id).exec( function(err, user) {
if (!user) {
var error = new Error('User with that id does not exist.');
return complete( error, null );
}
/*** Capusle Object
* ------------------------------------------------------------------------------
* 'show_history' : [{ show, date, seq }] -Tracks what show a user watched
* 'media_history' : [{ show, date, prog }] -Tracks what media a user watched
* 'queue' : [{ show, prio }] -Shows the user plans to watch
* ------------------------------------------------------------------------------
***/
if ( req.body.show_history ) user.push_shows(req.body.show_history, error_check);
if ( req.body.media_history ) user.push_media(req.body.media_history, error_check);
if ( req.body.queue ) user.push_queue(req.body.query, error_check);
complete( err, user );
});
function error_check( err ){
if( err ){
complete(err, null);
}
}
function complete( err, user ){
var msg;
if (err){
msg = err.message;
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(chalk.yellow('Saving...') );
user.save( function(err) {
if (err){
msg = 'Failed to save new User';
console.log(err.err);
console.log( chalk.red.bold( msg ) );
return res.json({ success: false, message: msg });
}
console.log(user);
msg = 'Push to ' + user.username + ' was Successfull!';
console.log( chalk.green( msg ) );
return res.json({ success: true, message: msg });
});
}
};
|
var ajax = {
init: function(){
if (window.ActiveXObject)
return new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest)
return new XMLHttpRequest();
return false;
},
arrayToString: function (ar,prefix) {
var out="";
for (var i in ar) {
if (ar[i] instanceof Array) {
ar[i]=this.arrayToString(ar[i], prefix+"["+i+"]");
} else {
ar[i]="&"+prefix+"["+i+"]="+encodeURIComponent(ar[i]);
}
}
for (var i in ar) { out+=ar[i]; }
return out;
},
formToData: function (id) {
var id_len=id.length;
var out=new Array();
var tmp=[document.getElementsByTagName('input'),document.getElementsByTagName('select'),document.getElementsByTagName('textarea')];
for (var t in tmp) {
for (var i in tmp[t]) {
if (tmp[t][i].id) {
if ((tmp[t][i].id).substring(0,id_len)==id) {
out[(tmp[t][i].id).substring(id_len)]=tmp[t][i].value || tmp[t][i].innerHTML;
}
}
}
}
return out;
},
dataToForm: function (id,data) {
for (var i in data) {
var obj=document.getElementById(id+i);
if (obj) {
obj.value=data[i];
}
}
},
send: function(url,method,args,cookies,async,_callback){
var q=ajax.init();
q.open(method,url,async);
q.onreadystatechange=function(){
if(this.readyState==4 && this.status==200) {
_callback(this.responseText);
}
};
if (cookies) {
q.setRequestHeader('Cookie',cookies);
}
if(method=='POST') {
q.setRequestHeader('Content-type','application/x-www-form-urlencoded');
q.send(args);
} else {
q.send(null);
}
}
}
|
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var createClass = require('create-react-class');
var ActionYoutubeSearchedFor = createClass({
displayName: 'ActionYoutubeSearchedFor',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M17.01 14h-.8l-.27-.27c.98-1.14 1.57-2.61 1.57-4.23 0-3.59-2.91-6.5-6.5-6.5s-6.5 3-6.5 6.5H2l3.84 4 4.16-4H6.51C6.51 7 8.53 5 11.01 5s4.5 2.01 4.5 4.5c0 2.48-2.02 4.5-4.5 4.5-.65 0-1.26-.14-1.82-.38L7.71 15.1c.97.57 2.09.9 3.3.9 1.61 0 3.08-.59 4.22-1.57l.27.27v.79l5.01 4.99L22 19l-4.99-5z' })
);
}
});
module.exports = ActionYoutubeSearchedFor; |
'use strict';
import { Handler } from '../../src/og/webgl/Handler.js';
import { Renderer } from '../../src/og/renderer/Renderer.js';
import { SimpleNavigation } from '../../src/og/control/SimpleNavigation.js';
import { Axes } from '../../src/og/scene/Axes.js';
import { Vec3 } from '../../src/og/math/Vec3.js';
import { RenderNode } from '../../src/og/scene/RenderNode.js';
import { Entity } from '../../src/og/entity/Entity.js';
import { EntityCollection } from '../../src/og/entity/EntityCollection.js';
let handler = new Handler("frame", { 'autoActivate': true });
let renderer = new Renderer(handler, {
'backgroundColor': new Vec3(0.5, 0.5, 0.5),
'controls': [new SimpleNavigation({
name: "SimpleNav"
})],
'autoActivate': true
});
class MyScene extends RenderNode {
constructor() {
super("MyScene");
let size = Number(document.querySelector("#fontSize").value);
document.querySelector("#valSize").innerText = size;
this.ec = new EntityCollection({
'labelMaxLetters': 33,
'entities': [
new Entity({
'cartesian': new Vec3(5, 10, 0),
'label': {
'text': "PressStart2P-Regular",
'color': "black",
'face': "PressStart2P-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 20, 0),
'label': {
'text': "VastShadow-Regular",
'color': "black",
'face': "VastShadow-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 30, 0),
'label': {
'text': "Sacramento-Regular",
'color': "black",
'face': "Sacramento-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 40, 0),
'label': {
'text': "Notable-Regular",
'color': "black",
'face': "Notable-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 50, 0),
'label': {
'text': "MrDeHaviland-Regular",
'color': "black",
'face': "MrDeHaviland-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 60, 0),
'label': {
'text': "Audiowide-Regular",
'color': "black",
'face': "Audiowide-Regular",
'outlineColor': "white",
'size': size
}
}), new Entity({
'cartesian': new Vec3(5, 70, 0),
'label': {
'text': "ArchitectsDaughter-Regular",
'color': "black",
'face': "ArchitectsDaughter-Regular",
'outlineColor': "white",
'size': size
}
}),
]
});
}
init() {
document.querySelector("#fontSize").addEventListener("input", (e) => {
let entities = this.ec.getEntities();
for (let i = 0; i < entities.length; i++) {
entities[i].label.setSize(Number(e.target.value));
}
document.querySelector("#valSize").innerText = e.target.value;
});
document.querySelector("#fontOutline").addEventListener("input", (e) => {
let entities = this.ec.getEntities();
for (let i = 0; i < entities.length; i++) {
entities[i].label.setOutline(Number(e.target.value));
}
document.querySelector("#valOutline").innerText = e.target.value;
});
document.querySelector("#text").addEventListener("input", (e) => {
let entities = this.ec.getEntities();
for (let i = 0; i < entities.length; i++) {
entities[i].label.setText(e.target.value);
}
});
document.querySelector("#text").addEventListener("focus", () => {
this.renderer.controls.SimpleNav.deactivate();
});
document.querySelector("#text").addEventListener("blur", () => {
this.renderer.controls.SimpleNav.activate();
});
this.renderer.fontAtlas.loadFont("PressStart2P-Regular", "./fonts/", "PressStart2P-Regular.json");
this.renderer.fontAtlas.loadFont("VastShadow-Regular", "./fonts/", "VastShadow-Regular.json");
this.renderer.fontAtlas.loadFont("Sacramento-Regular", "./fonts/", "Sacramento-Regular.json");
this.renderer.fontAtlas.loadFont("Notable-Regular", "./fonts/", "Notable-Regular.json");
this.renderer.fontAtlas.loadFont("MrDeHaviland-Regular", "./fonts/", "MrDeHaviland-Regular.json");
this.renderer.fontAtlas.loadFont("Audiowide-Regular", "./fonts/", "Audiowide-Regular.json");
this.renderer.fontAtlas.loadFont("ArchitectsDaughter-Regular", "./fonts/", "ArchitectsDaughter-Regular.json");
this.ec.addTo(this);
this.renderer.activeCamera.eye.set(57, 36, 120);
this.renderer.activeCamera.update();
}
frame() {
}
};
let myScene = new MyScene();
renderer.addNodes([new Axes(), myScene]);
window.Vec3 = Vec3;
window.renderer = renderer;
|
var utils = require('./utils')
, implode = require('implode')
exports.State = require('./state')
exports.initialize = exports.State.init
exports.Template = require('./template')
exports.Fragment = require('./fragment')
exports.Routes = {}
var isServer = exports.isServer = utils.isServer
, isClient = exports.isClient = utils.isClient
exports.UUID = utils.UUID
exports.register = function(name, helper) {
implode.register(name, helper, [])
}
if (isClient) {
var page = require('page')
, qs = require('qs')
window.swac = {
debug: false,
State: exports.State,
navigate: function(path, opts) {
if (!opts) opts = {}
var ctx = new page.Context(path, null)
if (opts.trigger !== false) {
page.dispatch(ctx)
}
if (!ctx.unhandled) {
if (opts.replaceState === true)
ctx.save()
else if (!opts.silent)
ctx.pushState()
}
}
}
function sameOrigin(href) {
var origin = location.protocol + "//" + location.hostname + ":" + location.port
return href.indexOf('http') == -1 || href.indexOf(origin) === 0
}
document.body.addEventListener('click', function(e) {
if (e.ctrlKey || e.metaKey) return
if (e.defaultPrevented) return
// ensure link
var el = e.target
while (el && 'A' != el.nodeName) el = el.parentNode
if (!el || 'A' != el.nodeName) return
// if the `data-external` attribute is set to `true`, do not
// intercept this link
if (Boolean(el.dataset.external)) return
// ensure protocol
if (el.protocol !== 'http:' && el.protocol !== 'https:') return
// ensure non has for the same path
var href = el.getAttribute('href')
if (el.hash || !href || href == '#') return
// do not intercept x-orgin links
if (!sameOrigin(href)) return
// intercept link
e.preventDefault()
var path = el.pathname + el.search
// provide confirm functionality through `data-confirm`
if (el.dataset.confirm && !confirm(el.dataset.confirm)) return
// trigger route
var ctx = new page.Context(path, {
// whether to actually execute the route
trigger: typeof el.dataset.trigger === 'undefined' ? true : Boolean(el.dataset.trigger)
})
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
})
document.body.addEventListener('submit', function(e) {
var el = e.target
// if the `data-side` attribute is set to `server`, do not
// intercept this link
if (el.dataset.side === 'server') return
var origin = window.location.protocol + "//" + window.location.host
, method = el.method
, path = el.action
, ctx
// remove origin from path (action)
if (path.indexOf(origin) === 0) {
path = path.substr(origin.length)
}
// POST submits
if (method === 'post') {
// support method overwrite
var _method = el.querySelector('input[name=_method]')
if (_method) method = _method.value
// non GET submits are reworked to /_VERB/..
path = '/_' + method + (path === '' ? '/' : path)
// serialize form elements
var body = qs.parse(utils.serializeForm(el))
// execute route
ctx = new page.Context(path, { body: body })
page.dispatch(ctx)
}
// GET submits
else {
// serialize form elements
if (path.indexOf('?') > -1) path += '&'
else path += '?'
path += utils.serializeForm(el)
// execute route
ctx = new page.Context(path)
page.dispatch(ctx)
if (!ctx.unhandled && !Boolean(el.dataset.silent)) {
ctx.pushState()
}
}
// if no route found, send POST request to server
if (!ctx.unhandled) {
e.preventDefault()
}
})
var routing = require('./routing')
exports.init = routing.init
exports.get = routing.get
exports.post = routing.post
exports.put = routing.put
exports.delete = routing.delete
} |
"use strict";
var chai = require("chai");
var sinonChai = require("sinon-chai");
global.sinon = require("sinon");
global.expect = chai.expect;
chai.use(sinonChai);
chai.should();
|
/**
* ownCloud - myapp
*
* This file is licensed under the MIT License. See the COPYING file.
*
* @author Dennis Blommesteijn <dennis@blommesteijn.com>
* @copyright Dennis Blommesteijn 2015
*/
(function ($, OC) {
$(document).ready(function () {
$('#hello').click(function () {
alert('Hello from your script file');
});
$('#echo').click(function () {
var url = OC.generateUrl('/apps/myapp/echo');
var data = {
echo: $('#echo-content').val()
};
$.post(url, data).success(function (response) {
$('#echo-result').text(response.echo);
});
});
});
})(jQuery, OC); |
(function(){var a=!1,b=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(c){function d(){!a&&this.init&&this.init.apply(this,arguments)}var e=this.prototype;a=!0;var f=new this;a=!1;for(var g in c)f[g]=typeof c[g]=="function"&&typeof e[g]=="function"&&b.test(c[g])?function(a,b){return function(){var c=this._super;this._super=e[a];var d=b.apply(this,arguments);this._super=c;return d}}(g,c[g]):c[g];d.prototype=f,d.prototype.constructor=d,d.extend=arguments.callee,d.prototype.base=e;return d}})() |
/*
jdPicker 1.0
Requires jQuery version: >= 1.2.6
2010 - ? -- Paul Da Silva, AMJ Groupe
Copyright (c) 2007-2008 Jonathan Leighton & Torchbox Ltd
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
jdPicker = (function($) {
function jdPicker(el, opts) {
if (typeof(opts) != "object") opts = {};
$.extend(this, jdPicker.DEFAULT_OPTS, opts);
this.input = $(el);
this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "keydownHandler", "selectDate");
this.build();
this.selectDate();
this.hide();
};
jdPicker.DEFAULT_OPTS = {
month_names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
short_month_names: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
short_day_names: ["S", "M", "T", "W", "T", "F", "S"],
error_out_of_range: "Selected date is out of range",
selectable_days: [0, 1, 2, 3, 4, 5, 6],
non_selectable: [],
rec_non_selectable: [],
start_of_week: 1,
show_week: 0,
select_week: 0,
week_label: "",
date_min: "",
date_max: "",
date_format: "YYYY/mm/dd"
};
jdPicker.prototype = {
build: function() {
this.wrapp = this.input.wrap('<div class="jdpicker_w">');
if(this.input.context.type!="hidden"){
/*var clearer = $('<span class="date_clearer">×</span>');
clearer.click(this.bindToObj(function(){this.input.val(""); this.selectDate();}));
this.input.after(clearer);*/
}
switch (this.date_format){
case "dd/mm/YYYY":
this.reg = new RegExp(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
this.date_decode = "new Date(matches[3], parseInt(matches[2]-1), matches[1]);";
this.date_encode = 'this.strpad(date.getDate()) + "/" + this.strpad(date.getMonth()+1) + "/" + date.getFullYear();';
this.date_encode_s = 'this.strpad(date.getDate()) + "/" + this.strpad(date.getMonth()+1)';
break;
case "FF dd YYYY":
this.reg = new RegExp(/^([a-zA-Z]+) (\d{1,2}) (\d{4})$/);
this.date_decode = "new Date(matches[3], this.indexFor(this.month_names, matches[1]), matches[2]);";
this.date_encode = 'this.month_names[date.getMonth()] + " " + this.strpad(date.getDate()) + " " + date.getFullYear();';
this.date_encode_s = 'this.month_names[date.getMonth()] + " " + this.strpad(date.getDate());';
break;
case "dd MM YYYY":
this.reg = new RegExp(/^(\d{1,2}) ([a-zA-Z]{3}) (\d{4})$/);
this.date_decode = "new Date(matches[3], this.indexFor(this.short_month_names, matches[2]), matches[1]);";
this.date_encode = 'this.strpad(date.getDate()) + " " + this.short_month_names[date.getMonth()] + " " + date.getFullYear();';
this.date_encode_s = 'this.strpad(date.getDate()) + " " + this.short_month_names[date.getMonth()];';
break;
case "MM dd YYYY":
this.reg = new RegExp(/^([a-zA-Z]{3}) (\d{1,2}) (\d{4})$/);
this.date_decode = "new Date(matches[3], this.indexFor(this.short_month_names, matches[1]), matches[2]);";
this.date_encode = 'this.short_month_names[date.getMonth()] + " " + this.strpad(date.getDate()) + " " + date.getFullYear();';
this.date_encode_s = 'this.short_month_names[date.getMonth()] + " " + this.strpad(date.getDate());';
break;
case "dd FF YYYY":
this.reg = new RegExp(/^(\d{1,2}) ([a-zA-Z]+) (\d{4})$/);
this.date_decode = "new Date(matches[3], this.indexFor(this.month_names, matches[2]), matches[1]);";
this.date_encode = 'this.strpad(date.getDate()) + " " + this.month_names[date.getMonth()] + " " + date.getFullYear();';
this.date_encode_s = 'this.strpad(date.getDate()) + " " + this.month_names[date.getMonth()];';
break;
case "YYYY/mm/dd":
default:
this.reg = new RegExp(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);
this.date_decode = "new Date(matches[1], parseInt(matches[2]-1), matches[3]);";
this.date_encode = 'date.getFullYear() + "/" + this.strpad(date.getMonth()+1) + "/" + this.strpad(date.getDate());';
this.date_encode_s = 'this.strpad(date.getMonth()+1) + "/" + this.strpad(date.getDate());';
break;
}
if(this.date_max != "" && this.date_max.match(this.reg)){
var matches = this.date_max.match(this.reg);
this.date_max = eval(this.date_decode);
}else
this.date_max = "";
if(this.date_min != "" && this.date_min.match(this.reg)){
var matches = this.date_min.match(this.reg);
this.date_min = eval(this.date_decode);
}else
this.date_min = "";
var monthNav = $('<p class="month_nav">' +
'<span class="button prev" title="[Page-Up]">«</span>' +
' <span class="month_name"></span> ' +
'<span class="button next" title="[Page-Down]">»</span>' +
'</p>');
this.monthNameSpan = $(".month_name", monthNav);
$(".prev", monthNav).click(this.bindToObj(function() { this.moveMonthBy(-1); }));
$(".next", monthNav).click(this.bindToObj(function() { this.moveMonthBy(1); }));
this.monthNameSpan.dblclick(this.bindToObj(function(){
this.monthNameSpan.empty().append(this.getMonthSelect());
$('select', this.monthNameSpan).change(this.bindToObj(function(){
this.moveMonthBy(parseInt($('select :selected', this.monthNameSpan).val()) - this.currentMonth.getMonth());
}));
}));
var yearNav = $('<p class="year_nav">' +
'<span class="button prev" title="[Ctrl+Page-Up]">«</span>' +
' <span class="year_name" id="year_name"></span> ' +
'<span class="button next" title="[Ctrl+Page-Down]">»</span>' +
'</p>');
this.yearNameSpan = $(".year_name", yearNav);
$(".prev", yearNav).click(this.bindToObj(function() { this.moveMonthBy(-12); }));
$(".next", yearNav).click(this.bindToObj(function() { this.moveMonthBy(12); }));
this.yearNameSpan.dblclick(this.bindToObj(function(){
if($('.year_name input', this.rootLayers).length==0){
var initialDate = this.yearNameSpan.html();
var yearNameInput = $('<input type="text" class="text year_input" value="'+initialDate+'" />');
this.yearNameSpan.empty().append(yearNameInput);
$(".year_input", yearNav).keyup(this.bindToObj(function(){
if($('input',this.yearNameSpan).val().length == 4 && $('input',this.yearNameSpan).val() != initialDate && parseInt($('input',this.yearNameSpan).val()) == $('input',this.yearNameSpan).val()){
this.moveMonthBy(parseInt(parseInt(parseInt($('input',this.yearNameSpan).val()) - initialDate)*12));
}else if($('input',this.yearNameSpan).val().length>4)
$('input',this.yearNameSpan).val($('input',this.yearNameSpan).val().substr(0, 4));
}));
$('input',this.yearNameSpan).focus();
$('input',this.yearNameSpan).select();
}
}));
var error_msg = $('<div class="error_msg"></div>');
var nav = $('<div class="nav"></div>').append(error_msg, monthNav, yearNav);
var tableShell = "<table><thead><tr>";
if(this.show_week == 1) tableShell +='<th class="week_label">'+(this.week_label)+'</th>';
$(this.adjustDays(this.short_day_names)).each(function() {
tableShell += "<th>" + this + "</th>";
});
tableShell += "</tr></thead><tbody></tbody></table>";
var style = (this.input.context.type=="hidden")?' style="display:block; position:static; margin:0 auto"':'';
this.dateSelector = this.rootLayers = $('<div class="date_selector" '+style+'></div>').append(nav, tableShell).insertAfter(this.input);
if ($.browser.msie && $.browser.version < 7) {
this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
this.rootLayers = this.rootLayers.add(this.ieframe);
$(".button", nav).mouseover(function() { $(this).addClass("hover"); });
$(".button", nav).mouseout(function() { $(this).removeClass("hover"); });
};
this.tbody = $("tbody", this.dateSelector);
this.input.change(this.bindToObj(function() { this.selectDate(); }));
this.selectDate();
},
selectMonth: function(date) {
var newMonth = new Date(date.getFullYear(), date.getMonth(), date.getDate());
if(this.isNewDateAllowed(newMonth)){
if (!this.currentMonth || !(this.currentMonth.getFullYear() == newMonth.getFullYear() &&
this.currentMonth.getMonth() == newMonth.getMonth())) {
this.currentMonth = newMonth;
var rangeStart = this.rangeStart(date), rangeEnd = this.rangeEnd(date);
var numDays = this.daysBetween(rangeStart, rangeEnd);
var dayCells = "";
for (var i = 0; i <= numDays; i++) {
var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i, 12, 00);
if (this.isFirstDayOfWeek(currentDay)){
var firstDayOfWeek = currentDay;
var lastDayOfWeek = new Date(currentDay.getFullYear(), currentDay.getMonth(), currentDay.getDate()+6, 12, 00);
if(this.select_week && this.isNewDateAllowed(firstDayOfWeek))
dayCells += "<tr date='" + this.dateToString(currentDay) + "' class='selectable_week'>";
else
dayCells += "<tr>";
if(this.show_week==1)
dayCells += '<td class="week_num">'+this.getWeekNum(currentDay)+'</td>';
}
if ((this.select_week == 0 && currentDay.getMonth() == date.getMonth() && this.isNewDateAllowed(currentDay) && !this.isHoliday(currentDay)) || (this.select_week==1 && currentDay.getMonth() == date.getMonth() && this.isNewDateAllowed(firstDayOfWeek))) {
dayCells += '<td class="selectable_day" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>';
} else {
dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>';
};
if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>";
};
this.tbody.empty().append(dayCells);
this.monthNameSpan.empty().append(this.monthName(date));
this.yearNameSpan.empty().append(this.currentMonth.getFullYear());
if(this.select_week == 0){
$(".selectable_day", this.tbody).click(this.bindToObj(function(event) {
this.changeInput($(event.target).attr("date"));
}));
}else{
$(".selectable_week", this.tbody).click(this.bindToObj(function(event) {
this.changeInput($(event.target.parentNode).attr("date"));
}));
}
$("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today");
if(this.select_week == 1){
$("tr", this.tbody).mouseover(function() { $(this).addClass("hover"); });
$("tr", this.tbody).mouseout(function() { $(this).removeClass("hover"); });
}else{
$("td.selectable_day", this.tbody).mouseover(function() { $(this).addClass("hover"); });
$("td.selectable_day", this.tbody).mouseout(function() { $(this).removeClass("hover"); });
}
};
$('.selected', this.tbody).removeClass("selected");
$('td[date=' + this.selectedDateString + '], tr[date=' + this.selectedDateString + ']', this.tbody).addClass("selected");
}else
this.show_error(this.error_out_of_range);
},
selectDate: function(date) {
if (typeof(date) == "undefined") {
date = this.stringToDate(this.input.val());
};
if (!date) date = new Date();
if(this.select_week == 1 && !this.isFirstDayOfWeek(date))
date = new Date(date.getFullYear(), date.getMonth(), (date.getDate() - date.getDay() + this.start_of_week), 12, 00);
if(this.isNewDateAllowed(date)){
this.selectedDate = date;
this.selectedDateString = this.dateToString(this.selectedDate);
this.selectMonth(this.selectedDate);
}else if((this.date_min) && this.daysBetween(this.date_min, date)<0){
this.selectedDate = this.date_min;
this.selectMonth(this.date_min);
this.input.val(" ");
}else{
this.selectMonth(this.date_max);
this.input.val(" ");
}
},
isNewDateAllowed: function(date){
return ((!this.date_min) || this.daysBetween(this.date_min, date)>=0) && ((!this.date_max) || this.daysBetween(date, this.date_max)>=0);
},
isHoliday: function(date){
return ((this.indexFor(this.selectable_days, date.getDay())===false || this.indexFor(this.non_selectable, this.dateToString(date))!==false) || this.indexFor(this.rec_non_selectable, this.dateToShortString(date))!==false);
},
changeInput: function(dateString) {
this.input.val(dateString).change();
if(this.input.context.type!="hidden")
this.hide();
},
show: function() {
$('.error_msg', this.rootLayers).css('display', 'none');
this.rootLayers.slideDown();
$([window, document.body]).click(this.hideIfClickOutside);
this.input.unbind("focus", this.show);
this.input.attr('readonly', true);
$(document.body).keydown(this.keydownHandler);
this.setPosition();
},
hide: function() {
if(this.input.context.type!="hidden"){
this.input.removeAttr('readonly');
this.rootLayers.slideUp();
$([window, document.body]).unbind("click", this.hideIfClickOutside);
this.input.focus(this.show);
$(document.body).unbind("keydown", this.keydownHandler);
}
},
hideIfClickOutside: function(event) {
if (event.target != this.input[0] && !this.insideSelector(event)) {
this.hide();
};
},
insideSelector: function(event) {
var offset = this.dateSelector.position();
offset.right = offset.left + this.dateSelector.outerWidth();
offset.bottom = offset.top + this.dateSelector.outerHeight();
return event.pageY < offset.bottom &&
event.pageY > offset.top &&
event.pageX < offset.right &&
event.pageX > offset.left;
},
keydownHandler: function(event) {
switch (event.keyCode)
{
case 9:
case 27:
this.hide();
return;
break;
case 13:
if(this.isNewDateAllowed(this.stringToDate(this.selectedDateString)) && !this.isHoliday(this.stringToDate(this.selectedDateString)))
this.changeInput(this.selectedDateString);
break;
case 33:
this.moveDateMonthBy(event.ctrlKey ? -12 : -1);
break;
case 34:
this.moveDateMonthBy(event.ctrlKey ? 12 : 1);
break;
case 38:
this.moveDateBy(-7);
break;
case 40:
this.moveDateBy(7);
break;
case 37:
if(this.select_week == 0) this.moveDateBy(-1);
break;
case 39:
if(this.select_week == 0) this.moveDateBy(1);
break;
default:
return;
}
event.preventDefault();
},
stringToDate: function(string) {
var matches;
if (matches = string.match(this.reg)) {
if(matches[3]==0 && matches[2]==0 && matches[1]==0)
return null;
else
return eval(this.date_decode);
} else {
return null;
};
},
dateToString: function(date) {
return eval(this.date_encode);
},
dateToShortString: function(date){
return eval(this.date_encode_s);
},
setPosition: function() {
var offset = this.input.offset();
this.rootLayers.css({
top: offset.top + this.input.outerHeight(),
left: offset.left
});
if (this.ieframe) {
this.ieframe.css({
width: this.dateSelector.outerWidth(),
height: this.dateSelector.outerHeight()
});
};
},
moveDateBy: function(amount) {
var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth(), this.selectedDate.getDate() + amount);
this.selectDate(newDate);
},
moveDateMonthBy: function(amount) {
var newDate = new Date(this.selectedDate.getFullYear(), this.selectedDate.getMonth() + amount, this.selectedDate.getDate());
if (newDate.getMonth() == this.selectedDate.getMonth() + amount + 1) {
newDate.setDate(0);
};
this.selectDate(newDate);
},
moveMonthBy: function(amount) {
if(amount<0)
var newMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + amount+1, -1);
else
var newMonth = new Date(this.currentMonth.getFullYear(), this.currentMonth.getMonth() + amount, 1);
this.selectMonth(newMonth);
},
monthName: function(date) {
return this.month_names[date.getMonth()];
},
getMonthSelect:function(){
var month_select = '<select>';
for(var i = 0; i<this.month_names.length; i++){
if(i==this.currentMonth.getMonth())
month_select += '<option value="'+(i)+'" selected="selected">'+this.month_names[i]+'</option>';
else
month_select += '<option value="'+(i)+'">'+this.month_names[i]+'</option>';
}
month_select += '</select>';
return month_select;
},
bindToObj: function(fn) {
var self = this;
return function() { return fn.apply(self, arguments) };
},
bindMethodsToObj: function() {
for (var i = 0; i < arguments.length; i++) {
this[arguments[i]] = this.bindToObj(this[arguments[i]]);
};
},
indexFor: function(array, value) {
for (var i = 0; i < array.length; i++) {
if (value == array[i]) return i;
};
return false;
},
monthNum: function(month_name) {
return this.indexFor(this.month_names, month_name);
},
shortMonthNum: function(month_name) {
return this.indexFor(this.short_month_names, month_name);
},
shortDayNum: function(day_name) {
return this.indexFor(this.short_day_names, day_name);
},
daysBetween: function(start, end) {
start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
return (end - start) / 86400000;
},
changeDayTo: function(dayOfWeek, date, direction) {
var difference = direction * (Math.abs(date.getDay() - dayOfWeek - (direction * 7)) % 7);
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference);
},
rangeStart: function(date) {
return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1);
},
rangeEnd: function(date) {
return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1);
},
isFirstDayOfWeek: function(date) {
return date.getDay() == this.start_of_week;
},
getWeekNum:function(date){
date_week= new Date(date.getFullYear(), date.getMonth(), date.getDate()+6);
var firstDayOfYear = new Date(date_week.getFullYear(), 0, 1, 12, 00);
var n = parseInt(this.daysBetween(firstDayOfYear, date_week)) + 1;
return Math.floor((date_week.getDay() + n + 5)/7) - Math.floor(date_week.getDay() / 5);
},
isLastDayOfWeek: function(date) {
return date.getDay() == (this.start_of_week - 1) % 7;
},
show_error: function(error){
$('.error_msg', this.rootLayers).html(error);
$('.error_msg', this.rootLayers).slideDown(400, function(){
setTimeout("$('.error_msg', this.rootLayers).slideUp(200);", 2000);
});
},
adjustDays: function(days) {
var newDays = [];
for (var i = 0; i < days.length; i++) {
newDays[i] = days[(i + this.start_of_week) % 7];
};
return newDays;
},
strpad: function(num){
if(parseInt(num)<10) return "0"+parseInt(num);
else return parseInt(num);
}
};
$.fn.jdPicker = function(opts) {
return this.each(function() { new jdPicker(this, opts); });
};
$.jdPicker = { initialize: function(opts) {
$("input.jdpicker").jdPicker(opts);
} };
return jdPicker;
})(jQuery);
$($.jdPicker.initialize);
|
(function ($) {
$(document).ready(function (event) {
var $page = $('#PageFrontIndex')
, previousPages = []
, $sample = $page.find('.PageFrontIndex-sample')
, $sampleContainer = $sample.find('.PageFrontIndex-sample-wrapper-content')
, $sampleBackButton = $sample.find('.PageFrontIndex-sample-backButton');
if (!$page) {
return;
}
var loadContent = function (url) {
$.get(url, function (data) {
$sampleContainer.html(data.html);
$sampleContainer.find('a').click(function (event) {
event.preventDefault();
previousPages.push(url);
if (previousPages.length) {
$sampleBackButton.removeClass('is-disabled');
}
loadContent($(this).attr('href'));
});
});
};
$sampleBackButton.addClass('is-disabled');
loadContent('/sample/');
$sampleBackButton.click(function (event) {
event.preventDefault();
if (!previousPages.length) {
return;
}
var url = previousPages.pop();
loadContent(url);
if (!previousPages.length) {
$sampleBackButton.addClass('is-disabled');
}
});
});
})(jQuery);
|
// Using jquery solution
// (function(){
// app.el['input_city'] = $('input[bs-typeahead="listCity"]');
// app.el['input_city'].typeahead({
// source: function(query, process) {
// var objects = [], data = [{"id":1, "city":"London"},{"id":2, "city":"Madrid"},{"id":3, "city":"Paris"}]
// $.each(data, function(i, object) {
// app.mapped[object.city] = object;
// objects.push(object.city);
// });
// process(objects);
// },
// updater: function(item) {
// // $("ul.typeahead.dropdown-menu:visible").siblings("input[type='hidden']").val(app.mapped[item].id);
// this.$element.siblings('input[type="hidden"]').val(app.mapped[item].id);
// return item;
// }
// });
// })(); |
import { Component } from './component';
// input switch on native, input checkbox on web
class Switch extends Component {
tag(instance) {
let iSwitch;
if (instance) {
iSwitch = instance;
} else {
iSwitch = document.createElement('input');
iSwitch.type = 'checkbox';
}
return iSwitch;
}
}
export { Switch };
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'no', {
button: 'Maler',
emptyListMsg: '(Ingen maler definert)',
insertOption: 'Erstatt gjeldende innhold',
options: 'Alternativer for mal',
selectPromptMsg: 'Velg malen du vil åpne i redigeringsverktøyet:',
title: 'Innholdsmaler'
} );
|
import angular from 'angular';
import 'angular-mocks';
import {TodoItem} from './TodoItem';
describe('TodoItem component', () => {
beforeEach(() => {
angular
.module('todoItem', ['app/components/TodoItem.html'])
.component('todoItem', TodoItem);
angular.mock.module('todoItem');
});
it('should render correctly', angular.mock.inject(($rootScope, $compile) => {
const $scope = $rootScope.$new();
const element = $compile('<todo-item></todo-item>')($scope);
$scope.$digest();
const li = element.find('li');
expect(li).not.toBeNull();
}));
it('should call set editing to true', angular.mock.inject($componentController => {
const component = $componentController('todoItem', {}, {});
spyOn(component, 'handleDoubleClick').and.callThrough();
component.handleDoubleClick();
expect(component.handleDoubleClick).toHaveBeenCalled();
expect(component.editing).toEqual(true);
}));
it('should call onSave', angular.mock.inject($componentController => {
const bindings = {
todo: {
text: 'Use ngrx/store',
completed: false,
id: 0
},
onSave: () => {}
};
const component = $componentController('todoItem', {}, bindings);
spyOn(component, 'onSave').and.callThrough();
component.handleSave('Hello');
expect(component.onSave).toHaveBeenCalledWith({
todo: {text: 'Hello', id: 0}
});
}));
});
|
/**
* @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.enterMode = CKEDITOR.ENTER_BR; // CKEDITOR.ENTER_P
config.extraPlugins = 'sourcedialog,codemirror';
config.toolbarGroups = [
{ name: 'document', groups: ['mode', 'document'] },
{ name: 'editing', groups: ['find', 'selection'] },
{ name: 'clipboard', groups: ['clipboard', 'undo'] },
'/',
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
{ name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'] },
{ name: 'links', groups: ['links'] },
{ name: 'insert', groups: ['insert'] },
'/',
{ name: 'styles', groups: ['styles'] },
{ name: 'colors', groups: ['colors'] },
{ name: 'tools', groups: ['tools'] },
{ name: 'others', groups: ['others'] },
{ name: 'about', groups: ['about'] }
];
config.removeButtons = 'Sourcedialog,Save,Templates,NewPage,Print,Flash,Smiley,SpecialChar,Iframe';
};
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.ActionListItem.
sap.ui.define(['jquery.sap.global', './ListItemBase', './library', 'sap/ui/core/EnabledPropagator'],
function(jQuery, ListItemBase, library, EnabledPropagator) {
"use strict";
/**
* Constructor for a new ActionListItem.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* The <code>sap.m.ActionListItem</code> can be used like a <code>button</code> to fire actions when pressed.
* <b>Note:</b> The inherited <code>selected</code> property of the <code>sap.m.ListItemBase</code> is not supported.
* @extends sap.m.ListItemBase
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @alias sap.m.ActionListItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ActionListItem = ListItemBase.extend("sap.m.ActionListItem", /** @lends sap.m.ActionListItem.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* Defines the text that appears in the control.
*/
text : {type : "string", group : "Misc", defaultValue : null}
}
}});
/**
* Initializes member variables which are needed later on.
*
* @private
*/
ActionListItem.prototype.init = function() {
this.setType(sap.m.ListType.Active);
ListItemBase.prototype.init.apply(this, arguments);
};
/**
* Determines item specific mode
*
* ActionListItems are not selectable because they are command controls (like Button or Link) so triggering the associated command, rather than selection is
* appropriate to happen upon user action on these items. By overwriting isSelectable (inherited from ListItemBase) we exclude the item from processing
* specific to selectable list-items.
*
* @protected
* @overwrite
*/
ActionListItem.prototype.getMode = function() {
return sap.m.ListMode.None;
};
/**
* Event handler called when the space key is pressed.
*
* ActionListItems are command controls so keydown [SPACE] should have the same effect as keydown [ENTER] (i.e. triggering the associated command, instead of
* selection)
*
* @param {jQuery.Event} oEvent
* @private
*/
ActionListItem.prototype.onsapspace = ActionListItem.prototype.onsapenter;
return ActionListItem;
}, /* bExport= */ true);
|
import Application from '../../app';
import config from '../../config/environment';
import { merge } from '@ember/polyfills';
import { run } from '@ember/runloop';
import registerAcceptanceTestHelpers from './201-created/register-acceptance-test-helpers';
export default function startApp(attrs) {
let attributes = merge({}, config.APP);
attributes.autoboot = true;
attributes = merge(attributes, attrs); // use defaults, but you can override;
return run(() => {
let application = Application.create(attributes);
const assert = attributes.assert || window.QUnit.assert;
registerAcceptanceTestHelpers(assert);
application.setupForTesting();
application.injectTestHelpers();
return application;
});
}
|
'use strict';
var mongoose = require('mongoose');
function AccountManager(options) {
this.core = options.core;
}
AccountManager.prototype.create = function(provider, options, cb) {
var User = mongoose.model('User');
var user = new User({ provider: provider });
Object.keys(options).forEach(function(key) {
user.set(key, options[key]);
});
user.save(cb);
};
AccountManager.prototype.update = function(id, options, cb) {
var User = mongoose.model('User');
var usernameChange = false;
User.findById(id, function (err, user) {
if (err) {
return cb(err);
}
if (options.firstName) {
user.firstName = options.firstName;
}
if (options.lastName) {
user.lastName = options.lastName;
}
if (options.displayName) {
user.displayName = options.displayName;
}
if (options.position) {
user.position = options.position;
}
if (options.email) {
user.email = options.email;
}
if (options.username && options.username !== user.username) {
var xmppConns = this.core.presence.connections.query({
userId: user._id,
type: 'xmpp'
});
if (xmppConns.length) {
return cb(null, null, 'You can not change your username ' +
'with active XMPP sessions.');
}
usernameChange = true;
user.username = options.username;
}
if (user.local) {
if (options.password || options.newPassword) {
user.password = options.password || options.newPassword;
}
}
user.save(function(err, user) {
if (err) {
return cb(err);
}
this.core.emit('account:update', {
usernameChanged: usernameChange,
user: user.toJSON()
});
if (cb) {
cb(null, user);
}
}.bind(this));
}.bind(this));
};
AccountManager.prototype.generateToken = function(id, cb) {
var User = mongoose.model('User');
User.findById(id, function (err, user) {
if (err) {
return cb(err);
}
user.generateToken(function(err, token) {
if (err) {
return cb(err);
}
user.save(function(err) {
if (err) {
return cb(err);
}
cb(null, token);
});
});
});
};
AccountManager.prototype.revokeToken = function(id, cb) {
var User = mongoose.model('User');
User.update({_id: id}, {$unset: {token: 1}}, cb);
};
module.exports = AccountManager;
|
var colors = [
"#000000",
"#FFFF00",
"#1CE6FF",
"#FF34FF",
"#FF4A46",
"#008941",
"#006FA6",
"#A30059",
"#FFDBE5",
"#7A4900",
"#0000A6",
"#63FFAC",
"#B79762",
"#004D43",
"#8FB0FF",
"#997D87",
"#5A0007",
"#809693",
"#FEFFE6",
"#1B4400",
"#4FC601",
"#3B5DFF",
"#4A3B53",
"#FF2F80",
"#61615A",
"#BA0900",
"#6B7900",
"#00C2A0",
"#FFAA92",
"#FF90C9",
"#B903AA",
"#D16100",
"#DDEFFF",
"#000035",
"#7B4F4B",
"#A1C299",
"#300018",
"#0AA6D8",
"#013349",
"#00846F",
"#372101",
"#FFB500",
"#C2FFED",
"#A079BF",
"#CC0744",
"#C0B9B2",
"#C2FF99",
"#001E09",
"#00489C",
"#6F0062",
"#0CBD66",
"#EEC3FF",
"#456D75",
"#B77B68",
"#7A87A1",
"#788D66",
"#885578",
"#FAD09F",
"#FF8A9A",
"#D157A0",
"#BEC459",
"#456648",
"#0086ED",
"#886F4C",
"#34362D",
"#B4A8BD",
"#00A6AA",
"#452C2C",
"#636375",
"#A3C8C9",
"#FF913F",
"#938A81",
"#575329",
"#00FECF",
"#B05B6F",
"#8CD0FF",
"#3B9700",
"#04F757",
"#C8A1A1",
"#1E6E00",
"#7900D7",
"#A77500",
"#6367A9",
"#A05837",
"#6B002C",
"#772600",
"#D790FF",
"#9B9700",
"#549E79",
"#FFF69F",
"#201625",
"#72418F",
"#BC23FF",
"#99ADC0",
"#3A2465",
"#922329",
"#5B4534",
"#FDE8DC",
"#404E55",
"#0089A3",
"#CB7E98",
"#A4E804",
"#324E72",
"#6A3A4C",
"#83AB58",
"#001C1E",
"#D1F7CE",
"#004B28",
"#C8D0F6",
"#A3A489",
"#806C66",
"#222800",
"#BF5650",
"#E83000",
"#66796D",
"#DA007C",
"#FF1A59",
"#8ADBB4",
"#1E0200",
"#5B4E51",
"#C895C5",
"#320033",
"#FF6832",
"#66E1D3",
"#CFCDAC",
"#D0AC94",
"#7ED379",
"#012C58",
"#7A7BFF",
"#D68E01",
"#353339",
"#78AFA1",
"#FEB2C6",
"#75797C",
"#837393",
"#943A4D",
"#B5F4FF",
"#D2DCD5",
"#9556BD",
"#6A714A",
"#001325",
"#02525F",
"#0AA3F7",
"#E98176",
"#DBD5DD",
"#5EBCD1",
"#3D4F44",
"#7E6405",
"#02684E",
"#962B75",
"#8D8546",
"#9695C5",
"#E773CE",
"#D86A78",
"#3E89BE",
"#CA834E",
"#518A87",
"#5B113C",
"#55813B",
"#E704C4",
"#00005F",
"#A97399",
"#4B8160",
"#59738A",
"#FF5DA7",
"#F7C9BF",
"#643127",
"#513A01",
"#6B94AA",
"#51A058",
"#A45B02",
"#1D1702",
"#E20027",
"#E7AB63",
"#4C6001",
"#9C6966",
"#64547B",
"#97979E",
"#006A66",
"#391406",
"#F4D749",
"#0045D2",
"#006C31",
"#DDB6D0",
"#7C6571",
"#9FB2A4",
"#00D891",
"#15A08A",
"#BC65E9",
"#FFFFFE",
"#C6DC99",
"#203B3C",
"#671190",
"#6B3A64",
"#F5E1FF",
"#FFA0F2",
"#CCAA35",
"#374527",
"#8BB400",
"#797868",
"#C6005A",
"#3B000A",
"#C86240",
"#29607C",
"#402334",
"#7D5A44",
"#CCB87C",
"#B88183",
"#AA5199",
"#B5D6C3",
"#A38469",
"#9F94F0",
"#A74571",
"#B894A6",
"#71BB8C",
"#00B433",
"#789EC9",
"#6D80BA",
"#953F00",
"#5EFF03",
"#E4FFFC",
"#1BE177",
"#BCB1E5",
"#76912F",
"#003109",
"#0060CD",
"#D20096",
"#895563",
"#29201D",
"#5B3213",
"#A76F42",
"#89412E",
"#1A3A2A",
"#494B5A",
"#A88C85",
"#F4ABAA",
"#A3F3AB",
"#00C6C8",
"#EA8B66",
"#958A9F",
"#BDC9D2",
"#9FA064",
"#BE4700",
"#658188",
"#83A485",
"#453C23",
"#47675D",
"#3A3F00",
"#061203",
"#DFFB71",
"#868E7E",
"#98D058",
"#6C8F7D",
"#D7BFC2",
"#3C3E6E",
"#D83D66",
"#2F5D9B",
"#6C5E46",
"#D25B88",
"#5B656C",
"#00B57F",
"#545C46",
"#866097",
"#365D25",
"#252F99",
"#00CCFF",
"#674E60",
"#FC009C",
"#92896B" ]
//This is an array of maxmimally distinct colours for colouring our different dictionaries.
//It was published here: http://godsnotwheregodsnot.blogspot.co.uk/2013/11/kmeans-color-quantization-seeding.html
// Thanks to Tatarize
|
define([
'marionette',
'router',
'view/appLayout'
], function (Marionette, appRouter, appLayout)
{
"use strict";
var app = new Marionette.Application();
// This will store the application title
app.title = 'Sample-App';
// This will store the application url
app.url = '/';
// This will store the user information
app.user = null;
// Add the main region
app.addRegions({
root: '#approot'
});
// Catch account updates
app.vent.on('account:updated', function (account)
{
app.user = account;
app.vent.trigger('account:updated:success');
});
// Launch routers and application main view
app.addInitializer(function(options)
{
// Add this app to default options for all objects
options.app = app;
// Store the title
app.title = options.title;
// Store the url
app.url = options.url;
// Initialize the layout
this.layout = new appLayout(options);
// Initialize the main router
this.router = new appRouter(options);
});
// Get session and launch page
app.vent.on('app:start', function(options)
{
// Start the session
this.router.startSession();
// Load the application view
this.root.show(this.layout);
// Get request from html
var fragment = $('#app').attr('data-fragment');
// What to load next ?
if (fragment && fragment.length > 0)
this.router.loadFragment(fragment);
else
this.router.loadPage('welcome');
}, app);
return app;
});
|
import {injectReducer} from '../../store/reducers';
export default (store) => ({
path : 'login',
/* Async getComponent is only invoked when route matches */
getComponent (nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const Login = require('./containers/LoginContainer').default;
const reducer = require('./modules/login').default;
/* Add the reducer to the store on key 'login' */
injectReducer(store, {key: 'login', reducer});
/* Return getComponent */
cb(null, Login);
/* Webpack named bundle */
}, 'login');
}
});
|
var singlePage = angular
.module('single-page', [])
.component('singlePageComp', singleComponent())
.config(function($stateProvider) {
$stateProvider
.state('single', {
url: '/single',
template: '<single-page-comp></single-page-comp>'
}
);
})
.name;
|
import assert from './assert';
import Vertex from './vertex';
/**
* 2D scattering algorithms.
* @type {Object}
*/
const algorithms = {
/**
* Uniform-random scattering algorithm.
* @param {Integer} width - the width of the scattering area
* @param {Integer} height - the height of the scattering area
* @param {Integer} size - the number of vertices to scatter
*/
random(width, height, size) {
var vertices = [],
grid = [],
x, y;
for (var i = 0; i < size; i += 1) {
// Generate a random position until one that isn't already occupied is found
do {
x = Math.floor(Math.random() * width);
y = Math.floor(Math.random() * height);
} while (grid[x] && grid[x][y]);
// Create a new Vertex at the position that was found
vertices.push(new Vertex(x, y));
// Mark the position as occupied
grid[x] = grid[x] || [];
grid[x][y] = true;
}
return vertices;
}
};
/**
* Generate a scatter of vertices.
* @param {String} alg - the scattering algorithm to use
* @param {Integer} width - the width of the scattering area
* @param {Integer} height - the height of the scattering area
* @param {Integer} count - the number of vertices to scatter
* @param {Object} options (optional)
* @return {Array} - the scattered vertices
*/
function generate(alg, width, height, count, options) {
assert.isNonEmptyString(alg);
assert.isIntegerGt0(width);
assert.isIntegerGt0(height);
assert.isIntegerGt0(count);
// Check that the algorithm is implemented
if (!algorithms[alg]) {
throw new Error(`algorithm not implemented: ${alg}`);
}
// Ensure that the area is big enough to accomodate the amount of vertices
if (width * height < count) {
throw new Error(`too many points to scatter: ${count}`);
}
return algorithms[alg](width, height, count, options);
}
export default { generate };
|
module.exports = function(io) {
var sockets = io.sockets;
sockets.on('connection', function (client) {
console.log("sockets[chat] client.handshake",client.handshake);
client.on('send-server', function (data) {
var msg = "<b>"+data.nome+":</b> "+data.msg+"<br>";
client.emit('send-client', msg);
client.broadcast.emit('send-client', msg);
});
});
} |
var time;
var delayTime;
$(function(){
// 增加浮动DIV
$('body').append("<div id='notice'><div class='notice_header'><span class='notice_title'> </span><span class='glyphicon glyphicon-remove cbtn'></span></div><div class='notice_content'></div></div>");
// 更改样式
$('#notice').css({right:"0",bottom:"0",cursor:"default",position:"fixed","z-index":"999","background-color": "#ffffff",border:"1px #F2F2FB solid",margin:"2px","line-height":"25px",display:"none",width:"300px",height:"200px"});
$('#notice .notice_header').css({width:"300px",height:"40px","background-color": "#f5f5f5","line-height":"40px"});
$('#notice .cbtn').css({cursor:"pointer",right:"10px",float:"right",position:"relative",top:"10px"});
$('#notice .notice_content').css({margin:"3px","font-weight":"normal","line-height":"20px","margin-bottom":"10px",height:"135px"});
/* 绑定事件*/
$('#notice').hover(
function(){
$(this).stop(true,true).slideDown();
clearTimeout(time);
},
function(){
time = setTimeout('_notice()',delayTime);
}
);
//绑定关闭事件
$('.cbtn').bind('click',function(){
$('#notice').slideUp('fast');
clearTimeout(time);
});
});
$.extend({
lay:function(_width,_height){
$('#notice').css({width:_width,height:_height});
},
show:function(_title,_msg,_time){
delayTime = _time;
$('.notice_title').html(_title);
$('.notice_content').html(_msg);
$('#notice').slideDown(2000);
time = setTimeout('_notice()',delayTime);
}
});
function _notice(){
$('#notice').slideUp(2000);
} |
const Benchmark = require("benchmark");
const {
test,
match,
sort: fuzzySort,
filter: fuzzyFilter,
} = require("../build/cjs");
process.stdout.write("Setting up benmarks...");
let cities = require("./cities.json");
cities = cities.map((city, i) => ({ id: i, ...city }));
console.log(" Done.");
const benchmarkUnoptimizedSort = new Benchmark("unoptimized sort", () => {
cities.sort(fuzzySort("ah", { sourceAccessor: (city) => city.city }));
});
const benchmarkOptimizedSort = new Benchmark("optimized sort", () => {
cities.sort(
fuzzySort("ah", {
sourceAccessor: (city) => city.city,
idAccessor: (city) => city.id,
})
);
});
const benchmarkFilter = new Benchmark("filter", () => {
cities.filter(fuzzyFilter("ah", { sourceAccessor: (city) => city.city }));
});
const benchmarkMatch = new Benchmark("match", () => {
match("av", cities[0].city, { withRanges: true, withScore: true });
});
const benchmarkTest = new Benchmark("test", () => {
test("av", cities[0].city);
});
process.stdout.write(`Running unoptimized sort on ${cities.length} objects...`);
benchmarkUnoptimizedSort.run();
console.log(" Done.");
process.stdout.write(`Running optimized sort on ${cities.length} objects...`);
benchmarkOptimizedSort.run();
console.log(" Done.");
process.stdout.write(`Running filter on ${cities.length} objects...`);
benchmarkFilter.run();
console.log(" Done.");
process.stdout.write(`Running match...`);
benchmarkMatch.run();
console.log(" Done.");
process.stdout.write(`Running test...`);
benchmarkTest.run();
console.log(" Done.");
console.log("");
console.log("Results:");
console.log(benchmarkUnoptimizedSort.toString());
console.log(benchmarkOptimizedSort.toString());
console.log(benchmarkFilter.toString());
console.log(benchmarkMatch.toString());
console.log(benchmarkTest.toString());
|
/*eslint-disable import/default*/
import environment from '../environments/environment'; |
/*******************************************************************************
* Name: QuizziPedia::Back-End::Config::Passport;
* Description: classe che permette la registrazione all'applicazione.
* Creation data: 27-04-2016;
* Author: Franco Berton.
********************************************************************************
* Updates history
* -------------------------------------------------------------------------------
* Update data: 13-06-2016;
* Description: Corretto vari bugs;
* Author: Matteo Granzotto.
*-------------------------------------------------------------------------------
* ID: Config_20160427;
* Update data: 27-04-2016;
* Description: Creata classe e inserite procedure necessarie all'avvio del
* server;
* Autore: Franco Berton.
*-------------------------------------------------------------------------------
* * ID: Config_20160427;
* Update data: 01-05-2016;
* Description: Creati i metodi: exports(), use();
* Autore: Franco Berton.
*-------------------------------------------------------------------------------
*******************************************************************************/
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../App/Model/UserModel');
var Topic = require('../App/Model/TopicModel');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose username is the same as the forms username
// we are checking to see if the user trying to login already exists
User.findOne({$or: [{'username' : username}, {'email' : req.body.email}]}, function(err, user) {
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
if (user.username == username && user.email == req.body.email)
return done(null, false, {code:4,title:'Errore Registrazione',message: 'Username e Email già presente'});
else {
if (user.email === req.body.email)
return done(null, false, {code:3, title:'Errore Registrazione', message: 'Email già presente'})
else
return done(null, false, {code:2, title:'Errore Registrazione', message: 'Username già presente'})
}
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.password = newUser.generateHash(password)
newUser.username = username;
newUser.email = req.body.email;
newUser.surname = req.body.surname;
newUser.name = req.body.name;
newUser.privilege = 'normal';
Topic.find({},function(err,topics){
if(err)
throw err;
topics.forEach(function(topic){
newUser.statistics.push({
topicName: topic.name
});
});
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser,{code:1, title:'Registrazione', message: 'Registrazione avvenuta con successo'});
});
});
}
});
});
}));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signin', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
var UsernameOrEmail = (username.indexOf('@') === -1) ? {'username': username} : {'email': username};
User.findOne( UsernameOrEmail , function(err, user) {
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
})
}));
};
|
"use strict";
(function (Filter) {
Filter[Filter["all"] = 9000] = "all";
Filter[Filter["audio"] = 1000] = "audio";
Filter[Filter["lossless"] = 1101] = "lossless";
Filter[Filter["mp3"] = 1102] = "mp3";
Filter[Filter["video"] = 2000] = "video";
Filter[Filter["tv"] = 2101] = "tv";
Filter[Filter["dvdrip"] = 2102] = "dvdrip";
Filter[Filter["hdrip"] = 2103] = "hdrip";
Filter[Filter["dvd"] = 2104] = "dvd";
Filter[Filter["lq"] = 2105] = "lq";
Filter[Filter["ebooks"] = 3000] = "ebooks";
Filter[Filter["comics"] = 3101] = "comics";
Filter[Filter["magazines"] = 3102] = "magazines";
Filter[Filter["tutorials"] = 3103] = "tutorials";
Filter[Filter["audiobook"] = 3104] = "audiobook";
Filter[Filter["images"] = 4000] = "images";
Filter[Filter["mobile"] = 5000] = "mobile";
Filter[Filter["games"] = 6000] = "games";
Filter[Filter["pc"] = 6101] = "pc";
Filter[Filter["nintendo"] = 6102] = "nintendo";
Filter[Filter["playstation"] = 6103] = "playstation";
Filter[Filter["xbox"] = 6104] = "xbox";
Filter[Filter["applications"] = 7000] = "applications";
Filter[Filter["adult"] = 8000] = "adult";
})(exports.Filter || (exports.Filter = {}));
var Filter = exports.Filter;
var FilterCategory = (function () {
function FilterCategory(filter, checked) {
this.filter = filter;
this.checked = checked;
}
return FilterCategory;
}());
exports.FilterCategory = FilterCategory;
//# sourceMappingURL=filters.js.map |
(function() {
var FuzzySet = function(arr, useLevenshtein, gramSizeLower, gramSizeUpper) {
var fuzzyset = {
};
// default options
arr = arr || [];
fuzzyset.gramSizeLower = gramSizeLower || 2;
fuzzyset.gramSizeUpper = gramSizeUpper || 3;
fuzzyset.useLevenshtein = (typeof useLevenshtein !== 'boolean') ? true : useLevenshtein;
// define all the object functions and attributes
fuzzyset.exactSet = {};
fuzzyset.matchDict = {};
fuzzyset.items = {};
// helper functions
var levenshtein = function(str1, str2) {
var current = [], prev, value;
for (var i = 0; i <= str2.length; i++)
for (var j = 0; j <= str1.length; j++) {
if (i && j)
if (str1.charAt(j - 1) === str2.charAt(i - 1))
value = prev;
else
value = Math.min(current[j], current[j - 1], prev) + 1;
else
value = i + j;
prev = current[j];
current[j] = value;
}
return current.pop();
};
// return an edit distance from 0 to 1
var _distance = function(str1, str2) {
if (str1 === null && str2 === null) throw 'Trying to compare two null values';
if (str1 === null || str2 === null) return 0;
str1 = String(str1); str2 = String(str2);
var distance = levenshtein(str1, str2);
if (str1.length > str2.length) {
return 1 - distance / str1.length;
} else {
return 1 - distance / str2.length;
}
};
var _nonWordRe = /[^a-zA-Z0-9\u00C0-\u00FF, ]+/g;
var _iterateGrams = function(value, gramSize) {
gramSize = gramSize || 2;
var simplified = '-' + value.toLowerCase().replace(_nonWordRe, '') + '-',
lenDiff = gramSize - simplified.length,
results = [];
if (lenDiff > 0) {
for (var i = 0; i < lenDiff; ++i) {
value += '-';
}
}
for (var i = 0; i < simplified.length - gramSize + 1; ++i) {
results.push(simplified.slice(i, i + gramSize));
}
return results;
};
var _gramCounter = function(value, gramSize) {
// return an object where key=gram, value=number of occurrences
gramSize = gramSize || 2;
var result = {},
grams = _iterateGrams(value, gramSize),
i = 0;
for (i; i < grams.length; ++i) {
if (grams[i] in result) {
result[grams[i]] += 1;
} else {
result[grams[i]] = 1;
}
}
return result;
};
// the main functions
fuzzyset.get = function(value, defaultValue, minMatchScore) {
// check for value in set, returning defaultValue or null if none found
if (minMatchScore === undefined) {
minMatchScore = .33
}
var result = this._get(value, minMatchScore);
if (!result && typeof defaultValue !== 'undefined') {
return defaultValue;
}
return result;
};
fuzzyset._get = function(value, minMatchScore) {
var normalizedValue = this._normalizeStr(value),
result = this.exactSet[normalizedValue];
if (result) {
return [[1, result]];
}
var results = [];
// start with high gram size and if there are no results, go to lower gram sizes
for (var gramSize = this.gramSizeUpper; gramSize >= this.gramSizeLower; --gramSize) {
results = this.__get(value, gramSize, minMatchScore);
if (results && results.length > 0) {
return results;
}
}
return null;
};
fuzzyset.__get = function(value, gramSize, minMatchScore) {
var normalizedValue = this._normalizeStr(value),
matches = {},
gramCounts = _gramCounter(normalizedValue, gramSize),
items = this.items[gramSize],
sumOfSquareGramCounts = 0,
gram,
gramCount,
i,
index,
otherGramCount;
for (gram in gramCounts) {
gramCount = gramCounts[gram];
sumOfSquareGramCounts += Math.pow(gramCount, 2);
if (gram in this.matchDict) {
for (i = 0; i < this.matchDict[gram].length; ++i) {
index = this.matchDict[gram][i][0];
otherGramCount = this.matchDict[gram][i][1];
if (index in matches) {
matches[index] += gramCount * otherGramCount;
} else {
matches[index] = gramCount * otherGramCount;
}
}
}
}
function isEmptyObject(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
if (isEmptyObject(matches)) {
return null;
}
var vectorNormal = Math.sqrt(sumOfSquareGramCounts),
results = [],
matchScore;
// build a results list of [score, str]
for (var matchIndex in matches) {
matchScore = matches[matchIndex];
results.push([matchScore / (vectorNormal * items[matchIndex][0]), items[matchIndex][1]]);
}
var sortDescending = function(a, b) {
if (a[0] < b[0]) {
return 1;
} else if (a[0] > b[0]) {
return -1;
} else {
return 0;
}
};
results.sort(sortDescending);
if (this.useLevenshtein) {
var newResults = [],
endIndex = Math.min(50, results.length);
// truncate somewhat arbitrarily to 50
for (var i = 0; i < endIndex; ++i) {
newResults.push([_distance(results[i][1], normalizedValue), results[i][1]]);
}
results = newResults;
results.sort(sortDescending);
}
var newResults = [];
results.forEach(function(scoreWordPair) {
if (scoreWordPair[0] >= minMatchScore) {
newResults.push([scoreWordPair[0], this.exactSet[scoreWordPair[1]]]);
}
}.bind(this))
return newResults;
};
fuzzyset.add = function(value) {
var normalizedValue = this._normalizeStr(value);
if (normalizedValue in this.exactSet) {
return false;
}
var i = this.gramSizeLower;
for (i; i < this.gramSizeUpper + 1; ++i) {
this._add(value, i);
}
};
fuzzyset._add = function(value, gramSize) {
var normalizedValue = this._normalizeStr(value),
items = this.items[gramSize] || [],
index = items.length;
items.push(0);
var gramCounts = _gramCounter(normalizedValue, gramSize),
sumOfSquareGramCounts = 0,
gram, gramCount;
for (gram in gramCounts) {
gramCount = gramCounts[gram];
sumOfSquareGramCounts += Math.pow(gramCount, 2);
if (gram in this.matchDict) {
this.matchDict[gram].push([index, gramCount]);
} else {
this.matchDict[gram] = [[index, gramCount]];
}
}
var vectorNormal = Math.sqrt(sumOfSquareGramCounts);
items[index] = [vectorNormal, normalizedValue];
this.items[gramSize] = items;
this.exactSet[normalizedValue] = value;
};
fuzzyset._normalizeStr = function(str) {
if (Object.prototype.toString.call(str) !== '[object String]') throw 'Must use a string as argument to FuzzySet functions';
return str.toLowerCase();
};
// return length of items in set
fuzzyset.length = function() {
var count = 0,
prop;
for (prop in this.exactSet) {
if (this.exactSet.hasOwnProperty(prop)) {
count += 1;
}
}
return count;
};
// return is set is empty
fuzzyset.isEmpty = function() {
for (var prop in this.exactSet) {
if (this.exactSet.hasOwnProperty(prop)) {
return false;
}
}
return true;
};
// return list of values loaded into set
fuzzyset.values = function() {
var values = [],
prop;
for (prop in this.exactSet) {
if (this.exactSet.hasOwnProperty(prop)) {
values.push(this.exactSet[prop]);
}
}
return values;
};
// initialization
var i = fuzzyset.gramSizeLower;
for (i; i < fuzzyset.gramSizeUpper + 1; ++i) {
fuzzyset.items[i] = [];
}
// add all the items to the set
for (i = 0; i < arr.length; ++i) {
fuzzyset.add(arr[i]);
}
return fuzzyset;
};
var root = this;
// Export the fuzzyset object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = FuzzySet;
root.FuzzySet = FuzzySet;
} else {
root.FuzzySet = FuzzySet;
}
})(); |
export class Empty {}
|
define("p3/widget/viewer/SpecialtyVFGeneList", [
"dojo/_base/declare", "./TabViewerBase", "dojo/on", "dojo/topic",
"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
"../PageGrid", "../formatter", "../SpecialtyVFGeneGridContainer", "../../util/PathJoin", "dojo/request", "dojo/_base/lang"
], function(declare, TabViewerBase, on, Topic,
domClass, ContentPane, domConstruct,
Grid, formatter, SpecialtyVFGeneGridContainer,
PathJoin, xhr, lang){
return declare([TabViewerBase], {
"baseClass": "SpecialtyVFGeneList",
"disabled": false,
"containerType": "spgene_ref_data",
"query": null,
defaultTab: "specialtyVFGenes",
perspectiveLabel: "Specialty Gene List View",
perspectiveIconClass: "icon-selection-FeatureList",
totalFeatures: 0,
warningContent: 'Your query returned too many results for detailed analysis.',
_setQueryAttr: function(query){
// console.log(this.id, " _setQueryAttr: ", query, this);
// if (!query) { console.log("GENOME LIST SKIP EMPTY QUERY: "); return; }
// console.log("SetQuery: ", query, this);
this._set("query", query);
// console.log("query: ", query);
if(!this._started){
return;
}
var _self = this;
// console.log('spGeneList setQuery - this.query: ', this.query);
//var url = PathJoin(this.apiServiceUrl, "sp_gene_ref", "?" + "eq(source,%22PATRIC_VF%22)" + "&limit(1)"); //&facet((field,genome_id),(limit,35000))");
var url = PathJoin(this.apiServiceUrl, "sp_gene_ref", "?" + this.query + "&limit(1)"); //&facet((field,genome_id),(limit,35000))");
// console.log("url: ", url);
xhr.get(url, {
headers: {
accept: "application/solr+json",
'X-Requested-With': null,
'Authorization': (window.App.authorizationToken || "")
},
handleAs: "json"
}).then(function(res){
if(res && res.response && res.response.docs){
var features = res.response.docs;
// console.log("res.response: ", res.response);
if(features){
_self._set("totalFeatures", res.response.numFound);
}
}else{
console.warn("Invalid Response for: ", url);
}
}, function(err){
console.error("Error Retreiving Specialty Genes: ", err);
});
},
onSetState: function(attr, oldVal, state){
// console.log(" onSetState() OLD: ", oldVal, " NEW: ", state);
this.inherited(arguments);
this.set("query", state.search);
this.setActivePanelState();
},
onSetQuery: function(attr, oldVal, newVal){
this.queryNode.innerHTML = decodeURIComponent(newVal);
},
setActivePanelState: function(){
var active = (this.state && this.state.hashParams && this.state.hashParams.view_tab) ? this.state.hashParams.view_tab : "specialtyVFGenes";
// console.log("Active: ", active, "state: ", this.state);
var activeTab = this[active];
if(!activeTab){
console.log("ACTIVE TAB NOT FOUND: ", active);
return;
}
switch(active){
case "specialtyVFGenes":
activeTab.set("state", this.state);
// console.log("state: ", this.state);
break;
}
// console.log("Set Active State COMPLETE");
},
/*
onSetSpecialtyGeneIds: function(attr, oldVal, genome_ids){
// console.log("onSetGenomeIds: ", genome_ids, this.feature_ids, this.state.feature_ids);
this.state.feature_ids = feature_ids;
this.setActivePanelState();
},
*/
postCreate: function(){
this.inherited(arguments);
this.watch("query", lang.hitch(this, "onSetQuery"));
this.watch("totalFeatures", lang.hitch(this, "onSetTotalSpecialtyGenes"));
this.specialtyVFGenes = new SpecialtyVFGeneGridContainer({
title: "Specialty Genes",
id: this.viewer.id + "_" + "specialtyVFGenes",
disabled: false,
});
this.viewer.addChild(this.specialtyVFGenes);
},
onSetTotalSpecialtyGenes: function(attr, oldVal, newVal){
// console.log("ON SET TOTAL GENOMES: ", newVal);
this.totalCountNode.innerHTML = " ( " + newVal + " PATRIC_VF Genes ) ";
},
hideWarning: function(){
if(this.warningPanel){
this.removeChild(this.warningPanel);
}
},
showWarning: function(msg){
if(!this.warningPanel){
this.warningPanel = new ContentPane({
style: "margin:0px; padding: 0px;margin-top: -10px;",
content: '<div class="WarningBanner">' + this.warningContent + "</div>",
region: "top",
layoutPriority: 3
});
}
this.addChild(this.warningPanel);
},
onSetAnchor: function(evt){
// console.log("onSetAnchor: ", evt, evt.filter);
evt.stopPropagation();
evt.preventDefault();
var parts = [];
if(this.query){
var q = (this.query.charAt(0) == "?") ? this.query.substr(1) : this.query;
if(q != "keyword(*)"){
parts.push(q);
}
}
if(evt.filter){
parts.push(evt.filter);
}
// console.log("parts: ", parts);
if(parts.length > 1){
q = "?and(" + parts.join(",") + ")";
}else if(parts.length == 1){
q = "?" + parts[0];
}else{
q = "";
}
// console.log("SetAnchor to: ", q);
var hp;
if(this.hashParams && this.hashParams.view_tab){
hp = {view_tab: this.hashParams.view_tab};
}else{
hp = {};
}
l = window.location.pathname + q + "#" + Object.keys(hp).map(function(key){
return key + "=" + hp[key];
}, this).join("&");
// console.log("NavigateTo: ", l);
Topic.publish("/navigate", {href: l});
}
});
});
|
/*
借书作为主页
*/
import * as types from '../constant/actionTypes';
const initState = {
catalogList: [],
isLoading: true,
};
export default function MainReducer(state = initState, action) {
switch (action.type) {
case types.LOAD_CATALOG_LIST:
return Object.assign({}, state, {
isLoading: action.isLoading,
});
case types.GET_CATALOG_LIST:
return Object.assign({}, state, {
isLoading: false,
catalogList: action.catalogList,
});
default:
return state;
}
}
|
import 'react-native'
import React from 'react'
import Index from '../index.android.js'
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer'
it('renders correctly', () => {
const tree = renderer.create(
<Index />
)
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Eye Schema
*/
var EyeSchema = new Schema({
cylinder: {
type: Number
},
sphere: {
type: Number
},
axis: {
type: Number
},
position: {
type: String
}
});
/**
* Prescription Schema
*/
var PrescriptionSchema = new Schema({
eyes: [EyeSchema],
number:{
type: Number
},
frame:{
type: String,
default: ''
},
lens:{
type: String,
default: ''
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Prescription', PrescriptionSchema); |
import React from "react";
import { GithubCorner } from "../../lib";
export default () => (
<div style={{ height: "100px"}}>
<GithubCorner size="60" left octoColor="#EB529A" />
</div>);
|
import React, { PropTypes } from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
import Divider from 'material-ui/Divider';
export default class MyDrawer extends React.Component {
constructor(props) {
super(props);
}
onToggleDrawer() {
return () => {
this.toggleDrawer();
};
}
toggleDrawer() {
this.props.toggleDrawer();
}
render() {
const { isDrawerOpen } = this.props;
return (
<div>
<Drawer open={isDrawerOpen}>
<MenuItem>Sign In</MenuItem>
<MenuItem>Feedback</MenuItem>
<Divider />
<MenuItem onTouchTap={this.onToggleDrawer()}>Close Menu</MenuItem>
</Drawer>
</div>
)
}
}
MyDrawer.propTypes = {
isDrawerOpen: PropTypes.bool.isRequired,
toggleDrawer: PropTypes.func.isRequired
}; |
import generatedConfigA from '../fixtures/generatedConfig'
import generateActionType from 'lib/generators/generateActionType'
describe('(Lib) generateActionCreator', () => {
it('should create an action type', () => {
const actionType = generateActionType(generatedConfigA.auth.mystring)
expect(actionType).to.be.eql('@@dollar/AUTH_SET_MYSTRING')
})
})
|
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
gulp.task('scripts', function() {
return gulp.src('public/js/scripts.js')
.pipe(plumber(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
})))
.pipe(uglify({
preserveComments: 'license'
}))
.pipe(rename({extname: '.min.js'}))
.pipe(gulp.dest('public/js'));
});
gulp.task('styles', function() {
return gulp.src('scss/styles.scss')
.pipe(plumber(plumber({
errorHandler: function (err) {
console.log(err);
this.emit('end');
}
})))
.pipe(sass({outputStyle: 'compressed'}))
.pipe(autoprefixer())
.pipe(gulp.dest('public/css'));
});
gulp.task('watch', ['scripts', 'styles'], function() {
gulp.watch('public/js/*.js', ['scripts']);
gulp.watch('scss/*.scss', ['styles']);
});
|
const hub = require('../../')
// const test = require('tape')
hub({
port: 6060,
monkeyballs: 'yoyoyo'
})
|
import stringify from 'json-stringify-safe'
import validator from 'validator'
const OBJLENGTH = 10
const ARRLENGTH = 10
const STRINGLIMIT = 1000
const STRINGTRUNCATE = 200
let sanitizeString = function (str) {
if (!str) {
return ''
}
return String(str)
.replace(/\./g, '_')
.replace(/\s/g, '')
.toLowerCase()
}
/**
* formats capability object into sanitized string for e.g.filenames
* @param {Object} caps Selenium capabilities
*/
let caps = function (caps) {
let result
/**
* mobile caps
*/
if (caps.deviceName) {
result = [sanitizeString(caps.deviceName), sanitizeString(caps.platformName), sanitizeString(caps.platformVersion), sanitizeString(caps.app)]
} else {
result = [sanitizeString(caps.browserName), sanitizeString(caps.version), sanitizeString(caps.platform)]
}
result = result.filter(n => n !== undefined && n !== '')
return result.join('.')
}
/**
* formats arguments into string
* @param {Array} args arguments object
*/
let args = function (args) {
return args.map((arg) => {
if (typeof arg === 'function' || (typeof arg === 'string' && arg.indexOf('return (function') === 0)) {
return '<Function>'
} else if (typeof arg === 'string') {
return '"' + arg + '"'
} else if (Array.isArray(arg)) {
return arg.join(', ')
}
return arg
}).join(', ')
}
let css = function (value) {
if (!value) {
return value
}
return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase()
}
/**
* Limit the length of an arbitrary variable of any type, suitable for being logged or displayed
* @param {Any} val Any variable
* @return {Any} Limited var of same type
*/
let limit = function (val) {
if (!val) return val
// Ensure we're working with a copy
val = JSON.parse(stringify(val))
switch (Object.prototype.toString.call(val)) {
case '[object String]':
if (val.length > 100 && validator.isBase64(val)) {
return '[base64] ' + val.length + ' bytes'
}
if (val.length > STRINGLIMIT) {
return val.substr(0, STRINGTRUNCATE) + ' ... (' + (val.length - STRINGTRUNCATE) + ' more bytes)'
}
return val
case '[object Array]':
const length = val.length
if (length > ARRLENGTH) {
val = val.slice(0, ARRLENGTH)
val.push('(' + (length - ARRLENGTH) + ' more items)')
}
return val.map(limit)
case '[object Object]':
const keys = Object.keys(val)
const removed = []
for (let i = 0, l = keys.length; i < l; i++) {
if (i < OBJLENGTH) {
val[keys[i]] = limit(val[keys[i]])
} else {
delete val[keys[i]]
removed.push(keys[i])
}
}
if (removed.length) {
val._ = (keys.length - OBJLENGTH) + ' more keys: ' + JSON.stringify(removed)
}
return val
}
return val
}
export default {
css,
args,
caps,
limit
}
|
var is_connected=false;
var user_email_name=[];
var user_data={};
var user_fiends_data={};
var user_picture={};
public_profile='id ,name ,first_name ,last_name ,age_range ,link ,gender ,locale ,picture, timezone ,updated_time ,verified,email';
function fb_signin(){
FB.login(function(response){
if (response.status === 'connected') {
get_user_info();
get_user_picture();
user_data['picture']=user_picture;
create_redirect_user();
}
else if (response.status === 'not_authorized') {}
else {}
}, {scope: 'email,user_friends'});
};
function fb_login(){
FB.login(function(response){
if (response.status === 'connected') {
get_user_email_name();
check_redirect_user();
}
else if (response.status === 'not_authorized') {}
else {}
}, {scope: 'email'});
};
function create_redirect_user(){
url='/create_redirect_user';
$.ajax({
url: url,
method: "POST",
headers: {'X-CSRFToken': get_csrf()},
data:{data:JSON.stringify(user_data)},
dataType: "json",
success: function (data) {
if (data['redirect']){
redirect_me(data['data']['url']);
}
else{
alert(data['message']);
}
}
});
};
function check_redirect_user(){
url='/check_redirect_user';
$.ajax({
url: url,
method: "POST",
headers: {'X-CSRFToken': get_csrf()},
data:{data:JSON.stringify(user_email_name)},
dataType: "json",
success: function (data) {
if (data['redirect']){
redirect_me(data['data']['url']);
}
else{
alert(data['message']);
}
}
});
};
function get_csrf(){
return ($('.csrf').val());
};
function get_user_email_name(){
FB.api('/me','get' ,{fields:'email,first_name,last_name'}, function(response) {
if (response['email']==undefined){
user_email_name={type:'name',first_name:response['first_name'] ,last_name:response['last_name']};
}
else{
user_email_name={type:'email',email:response['email']};
}
});
};
function get_user_info(){
FB.api('/me', 'get', {fields: public_profile }, function(response) {
user_data=response;
});
};
function get_user_freinds(){
FB.api('/me/friends', 'get', function(response) {
user_fiends_data=response;
});
};
function get_user_picture(){
FB.api('/me/picture?height=600', 'get', function(response) {
user_picture=response;
});
};
function redirect_me(url){
window.location.replace(url);
};
$(document).ready(
function() {
window.fbAsyncInit = function() {
//SDK loaded, initialize it
FB.init({
appId : '685715351578146',
xfbml : true,
cookie : true,
version : 'v2.8'});
//check user session and refresh it
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//user is authorized
get_user_email_name();
} else {
//user is not authorized
}
});
};
});
//load the JavaScript SDK
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.com/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
|
/*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*
* Modified by @4lbertoC
*/
module.exports = {
GITHUB: {
LOAD_REPO_LANGUAGES: 'LOAD_REPO_LANGUAGES',
LOAD_REPO_LIST: 'LOAD_REPO_LIST',
LOAD_USER_INFO: 'LOAD_USER_INFO',
ERROR: 'ERROR'
},
NAVIGATION: {
// Route action types
SET_CURRENT_ROUTE: 'SET_CURRENT_ROUTE',
// Page action types
SET_CURRENT_PAGE: 'SET_CURRENT_PAGE'
}
};
|
/**
* @author jerry
*/
(function(win,$){
/**
* param {object} require and todo param
* param.imageUrl {string} images
* param.width {NUmber} image width
* param.style {string} image height value:max | min
* param.height {Number} image height
* param.zoom {bool} if images size than param.width latter,is or not reset size
*/
var init=function(param,fn){
var defalts={};
$.extend(defalts,{
zoom:true
},param)
todo(defalts,fn);
};
var todo=function(p,cb){
getJs('../src/js/preOnloadImgSize.js','preOnloadImgSize',function(loadimg){
loadimg(p.imageUrl,function(){
var newWH;
if(p.style=='max'){
newWH=setWH(p,this);
}else if(p.style=='min'){
newWH=setMinWH(p,this);
}
cb&&cb(newWH,p.imageUrl);
});
})
},
getJs=function(url,method,fn){
if(win[method]){
fn&&fn(win[method]);
}else{
$.getScript(url,function(){
fn&&fn(win[method]);
});
}
},
setWH=function(p,img){
var iw=img.width,ih=img.height;
var nw,nh;
if(iw<=p.width && ih <= p.height){
return [iw,ih];
}
var ratio=iw/ih;
if(iw>=ih){
if(iw>=p.width){
nw=p.width;
nh=nw/ratio;
}else if(ih>=p.height){
nh=p.height;
nw=ratio*nh;
}
}else{
if(ih>=p.height){
nh=p.height;
nw=ratio*nh;
}else if(iw>=p.width){
nw=p.width;
nh=nw/ratio
}
}
return [nw,nh];
},
setMinWH=function(p,img){
var iw=img.width,ih=img.height;
var nw,nh;
var ratio=p.width/p.height;
var lratio=iw/ih;
if(!p.zoom){
if(iw<=p.width && ih <= p.height){
return [iw,ih];
}
}
if(ratio>lratio){
nw=p.width;
nh=nw/lratio;
}else{
nh=p.height;
nw=lratio*nh
}
return [nw,nh];
};
win.resetImgSize = init;
}(window,$)); |
import React, {Component, PropTypes} from 'react';
import ReactEcharts from 'echarts-for-react';
import 'echarts-liquidfill';
// 用于统计当日金额的组件
class LiquidBall extends Component {
constructor(props) {
super(props);
}
// 初次渲染后执行此方法
componentDidMount() {
setTimeout(() => {
this.refs.liquidBall.getEchartsInstance().resize();
}, 0);
}
render() {
return (
<ReactEcharts ref='liquidBall'
option={this.getOption()}
style={{height: '100%', width: '100%'}}/>
);
}
getOption() {
let {name, value, unit, borderColor, rippleColor = []} = this.props;
var option = {
series: [{
type: 'liquidFill',
name: name,
radius: '90%',
backgroundStyle: {
color: '#0e1e37'
},
data: [{
name: value + unit,
value: 0.8,
itemStyle: {
normal: {
color: rippleColor[0]
}
}
}, {
// name: value + unit,
value: 0.7,
itemStyle: {
normal: {
color: rippleColor[1]
}
}
}],
itemStyle: {
normal: {
shadowBlur: 0
}
},
outline: {
borderDistance: 0,
itemStyle: {
borderWidth: 3,
borderColor: borderColor || '#6176a5',
shadowBlur: 2
}
},
label: {
normal: {
formatter: function (param) {
return param.seriesName + '\n' + '\n'
+ param.name + '\n';
// let str =[
// '<p>'+param.seriesName+'</p>',
// '<p>'+param.name+'</span>',
// ];
//
// return str;
},
// color: 'red',
// insideColor: 'yellow',
textStyle: {
fontSize: 16,
align: 'center',
baseline: 'middle',
fontWeight: 300
},
position: ['50%', '65%']
}
}
}]
};
return option;
}
}
export default LiquidBall; |
import Vorpal from 'vorpal';
import { magenta } from 'chalk';
import Debug from './src/debug';
import { bot, user } from './src/config';
import download from './src/download/vorpal';
import convert from './src/convert/vorpal';
// eslint-disable-next-line
const debug = new Debug('index');
const vorpal = new Vorpal();
debug('Heritage-bot initialized');
/* istanbul ignore next */
vorpal
.log(`${bot}${magenta('Hi! How can I help?')}`)
.delimiter(user)
.use(download)
.use(convert)
.show();
/* istanbul ignore next */
vorpal.parse(process.argv);
export { vorpal as default };
|
chrome.webNavigation.onCommitted.addListener(function(e) {
console.log("You are on Lou's List!");
$("body").append("YoYoYo");
}, { url: [{ hostSuffix: "rabi.phys.virginia.edu" }, { pathPrefix: "/mySIS/CS2/" } ] });
|
'use strict';
const service = require('feathers-mongoose');
const contact = require('./contact-model');
const hooks = require('./hooks');
module.exports = function() {
const app = this;
const options = {
Model: contact,
paginate: {
default: 5,
max: 25
}
};
// Initialize our service with any options it requires
app.use('/contacts', service(options));
// Get our initialize service to that we can bind hooks
const contactService = app.service('/contacts');
// Set up our before hooks
contactService.before(hooks.before);
// Set up our after hooks
contactService.after(hooks.after);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:3ca07b55618bf6f8c5046894e3f285497a9d9a8c50d7b44f8407f1057850c884
size 2930
|
function RGBEffect() {
this.canvas = new MEDIA.Canvas();
this.name = 'RGBEffect';
this.controls = {
RedThreshold: {
value: 128,
min: 0,
max: 255,
step: 2
}
};
}
RGBEffect.prototype = {
draw: function () {
var canvas = this.canvas;
var redThreshold = this.controls.RedThreshold.value;
APP.drawImage(canvas);
var img = canvas.getImageData();
var data = img.data;
// Pixel data here
// 0 red : 1st pixel (0 - 255)
// 1 green : 1st pixel
// 2 blue : 1st pixel
// 3 alpha : 1st pixel
// 4 red : 2nd pixel
// 5 green : 2nd pixel
// 6 blue : 2nd pixel
// 7 alpha : 2nd pixel
for (var i = 0, len = data.length; i < len; i += 4) {
var r = data[i];
// data[i] = r > redThreshold ? r : 0;
if (r > redThreshold) {
data[i] = r;
} else {
data[i] = 0;
}
}
canvas.putImageData(img);
}
}; |
/*! Backstretch - v2.0.4 - 2013-06-19
* http://srobbin.com/jquery-plugins/backstretch/
* Copyright (c) 2013 Scott Robbin; Licensed MIT */
;
(function ($, window, undefined) {
'use strict';
/* PLUGIN DEFINITION
* ========================= */
$.fn.backstretch = function (images, options) {
// We need at least one image or method name
if (images === undefined || images.length === 0) {
$.error("No images were supplied for Backstretch");
}
/*
* Scroll the page one pixel to get the right window height on iOS
* Pretty harmless for everyone else
*/
if ($(window).scrollTop() === 0) {
window.scrollTo(0, 0);
}
return this.each(function () {
var $this = $(this)
, obj = $this.data('backstretch');
// Do we already have an instance attached to this element?
if (obj) {
// Is this a method they're trying to execute?
if (typeof images == 'string' && typeof obj[images] == 'function') {
// Call the method
obj[images](options);
// No need to do anything further
return;
}
// Merge the old options with the new
options = $.extend(obj.options, options);
// Remove the old instance
obj.destroy(true);
}
obj = new Backstretch(this, images, options);
$this.data('backstretch', obj);
});
};
// If no element is supplied, we'll attach to body
$.backstretch = function (images, options) {
// Return the instance
return $('body')
.backstretch(images, options)
.data('backstretch');
};
// Custom selector
$.expr[':'].backstretch = function (elem) {
return $(elem).data('backstretch') !== undefined;
};
/* DEFAULTS
* ========================= */
$.fn.backstretch.defaults = {
centeredX: true // Should we center the image on the X axis?
, centeredY: true // Should we center the image on the Y axis?
, duration: 5000 // Amount of time in between slides (if slideshow)
, fade: 0 // Speed of fade transition between slides
};
/* STYLES
*
* Baked-in styles that we'll apply to our elements.
* In an effort to keep the plugin simple, these are not exposed as options.
* That said, anyone can override these in their own stylesheet.
* ========================= */
var styles = {
wrap: {
left: 0
, top: 0
, overflow: 'hidden'
, margin: 0
, padding: 0
, height: '100%'
, width: '100%'
, zIndex: -999999
}
, img: {
position: 'absolute'
, display: 'none'
, margin: 0
, padding: 0
, border: 'none'
, width: 'auto'
, height: 'auto'
, maxHeight: 'none'
, maxWidth: 'none'
, zIndex: -999999
}
};
/* CLASS DEFINITION
* ========================= */
var Backstretch = function (container, images, options) {
this.options = $.extend({}, $.fn.backstretch.defaults, options || {});
/* In its simplest form, we allow Backstretch to be called on an image path.
* e.g. $.backstretch('/path/to/image.jpg')
* So, we need to turn this back into an array.
*/
this.images = $.isArray(images) ? images : [images];
// Preload images
$.each(this.images, function () {
$('<img />')[0].src = this;
});
// Convenience reference to know if the container is body.
this.isBody = container === document.body;
/* We're keeping track of a few different elements
*
* Container: the element that Backstretch was called on.
* Wrap: a DIV that we place the image into, so we can hide the overflow.
* Root: Convenience reference to help calculate the correct height.
*/
this.$container = $(container);
this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container;
// Don't create a new wrap if one already exists (from a previous instance of Backstretch)
var $existing = this.$container.children(".backstretch").first();
this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container);
// Non-body elements need some style adjustments
if (!this.isBody) {
// If the container is statically positioned, we need to make it relative,
// and if no zIndex is defined, we should set it to zero.
var position = this.$container.css('position')
, zIndex = this.$container.css('zIndex');
this.$container.css({
position: position === 'static' ? 'relative' : position
, zIndex: zIndex === 'auto' ? 0 : zIndex
, background: 'none'
});
// Needs a higher z-index
this.$wrap.css({zIndex: -999998});
}
// Fixed or absolute positioning?
this.$wrap.css({
position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
});
// Set the first image
this.index = 0;
this.show(this.index);
// Listen for resize
$(window).on('resize.backstretch', $.proxy(this.resize, this))
.on('orientationchange.backstretch', $.proxy(function () {
// Need to do this in order to get the right window height
if (this.isBody && window.pageYOffset === 0) {
window.scrollTo(0, 1);
this.resize();
}
}, this));
};
/* PUBLIC METHODS
* ========================= */
Backstretch.prototype = {
resize: function () {
try {
var bgCSS = {left: 0, top: 0}
, rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
, bgWidth = rootWidth
, rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight()
, bgHeight = bgWidth / this.$img.data('ratio')
, bgOffset;
// Make adjustments based on image ratio
if (bgHeight >= rootHeight) {
bgOffset = (bgHeight - rootHeight) / 2;
if (this.options.centeredY) {
bgCSS.top = '-' + bgOffset + 'px';
}
} else {
bgHeight = rootHeight;
bgWidth = bgHeight * this.$img.data('ratio');
bgOffset = (bgWidth - rootWidth) / 2;
if (this.options.centeredX) {
bgCSS.left = '-' + bgOffset + 'px';
}
}
this.$wrap.css({width: rootWidth, height: rootHeight})
.find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS);
} catch (err) {
// IE7 seems to trigger resize before the image is loaded.
// This try/catch block is a hack to let it fail gracefully.
}
return this;
}
// Show the slide at a certain position
, show: function (newIndex) {
// Validate index
if (Math.abs(newIndex) > this.images.length - 1) {
return;
}
// Vars
var self = this
, oldImage = self.$wrap.find('img').addClass('deleteable')
, evtOptions = {relatedTarget: self.$container[0]};
// Trigger the "before" event
self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]);
// Set the new index
this.index = newIndex;
// Pause the slideshow
clearInterval(self.interval);
// New image
self.$img = $('<img />')
.css(styles.img)
.bind('load', function (e) {
var imgWidth = this.width || $(e.target).width()
, imgHeight = this.height || $(e.target).height();
// Save the ratio
$(this).data('ratio', imgWidth / imgHeight);
// Show the image, then delete the old one
// "speed" option has been deprecated, but we want backwards compatibilty
$(this).fadeIn(self.options.speed || self.options.fade, function () {
oldImage.remove();
// Resume the slideshow
if (!self.paused) {
self.cycle();
}
// Trigger the "after" and "show" events
// "show" is being deprecated
$(['after', 'show']).each(function () {
self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]);
});
});
// Resize
self.resize();
})
.appendTo(self.$wrap);
// Hack for IE img onload event
self.$img.attr('src', self.images[newIndex]);
return self;
}
, next: function () {
// Next slide
return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0);
}
, prev: function () {
// Previous slide
return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1);
}
, pause: function () {
// Pause the slideshow
this.paused = true;
return this;
}
, resume: function () {
// Resume the slideshow
this.paused = false;
this.next();
return this;
}
, cycle: function () {
// Start/resume the slideshow
if (this.images.length > 1) {
// Clear the interval, just in case
clearInterval(this.interval);
this.interval = setInterval($.proxy(function () {
// Check for paused slideshow
if (!this.paused) {
this.next();
}
}, this), this.options.duration);
}
return this;
}
, destroy: function (preserveBackground) {
// Stop the resize events
$(window).off('resize.backstretch orientationchange.backstretch');
// Clear the interval
clearInterval(this.interval);
// Remove Backstretch
if (!preserveBackground) {
this.$wrap.remove();
}
this.$container.removeData('backstretch');
}
};
/* SUPPORTS FIXED POSITION?
*
* Based on code from jQuery Mobile 1.1.0
* http://jquerymobile.com/
*
* In a nutshell, we need to figure out if fixed positioning is supported.
* Unfortunately, this is very difficult to do on iOS, and usually involves
* injecting content, scrolling the page, etc.. It's ugly.
* jQuery Mobile uses this workaround. It's not ideal, but works.
*
* Modified to detect IE6
* ========================= */
var supportsFixedPosition = (function () {
var ua = navigator.userAgent
, platform = navigator.platform
// Rendering engine is Webkit, and capture major version
, wkmatch = ua.match(/AppleWebKit\/([0-9]+)/)
, wkversion = !!wkmatch && wkmatch[1]
, ffmatch = ua.match(/Fennec\/([0-9]+)/)
, ffversion = !!ffmatch && ffmatch[1]
, operammobilematch = ua.match(/Opera Mobi\/([0-9]+)/)
, omversion = !!operammobilematch && operammobilematch[1]
, iematch = ua.match(/MSIE ([0-9]+)/)
, ieversion = !!iematch && iematch[1];
return !(
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
((platform.indexOf("iPhone") > -1 || platform.indexOf("iPad") > -1 || platform.indexOf("iPod") > -1 ) && wkversion && wkversion < 534) ||
// Opera Mini
(window.operamini && ({}).toString.call(window.operamini) === "[object OperaMini]") ||
(operammobilematch && omversion < 7458) ||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
(ua.indexOf("Android") > -1 && wkversion && wkversion < 533) ||
// Firefox Mobile before 6.0 -
(ffversion && ffversion < 6) ||
// WebOS less than 3
("palmGetResource" in window && wkversion && wkversion < 534) ||
// MeeGo
(ua.indexOf("MeeGo") > -1 && ua.indexOf("NokiaBrowser/8.5.0") > -1) ||
// IE6
(ieversion && ieversion <= 6)
);
}());
}(jQuery, window)); |
/*global FormFiller, JSONF, jQuery, Logger, Libs */
/*eslint complexity:0 */
var poorMansDelayMaxCyles = 10000;
// Warp the waitUntil function so that invalid selectors and other jQuery expections get caught
var wrapWaitUntilFunction = function(waitUntilFunction) {
return function wrappedWaitUntilFunction() {
try {
return waitUntilFunction();
} catch (exception) {
return false;
}
};
};
// Handles the value of "waitUntil" in a step.
// If it is a string it is assumed that it is an selector which should be on the page to continue.
// If it is a function it must returen true to continue
// If it is not set (undefined) then we wait for the selector of the step
var handleWaitUntil = function(selector, waitUntilSerialized) {
var waitUntil = JSONF.parse(waitUntilSerialized);
var poorMansDelay = 0;
var waitUntilFunction = null;
// Look for the step selector
if (typeof waitUntil === "undefined") {
waitUntilFunction = function() {
return jQuery.find(selector).length > 0;
};
}
// If string: use that as selector
if (typeof waitUntil === "string") {
waitUntilFunction = function() {
return jQuery.find(waitUntil).length > 0;
};
}
// If function evaluate it
if (typeof waitUntil === "function") {
waitUntilFunction = waitUntil;
}
waitUntilFunction = wrapWaitUntilFunction(waitUntilFunction);
while (waitUntilFunction() !== true && poorMansDelay < poorMansDelayMaxCyles) {
poorMansDelay++;
}
};
// This listens for messages coming from the background page
// This is a long running communication channel
chrome.runtime.onConnect.addListener(function (port) {
var errors = [];
var currentError = null;
var workingOverlayId = "form-o-fill-working-overlay";
var workingTimeout = null;
var takingLongTimeout = null;
var wontFinishTimeout = null;
var displayTimeout = null;
Logger.info("[content.js] Got a connection from " + port.name);
if (port.name !== "FormOFill") {
return;
}
// Returns the HTML used for the throbbing overlay
var overlayHtml = function(text, isVisible) {
if (typeof text === "undefined") {
text = chrome.i18n.getMessage("content_fof_is_working");
}
if (typeof isVisible === "undefined") {
isVisible = false;
}
return "<div id='" + workingOverlayId + "' style='display: " + (isVisible ? "block" : "none") + ";'>" + text + "</div>";
};
// Hide overlay and cancel all timers
var hideOverlay = function() {
jQuery("#" + workingOverlayId).remove();
clearTimeout(workingTimeout);
clearTimeout(takingLongTimeout);
clearTimeout(wontFinishTimeout);
clearTimeout(displayTimeout);
};
// Shows and hides a customized overlay throbber
var showOverlay = function(message) {
hideOverlay();
jQuery("body").find("#" + workingOverlayId).remove().end().append(overlayHtml(message, true));
displayTimeout = setTimeout(hideOverlay, 3000);
};
// Connect to background.js which opens a long running port connection
port.onMessage.addListener(function (message) {
Logger.info("[content.js] Got message via port.onMessage : " + JSONF.stringify(message) + " from bg.js");
// Request to fill fields
if (message.action === "fillFields" && message.steps && message.steps.length > 0) {
Logger.info("[content.js] Filling " + message.steps.length + " fields");
// Loop over every step
message.steps.forEach(function(step) {
// REMOVE START
if (step.within && step.within !== null) {
Logger.info("[content.js] Using within selector " + message.within);
}
// REMOVE END
// Wait a little if necessary
handleWaitUntil(step.selector, step.waitUntil);
currentError = FormFiller.fill(step.selector, step.value, step.beforeData, step.flags, step.meta);
// Remember the error
if (typeof currentError !== "undefined" && currentError !== null) {
Logger.info("[content.js] Got error " + JSONF.stringify(currentError));
errors.push(currentError);
}
});
// Send a message that we are done filling the form
Logger.info("[content.js] Sending fillFieldFinished since we are done with the last field definition");
chrome.runtime.sendMessage({
"action": "fillFieldFinished",
"errors": JSONF.stringify(errors)
});
}
// request to return all accumulated errors
if (message.action === "getErrors") {
Logger.info("[content.js] Returning " + errors.length + " errors to bg.js");
var response = {
"action": "getErrors",
"errors": JSONF.stringify(errors)
};
port.postMessage(response);
}
// Show Working overlay
// This should only be triggered for the default "WORKING"
// overlay.
// For the customized Lib.halt() message see down below
if (message.action === "showOverlay" && typeof message.message === "undefined") {
Logger.info("[content.js] Showing working overlay");
if (document.querySelectorAll("#" + workingOverlayId).length === 0) {
jQuery("body").append(overlayHtml());
}
// Show working overlay after some time
workingTimeout = setTimeout(function() {
jQuery("#" + workingOverlayId).show();
}, 350);
// Show another overlay when things take REALLY long to finish
takingLongTimeout = setTimeout(function () {
jQuery("#" + workingOverlayId).html(chrome.i18n.getMessage("content_fof_is_working_2"));
}, 5000);
// Finally if everything fails, clear overlay after 12 seconds
wontFinishTimeout = setTimeout(hideOverlay, 12000);
}
// Hide the overlay
if (message.action === "hideWorkingOverlay") {
Logger.info("[content.js] Hiding working overlay");
hideOverlay();
}
// Show a custom message
if (message.action === "showMessage" && typeof message.message !== "undefined") {
showOverlay(message.message);
}
// Reload the libraries
if (message.action === "reloadLibs") {
Libs.import();
}
// Execute setupContent function
// It has jQuery available
if (message.action === "setupContent" && message.value) {
Logger.info("[content.js] Executing setupContent function", message.value);
// Parse and execute function
var error = null;
try {
var setupContentFunction = JSONF.parse(message.value);
// Check if promises should be used:
if (setupContentFunction.length > 0) {
var setupContentFunctionPr = new Promise(function(resolve) {
setupContentFunction(resolve);
});
setupContentFunctionPr.then(function() {
port.postMessage({action: "setupContentDone", value: JSONF.stringify(error)});
});
} else {
setupContentFunction();
port.postMessage({action: "setupContentDone", value: JSONF.stringify(error)});
}
} catch (e) {
Logger.error("[content.js] error while executing setupContent function");
error = e.message;
}
}
// Execute teardownContent function
// It has jQuery available and the context object from value functions and setupContent
if (message.action === "teardownContent" && message.value) {
Logger.info("[content.js] Executing teardownContent function", message.value);
try {
JSONF.parse(message.value)();
} catch (e) {
Logger.error("[content.js] error while executing teardownContent function");
}
}
});
// Simple one-shot callbacks
chrome.runtime.onMessage.addListener(function (message, sender, responseCb) {
Logger.info("[content.js] Got message via runtime.onMessage : " + JSONF.stringify(message) + " from bg.j");
// This is the content grabber available as context.findHtml() in before functions
if (message.action === "grabContentBySelector") {
Logger.info("[content.js] Grabber asked for '" + message.message + "'");
var domElements = jQuery(message.message).map(function (index, $el) {
return $el;
});
if (domElements.length === 0) {
responseCb({count: 0, nodes: []});
} else if (domElements.length === 1) {
responseCb({count: 1, nodes: domElements[0].outerHTML});
} else {
var elements = domElements.map(function(index, el) {
return el.outerHTML;
});
responseCb({count: elements.length, nodes: jQuery.makeArray(elements)});
}
}
// Show a custom message
// This appears twice in c/content.js because it uses a port and a one-shot
// listener
if (message.action === "showOverlay" && typeof message.message !== "undefined") {
showOverlay(message.message);
responseCb();
}
// Save a variable set in background via storage.set in the context of the content script
// This makes the storage usable in value functions
if (message.action === "storageSet" && typeof message.key !== "undefined" && typeof message.value !== "undefined") {
Logger.info("[content.js] Saving " + message.key + " = " + message.value);
window.sessionStorage.setItem(message.key, message.value);
}
// Inject a <script> tag into the page which gets executed and replaces itself with the JSON serialized
// data the user wants.
// <script id="fof-get-variable-some-name">{data: { some: "JSON" }}</script>
// Only works with simple data, not functions :(
if (message.action === "getVar" && typeof message.key !== "undefined") {
var id = "fof-get-variable-" + message.key.replace(/[^a-zA-Z0-9_-]/g, "-");
// Insert the node only if not present
if (document.querySelectorAll("#" + id).length === 0) {
var elem = document.createElement("script");
elem.id = id;
elem.type = "text/javascript";
elem.dataset.purpose = "Used by Form-O-Fill to access JS variables on the site.";
elem.className = "fof-get-variable";
document.head.appendChild(elem);
elem.innerHTML = "var c = '**JSONF-UNDEFINED**'; try { c = JSON.stringify(" + message.key + "); } catch(e) {}; document.querySelector('#" + id + "').innerHTML = c;";
}
// Now return the JSON to the caller
var jsonNode = document.querySelector("#" + id);
Logger.info("[content.js] getVar received " + jsonNode.innerText);
responseCb(JSONF.parse(jsonNode.innerText));
// ... and remove the node
jsonNode.remove();
}
// Must return true to signal chrome that we do some work
// asynchronously (see https://developer.chrome.com/extensions/runtime#event-onMessage)
return true;
});
});
|
'use strict'
import React from 'react'
import {Link} from 'react-router'
const NotFoundPage = React.createClass({
render: () => {
return (
<div className='container-fluid'>
<h1>Page Not Found</h1>
<p>Woops! Sorry, there is nothing to see here.</p>
<p><Link to='/'>Back to Home</Link></p>
</div>
)
}
})
module.exports = NotFoundPage
|
import Ember from "ember";
import notAmong from "ember-cpm/macros/not-among";
module("notAmong");
var MyObj = Ember.Object.extend({
notCartoonDog: notAmong('value', 'Odie', 'Snoopy')
});
test('returns false if the value is among the given values', function() {
var o = MyObj.create({ value: 'Snoopy' });
equal(o.get('notCartoonDog'), false);
});
test('returns true if the value is not among the given values', function() {
var o = MyObj.create({ value: 'Garfield' });
equal(o.get('notCartoonDog'), true);
});
|
var makr = require('../lib/index')
function Component() {}
var em = makr(Component)
var entity = em.create()
var component = new Component()
suite('Entity', function() {
bench('#add', function() {
entity.add(component)
})
bench('#get', function() {
entity.get(Component)
})
bench('#has', function() {
entity.has(Component)
})
bench('#remove', function() {
entity.remove(Component)
})
bench('#destroy', function() {
entity.destroy()
})
})
|
// TODO Add README for GIT
var RxBotics = module.exports = {
}
RxBotics.Behaviour = require('./rxbotics.behaviour.js');
RxBotics.Controller = require('./rxbotics.controller.js');
RxBotics.Driver = require('./rxbotics.driver.js');
RxBotics.Math = require('./rxbotics.math.js');
RxBotics.Sensor = require('./rxbotics.sensor.js');
RxBotics.Encoder = require('./rxbotics.encoder.js');
// For testing only
RxBotics.Mock = require('./rxbotics.mock.js');
module.exports = RxBotics; |
__report = {
"reports": [
{
"info": {
"file": "lib/DataType.js",
"fileShort": "lib/DataType.js",
"fileSafe": "lib_DataType_js",
"link": "files/lib_DataType_js/index.html"
},
"jshint": {
"messages": 19
},
"complexity": {
"aggregate": {
"line": 1,
"complexity": {
"sloc": {
"physical": 380,
"logical": 219
},
"cyclomatic": 62,
"halstead": {
"operators": {
"distinct": 39,
"total": 571,
"identifiers": [
"__stripped__"
]
},
"operands": {
"distinct": 157,
"total": 796,
"identifiers": [
"__stripped__"
]
},
"length": 1367,
"vocabulary": 196,
"difficulty": 98.86624203821655,
"volume": 10409.308356905489,
"effort": 1029129.1994642484,
"bugs": 3.4697694523018296,
"time": 57173.84441468047
},
"params": 63
}
},
"module": "lib/DataType.js",
"maintainability": 61.10389346949256
}
}
],
"summary": {
"total": {
"sloc": 380,
"maintainability": 61.10389346949256
},
"average": {
"sloc": 380,
"maintainability": "61.10"
}
}
}
|
var app = angular.module('HomePageApp', []); |
export class Connection {
constructor (url) {
this._url = url
this.connecting = false
this.connect(this._url)
this.listener = null
}
get url () {
return this._url
}
set url (v) {
if (v !== this._url) {
this._url = v
this.connect()
}
}
connect () {
this.connecting = true
this._close()
this.ws = new WebSocket(this._url)
this.ws.onclose = () => this.onClose()
this.ws.onerror = () => {
this.connecting = false
this.onClose()
}
this.ws.onmessage = (msg) => {
let data = msg.data
try {
data = JSON.parse(data)
} catch (e) {
return
}
this.onMessage(data)
}
this.ws.onopen = () => {
this.connecting = false
this.onOpen()
}
}
_close () {
if (this.ws) {
this.ws.close()
}
}
onClose () {
setTimeout(() => {
if (this.connecting) {
return
}
this.connect()
}, 1000)
if (this.listener) {
this.listener.onClose()
}
}
onMessage (data) {
}
onOpen () {
if (this.listener) {
this.listener.onOpen()
}
}
send (data) {
this.ws.send(JSON.stringify(data))
}
}
export class Subscriptor extends Connection {
constructor (url) {
super(url)
this.items = []
this.map = {}
this.nextId = 1
this.onPublish = () => null
this.onPackage = () => null
}
onOpen () {
if (this.items.length > 0) {
this.send({
type: 'SubscribeAll',
items: this.items
})
}
}
onMessage (data) {
if (data.type === 'Data') {
const item = this.map[data.id]
if (item) {
if (item.callback) {
item.callback(data.value, item.name, item.args)
} else {
this.onPublish(data.value, item.name, item.args)
}
}
} else {
this.onPackage(data)
}
}
unsubscribe (id) {
const item = this.items.find(i => i.id === id)
if (!item) {
return false
}
try {
this.send({
type: 'Unsubscribe',
id
})
this.items.splice(this.items.indexOf(item), 1)
delete this.map[id]
return true
} catch (e) {
console.log('fail to unsubscribe')
return false
}
}
subscribe (name, ...args) {
const callback = args[args.length - 1]
const item = {
id: this.nextId++,
name,
args: args.slice(0, args.length - 1),
callback
}
this.items.push(item)
this.map[item.id] = item
try {
this.send({
type: 'Subscribe',
id: item.id,
name: item.name,
args: item.args
})
} catch (e) {
console.log('fail to subscribe')
}
return item.id
}
}
|
'use strict';
let datafire = require('datafire');
let openapi = require('./openapi.json');
let aws = require('aws-sdk');
const INTEGRATION_ID = 'amazonaws_mediaconvert';
const SDK_ID = 'MediaConvert';
let integ = module.exports = new datafire.Integration({
id: INTEGRATION_ID,
title: openapi.info.title,
description: openapi.info.description,
logo: openapi.info['x-logo'],
});
integ.security[INTEGRATION_ID]= {
integration: INTEGRATION_ID,
fields: {
accessKeyId: "",
secretAccessKey: "",
region: "AWS region (if applicable)",
}
}
function maybeCamelCase(str) {
return str.replace(/_(\w)/g, (match, char) => char.toUpperCase())
}
// We use this instance to make sure each action is available in the SDK at startup.
let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'});
for (let path in openapi.paths) {
for (let method in openapi.paths[path]) {
if (method === 'parameters') continue;
let op = openapi.paths[path][method];
let actionID = op.operationId;
actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, '');
if (actionID.indexOf('_') !== -1) {
actionID = actionID.split('_')[1];
}
let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1);
if (!dummyInstance[functionID]) {
console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found");
console.log(method, path, op.operationId, actionID);
continue;
}
let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {};
let response = (op.responses || {})[200] || {};
let inputSchema = {
type: 'object',
properties: {},
};
if (inputParam.schema) inputSchema.allOf = [inputParam.schema];
(op.parameters || []).forEach(p => {
if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) {
inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type};
if (p.required) {
inputSchema.required = inputSchema.required || [];
inputSchema.required.push(p.name);
}
}
})
function getSchema(schema) {
if (!schema) return;
return Object.assign({definitions: openapi.definitions}, schema);
}
integ.addAction(actionID, new datafire.Action({
inputSchema: getSchema(inputSchema),
outputSchema: getSchema(response.schema),
handler: (input, context) => {
let lib = new aws[SDK_ID](Object.assign({
version: openapi.info.version,
}, context.accounts[INTEGRATION_ID]));
return lib[functionID](input).promise()
.then(data => {
return JSON.parse(JSON.stringify(data));
})
}
}));
}
}
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['ml_IN'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%z%c%T%s%b%e%r",
"country_name": "\u0d07\u0d28\u0d4d\u0d24\u0d4d\u0d2f",
"country_post": null,
"country_ab2": "IN",
"country_ab3": "IND",
"country_num": 356,
"country_car": "IND",
"country_isbn": null,
"lang_name": "\u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02",
"lang_ab": "ml",
"lang_term": "mal",
"lang_lib": "mal"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1yY\u0d09]",
"noexpr": "^[-0nN\u0d05]",
"yesstr": "\u0d09\u0d35\u0d4d\u0d35\u0d4d",
"nostr": "\u0d05\u0d32\u0d4d\u0d32"
},
"LC_MONETARY": {
"currency_symbol": "\u20b9",
"mon_decimal_point": ".",
"mon_thousands_sep": ",",
"mon_grouping": [
3,
2
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 0,
"n_cs_precedes": 1,
"n_sep_by_space": 0,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "INR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%p%t%f%t%g",
"name_gen": "\u0d36\u0d4d\u0d30\u0d40",
"name_mr": "\u0d36\u0d4d\u0d30\u0d40\u0d2e\u0d3e\u0d28\u0d41\u0d4d",
"name_mrs": "\u0d36\u0d4d\u0d30\u0d40\u0d2e\u0d24\u0d3f",
"name_miss": "\u0d15\u0d41\u0d2e\u0d3e\u0d30\u0d3f",
"name_ms": "\u0d36\u0d4d\u0d30\u0d40\u0d2e\u0d24\u0d3f"
},
"LC_NUMERIC": {
"decimal_point": ".",
"thousands_sep": ",",
"grouping": [
3,
2
]
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": [
"+%c ",
0,
0
],
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "91"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"\u0d1e\u0d3e",
"\u0d24\u0d3f",
"\u0d1a\u0d4a",
"\u0d2c\u0d41",
"\u0d35\u0d4d\u0d2f\u0d3e",
"\u0d35\u0d46",
"\u0d36"
],
"day": [
"\u0d1e\u0d3e\u0d2f\u0d30\u0d4d\u200d",
"\u0d24\u0d3f\u0d19\u0d4d\u0d15\u0d33\u0d4d\u200d",
"\u0d1a\u0d4a\u0d35\u0d4d\u0d35",
"\u0d2c\u0d41\u0d27\u0d28\u0d4d\u200d",
"\u0d35\u0d4d\u0d2f\u0d3e\u0d34\u0d02",
"\u0d35\u0d46\u0d33\u0d4d\u0d33\u0d3f",
"\u0d36\u0d28\u0d3f"
],
"week": [
7,
19971130,
1
],
"abmon": [
"\u0d1c\u0d28\u0d41",
"\u0d2b\u0d46\u0d2c\u0d4d\u0d30\u0d41",
"\u0d2e\u0d3e\u0d7c",
"\u0d0f\u0d2a\u0d4d\u0d30\u0d3f",
"\u0d2e\u0d47\u0d2f\u0d4d",
"\u0d1c\u0d42\u0d7a",
"\u0d1c\u0d42\u0d32\u0d48",
"\u0d13\u0d17",
"\u0d38\u0d46\u0d2a\u0d4d\u0d31\u0d4d\u0d31\u0d02",
"\u0d12\u0d15\u0d4d\u0d1f\u0d4b",
"\u0d28\u0d35\u0d02",
"\u0d21\u0d3f\u0d38\u0d02"
],
"mon": [
"\u0d1c\u0d28\u0d41\u0d35\u0d30\u0d3f",
"\u0d2b\u0d46\u0d2c\u0d4d\u0d30\u0d41\u0d35\u0d30\u0d3f",
"\u0d2e\u0d3e\u0d7c\u0d1a\u0d4d\u0d1a\u0d4d",
"\u0d0f\u0d2a\u0d4d\u0d30\u0d3f\u0d7d",
"\u0d2e\u0d47\u0d2f\u0d4d",
"\u0d1c\u0d42\u0d7a",
"\u0d1c\u0d42\u0d32\u0d48",
"\u0d13\u0d17\u0d38\u0d4d\u0d31\u0d4d\u0d31\u0d4d",
"\u0d38\u0d46\u0d2a\u0d4d\u0d31\u0d4d\u0d31\u0d02\u0d2c\u0d7c",
"\u0d12\u0d15\u0d4d\u200c\u0d1f\u0d4b\u0d2c\u0d7c",
"\u0d28\u0d35\u0d02\u0d2c\u0d7c",
"\u0d21\u0d3f\u0d38\u0d02\u0d2c\u0d7c"
],
"d_t_fmt": "%A %d %B %Y %I:%M:%S %p %Z",
"d_fmt": "%-d\/\/%-m\/\/%y",
"t_fmt": "%I:%M:%S %p %Z",
"am_pm": [
"\u0d30\u0d3e\u0d35\u0d3f\u0d32\u0d46",
"\u0d35\u0d48\u0d15\u0d41"
],
"t_fmt_ampm": "%I:%M:%S %p %Z",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": null,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
var shapeways = require('../index.js')
, path = require('path');
if(process.argv.length !== 4) {
console.log("Please specify your [username] and [password] as commandline arguments.");
process.exit(1);
}
shapeways.connect({
username: process.argv[2]
, password: process.argv[3]
}, function(err, sw) {
if(err) {
console.log(err);
return;
}
sw.upload({
title: 'Test JSON Cube'
, units: 'cm'
, model_json: {
verts: [
[0, 0, 0]
, [1, 0, 0]
, [0, 1, 0]
, [1, 1, 0]
, [0, 0, 1]
, [1, 0, 1]
, [0, 1, 1]
, [1, 1, 1]
]
, faces: [
[3, 1, 0, 2]
, [0, 1, 5, 4]
, [6, 2, 0, 4]
, [1, 3, 7, 5]
, [7, 3, 2, 6]
, [4, 5, 7, 6]
]
, face_colors: [
[1, 0, 0]
, [0, 1, 0]
, [0, 0, 1]
, [0, 1, 1]
, [1, 0, 1]
, [1, 1, 0]
]
}
}, function(err, model_id) {
if(err) {
console.log("Failed to upload JSON:", err);
return;
}
console.log("Uploaded model: " + model_id);
console.log("ShapeWays URL: http://www.shapeways.com/model/"+model_id);
});
});
|
(function() {
"use strict";
angular.module("CursoService", [])
.service("CursoService", CursoService);
function CursoService($http) {
// const urlBase = 'https://falafsm-api.herokuapp.com/rest';
const urlBase = 'http://www.falafsm.com.br:8080/falafsm-api/rest';
const methods = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE'
}
this.cursosDisponiveis = function() {
let path = 'curso/cursos';
let request = {
url: urlBase + "/" + path,
method: methods.GET,
headers: { 'Authorization': 'Bearer ' + localStorage.token }
}
return $http(request);
}
}
CursoService.$inject = ["$http"];
})(); |
import Vue from 'vue';
import template from './navigation.html';
export default Vue.extend({
template,
data() {
return {
hideNav: true,
};
}
});
|
mf.include("navigator_3d.js");
mf.include("giver.js");
mf.include("auto_respawn.js");
mf.include("block_finder.js");
mf.include("items.js");
mf.include("chat_commands.js");
mf.include("inventory.js");
mf.include("navigator.js");
var window_open_func;
mf.onWindowOpened(function(window_type) {
mf.debug("window opened of type: " + window_type);
if (window_open_func != undefined) {
window_open_func(window_type);
}
});
mf.onEquippedItemChanged(function() {
var item = inventory.equippedItem();
mf.debug("equipped item changed. now holding " + item.count + " " + items.nameForId(item.type));
});
mf.onInventoryUpdated(function() {
mf.debug("inventory update");
});
chat_commands.registerCommand("list", function() {
mf.debug("----- my inventory ------");
for (var i = 0; i < inventory.slot_count; i++) {
var item = mf.inventoryItem(i);
if (item.type == mf.ItemType.NoItem) { continue; }
mf.debug("slot " + i + ": " + items.nameForId(item.type) + " x " + item.count);
}
mf.debug("-------------------------");
});
chat_commands.registerCommand("next", function() {
mf.selectEquipSlot((mf.selectedEquipSlot() + 1) % inventory.column_count);
});
chat_commands.registerCommand("prev", function() {
mf.selectEquipSlot((mf.selectedEquipSlot() - 1) % inventory.column_count);
});
chat_commands.registerCommand("toss", function(speaker, args) {
var slot = parseInt(args[0]);
window_open_func = function(window_type) {
window_open_func = undefined;
mf.clickInventorySlot(slot, mf.MouseButton.Left);
mf.clickOutsideWindow(mf.MouseButton.Left);
mf.closeWindow();
};
mf.openInventoryWindow();
}, 1);
var build_under_myself = false;
chat_commands.registerCommand("build", function() {
mf.setControlState(mf.Control.Jump, true);
build_under_myself = true;
});
chat_commands.registerCommand("build1", function(user, arg) {
var glass_pos_arr = block_finder.findNearest(mf.self().position, mf.ItemType.Glass, 10, 1);
if (glass_pos_arr.length === 0) {
mf.chat("I see no glass.");
return;
}
mf.hax.placeBlock(glass_pos_arr[0], parseInt(arg));
}, 1);
chat_commands.registerCommand("stopbuild", function() {
mf.setControlState(mf.Control.Jump, false);
build_under_myself = false;
});
chat_commands.registerCommand("where", function() {
var pos = mf.self().position;
mf.chat("I'm at " + pos.x + " " + pos.y + " " + pos.z);
});
mf.onSelfMoved(function() {
if (build_under_myself) {
var below = mf.self().position.offset(0, -1.5, 0).floored();
if (mf.blockAt(below.offset(0, 1, 0)).type == mf.ItemType.Air) {
mf.debug("js: place block at "+ below.x + " " + below.y + " " + below.z);
mf.hax.placeBlock(below, mf.Face.PositiveY);
}
}
});
chat_commands.registerCommand("woodplank", function() {
var wood_count = inventory.itemCount(mf.ItemType.Wood);
if (wood_count < 1) {
mf.chat("not enough wood to create plank");
return
}
var wood_slot = inventory.itemSlot(mf.ItemType.Wood);
var wood_item = mf.inventoryItem(wood_slot);
window_open_func = function(window_type) {
window_open_func = undefined;
mf.debug("now crafting");
mf.clickInventorySlot(wood_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(1, mf.MouseButton.Left);
mf.clickUniqueSlot(0, mf.MouseButton.Left);
mf.closeWindow();
};
mf.openInventoryWindow();
});
chat_commands.registerCommand("torch", function() {
var stick_count = inventory.itemCount(mf.ItemType.Stick);
if (stick_count < 1) {
mf.chat("not enough sticks to create torch");
return
}
var coal_count = inventory.itemCount(mf.ItemType.Coal);
if (coal_count < 1) {
mf.chat("not enough coal to create torch");
return
}
var stick_slot = inventory.itemSlot(mf.ItemType.Stick);
var stick_item = mf.inventoryItem(stick_slot);
var coal_slot = inventory.itemSlot(mf.ItemType.Coal);
var coal_item = mf.inventoryItem(coal_slot);
window_open_func = function(window_type) {
window_open_func = undefined;
mf.debug("now crafting");
mf.clickInventorySlot(stick_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(3, mf.MouseButton.Right);
mf.clickInventorySlot(coal_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(1, mf.MouseButton.Right);
mf.clickInventorySlot(stick_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(0, mf.MouseButton.Left);
mf.clickInventorySlot(inventory.firstEmptySlot(), mf.MouseButton.Left);
mf.closeWindow();
};
mf.openInventoryWindow();
});
chat_commands.registerCommand("craft", function() {
var stone_count = inventory.itemCount(mf.ItemType.Cobblestone);
if (stone_count < 3) {
mf.chat("not enough stone to create pick axe");
return;
}
var stick_count = inventory.itemCount(mf.ItemType.Stick);
if (stick_count < 2) {
mf.chat("not enough sticks to create pick axe");
return
}
var stone_slot = inventory.itemSlot(mf.ItemType.Cobblestone);
var stone_item = mf.inventoryItem(stone_slot);
if (stone_item.count < 3) {
mf.chat("stone stack too small.");
}
var stick_slot = inventory.itemSlot(mf.ItemType.Stick);
var stick_item = mf.inventoryItem(stick_slot);
if (stick_item.count < 2) {
mf.chat("stick stack too small.");
}
var table_pt_arr = block_finder.findNearest(mf.self().position, mf.ItemType.CraftingTable, 20, 1);
if (table_pt_arr.length === 0) {
mf.chat("I see no crafting table.");
return;
}
var table_pt = table_pt_arr[0];
navigator.navigateTo(table_pt, {
"end_radius": 3,
"arrived_func": function() {
mf.debug("done navigating");
window_open_func = function(window_type) {
window_open_func = undefined;
mf.debug("now crafting");
mf.clickInventorySlot(stick_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(8, mf.MouseButton.Right);
mf.clickUniqueSlot(5, mf.MouseButton.Right);
mf.clickInventorySlot(stone_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(1, mf.MouseButton.Right);
mf.clickUniqueSlot(2, mf.MouseButton.Right);
mf.clickUniqueSlot(3, mf.MouseButton.Right);
mf.clickInventorySlot(stick_slot, mf.MouseButton.Left);
mf.clickUniqueSlot(0, mf.MouseButton.Left);
//mf.clickInventorySlot(inventory.firstEmptySlot(), mf.MouseButton.Left);
mf.clickOutsideWindow(mf.MouseButton.Left);
mf.closeWindow();
};
mf.hax.activateBlock(table_pt);
},
});
});
chat_commands.registerCommand("loot", function() {
var chest_pts = block_finder.findNearest(mf.self().position, mf.ItemType.Chest, 20, 1);
if (chest_pts.length === 0) {
mf.chat("I see no chest.");
return;
}
var chest_pt = chest_pts[0];
navigator.navigateTo(chest_pt, {
"end_radius": 3,
"arrived_func": function() {
mf.debug("done navigating");
window_open_func = function(window_type) {
window_open_func = undefined;
mf.debug("now looting");
for (var i = 0; i < 27; i++) {
var item = mf.uniqueWindowItem(i);
if (item.type != mf.ItemType.NoItem) {
mf.debug("looting " + item.count + " " + items.nameForId(item.type));
mf.clickUniqueSlot(i, mf.MouseButton.Left);
mf.debug("dropping outside window");
mf.clickOutsideWindow(mf.MouseButton.Left);
}
}
mf.closeWindow();
};
mf.hax.activateBlock(chest_pt);
},
});
});
|
angular.module('app')
.config(($routeProvider) => {
$routeProvider
.when('/login', {
controller: 'LoginCtrl',
controllerAs: 'auth',
templateUrl: '/app/auth/login.html'
})
.when('/logout', {
controller: 'LogoutCtrl',
controllerAs: 'auth',
template: ''
})
})
|
'use strict';
const _ = require('lodash');
const utils = require('../utils');
const fileUtils = require('../fileUtils');
const AffianceError = require('../error');
const HookMessage = require('./Message');
const HookMessageProcessor = require('./MessageProcessor');
/**
* @class HookBase
* @classdesc The base implementation for a hook.
* Provides common methods for getting standard meta data about
* the hook and enforcing common configuration based features
* like checking for required executables.
*
* @property {object} config - the hook specific config as a plain object
* @property {HookContextBase} context - an instance of the hook script's context
*/
module.exports = class HookBase {
/**
* Create a hook instance.
* It will use the context to find the configuration specific
* to this hook and assign the flat object to config.
*
* @param {Config} config - the full HookConfig instance.
* @param {HookContextBase} context - the hook context
*/
constructor(config, context) {
this.config = _.extend({}, config.forHook(this.hookName(), context.hookConfigName));
this.context = context;
}
/**
* The name of the hook.
* This the same CapitalCamelCase name as found in the the
* `default.yml` file or the custom hook's name in the plugin directory.
* Can be set directly by subclasses, but defaults to `constructor.name`
*
* @returns {string} - the hook's name
*/
hookName() {
if(!this._hookName) {
this._hookName = this.constructor.name;
}
return this._hookName;
}
/**
* The name of the hook.
* This the same CapitalCamelCase name as found in the the
* `default.yml` file or the custom hook's name in the plugin directory.
* Can be set directly by subclasses, but defaults to `constructor.name`
*
* @params {string} hookName - the hook's name
* @returns {this} - the hook instance in case you want to chain.
*/
setHookName(hookName) {
this._hookName = hookName;
return this;
}
/**
* Run the hook. Subclasses _must_ implement this method.
*
* @abstract
*/
run() { throw new Error('Hook must define `run`'); }
/**
* The wrapped result of a hook's `run` method.
* @typedef {object} HookResult
* @property {string} status - the status of the hook run {fail, warn, pass}
* @property {output} string - the output of the hook run
*/
/**
* Wrap the run function with the configured environment after
* checking that all requirements are met to run the hook.
* Will return a promise that resulves with a result object like
*
*
* @returns {Promise}
* @resolve {HookResult} - a hook result object
* @rejects {Error} - an error thrown during the hook run
*/
wrapRun() {
// Any output is bad here.
let requirementsOutput = this.checkForRequirements();
if (requirementsOutput) {
return Promise.resolve({
status: 'fail',
output: requirementsOutput
});
}
return new Promise((resolve, reject) => {
// Since we allow hooks to configure their own environment, we wrap the run call
// with a temporary change to process.env
this.wrapEnvAroundRun().then((hookReturnValue) => {
let runResult = this.processHookReturnValue(hookReturnValue);
runResult.status = this.transformStatus(runResult.status);
resolve(runResult);
}, reject);
});
}
/**
* Wrap the run function with the configured environment before running.
* Will also wrap the run's result with a promise if the hook runs synchronously.
*
* @returns {Promise}
* @resolve {*} - the return value of the hook's `run` method
* @rejects {Error} - an error thrown during the hook run
*/
wrapEnvAroundRun() {
let oldEnv = _.defaultsDeep({}, process.env);
// Merge the configured env with the old env, using the current env as the defaults.
let runEnv = _.defaultsDeep({}, this.config['env'] || {}, oldEnv);
// Set the process env so the hook can run with it's configured env set.
process.env = runEnv;
// Run the hook!
let hookRunPromise = this.run();
// Coerce result into a Promise when hook has simple return value
if (!(hookRunPromise instanceof Promise)) {
hookRunPromise = Promise.resolve(hookRunPromise);
}
// Close over `oldEnv` to reset after hook result is resolved.
// Reset env back to normal.
let afterHookRun = () => {
process.env = oldEnv;
};
hookRunPromise.then(afterHookRun, afterHookRun);
return hookRunPromise;
}
/**
* A description of the hook.
* If no description is configured, will use the default of:
* Run HookName
*
* @returns {string}
*/
description() {
return this.config['description'] || `Run ${this.hookName()}`;
}
/**
* Returns true if the hook is required.
* Required hooks can't be skipped.
*
* @returns {boolean}
*/
isRequired() {
return !!this.config['required'];
}
/**
* Returns true if the hook is configured to parallelize itself.
*
* @returns {boolean}
*/
canParallelize() {
return this.config['parallelize'] !== false;
}
/**
* Returns the number of processors to use to run this hook.
* Defaults to 1 if `processors` not configured.
*
* @returns {number}
*/
processors() {
return this.config['processors'] ? parseInt(this.config['processors'], 10) : 1;
}
/**
* Returns true if the hook is configured to run quietly
*
* @returns {boolean}
*/
isQuiet() {
return !!this.config['quiet'];
}
/**
* Returns true if the hook is enabled.
*
* @returns {boolean}
*/
isEnabled() {
return this.config['enabled'] !== false;
}
/**
* Returns true if the hook can be skipped.
*
* @returns {boolean}
*/
canSkip() {
return !!this.config['skip'];
}
/**
* Returns true if the hook can be run.
* To be run a hook needs to be enabled and, if it requires files,
* that there are files to run against.
*
* @returns {boolean}
*/
canRun() {
return this.isEnabled() && !(this.config['requiresFiles'] && !this.applicableFiles().length);
}
/**
* The result object of a ChildProcess.spawnSync call.
* @typedef {object} SpawnResult
* @property {number} pid - Pid of child process
* @property {Array} output - Array of results from stdio output
* @property {Buffer|string} stdout - The contents of output[1]
* @property {Buffer|string} stderr - The contents of output[2]
* @property {number} status - The exit code of the child process
* @property {string} signal - The signal used to kill the child process
* @property {Error} error - The error object if the child process failed or timed out
*/
/**
* Synchronously executes a command with the provided arguments.
* The command, args, and options are passed through to `ChildProcess#spawnSync`
*
* @returns {SpawnResult} the result of the spawned process
*/
execute(command, args, options) {
args = args || [];
options = options || {};
return utils.spawnSync(command, args, options);
}
/**
* Synchronously executes the configured command on applicable files.
*
* @returns {SpawnResult} the result of the spawned process
*/
executeCommandOnApplicableFiles() {
let commandArgs = _.compact(this.flags().concat(this.applicableFiles()));
return this.execute(this.command(), commandArgs);
}
/**
* Asynchronously executes a command with the provided arguments.
*
* @returns {ChildProcess} the spawned ChildProcess instance
*/
spawnCommand(command, args, options) {
args = args || [];
options = options || {};
return utils.spawn(command, args, options);
}
/**
* Asynchronously executes a command with the provided arguments.
* Respects the processCount by requesting a process slot from
* the hook context before spawning the process.
*
* @param {string} command - the name of the command to run
* @param {string[]} args - a list of arguments to provide to the command
* @param {object} options - options to provide to `ChildProcess.spawn`
*
* @returns {Promise} a promise wrapping the spawned process.
* @resolve {SpawnResult} the result of the spawned process resolves the returned promise
* @rejects {Error} an error thrown or emitted during the process run
*/
spawnPromise(command, args, options) {
return new Promise((resolve, reject) => {
let result = {
pid: null,
error: null,
output: null,
stdout: '',
stderr: '',
status: null,
signal: null
};
this.context.waitForProcessSlot().then((slotId) => {
let commandProcess = this.spawnCommand(command, args, options);
result.pid = commandProcess.pid || 'no-pid';
if (this.debugLoggingEnabled()) {
console.log(`${this.hookName()} spawned ${command} process: ${result.pid}`);
}
commandProcess.stdout.on('data', (data) => { result.stdout += data; });
commandProcess.stderr.on('data', (data) => { result.stderr += data; });
commandProcess.on('close', (code, signal) => {
this.context.releaseProcessSlot(slotId);
// Reject the promise with the named affiance error if we received a SIGINT signal.
if (result.signal === 'SIGINT') {
return reject(AffianceError.error(
AffianceError.InterruptReceived,
'Hook interrupted while running shell command'
));
}
result.output = commandProcess.stdio;
result.status = code;
result.signal = signal;
if (this.debugLoggingEnabled()) {
console.log(`${this.hookName()} closed ${command} process: ${result.pid}`);
}
resolve(result);
});
commandProcess.on('error', (err) => {
this.context.releaseProcessSlot(slotId);
if (this.debugLoggingEnabled()) {
console.log(`${this.hookName()} errored ${command} process: ${result.pid}`);
}
result.error = err;
resolve(result);
});
}, reject);
});
}
debugLoggingEnabled() {
return this._debug || process.env.LOG_LEVEL === 'debug';
}
/**
* Returns the number of processes the hook should use.
*
* @returns {number}
*/
processCount() {
return this.canParallelize() ? this.processors() : this.context.config.concurrency();
}
/**
* Spawns commands concurrently on chunks of files in order
* to achieve better performance while respecting the limit on number of
* spawned child processes.
*
* This works well with hooks who rely on commands that can receive a
* list of files to run against as extra command line arguments.
* This chunks the list of applicable files into a chunk for each
* `processCount`. It then invokes the command asynchronously on each
* chunk of files. Finally, it resolves the returned promise with
* the combined output of each process.
*
* @returns {Promise} a promise wrapping the spawned processes.
* @resolve {SpawnResult} the combined result of the spawned processes
* @rejects {Error} an error thrown or emitted during the process run
*/
spawnPromiseOnApplicableFiles() {
let numCommands = this.processCount();
// Find the size of each chunk of files to process to maximize parallelism
let chunkSize = Math.ceil(this.applicableFiles().length / numCommands);
let fileChunks = _.chunk(this.applicableFiles(), chunkSize);
return new Promise((resolve, reject) => {
// Spawn and gather promises that will resolve when the commands exit
let commandPromises = fileChunks.map((applicableFilesChunk) => {
let commandArgs = _.compact(this.flags().concat(applicableFilesChunk));
return this.spawnPromise(this.command(), commandArgs);
});
// Gather all child process results into a single result object and to
// concatenate output in the order they were run
Promise.all(commandPromises).then((commandResults) => {
let result = {
status: null,
signal: null,
stderr: '',
stdout: ''
};
commandResults.forEach((commandResult) => {
result.status = result.status || commandResult.status || 0;
result.signal = result.signal || commandResult.signal || null;
result.stdout += commandResult.stdout;
result.stderr += commandResult.stderr;
});
// Resolve the promise with the combined result
resolve(result);
}, reject);
});
}
/**
* Returns the configured flags to send to the command
*
* @returns {string[]}
*/
flags() {
return _.compact([].concat(this.config['flags']));
}
/**
* Returns the list of files this hook applies to.
* @returns {string[]} applicable file paths
*/
applicableFiles() {
if (!this._applicableFiles) {
this._applicableFiles = this.selectApplicable(this.context.modifiedFiles());
}
return this._applicableFiles;
}
/**
* Returns the list of files that could possibly be included.
*
* @returns {string[]} included file paths
*/
includedFiles() {
if (!this._includedFiles) {
this._includedFiles = this.selectApplicable(this.context.allFiles());
}
return this._includedFiles;
}
/**
* Select the applicable files out of a list of file paths.
*
* @param {string[]} filePaths - select applicable files out of a list of file paths
* @returns {string[]} the applicable file paths
*/
selectApplicable(filePaths) {
return filePaths.filter((filePath) => {
return this.isApplicable(filePath);
});
}
/**
* Check if a path is applicable to the hook.
* Considers the `include` and `exclude` configuration of the hook.
*
* @param {string} filePath - the absolute path of the file.
* @returns {boolean}
*/
isApplicable(filePath) {
let includes = _.compact(_.flatten([].concat(this.config['include']))).map(fileUtils.convertGlobToAbsolute.bind(fileUtils));
let included = !includes.length;
for (let i in includes) {
if (fileUtils.matchesPath(includes[i], filePath)) {
included = true;
break;
}
}
let excluded = false;
let excludes = _.compact(_.flatten([].concat(this.config['exclude']))).map(fileUtils.convertGlobToAbsolute.bind(fileUtils));
for (let j in excludes) {
if (fileUtils.matchesPath(excludes[j], filePath)) {
excluded = true;
break;
}
}
return (included && !excluded);
}
/**
* Process the raw hook return value and case to a HookResult object.
*
* @param {*} hookReturnValue - the return value of the hook#run method.
* @returns {HookResult}
*/
processHookReturnValue(hookReturnValue) {
// Could be an array of `HookMessage` objects for more complex hooks.
if (Array.isArray(hookReturnValue) &&
(!hookReturnValue.length || hookReturnValue[0] instanceof HookMessage)) {
let messageProcessor = new HookMessageProcessor(
this,
this.config['problemOnUnmodifiedLine'],
this.config['ignoreMessagePattern']
);
return messageProcessor.hookResult(hookReturnValue);
// Could be an array of strings where the first is the status, and the second is the output
} else if (Array.isArray(hookReturnValue) && typeof hookReturnValue[0] === 'string' && hookReturnValue.length === 2){
return { status: hookReturnValue[0], output: hookReturnValue[1] };
// Could be a lonely string that indicates the status
} else if (typeof hookReturnValue === 'string') {
return { status: hookReturnValue };
// Could be a properly formed hookResult object already.
} else {
return hookReturnValue;
}
}
/**
* Check for requirements to run the hook.
* Returns a string of instructions if there are missing requirements.
*
* @returns {string|undefined}
*/
checkForRequirements() {
return this.checkForExecutable() || this.checkForLibraries();
}
/**
* Checks if the required executable is indeed executable.
* Returns a message if something is wrong.
*
* @returns {string|unedefined}
*/
checkForExecutable() {
// If this hook doesn't require an executable, or it is in the path continue
if (!this.requiredExecutable() || utils.isInPath(this.requiredExecutable())) {
return;
}
let output = this.requiredExecutable() + ' is not installed, not in your PATH, ';
output += 'or does not have execute permissions';
output += this.installCommandPrompt();
return output;
}
/**
* Returns the configured instructions to install the command
*
* @returns {string}
*/
installCommandPrompt() {
let installCommand = '';
if (this.context.config.useGlobalNodeModules() && this.config['globalInstallCommand']) {
installCommand = this.config['globalInstallCommand'];
} else {
installCommand = this.config['installCommand'];
}
if (installCommand) {
return `\nInstall it by running ${installCommand}`;
} else {
return '';
}
}
/**
* Ensures referenced node module libraries can be loaded.
* Returns a message if something is wrong.
*
* @returns {string|undefined}
*/
checkForLibraries() {
// If global node modules are being used, do not try to require them.
if (this.context.config.useGlobalNodeModules()) { return; }
let output = [];
this.requiredLibraries().forEach((library) => {
try {
require(library);
} catch(e) {
// Do not swallow any other type of error.
if (e.code !== 'MODULE_NOT_FOUND') {
throw(e);
}
let outputMsg = 'Unable to load "' + library + '"';
outputMsg += this.installCommandPrompt();
output.push(outputMsg);
}
});
if(!output.length) { return; }
return output.join('\n');
}
/**
* Returns the configured required executable
*
* @returns {string|undefined}
*/
requiredExecutable() {
if (this.context.config.useGlobalNodeModules() && this.config['globalRequiredExecutable']) {
return this.config['globalRequiredExecutable'];
} else {
return this.config['requiredExecutable'];
}
}
/**
* Returns the list of required libraries
*
* @returns {string[]}
*/
requiredLibraries() {
if (!this._requiredLibraries) {
let configuredLibraries = this.config['requiredLibrary'] || this.config['requiredLibraries'];
this._requiredLibraries = (configuredLibraries && configuredLibraries.length) ? [].concat(configuredLibraries) : [];
}
return this._requiredLibraries;
}
/**
* The command to run to handle the hook.
*
* @returns {string|undefined}
*/
command() {
return this.config['command'] || this.requiredExecutable();
}
/**
* Transforms the status based on the hook's configuration.
*
* @param {string} status - the status of the hook
* @returns {string}
*/
transformStatus(status) {
switch(status) {
case 'fail':
return this.config['onFail'] || 'fail';
case 'warn':
return this.config['onWarn'] || 'warn';
default:
return status;
}
}
/**
* Delegate a list of method names to the hook's context.
*
* @static
* @param {HookBase} SubClass - A hook subclass
* @param {string[]} contextDelegations - A list of methods to delegate
*/
static delegateToContext(SubClass, contextDelegations) {
contextDelegations.forEach((delegateMethod) => {
SubClass.prototype[delegateMethod] = function() {
return this.context[delegateMethod].apply(this.context, arguments);
};
});
}
};
|
describe('Mobile Navigation', function() {
var toggleButton,
navigation,
e,
html ='<div class="menu">' +
'<a href="" class="navigation-main-button" title="">menu</a>' +
'<nav>' +
'<ul class="navigation-toggle" style="display: none">' +
'<li class="navigation-toggle-item"><a title="" href="" class="active">home</a></li>' +
'</ul>' +
'</nav>' +
'</div>';
function init() {
toggleButton = $('.navigation-main-button'),
navigation = $('.navigation-toggle'),
e = {
preventDefault: sinon.spy(),
data: {
button: toggleButton,
menu: navigation
}
};
}
before(function() {
$('body').append(html);
init();
});
describe('Click on Menu button', function () {
it('Should display navigation', function () {
menu.toggle(e);
expect(toggleButton.hasClass('navigation-main-button--open')).to.be.true;
expect(navigation.hasClass('navigation-toggle--open')).to.be.true;
});
it('Should hide navigation', function () {
menu.toggle(e);
expect(toggleButton.hasClass('navigation-main-button--open')).to.be.false;
expect(navigation.hasClass('navigation-toggle--open')).to.be.false;
});
});
after(function () {
$('.menu').remove();
});
});
|
export default {
caption: 'Comment edit',
'text-caption': 'Text',
'votes-caption': 'Votes',
'moderated-caption': 'Moderated',
'suggestion-caption': 'Address',
'author-caption': 'Author',
'userVotes-caption': 'User votes'
};
|
'use strict'
var tap = require('tap')
var parseAndSend = require('../lib/parseAndSend')
tap.test('it requires a request object', function (test) {
var request = false
var expectedErrorMessage = 'Missing required input: request'
parseAndSend(request, function errorIfMissingOptions (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
|
//dom vars
var $yamlInput = $("#yamlInput");
var $yaqlInput = $("#yaqlInput");
var $exampleDropDown = $("#exampleDropDown");
var $resultArea = $("#result");
var $yaqlAlert = $("#yaqlAlert");
var $yamlAlert = $("#yamlAlert");
//api
//var apiServerString = "http://135.248.18.42:5000";
var apiServerString = "/api";
var apiListExample = "/examples/";
var apiEvaluate = "/evaluate/";
var apiExampleName = "/examples/";
var autoComplete = apiServerString + "/autoComplete/";
var evalReqObj = {
"yaml": "",
"yaql_expression": "",
"legacy": false
};
//methods
/**
* @param args [hitType, eventCategory, eventAction, eventLabel, eventValue]
*/
function ga_send(args) {
if (typeof ga == 'function') {
args.splice(0, 0, 'send');
ga.apply(window, args);
}
}
function contactUs() {
ga_send(['event', 'contact-us', 'contact-us-email']);
window.open('http://www.google.com/recaptcha/mailhide/d?k\07501oEv-WCbjRcvjwi6IYnuxWQ\75\75\46c\75T_zEuodiHDnHFr7SCIDLdl1eZ5DmNKeclK_TNeCB2pg\075', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300');
}
function initDropdown() {
var url = apiServerString + apiListExample;
$.ajax({
url: url,
type: "get",
dataType: "json",
success: function (result) {
var results = result.examples;
$exampleDropDown.select2({data: results});
},
error: function (xhr, status, error) {
//alert(status);
console.error(status);
}
});
}
function toggleError($alertDiv, addError) {
if (addError) {
$alertDiv.parents('.y-container').addClass('has-error');
} else {
$alertDiv.parents('.y-container').removeClass('has-error');
// empty the error
$alertDiv.html("");
}
}
function setYaml(yaml) {
$yamlInput.val(JSON.stringify(yaml, undefined, 4));
}
function selectTextareaLine(tarea, lineNum) {
lineNum--; // array starts at 0
var lines = tarea.value.split("\n");
// calculate start/end
var startPos = 0;
for (var x = 0; x < lines.length; x++) {
if (x == lineNum) {
break;
}
startPos += (lines[x].length + 1);
}
var endPos = lines[lineNum].length + startPos;
// do selection
// Chrome / Firefox
if (typeof(tarea.selectionStart) != "undefined") {
tarea.focus();
tarea.selectionStart = startPos;
tarea.selectionEnd = endPos;
return true;
}
// IE
if (document.selection && document.selection.createRange) {
tarea.focus();
tarea.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
return true;
}
return false;
}
function evaluate(obj) {
var url = apiServerString + apiEvaluate;
toggleError($yaqlAlert, false);
toggleError($yamlAlert, false);
$resultArea.val("");
$.ajax({
url: url,
type: "POST",
crossDomain: false,
data: obj,
dataType: "json",
success: function (result) {
//alert(JSON.stringify(result));
if (result.statusCode > 0) {
$resultArea.val(JSON.stringify(result.value, undefined, 4));
} else {
var errorHandled = false;
if (result.error && result.error.indexOf("YAML") > -1) {
$yamlAlert.html(result.error);
toggleError($yamlAlert, true);
errorHandled = true;
// Check if the error message contains line and column and find the last occurrence
// Example error message:
// Invalid YAML: while parsing a flow mapping in "", line 11, column 9: { ^ expected ',' or '}', but got '' in "", line 16, column 13: "tenantId": "c2edb9de95964f8ca45 ... ^
var pattern = /line (\d*), column (\d*)/gm;
var lastMatch = null;
while (match = pattern.exec(result.error)) {
lastMatch = match;
}
// If there is a line and column in the error message
if (lastMatch != null) {
lineNumber = lastMatch[1];
charNumber = lastMatch[2];
// Select the line
selectTextareaLine(document.getElementById("yamlInput"), lineNumber);
}
}
if (!errorHandled || (result.error && result.error.indexOf("YAQL") > -1)) {
$yaqlAlert.html(result.error);
toggleError($yaqlAlert, true);
}
}
},
error: function (xhr, status, error) {
//alert(status);
console.error(error + " (" + status + ")");
$yaqlAlert.html(error);
toggleError($yaqlAlert, true);
}
});
ga_send(['event', 'evaluate', 'evaluate-yaql', $yaqlInput.val()]);
}
function initYaqlInput() {
$yaqlInput.keyup(function (event) {
if (event.keyCode == 13) {
$("#evaluate").click();
}
if (event.keyCode != 8 && event.keyCode != 32 && event.keyCode != 46 && event.keyCode < 48) {
return;
}
// Cancel the current request and clear future ones
$.ajaxq.abort("yaqlInputKeyupAjaxQueue");
console.log("Sending autocomplete with YAQL expression " + $yaqlInput.val());
toggleError($yaqlAlert, false);
// Add a new AJAX request to the queue
$.ajaxq("yaqlInputKeyupAjaxQueue", {
url: autoComplete,
type: "POST",
crossDomain: false,
data: {"yaml": $yamlInput.val(), "yaql_expression": $yaqlInput.val()},
dataType: "json",
success: function (result) {
var suggestions = [];
if (result.statusCode > 0) {
var currentValue = $yaqlInput.val();
var prefix = currentValue.substring(0, currentValue.lastIndexOf("."));
suggestions = result.value.suggestions.map(function (item) {
return prefix + "." + item
});
toggleError($yaqlAlert, result.value.yaql_valid == false);
}
console.log("Suggestions for YAQL expression " + $yaqlInput.val() + " are: " + suggestions);
$yaqlInput.typeahead('destroy');
$yaqlInput.typeahead({source: suggestions, items: 'all', showHintOnFocus: true});
$yaqlInput.focus(); // this fixes dropdown closes on mouseleave
$yaqlInput.typeahead('lookup');
initYaqlInput();
},
error: function (xhr, status, error) {
//alert(status);
console.error(error + " (" + status + ")");
$yaqlAlert.html(error);
toggleError($yaqlAlert, true);
}
});
});
}
function handleFiles() {
var file = $("#fileInput")[0].files[0];
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
$yamlInput.val(evt.target.result);
//setYaml(evt.target.result);
};
reader.onerror = function (evt) {
$yamlAlert.html("error reading file");
};
ga_send(['event', 'yaml-input', 'browse-file']);
}
function initAboutImage(itemId, url) {
var img = new Image(),
container = document.getElementById(itemId);
img.onload = function () { container.appendChild(img); };
img.src = url;
img.alt = "...";
}
$(function () {
$yamlInput = $("#yamlInput");
$yaqlInput = $("#yaqlInput");
$exampleDropDown = $("#exampleDropDown");
$resultArea = $("#result");
$yaqlAlert = $("#yaqlAlert");
$yamlAlert = $("#yamlAlert");
//event handlers
$(document).on('click', '#evaluate', function () {
evalReqObj.yaml = $yamlInput.val();
evalReqObj.yaql_expression = $yaqlInput.val();
evalReqObj.legacy = $("#legacy").prop('checked');
evaluate(evalReqObj);
});
$exampleDropDown.change(function () {
var exampleName = $(this).val();
if (exampleName == "") {
$yamlInput.val("");
return;
}
$yamlInput.prop('readonly', true);
var url = apiServerString + apiExampleName + exampleName;
$.ajax({
url: url,
type: "get",
crossDomain: true,
dataType: "json",
success: function (result) {
//alert(JSON.stringify(result));
//$yamlInput.val(JSON.stringify(result.value, undefined, 4));
setYaml(result.value);
$yamlInput.prop('readonly', false);
},
error: function (xhr, status, error) {
//alert(status);
console.error(status);
$yamlInput.prop('readonly', false);
}
});
ga_send(['event', 'yaml-input', 'example-select', exampleName]);
});
//main
initDropdown();
initYaqlInput();
$("#fileInput").on("change", handleFiles, false);
// Google Analytics (only when running on real website)
if (document.location.hostname.search("yaqluator.com") !== -1) {
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-65411362-3', 'auto');
ga('send', 'pageview');
}
for ( var index = 1; index <= 5; index++ ) {
initAboutImage("imageItem" + index, "static/images/CloudBand-PyKathon-2015_" + index + ".jpg");
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e5c3f03fc4706299f0a1428da4f7c1453b1dcb5987daf3bd90a5929402afaa47
size 630
|
'use strict';
var moment = require('moment');
var _ = require('underscore');
var config = require('../config');
moment.locale('ru');
module.exports = {
moment: moment,
_: _,
config: config
};
|
function kdTree(points, metric, dimensions) {
function Node(obj, d, parent) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.dimension = d;
}
var self = this;
this.root = buildTree(points, 0, null);
function buildTree(points, depth, parent) {
var dim = depth % dimensions.length;
if(points.length == 0) return null;
if(points.length == 1) return new Node(points[0], dim, parent);
points.sort(function(a,b){ return a[dimensions[dim]] - b[dimensions[dim]]; });
var median = Math.floor(points.length/2);
var node = new Node(points[median], dim, parent);
node.left = buildTree(points.slice(0,median), depth+1, node);
node.right = buildTree(points.slice(median+1), depth+1, node);
return node;
}
this.insert = function(point) {
var insertPosition = innerSearch(self.root, null);
if(insertPosition == null) {
self.root = new Node(point, 0, null);
return;
}
var newNode = new Node(point, (insertPosition.dimension+1)%dimensions.length, insertPosition);
var dimension = dimensions[insertPosition.dimension];
if(point[dimension] < insertPosition.obj[dimension]) {
insertPosition.left = newNode;
} else {
insertPosition.right = newNode;
}
function innerSearch(node, parent) {
if(node == null) return parent;
var dimension = dimensions[node.dimension];
if(point[dimension] < node.obj[dimension]) {
return innerSearch(node.left, node);
} else {
return innerSearch(node.right, node);
}
}
}
this.remove = function(point) {
var node = nodeSearch(self.root);
if(node == null) return;
removeNode(node);
function nodeSearch(node) {
if(node == null) return null;
if(node.obj === point) return node;
var dimension = dimensions[node.dimension];
if(point[dimension] < node.obj[dimension]) {
return nodeSearch(node.left, node);
} else {
return nodeSearch(node.right, node);
}
}
function removeNode(node) {
if(node.left == null && node.right == null) {
if(node.parent == null) {
self.root = null;
return;
}
var pDimension = dimensions[node.parent.dimension];
if(node.obj[pDimension] < node.parent.obj[pDimension]) {
node.parent.left = null;
} else {
node.parent.right = null;
}
return;
}
if(node.left != null) {
var nextNode = findMax(node.left, node.dimension);
} else {
var nextNode = findMin(node.right, node.dimension);
}
var nextObj = nextNode.obj;
removeNode(nextNode);
node.obj = nextObj;
function findMax(node, dim) {
if(node == null) return null;
var dimension = dimensions[dim];
if(node.dimension == dim) {
if(node.right != null) return findMax(node.right, dim);
return node;
}
var own = node.obj[dimension]
var left = findMax(node.left, dim);
var right = findMax(node.right, dim);
var max = node;
if(left != null && left.obj[dimension] > own) max = left;
if(right != null && right.obj[dimension] > max.obj[dimension]) max = right;
return max;
}
function findMin(node, dim) {
if(node == null) return null;
var dimension = dimensions[dim];
if(node.dimension == dim) {
if(node.left != null) return findMin(node.left, dim);
return node;
}
var own = node.obj[dimension]
var left = findMin(node.left, dim);
var right = findMin(node.right, dim);
var min = node;
if(left != null && left.obj[dimension] < own) min = left;
if(right != null && right.obj[dimension] < min.obj[dimension]) min = right;
return min;
}
}
}
this.nearest = function(point, maxNodes, maxDistance) {
bestNodes = new BinaryHeap(function(e){ return -e[1]; });
if(maxDistance) {
for(var i=0; i<maxNodes; i++) {
bestNodes.push([null, maxDistance]);
}
}
nearestSearch(self.root);
function nearestSearch(node) {
var bestChild;
var dimension = dimensions[node.dimension];
var ownDistance = metric(point, node.obj);
var linearPoint = {};
for(var i=0; i<dimensions.length; i++) {
if(i == node.dimension) {
linearPoint[dimensions[i]] = point[dimensions[i]];
} else {
linearPoint[dimensions[i]] = node.obj[dimensions[i]];
}
}
var linearDistance = metric(linearPoint, node.obj);
if(node.right == null && node.left == null) {
if(bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
return;
}
if(node.right == null) {
bestChild = node.left;
} else if(node.left == null) {
bestChild = node.right;
} else {
if(point[dimension] < node.obj[dimension]) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
nearestSearch(bestChild);
if(bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
if(bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {
var otherChild;
if(bestChild == node.left) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if(otherChild != null) nearestSearch(otherChild);
}
function saveNode(node, distance) {
bestNodes.push([node, distance]);
if(bestNodes.size() > maxNodes) {
bestNodes.pop();
}
}
}
var result = [];
for(var i=0; i<maxNodes; i++) {
if(bestNodes.content[i][0]) {
result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);
}
}
return result;
}
this.balanceFactor = function() {
return height(self.root)/(Math.log(count(self.root))/Math.log(2));
function height(node) {
if(node == null) return 0;
return Math.max(height(node.left), height(node.right)) + 1;
}
function count(node) {
if(node == null) return 0;
return count(node.left) + count(node.right) + 1;
}
}
// Binary heap implementation from:
// http://eloquentjavascript.net/appendix2.html
function BinaryHeap(scoreFunction){
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
this.content.push(element);
this.bubbleUp(this.content.length - 1);
},
pop: function() {
var result = this.content[0];
var end = this.content.pop();
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
},
peek: function() {
return this.content[0];
},
remove: function(node) {
var len = this.content.length;
for (var i = 0; i < len; i++) {
if (this.content[i] == node) {
var end = this.content.pop();
if (i != len - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node))
this.bubbleUp(i);
else
this.sinkDown(i);
}
return;
}
}
throw new Error("Node not found.");
},
size: function() {
return this.content.length;
},
bubbleUp: function(n) {
var element = this.content[n];
while (n > 0) {
var parentN = Math.floor((n + 1) / 2) - 1,
parent = this.content[parentN];
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
n = parentN;
}
else {
break;
}
}
},
sinkDown: function(n) {
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while(true) {
var child2N = (n + 1) * 2, child1N = child2N - 1;
var swap = null;
if (child1N < length) {
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
if (child1Score < elemScore)
swap = child1N;
}
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score))
swap = child2N;
}
if (swap != null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
else {
break;
}
}
}
};
}
|
/* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses.
language: "en",
timeFormat: 24,
units: "metric",
modules: [
{
module: 'MMM-Hello-Mirror',
position: 'lower_third',
debugging: true,
config: {
// See 'Configuration options' for more information.
language: "pt_br",
voice: "US English Female",
}
},
{
module: 'MMM-Facial-Recognition',
config: {
// 1=LBPH | 2=Fisher | 3=Eigen
recognitionAlgorithm: 1,
// Threshold for the confidence of a recognized face before it's considered a
// positive match. Confidence values below this threshold will be considered
// a positive match because the lower the confidence value, or distance, the
// more confident the algorithm is that the face was correctly detected.
lbphThreshold: 45,
fisherThreshold: 250,
eigenThreshold: 3000,
// force the use of a usb webcam on raspberry pi (on other platforms this is always true automatically)
useUSBCam: false,
// Path to your training xml
trainingFile: 'modules/MMM-Facial-Recognition/training.xml',
// recognition intervall in seconds (smaller number = faster but CPU intens!)
interval: 1,
// Logout delay after last recognition so that a user does not get instantly logged out if he turns away from the mirror for a few seconds
logoutDelay: 15,
// Array with usernames (copy and paste from training script)
users: ['ricardo'],
//Module set used for strangers and if no user is detected
defaultClass: "default",
//Set of modules which should be shown for every user
everyoneClass: "everyone",
// Boolean to toggle welcomeMessage
welcomeMessage: true
}
},
{
module: "alert",
classes: "default everyone",
},
{
module: "updatenotification",
position: "top_bar",
classes: "default everyone",
},
{
module: "clock",
position: "top_right",
classes: "default everyone",
},
{
module: "calendar",
header: "Quero Calendar",
position: "top_right",
classes: "default everyone",
config: {
calendars: [
{
symbol: "calendar-check-o ",
url: "./quero_calendar.ics"
// url: "http://www.calendarlabs.com/templates/ical/US-Holidays.ics"
}
]
}
},
/* {
module: "compliments",
position: "lower_third"
},*/
{
module: "currentweather",
position: "top_left",
classes: "default everyone",
config: {
location: "Sao Jose",
locationID: "3448636", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "c3c41882d0bf0a81513e449b6712c778",
fetchInterval: 600000
}
},
{
module: "weatherforecast",
position: "top_left",
header: "Weather Forecast",
classes: "default everyone",
config: {
location: "Sao Jose",
locationID: "3448636", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "c3c41882d0bf0a81513e449b6712c778",
fetchInterval: 600000
}
},
{
module: "newsfeed",
position: "lower_third",
classes: "default everyone",
config: {
feeds: [
{
title: "QueroNews",
url: "http://feeds.feedburner.com/queroacademy/WqdG"
}
],
showSourceTitle: true,
showPublishDate: true
}
},
{
module: "portugues/cumprimento",
classes: "default everyone",
},
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {module.exports = config;}
|
var config = {
"copy":{
"html":{
"sourceDir": "src/demo",
"sourceFiles": ["index"],
"destinationDir":"demo"
},
"js":{
"sourceDir": null,
"sourceFiles": null,
"destinationDir":null
},
"css":{
"sourceDir":null,
"sourceFiles": null,
"destinationDir":null
},
"json":{
"sourceDir":null,
"sourceFiles": null,
"destinationDir":null
},
"other":{
"sourceDir":null,
"sourceFiles": null,
"destinationDir":null
}
}
};
module.exports = config;
|
"use strict";
/**
* Build test scenario (HTML, JS).
*/
var Build = require("../../util/build");
var build = module.exports = new Build({
rootDir: __dirname
});
if (require.main === module) {
build.run();
}
|
import { helper } from '@ember/component/helper';
export function combineValidators(validators) {
return validators.reduce((previousValidator, currentValidator) => (
(value) => {
const currentValidatorResult = currentValidator(value);
return currentValidatorResult === true ? previousValidator(value) : currentValidatorResult;
}
), () => true);
}
export default helper(combineValidators);
|
version https://git-lfs.github.com/spec/v1
oid sha256:ebc11e1ae16df1e29d5533fb898179a70498b57bede817f326e9c1bcaf6aaa26
size 8846
|
import React from "react";
// import fetch from "isomorphic-fetch";
// lets us dispatch() functions from API calls
import thunkMiddleware from "redux-thunk";
// neat middleware that logs actions
import { createLogger } from "redux-logger";
import { render } from "react-dom";
import { Provider } from 'react-redux';
import "./styles/todo.scss";
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter } from 'react-router-dom';
// import { addTodo, deleteTodo, toggleTodo, changeVisibity, setIsFetching } from "./actions/actionsCreators"
import { todoApp } from './reducers/reducer'
import { AppComponent } from './components/app';
import runtime from 'serviceworker-webpack-plugin/lib/runtime';
let loggerMiddleware = createLogger();
let store = createStore(todoApp, applyMiddleware(
loggerMiddleware,
thunkMiddleware
));
render(
<Provider store={store}>
<BrowserRouter>
<AppComponent />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
if ('serviceWorker' in navigator) {
runtime.register();
}
|
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
var base = grunt.option('base') || '.';
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * http://lab.hakim.se/reveal-js\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) 2016 Hakim El Hattab, http://hakim.se\n' +
' */'
},
qunit: {
files: [ 'test/*.html' ]
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
src: 'js/reveal.js',
dest: 'js/reveal.min.js'
}
},
sass: {
core: {
files: {
'css/reveal.css': 'css/reveal.scss',
}
},
themes: {
files: [
{
expand: true,
cwd: 'css/theme/source',
src: ['*.scss'],
dest: 'css/theme',
ext: '.css'
}
]
}
},
autoprefixer: {
core: {
src: 'css/reveal.css'
},
themes: {
src: 'css/theme/*.css'
}
},
cssmin: {
compress: {
files: {
'css/reveal.min.css': [ 'css/reveal.css' ]
}
}
},
jshint: {
options: {
curly: false,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
expr: true,
globals: {
head: false,
module: false,
console: false,
unescape: false,
define: false,
exports: false
}
},
files: [ 'Gruntfile.js', 'js/reveal.js' ]
},
connect: {
server: {
options: {
port: port,
base: base,
livereload: true,
open: true
}
}
},
zip: {
'reveal-js-presentation.zip': [
'index.html',
'css/**',
'js/**',
'lib/**',
'images/**',
'plugin/**',
'**.md'
]
},
watch: {
js: {
files: [ 'Gruntfile.js', 'js/reveal.js' ],
tasks: 'js'
},
theme: {
files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
tasks: 'css-themes'
},
css: {
files: [ 'css/reveal.scss' ],
tasks: 'css-core'
},
html: {
files: [ '*.html']
},
markdown: {
files: [ '*.md' ]
},
options: {
livereload: true
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks( 'grunt-sass' );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-autoprefixer' );
grunt.loadNpmTasks( 'grunt-zip' );
// Default task
grunt.registerTask( 'default', [ 'css', 'js' ] );
// JS task
grunt.registerTask( 'js', [ 'jshint', 'uglify', 'qunit' ] );
// Theme CSS
grunt.registerTask( 'css-themes', [ 'sass:themes', 'autoprefixer:themes' ] );
// Core framework CSS
grunt.registerTask( 'css-core', [ 'sass:core', 'autoprefixer:core', 'cssmin' ] );
// All CSS
grunt.registerTask( 'css', [ 'sass', 'autoprefixer', 'cssmin' ] );
// Package presentation to archive
grunt.registerTask( 'package', [ 'default', 'zip' ] );
// Serve presentation locally
grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
// Run tests
grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
};
|
import { AUTO_COMPLETE } from '../actions/index'
const INITIAL_STATE = {
locations: []
}
export default function(state = INITIAL_STATE, action) {
switch(action.type){
case AUTO_COMPLETE:
console.log('action recieved for AUTO COMPLETE', action.payload.RESULTS)
return {...state, locations: [action.payload.results]}
default:
return state
}
}
|
'use strict';
// Uncomment the following lines to use the react test utilities
// import React from 'react/addons';
// const TestUtils = React.addons.TestUtils;
import createComponent from 'helpers/createComponent';
import Results from 'components/Results.js';
describe('Results', () => {
let ResultsComponent;
beforeEach(() => {
ResultsComponent = createComponent(Results);
});
it('should have its component name as default className', () => {
expect(ResultsComponent._store.props.className).toBe('Results');
});
});
|
//运行命令:fis3 release
//js md5
fis.match('/js/**.js', {
useHash: true
});
//css md5
fis.match('/css/**.css', {
useHash: true
});
//image md5
fis.match('/css/**.{svg,tif,tiff,wbmp,png,bmp,fax,gif,ico,jfif,jpe,jpeg,jpg,woff,cur}', {
useHash: true
});
fis.match('*', {
useCache: false,
deploy: fis.plugin('local-deliver', {
to: './build'
})
});
fis.match('/build/**', {
release: false
});
|
define("ghost/adapters/application",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ghostPaths = __dependency1__["default"];
var ApplicationAdapter = DS.RESTAdapter.extend({
host: window.location.origin,
namespace: ghostPaths().apiRoot.slice(1),
findQuery: function (store, type, query) {
var id;
if (query.id) {
id = query.id;
delete query.id;
}
return this.ajax(this.buildURL(type.typeKey, id), 'GET', {data: query});
},
buildURL: function (type, id) {
// Ensure trailing slashes
var url = this._super(type, id);
if (url.slice(-1) !== '/') {
url += '/';
}
return url;
},
// Override deleteRecord to disregard the response body on 2xx responses.
// This is currently needed because the API is returning status 200 along
// with the JSON object for the deleted entity and Ember expects an empty
// response body for successful DELETEs.
// Non-2xx (failure) responses will still work correctly as Ember will turn
// them into rejected promises.
deleteRecord: function () {
var response = this._super.apply(this, arguments);
return response.then(function () {
return null;
});
}
});
__exports__["default"] = ApplicationAdapter;
});
define("ghost/adapters/embedded-relation-adapter",
["ghost/adapters/application","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ApplicationAdapter = __dependency1__["default"];
// EmbeddedRelationAdapter will augment the query object in calls made to
// DS.Store#find, findQuery, and findAll with the correct "includes"
// (?include=relatedType) by introspecting on the provided subclass of the DS.Model.
//
// Example:
// If a model has an embedded hasMany relation, the related type will be included:
// roles: DS.hasMany('role', { embedded: 'always' }) => ?include=roles
var EmbeddedRelationAdapter = ApplicationAdapter.extend({
find: function (store, type, id) {
return this.findQuery(store, type, this.buildQuery(store, type, id));
},
findQuery: function (store, type, query) {
return this._super(store, type, this.buildQuery(store, type, query));
},
findAll: function (store, type, sinceToken) {
return this.findQuery(store, type, this.buildQuery(store, type, sinceToken));
},
buildQuery: function (store, type, options) {
var model,
toInclude = [],
query = {},
deDupe = {};
// Get the class responsible for creating records of this type
model = store.modelFor(type);
// Iterate through the model's relationships and build a list
// of those that need to be pulled in via "include" from the API
model.eachRelationship(function (name, meta) {
if (meta.kind === 'hasMany' &&
Object.prototype.hasOwnProperty.call(meta.options, 'embedded') &&
meta.options.embedded === 'always') {
toInclude.push(name);
}
});
if (toInclude.length) {
// If this is a find by id, build a query object and attach the includes
if (typeof options === 'string' || typeof options === 'number') {
query.id = options;
query.include = toInclude.join(',');
} else if (typeof options === 'object' || Ember.isNone(options)) {
// If this is a find all (no existing query object) build one and attach
// the includes.
// If this is a find with an existing query object then merge the includes
// into the existing object. Existing properties and includes are preserved.
query = options || query;
toInclude = toInclude.concat(query.include ? query.include.split(',') : []);
toInclude.forEach(function (include) {
deDupe[include] = true;
});
query.include = Object.keys(deDupe).join(',');
}
}
return query;
}
});
__exports__["default"] = EmbeddedRelationAdapter;
});
define("ghost/adapters/post",
["ghost/adapters/embedded-relation-adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EmbeddedRelationAdapter = __dependency1__["default"];
var PostAdapter = EmbeddedRelationAdapter.extend({
createRecord: function (store, type, record) {
var data = {},
serializer = store.serializerFor(type.typeKey),
url = this.buildURL(type.typeKey);
// make the server return with the tags embedded
url = url + '?include=tags';
// use the PostSerializer to transform the model back into
// an array with a post object like the API expects
serializer.serializeIntoHash(data, type, record);
return this.ajax(url, 'POST', {data: data});
},
updateRecord: function (store, type, record) {
var data = {},
serializer = store.serializerFor(type.typeKey),
id = Ember.get(record, 'id'),
url = this.buildURL(type.typeKey, id);
// make the server return with the tags embedded
url = url + '?include=tags';
// use the PostSerializer to transform the model back into
// an array of posts objects like the API expects
serializer.serializeIntoHash(data, type, record);
// use the ApplicationAdapter's buildURL method
return this.ajax(url, 'PUT', {data: data});
}
});
__exports__["default"] = PostAdapter;
});
define("ghost/adapters/setting",
["ghost/adapters/application","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ApplicationAdapter = __dependency1__["default"];
var SettingAdapter = ApplicationAdapter.extend({
updateRecord: function (store, type, record) {
var data = {},
serializer = store.serializerFor(type.typeKey);
// remove the fake id that we added onto the model.
delete record.id;
// use the SettingSerializer to transform the model back into
// an array of settings objects like the API expects
serializer.serializeIntoHash(data, type, record);
// use the ApplicationAdapter's buildURL method but do not
// pass in an id.
return this.ajax(this.buildURL(type.typeKey), 'PUT', {data: data});
}
});
__exports__["default"] = SettingAdapter;
});
define("ghost/adapters/user",
["ghost/adapters/embedded-relation-adapter","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EmbeddedRelationAdapter = __dependency1__["default"];
var UserAdapter = EmbeddedRelationAdapter.extend({
createRecord: function (store, type, record) {
var data = {},
serializer = store.serializerFor(type.typeKey),
url = this.buildURL(type.typeKey);
// Ask the API to include full role objects in its response
url += '?include=roles';
// Use the UserSerializer to transform the model back into
// an array of user objects like the API expects
serializer.serializeIntoHash(data, type, record);
// Use the url from the ApplicationAdapter's buildURL method
return this.ajax(url, 'POST', {data: data});
},
updateRecord: function (store, type, record) {
var data = {},
serializer = store.serializerFor(type.typeKey),
id = Ember.get(record, 'id'),
url = this.buildURL(type.typeKey, id);
// Ask the API to include full role objects in its response
url += '?include=roles';
// Use the UserSerializer to transform the model back into
// an array of user objects like the API expects
serializer.serializeIntoHash(data, type, record);
// Use the url from the ApplicationAdapter's buildURL method
return this.ajax(url, 'PUT', {data: data});
},
find: function (store, type, id) {
var url = this.buildQuery(store, type, id);
url.status = 'all';
return this.findQuery(store, type, url);
}
});
__exports__["default"] = UserAdapter;
});
define("ghost/app",
["ember/resolver","ember/load-initializers","ghost/utils/link-view","ghost/utils/text-field","ghost/config","ghost/helpers/ghost-paths","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __exports__) {
"use strict";
var Resolver = __dependency1__["default"];
var loadInitializers = __dependency2__["default"];
var configureApp = __dependency5__["default"];
var ghostPathsHelper = __dependency6__["default"];
Ember.MODEL_FACTORY_INJECTIONS = true;
var App = Ember.Application.extend({
modulePrefix: 'ghost',
Resolver: Resolver['default']
});
// Runtime configuration of Ember.Application
configureApp(App);
loadInitializers(App, 'ghost');
Ember.Handlebars.registerHelper('gh-path', ghostPathsHelper);
__exports__["default"] = App;
});
define("ghost/assets/lib/touch-editor",
["exports"],
function(__exports__) {
"use strict";
var createTouchEditor = function createTouchEditor() {
var noop = function () {},
TouchEditor;
TouchEditor = function (el, options) {
/*jshint unused:false*/
this.textarea = el;
this.win = {document: this.textarea};
this.ready = true;
this.wrapping = document.createElement('div');
var textareaParent = this.textarea.parentNode;
this.wrapping.appendChild(this.textarea);
textareaParent.appendChild(this.wrapping);
this.textarea.style.opacity = 1;
};
TouchEditor.prototype = {
setOption: function (type, handler) {
if (type === 'onChange') {
$(this.textarea).change(handler);
}
},
eachLine: function () {
return [];
},
getValue: function () {
return this.textarea.value;
},
setValue: function (code) {
this.textarea.value = code;
},
focus: noop,
getCursor: function () {
return {line: 0, ch: 0};
},
setCursor: noop,
currentLine: function () {
return 0;
},
cursorPosition: function () {
return {character: 0};
},
addMarkdown: noop,
nthLine: noop,
refresh: noop,
selectLines: noop,
on: noop,
off: noop
};
return TouchEditor;
};
__exports__["default"] = createTouchEditor;
});
define("ghost/assets/lib/uploader",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ghostPaths = __dependency1__["default"];
var UploadUi,
upload,
Ghost = ghostPaths();
UploadUi = function ($dropzone, settings) {
var $url = '<div class="js-url"><input class="url js-upload-url" type="url" placeholder="http://"/></div>',
$cancel = '<a class="image-cancel js-cancel" title="Delete"><span class="hidden">Delete</span></a>',
$progress = $('<div />', {
class: 'js-upload-progress progress progress-success active',
role: 'progressbar',
'aria-valuemin': '0',
'aria-valuemax': '100'
}).append($('<div />', {
class: 'js-upload-progress-bar bar',
style: 'width:0%'
}));
$.extend(this, {
complete: function (result) {
var self = this;
function showImage(width, height) {
$dropzone.find('img.js-upload-target').attr({width: width, height: height}).css({display: 'block'});
$dropzone.find('.fileupload-loading').remove();
$dropzone.css({height: 'auto'});
$dropzone.delay(250).animate({opacity: 100}, 1000, function () {
$('.js-button-accept').prop('disabled', false);
self.init();
});
}
function animateDropzone($img) {
$dropzone.animate({opacity: 0}, 250, function () {
$dropzone.removeClass('image-uploader').addClass('pre-image-uploader');
$dropzone.css({minHeight: 0});
self.removeExtras();
$dropzone.animate({height: $img.height()}, 250, function () {
showImage($img.width(), $img.height());
});
});
}
function preLoadImage() {
var $img = $dropzone.find('img.js-upload-target')
.attr({src: '', width: 'auto', height: 'auto'});
$progress.animate({opacity: 0}, 250, function () {
$dropzone.find('span.media').after('<img class="fileupload-loading" src="' + Ghost.subdir + '/ghost/img/loadingcat.gif" />');
if (!settings.editor) {$progress.find('.fileupload-loading').css({top: '56px'}); }
});
$dropzone.trigger('uploadsuccess', [result]);
$img.one('load', function () {
animateDropzone($img);
}).attr('src', result);
}
preLoadImage();
},
bindFileUpload: function () {
var self = this;
$dropzone.find('.js-fileupload').fileupload().fileupload('option', {
url: Ghost.apiRoot + '/uploads/',
add: function (e, data) {
/*jshint unused:false*/
$('.js-button-accept').prop('disabled', true);
$dropzone.find('.js-fileupload').removeClass('right');
$dropzone.find('.js-url').remove();
$progress.find('.js-upload-progress-bar').removeClass('fail');
$dropzone.trigger('uploadstart', [$dropzone.attr('id')]);
$dropzone.find('span.media, div.description, a.image-url, a.image-webcam')
.animate({opacity: 0}, 250, function () {
$dropzone.find('div.description').hide().css({opacity: 100});
if (settings.progressbar) {
$dropzone.find('div.js-fail').after($progress);
$progress.animate({opacity: 100}, 250);
}
data.submit();
});
},
dropZone: settings.fileStorage ? $dropzone : null,
progressall: function (e, data) {
/*jshint unused:false*/
var progress = parseInt(data.loaded / data.total * 100, 10);
if (!settings.editor) {$progress.find('div.js-progress').css({position: 'absolute', top: '40px'}); }
if (settings.progressbar) {
$dropzone.trigger('uploadprogress', [progress, data]);
$progress.find('.js-upload-progress-bar').css('width', progress + '%');
}
},
fail: function (e, data) {
/*jshint unused:false*/
$('.js-button-accept').prop('disabled', false);
$dropzone.trigger('uploadfailure', [data.result]);
$dropzone.find('.js-upload-progress-bar').addClass('fail');
if (data.jqXHR.status === 413) {
$dropzone.find('div.js-fail').text('The image you uploaded was larger than the maximum file size your server allows.');
} else if (data.jqXHR.status === 415) {
$dropzone.find('div.js-fail').text('The image type you uploaded is not supported. Please use .PNG, .JPG, .GIF, .SVG.');
} else {
$dropzone.find('div.js-fail').text('Something went wrong :(');
}
$dropzone.find('div.js-fail, button.js-fail').fadeIn(1500);
$dropzone.find('button.js-fail').on('click', function () {
$dropzone.css({minHeight: 0});
$dropzone.find('div.description').show();
self.removeExtras();
self.init();
});
},
done: function (e, data) {
/*jshint unused:false*/
self.complete(data.result);
}
});
},
buildExtras: function () {
if (!$dropzone.find('span.media')[0]) {
$dropzone.prepend('<span class="media"><span class="hidden">Image Upload</span></span>');
}
if (!$dropzone.find('div.description')[0]) {
$dropzone.append('<div class="description">Add image</div>');
}
if (!$dropzone.find('div.js-fail')[0]) {
$dropzone.append('<div class="js-fail failed" style="display: none">Something went wrong :(</div>');
}
if (!$dropzone.find('button.js-fail')[0]) {
$dropzone.append('<button class="js-fail btn btn-green" style="display: none">Try Again</button>');
}
if (!$dropzone.find('a.image-url')[0]) {
$dropzone.append('<a class="image-url" title="Add image from URL"><span class="hidden">URL</span></a>');
}
// if (!$dropzone.find('a.image-webcam')[0]) {
// $dropzone.append('<a class="image-webcam" title="Add image from webcam"><span class="hidden">Webcam</span></a>');
// }
},
removeExtras: function () {
$dropzone.find('span.media, div.js-upload-progress, a.image-url, a.image-upload, a.image-webcam, div.js-fail, button.js-fail, a.js-cancel').remove();
},
initWithDropzone: function () {
var self = this;
// This is the start point if no image exists
$dropzone.find('img.js-upload-target').css({display: 'none'});
$dropzone.removeClass('pre-image-uploader image-uploader-url').addClass('image-uploader');
this.removeExtras();
this.buildExtras();
this.bindFileUpload();
if (!settings.fileStorage) {
self.initUrl();
return;
}
$dropzone.find('a.image-url').on('click', function () {
self.initUrl();
});
},
initUrl: function () {
var self = this, val;
this.removeExtras();
$dropzone.addClass('image-uploader-url').removeClass('pre-image-uploader');
$dropzone.find('.js-fileupload').addClass('right');
if (settings.fileStorage) {
$dropzone.append($cancel);
}
$dropzone.find('.js-cancel').on('click', function () {
$dropzone.find('.js-url').remove();
$dropzone.find('.js-fileupload').removeClass('right');
self.removeExtras();
self.initWithDropzone();
});
$dropzone.find('div.description').before($url);
if (settings.editor) {
$dropzone.find('div.js-url').append('<button class="btn btn-blue js-button-accept">Save</button>');
}
$dropzone.find('.js-button-accept').on('click', function () {
val = $dropzone.find('.js-upload-url').val();
$dropzone.find('div.description').hide();
$dropzone.find('.js-fileupload').removeClass('right');
$dropzone.find('.js-url').remove();
if (val === '') {
$dropzone.trigger('uploadsuccess', 'http://');
self.initWithDropzone();
} else {
self.complete(val);
}
});
// Only show the toggle icon if there is a dropzone mode to go back to
if (settings.fileStorage !== false) {
$dropzone.append('<a class="image-upload" title="Add image"><span class="hidden">Upload</span></a>');
}
$dropzone.find('a.image-upload').on('click', function () {
$dropzone.find('.js-url').remove();
$dropzone.find('.js-fileupload').removeClass('right');
self.initWithDropzone();
});
},
initWithImage: function () {
var self = this;
// This is the start point if an image already exists
$dropzone.removeClass('image-uploader image-uploader-url').addClass('pre-image-uploader');
$dropzone.find('div.description').hide();
$dropzone.append($cancel);
$dropzone.find('.js-cancel').on('click', function () {
$dropzone.find('img.js-upload-target').attr({src: ''});
$dropzone.find('div.description').show();
$dropzone.delay(2500).animate({opacity: 100}, 1000, function () {
self.init();
});
$dropzone.trigger('uploadsuccess', 'http://');
self.initWithDropzone();
});
},
init: function () {
var imageTarget = $dropzone.find('img.js-upload-target');
// First check if field image is defined by checking for js-upload-target class
if (!imageTarget[0]) {
// This ensures there is an image we can hook into to display uploaded image
$dropzone.prepend('<img class="js-upload-target" style="display: none" src="" />');
}
$('.js-button-accept').prop('disabled', false);
if (imageTarget.attr('src') === '' || imageTarget.attr('src') === undefined) {
this.initWithDropzone();
} else {
this.initWithImage();
}
}
});
};
upload = function (options) {
var settings = $.extend({
progressbar: true,
editor: false,
fileStorage: true
}, options);
return this.each(function () {
var $dropzone = $(this),
ui;
ui = new UploadUi($dropzone, settings);
ui.init();
});
};
__exports__["default"] = upload;
});
define("ghost/components/gh-activating-list-item",
["exports"],
function(__exports__) {
"use strict";
var ActivatingListItem = Ember.Component.extend({
tagName: 'li',
classNameBindings: ['active'],
active: false
});
__exports__["default"] = ActivatingListItem;
});
define("ghost/components/gh-codemirror",
["ghost/mixins/marker-manager","ghost/utils/codemirror-mobile","ghost/utils/set-scroll-classname","ghost/utils/codemirror-shortcuts","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/*global CodeMirror */
var MarkerManager = __dependency1__["default"];
var mobileCodeMirror = __dependency2__["default"];
var setScrollClassName = __dependency3__["default"];
var codeMirrorShortcuts = __dependency4__["default"];
var onChangeHandler,
onScrollHandler,
Codemirror;
codeMirrorShortcuts.init();
onChangeHandler = function (cm, changeObj) {
var line,
component = cm.component;
// fill array with a range of numbers
for (line = changeObj.from.line; line < changeObj.from.line + changeObj.text.length; line += 1) {
component.checkLine.call(component, line, changeObj.origin);
}
// Is this a line which may have had a marker on it?
component.checkMarkers.call(component);
cm.component.set('value', cm.getValue());
component.sendAction('typingPause');
};
onScrollHandler = function (cm) {
var scrollInfo = cm.getScrollInfo(),
component = cm.component;
scrollInfo.codemirror = cm;
// throttle scroll updates
component.throttle = Ember.run.throttle(component, function () {
this.set('scrollInfo', scrollInfo);
}, 10);
};
Codemirror = Ember.TextArea.extend(MarkerManager, {
focus: true,
focusCursorAtEnd: false,
setFocus: function () {
if (this.get('focus')) {
this.$().val(this.$().val()).focus();
}
}.on('didInsertElement'),
didInsertElement: function () {
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
},
afterRenderEvent: function () {
var self = this,
codemirror;
// replaces CodeMirror with TouchEditor only if we're on mobile
mobileCodeMirror.createIfMobile();
codemirror = this.initCodemirror();
this.set('codemirror', codemirror);
this.sendAction('setCodeMirror', this);
if (this.get('focus') && this.get('focusCursorAtEnd')) {
codemirror.execCommand('goDocEnd');
}
codemirror.eachLine(function initMarkers() {
self.initMarkers.apply(self, arguments);
});
},
// this needs to be placed on the 'afterRender' queue otherwise CodeMirror gets wonky
initCodemirror: function () {
// create codemirror
var codemirror,
self = this;
codemirror = CodeMirror.fromTextArea(this.get('element'), {
mode: 'gfm',
tabMode: 'indent',
tabindex: '2',
cursorScrollMargin: 10,
lineWrapping: true,
dragDrop: false,
extraKeys: {
Home: 'goLineLeft',
End: 'goLineRight',
'Ctrl-U': false,
'Cmd-U': false,
'Shift-Ctrl-U': false,
'Shift-Cmd-U': false,
'Ctrl-S': false,
'Cmd-S': false,
'Ctrl-D': false,
'Cmd-D': false
}
});
// Codemirror needs a reference to the component
// so that codemirror originating events can propogate
// up the ember action pipeline
codemirror.component = this;
// propagate changes to value property
codemirror.on('change', onChangeHandler);
// on scroll update scrollPosition property
codemirror.on('scroll', onScrollHandler);
codemirror.on('scroll', Ember.run.bind(Ember.$('.CodeMirror-scroll'), setScrollClassName, {
target: Ember.$('.js-entry-markdown'),
offset: 10
}));
codemirror.on('focus', function () {
self.sendAction('onFocusIn');
});
return codemirror;
},
disableCodeMirror: function () {
var codemirror = this.get('codemirror');
codemirror.setOption('readOnly', 'nocursor');
codemirror.off('change', onChangeHandler);
},
enableCodeMirror: function () {
var codemirror = this.get('codemirror');
codemirror.setOption('readOnly', false);
// clicking the trash button on an image dropzone causes this function to fire.
// this line is a hack to prevent multiple event handlers from being attached.
codemirror.off('change', onChangeHandler);
codemirror.on('change', onChangeHandler);
},
removeThrottle: function () {
Ember.run.cancel(this.throttle);
}.on('willDestroyElement'),
removeCodemirrorHandlers: function () {
// not sure if this is needed.
var codemirror = this.get('codemirror');
codemirror.off('change', onChangeHandler);
codemirror.off('scroll');
}.on('willDestroyElement'),
clearMarkerManagerMarkers: function () {
this.clearMarkers();
}.on('willDestroyElement')
});
__exports__["default"] = Codemirror;
});
define("ghost/components/gh-dropdown-button",
["ghost/mixins/dropdown-mixin","exports"],
function(__dependency1__, __exports__) {
"use strict";
var DropdownMixin = __dependency1__["default"];
var DropdownButton = Ember.Component.extend(DropdownMixin, {
tagName: 'button',
// matches with the dropdown this button toggles
dropdownName: null,
// Notify dropdown service this dropdown should be toggled
click: function (event) {
this._super(event);
this.get('dropdown').toggleDropdown(this.get('dropdownName'), this);
}
});
__exports__["default"] = DropdownButton;
});
define("ghost/components/gh-dropdown",
["ghost/mixins/dropdown-mixin","exports"],
function(__dependency1__, __exports__) {
"use strict";
var DropdownMixin = __dependency1__["default"];
var GhostDropdown = Ember.Component.extend(DropdownMixin, {
classNames: 'ghost-dropdown',
name: null,
closeOnClick: false,
// Helps track the user re-opening the menu while it's fading out.
closing: false,
// Helps track whether the dropdown is open or closes, or in a transition to either
isOpen: false,
// Managed the toggle between the fade-in and fade-out classes
fadeIn: Ember.computed('isOpen', 'closing', function () {
return this.get('isOpen') && !this.get('closing');
}),
classNameBindings: ['fadeIn:fade-in-scale:fade-out', 'isOpen:open:closed'],
open: function () {
this.set('isOpen', true);
this.set('closing', false);
this.set('button.isOpen', true);
},
close: function () {
var self = this;
this.set('closing', true);
if (this.get('button')) {
this.set('button.isOpen', false);
}
this.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
if (event.originalEvent.animationName === 'fade-out') {
if (self.get('closing')) {
self.set('isOpen', false);
self.set('closing', false);
}
}
});
},
// Called by the dropdown service when any dropdown button is clicked.
toggle: function (options) {
var isClosing = this.get('closing'),
isOpen = this.get('isOpen'),
name = this.get('name'),
button = this.get('button'),
targetDropdownName = options.target;
if (name === targetDropdownName && (!isOpen || isClosing)) {
if (!button) {
button = options.button;
this.set('button', button);
}
this.open();
} else if (isOpen) {
this.close();
}
},
click: function (event) {
this._super(event);
if (this.get('closeOnClick')) {
return this.close();
}
},
didInsertElement: function () {
this._super();
var dropdownService = this.get('dropdown');
dropdownService.on('close', this, this.close);
dropdownService.on('toggle', this, this.toggle);
},
willDestroyElement: function () {
this._super();
var dropdownService = this.get('dropdown');
dropdownService.off('close', this, this.close);
dropdownService.off('toggle', this, this.toggle);
}
});
__exports__["default"] = GhostDropdown;
});
define("ghost/components/gh-file-upload",
["exports"],
function(__exports__) {
"use strict";
var FileUpload = Ember.Component.extend({
_file: null,
uploadButtonText: 'Text',
uploadButtonDisabled: true,
change: function (event) {
this.set('uploadButtonDisabled', false);
this.sendAction('onAdd');
this._file = event.target.files[0];
},
onUpload: 'onUpload',
actions: {
upload: function () {
if (!this.uploadButtonDisabled && this._file) {
this.sendAction('onUpload', this._file);
}
// Prevent double post by disabling the button.
this.set('uploadButtonDisabled', true);
}
}
});
__exports__["default"] = FileUpload;
});
define("ghost/components/gh-form",
["exports"],
function(__exports__) {
"use strict";
var Form = Ember.View.extend({
tagName: 'form',
attributeBindings: ['enctype'],
reset: function () {
this.$().get(0).reset();
},
didInsertElement: function () {
this.get('controller').on('reset', this, this.reset);
},
willClearRender: function () {
this.get('controller').off('reset', this, this.reset);
}
});
__exports__["default"] = Form;
});
define("ghost/components/gh-input",
["ghost/mixins/text-input","exports"],
function(__dependency1__, __exports__) {
"use strict";
var TextInputMixin = __dependency1__["default"];
var Input = Ember.TextField.extend(TextInputMixin);
__exports__["default"] = Input;
});
define("ghost/components/gh-markdown",
["ghost/assets/lib/uploader","exports"],
function(__dependency1__, __exports__) {
"use strict";
var uploader = __dependency1__["default"];
var Markdown = Ember.Component.extend({
didInsertElement: function () {
this.set('scrollWrapper', this.$().closest('.entry-preview-content'));
},
adjustScrollPosition: function () {
var scrollWrapper = this.get('scrollWrapper'),
scrollPosition = this.get('scrollPosition');
scrollWrapper.scrollTop(scrollPosition);
}.observes('scrollPosition'),
// fire off 'enable' API function from uploadManager
// might need to make sure markdown has been processed first
reInitDropzones: function () {
function handleDropzoneEvents() {
var dropzones = $('.js-drop-zone');
uploader.call(dropzones, {
editor: true,
fileStorage: this.get('config.fileStorage')
});
dropzones.on('uploadstart', Ember.run.bind(this, 'sendAction', 'uploadStarted'));
dropzones.on('uploadfailure', Ember.run.bind(this, 'sendAction', 'uploadFinished'));
dropzones.on('uploadsuccess', Ember.run.bind(this, 'sendAction', 'uploadFinished'));
dropzones.on('uploadsuccess', Ember.run.bind(this, 'sendAction', 'uploadSuccess'));
}
Ember.run.scheduleOnce('afterRender', this, handleDropzoneEvents);
}.observes('markdown')
});
__exports__["default"] = Markdown;
});
define("ghost/components/gh-modal-dialog",
["exports"],
function(__exports__) {
"use strict";
var ModalDialog = Ember.Component.extend({
didInsertElement: function () {
this.$('.js-modal-container').fadeIn(50);
this.$('.js-modal-background').show().fadeIn(10, function () {
$(this).addClass('in');
});
this.$('.js-modal').addClass('in');
},
willDestroyElement: function () {
this.$('.js-modal').removeClass('in');
this.$('.js-modal-background').removeClass('in');
return this._super();
},
confirmaccept: 'confirmAccept',
confirmreject: 'confirmReject',
actions: {
closeModal: function () {
this.sendAction();
},
confirm: function (type) {
this.sendAction('confirm' + type);
this.sendAction();
}
},
klass: Ember.computed('type', 'style', 'animation', function () {
var classNames = [];
classNames.push(this.get('type') ? 'modal-' + this.get('type') : 'modal');
if (this.get('style')) {
this.get('style').split(',').forEach(function (style) {
classNames.push('modal-style-' + style);
});
}
classNames.push(this.get('animation'));
return classNames.join(' ');
}),
acceptButtonClass: Ember.computed('confirm.accept.buttonClass', function () {
return this.get('confirm.accept.buttonClass') ? this.get('confirm.accept.buttonClass') : 'btn btn-green';
}),
rejectButtonClass: Ember.computed('confirm.reject.buttonClass', function () {
return this.get('confirm.reject.buttonClass') ? this.get('confirm.reject.buttonClass') : 'btn btn-red';
})
});
__exports__["default"] = ModalDialog;
});
define("ghost/components/gh-notification",
["exports"],
function(__exports__) {
"use strict";
var NotificationComponent = Ember.Component.extend({
classNames: ['js-bb-notification'],
typeClass: Ember.computed(function () {
var classes = '',
message = this.get('message'),
type,
dismissible;
// Check to see if we're working with a DS.Model or a plain JS object
if (typeof message.toJSON === 'function') {
type = message.get('type');
dismissible = message.get('dismissible');
} else {
type = message.type;
dismissible = message.dismissible;
}
classes += 'notification-' + type;
if (type === 'success' && dismissible !== false) {
classes += ' notification-passive';
}
return classes;
}),
didInsertElement: function () {
var self = this;
self.$().on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function (event) {
/* jshint unused: false */
if (event.originalEvent.animationName === 'fade-out') {
self.notifications.removeObject(self.get('message'));
}
});
},
actions: {
closeNotification: function () {
var self = this;
self.notifications.closeNotification(self.get('message'));
}
}
});
__exports__["default"] = NotificationComponent;
});
define("ghost/components/gh-notifications",
["exports"],
function(__exports__) {
"use strict";
var NotificationsComponent = Ember.Component.extend({
tagName: 'aside',
classNames: 'notifications',
classNameBindings: ['location'],
messages: Ember.computed.filter('notifications', function (notification) {
// If this instance of the notifications component has no location affinity
// then it gets all notifications
if (!this.get('location')) {
return true;
}
var displayLocation = (typeof notification.toJSON === 'function') ?
notification.get('location') : notification.location;
return this.get('location') === displayLocation;
}),
messageCountObserver: function () {
this.sendAction('notify', this.get('messages').length);
}.observes('messages.[]')
});
__exports__["default"] = NotificationsComponent;
});
define("ghost/components/gh-popover-button",
["ghost/components/gh-dropdown-button","exports"],
function(__dependency1__, __exports__) {
"use strict";
var DropdownButton = __dependency1__["default"];
var PopoverButton = DropdownButton.extend({
click: Ember.K, // We don't want clicks on popovers, but dropdowns have them. So `K`ill them here.
mouseEnter: function (event) {
this._super(event);
this.get('dropdown').toggleDropdown(this.get('popoverName'), this);
},
mouseLeave: function (event) {
this._super(event);
this.get('dropdown').toggleDropdown(this.get('popoverName'), this);
}
});
__exports__["default"] = PopoverButton;
});
define("ghost/components/gh-popover",
["ghost/components/gh-dropdown","exports"],
function(__dependency1__, __exports__) {
"use strict";
var GhostDropdown = __dependency1__["default"];
var GhostPopover = GhostDropdown.extend({
classNames: 'ghost-popover'
});
__exports__["default"] = GhostPopover;
});
define("ghost/components/gh-role-selector",
["ghost/components/gh-select","exports"],
function(__dependency1__, __exports__) {
"use strict";
var GhostSelect = __dependency1__["default"];
var RolesSelector = GhostSelect.extend({
roles: Ember.computed.alias('options'),
options: Ember.computed(function () {
var rolesPromise = this.store.find('role', {permissions: 'assign'});
return Ember.ArrayProxy.extend(Ember.PromiseProxyMixin)
.create({promise: rolesPromise});
})
});
__exports__["default"] = RolesSelector;
});
define("ghost/components/gh-select",
["exports"],
function(__exports__) {
"use strict";
// GhostSelect is a solution to Ember.Select being evil and worthless.
// (Namely, this solves problems with async data in Ember.Select)
// Inspired by (that is, totally ripped off from) this JSBin
// http://emberjs.jsbin.com/rwjblue/40/edit
// Usage:
// Extend this component and create a template for your component.
// Your component must define the `options` property.
// Optionally use `initialValue` to set the object
// you want to have selected to start with.
// Both options and initalValue are promise safe.
// Set onChange in your template to be the name
// of the action you want called in your
// For an example, see gh-roles-selector
var GhostSelect = Ember.Component.extend({
tagName: 'span',
classNames: ['gh-select'],
attributeBindings: ['tabindex'],
tabindex: '0', // 0 must be a string, or else it's interpreted as false
options: null,
initialValue: null,
resolvedOptions: null,
resolvedInitialValue: null,
// Convert promises to their values
init: function () {
var self = this;
this._super.apply(this, arguments);
Ember.RSVP.hash({
resolvedOptions: this.get('options'),
resolvedInitialValue: this.get('initialValue')
}).then(function (resolvedHash) {
self.setProperties(resolvedHash);
// Run after render to ensure the <option>s have rendered
Ember.run.schedule('afterRender', function () {
self.setInitialValue();
});
});
},
setInitialValue: function () {
var initialValue = this.get('resolvedInitialValue'),
options = this.get('resolvedOptions'),
initialValueIndex = options.indexOf(initialValue);
if (initialValueIndex > -1) {
this.$('option:eq(' + initialValueIndex + ')').prop('selected', true);
}
},
// Called by DOM events
change: function () {
this._changeSelection();
},
// Send value to specified action
_changeSelection: function () {
var value = this._selectedValue();
Ember.set(this, 'value', value);
this.sendAction('onChange', value);
},
_selectedValue: function () {
var selectedIndex = this.$('select')[0].selectedIndex;
return this.get('options').objectAt(selectedIndex);
}
});
__exports__["default"] = GhostSelect;
});
define("ghost/components/gh-tab-pane",
["exports"],
function(__exports__) {
"use strict";
// See gh-tabs-manager.js for use
var TabPane = Ember.Component.extend({
classNameBindings: ['active'],
tabsManager: Ember.computed(function () {
return this.nearestWithProperty('isTabsManager');
}),
tab: Ember.computed('tabsManager.tabs.[]', 'tabsManager.tabPanes.[]', function () {
var index = this.get('tabsManager.tabPanes').indexOf(this),
tabs = this.get('tabsManager.tabs');
return tabs && tabs.objectAt(index);
}),
active: Ember.computed.alias('tab.active'),
// Register with the tabs manager
registerWithTabs: function () {
this.get('tabsManager').registerTabPane(this);
}.on('didInsertElement'),
unregisterWithTabs: function () {
this.get('tabsManager').unregisterTabPane(this);
}.on('willDestroyElement')
});
__exports__["default"] = TabPane;
});
define("ghost/components/gh-tab",
["exports"],
function(__exports__) {
"use strict";
// See gh-tabs-manager.js for use
var Tab = Ember.Component.extend({
tabsManager: Ember.computed(function () {
return this.nearestWithProperty('isTabsManager');
}),
active: Ember.computed('tabsManager.activeTab', function () {
return this.get('tabsManager.activeTab') === this;
}),
index: Ember.computed('tabsManager.tabs.@each', function () {
return this.get('tabsManager.tabs').indexOf(this);
}),
// Select on click
click: function () {
this.get('tabsManager').select(this);
},
// Registration methods
registerWithTabs: function () {
this.get('tabsManager').registerTab(this);
}.on('didInsertElement'),
unregisterWithTabs: function () {
this.get('tabsManager').unregisterTab(this);
}.on('willDestroyElement')
});
__exports__["default"] = Tab;
});
define("ghost/components/gh-tabs-manager",
["exports"],
function(__exports__) {
"use strict";
/**
Heavily inspired by ic-tabs (https://github.com/instructure/ic-tabs)
Three components work together for smooth tabbing.
1. tabs-manager (gh-tabs)
2. tab (gh-tab)
3. tab-pane (gh-tab-pane)
## Usage:
The tabs-manager must wrap all tab and tab-pane components,
but they can be nested at any level.
A tab and its pane are tied together via their order.
So, the second tab within a tab manager will activate
the second pane within that manager.
```hbs
{{#gh-tabs-manager}}
{{#gh-tab}}
First tab
{{/gh-tab}}
{{#gh-tab}}
Second tab
{{/gh-tab}}
....
{{#gh-tab-pane}}
First pane
{{/gh-tab-pane}}
{{#gh-tab-pane}}
Second pane
{{/gh-tab-pane}}
{{/gh-tabs-manager}}
```
## Options:
the tabs-manager will send a "selected" action whenever one of its
tabs is clicked.
```hbs
{{#gh-tabs-manager selected="myAction"}}
....
{{/gh-tabs-manager}}
```
## Styling:
Both tab and tab-pane elements have an "active"
class applied when they are active.
*/
var TabsManager = Ember.Component.extend({
activeTab: null,
tabs: [],
tabPanes: [],
// Called when a gh-tab is clicked.
select: function (tab) {
this.set('activeTab', tab);
this.sendAction('selected');
},
// Used by children to find this tabsManager
isTabsManager: true,
// Register tabs and their panes to allow for
// interaction between components.
registerTab: function (tab) {
this.get('tabs').addObject(tab);
},
unregisterTab: function (tab) {
this.get('tabs').removeObject(tab);
},
registerTabPane: function (tabPane) {
this.get('tabPanes').addObject(tabPane);
},
unregisterTabPane: function (tabPane) {
this.get('tabPanes').removeObject(tabPane);
}
});
__exports__["default"] = TabsManager;
});
define("ghost/components/gh-textarea",
["ghost/mixins/text-input","exports"],
function(__dependency1__, __exports__) {
"use strict";
var TextInputMixin = __dependency1__["default"];
var TextArea = Ember.TextArea.extend(TextInputMixin);
__exports__["default"] = TextArea;
});
define("ghost/components/gh-trim-focus-input",
["exports"],
function(__exports__) {
"use strict";
var TrimFocusInput = Ember.TextField.extend({
focus: true,
setFocus: function () {
if (this.focus) {
this.$().val(this.$().val()).focus();
}
}.on('didInsertElement'),
focusOut: function () {
var text = this.$().val();
this.$().val(text.trim());
}
});
__exports__["default"] = TrimFocusInput;
});
define("ghost/components/gh-upload-modal",
["ghost/components/gh-modal-dialog","ghost/assets/lib/uploader","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ModalDialog = __dependency1__["default"];
var upload = __dependency2__["default"];
var UploadModal = ModalDialog.extend({
layoutName: 'components/gh-modal-dialog',
didInsertElement: function () {
this._super();
upload.call(this.$('.js-drop-zone'), {fileStorage: this.get('config.fileStorage')});
},
confirm: {
reject: {
func: function () { // The function called on rejection
return true;
},
buttonClass: 'btn btn-default',
text: 'Cancel' // The reject button text
},
accept: {
buttonClass: 'btn btn-blue right',
text: 'Save', // The accept button texttext: 'Save'
func: function () {
var imageType = 'model.' + this.get('imageType');
if (this.$('.js-upload-url').val()) {
this.set(imageType, this.$('.js-upload-url').val());
} else {
this.set(imageType, this.$('.js-upload-target').attr('src'));
}
return true;
}
}
},
actions: {
closeModal: function () {
this.sendAction();
},
confirm: function (type) {
var func = this.get('confirm.' + type + '.func');
if (typeof func === 'function') {
func.apply(this);
}
this.sendAction();
this.sendAction('confirm' + type);
}
}
});
__exports__["default"] = UploadModal;
});
define("ghost/components/gh-uploader",
["ghost/assets/lib/uploader","exports"],
function(__dependency1__, __exports__) {
"use strict";
var uploader = __dependency1__["default"];
var PostImageUploader = Ember.Component.extend({
classNames: ['image-uploader', 'js-post-image-upload'],
setup: function () {
var $this = this.$(),
self = this;
uploader.call($this, {
editor: true,
fileStorage: this.get('config.fileStorage')
});
$this.on('uploadsuccess', function (event, result) {
if (result && result !== '' && result !== 'http://') {
self.sendAction('uploaded', result);
}
});
$this.find('.js-cancel').on('click', function () {
self.sendAction('canceled');
});
}.on('didInsertElement'),
removeListeners: function () {
var $this = this.$();
$this.off();
$this.find('.js-cancel').off();
}.on('willDestroyElement')
});
__exports__["default"] = PostImageUploader;
});
define("ghost/config",
["exports"],
function(__exports__) {
"use strict";
function configureApp(App) {
if (!App instanceof Ember.Application) {
return;
}
App.reopen({
LOG_ACTIVE_GENERATION: true,
LOG_MODULE_RESOLVER: true,
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_VIEW_LOOKUPS: true
});
}
__exports__["default"] = configureApp;
});
define("ghost/controllers/application",
["exports"],
function(__exports__) {
"use strict";
var ApplicationController = Ember.Controller.extend({
// jscs: disable
hideNav: Ember.computed.match('currentPath', /(error|signin|signup|setup|forgotten|reset)/),
// jscs: enable
topNotificationCount: 0,
showGlobalMobileNav: false,
showSettingsMenu: false,
userImageAlt: Ember.computed('session.user.name', function () {
var name = this.get('session.user.name');
return name + '\'s profile picture';
}),
actions: {
topNotificationChange: function (count) {
this.set('topNotificationCount', count);
}
}
});
__exports__["default"] = ApplicationController;
});
define("ghost/controllers/debug",
["exports"],
function(__exports__) {
"use strict";
var DebugController = Ember.Controller.extend(Ember.Evented, {
uploadButtonText: 'Import',
importErrors: '',
actions: {
onUpload: function (file) {
var self = this,
formData = new FormData();
this.set('uploadButtonText', 'Importing');
this.notifications.closePassive();
formData.append('importfile', file);
ic.ajax.request(this.get('ghostPaths.url').api('db'), {
type: 'POST',
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false
}).then(function () {
self.notifications.showSuccess('Import successful.');
}).catch(function (response) {
if (response && response.jqXHR && response.jqXHR.responseJSON && response.jqXHR.responseJSON.errors) {
self.set('importErrors', response.jqXHR.responseJSON.errors);
}
self.notifications.showError('Import Failed');
}).finally(function () {
self.set('uploadButtonText', 'Import');
self.trigger('reset');
});
},
exportData: function () {
var iframe = $('#iframeDownload'),
downloadURL = this.get('ghostPaths.url').api('db') +
'?access_token=' + this.get('session.access_token');
if (iframe.length === 0) {
iframe = $('<iframe>', {id: 'iframeDownload'}).hide().appendTo('body');
}
iframe.attr('src', downloadURL);
},
sendTestEmail: function () {
var self = this;
ic.ajax.request(this.get('ghostPaths.url').api('mail', 'test'), {
type: 'POST'
}).then(function () {
self.notifications.showSuccess('Check your email for the test message.');
}).catch(function (error) {
if (typeof error.jqXHR !== 'undefined') {
self.notifications.showAPIError(error);
} else {
self.notifications.showErrors(error);
}
});
}
}
});
__exports__["default"] = DebugController;
});
define("ghost/controllers/editor/edit",
["ghost/mixins/editor-base-controller","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EditorControllerMixin = __dependency1__["default"];
var EditorEditController = Ember.ObjectController.extend(EditorControllerMixin);
__exports__["default"] = EditorEditController;
});
define("ghost/controllers/editor/new",
["ghost/mixins/editor-base-controller","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EditorControllerMixin = __dependency1__["default"];
var EditorNewController = Ember.ObjectController.extend(EditorControllerMixin, {
actions: {
/**
* Redirect to editor after the first save
*/
save: function (options) {
var self = this;
return this._super(options).then(function (model) {
if (model.get('id')) {
self.replaceRoute('editor.edit', model);
}
});
}
}
});
__exports__["default"] = EditorNewController;
});
define("ghost/controllers/error",
["exports"],
function(__exports__) {
"use strict";
var ErrorController = Ember.Controller.extend({
code: Ember.computed('content.status', function () {
return this.get('content.status') > 200 ? this.get('content.status') : 500;
}),
message: Ember.computed('content.statusText', function () {
if (this.get('code') === 404) {
return 'No Ghost Found';
}
return this.get('content.statusText') !== 'error' ? this.get('content.statusText') : 'Internal Server Error';
}),
stack: false
});
__exports__["default"] = ErrorController;
});
define("ghost/controllers/forgotten",
["ghost/utils/ajax","ghost/mixins/validation-engine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/* jshint unused: false */
var ajax = __dependency1__["default"];
var ValidationEngine = __dependency2__["default"];
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
actions: {
submit: function () {
var self = this,
data = self.getProperties('email');
this.toggleProperty('submitting');
this.validate({format: false}).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: data.email
}]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess('Please check your email for instructions.', {delayed: true});
self.set('email', '');
self.transitionToRoute('signin');
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp, {defaultErrorText: 'There was a problem logging in, please try again.'});
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
__exports__["default"] = ForgottenController;
});
define("ghost/controllers/modals/auth-failed-unsaved",
["exports"],
function(__exports__) {
"use strict";
var AuthFailedUnsavedController = Ember.Controller.extend({
editorController: Ember.computed.alias('model'),
actions: {
confirmAccept: function () {
var editorController = this.get('editorController');
if (editorController) {
editorController.get('model').rollback();
}
window.onbeforeunload = null;
window.location = this.get('ghostPaths').adminRoot + '/signin/';
},
confirmReject: function () {
}
},
confirm: {
accept: {
text: 'Leave',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Stay',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = AuthFailedUnsavedController;
});
define("ghost/controllers/modals/copy-html",
["exports"],
function(__exports__) {
"use strict";
var CopyHTMLController = Ember.Controller.extend({
generatedHTML: Ember.computed.alias('model.generatedHTML')
});
__exports__["default"] = CopyHTMLController;
});
define("ghost/controllers/modals/delete-all",
["exports"],
function(__exports__) {
"use strict";
var DeleteAllController = Ember.Controller.extend({
actions: {
confirmAccept: function () {
var self = this;
ic.ajax.request(this.get('ghostPaths.url').api('db'), {
type: 'DELETE'
}).then(function () {
self.notifications.showSuccess('All content deleted from database.');
}).catch(function (response) {
self.notifications.showErrors(response);
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Delete',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = DeleteAllController;
});
define("ghost/controllers/modals/delete-post",
["exports"],
function(__exports__) {
"use strict";
var DeletePostController = Ember.Controller.extend({
actions: {
confirmAccept: function () {
var self = this,
model = this.get('model');
// definitely want to clear the data store and post of any unsaved, client-generated tags
model.updateTags();
model.destroyRecord().then(function () {
self.get('dropdown').closeDropdowns();
self.transitionToRoute('posts.index');
self.notifications.showSuccess('Your post has been deleted.', {delayed: true});
}, function () {
self.notifications.showError('Your post could not be deleted. Please try again.');
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Delete',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = DeletePostController;
});
define("ghost/controllers/modals/delete-user",
["exports"],
function(__exports__) {
"use strict";
var DeleteUserController = Ember.Controller.extend({
actions: {
confirmAccept: function () {
var self = this,
user = this.get('model');
user.destroyRecord().then(function () {
self.store.unloadAll('post');
self.transitionToRoute('settings.users');
self.notifications.showSuccess('The user has been deleted.', {delayed: true});
}, function () {
self.notifications.showError('The user could not be deleted. Please try again.');
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Delete User',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = DeleteUserController;
});
define("ghost/controllers/modals/invite-new-user",
["exports"],
function(__exports__) {
"use strict";
var InviteNewUserController = Ember.Controller.extend({
// Used to set the initial value for the dropdown
authorRole: Ember.computed(function () {
var self = this;
return this.store.find('role').then(function (roles) {
var authorRole = roles.findBy('name', 'Author');
// Initialize role as well.
self.set('role', authorRole);
self.set('authorRole', authorRole);
return authorRole;
});
}),
confirm: {
accept: {
text: 'send invitation now'
},
reject: {
buttonClass: 'hidden'
}
},
actions: {
setRole: function (role) {
this.set('role', role);
},
confirmAccept: function () {
var email = this.get('email'),
role = this.get('role'),
self = this,
newUser;
// reset the form and close the modal
self.set('email', '');
self.set('role', self.get('authorRole'));
self.send('closeModal');
this.store.find('user').then(function (result) {
var invitedUser = result.findBy('email', email);
if (invitedUser) {
if (invitedUser.get('status') === 'invited' || invitedUser.get('status') === 'invited-pending') {
self.notifications.showWarn('A user with that email address was already invited.');
} else {
self.notifications.showWarn('A user with that email address already exists.');
}
} else {
newUser = self.store.createRecord('user', {
email: email,
status: 'invited',
role: role
});
newUser.save().then(function () {
var notificationText = 'Invitation sent! (' + email + ')';
// If sending the invitation email fails, the API will still return a status of 201
// but the user's status in the response object will be 'invited-pending'.
if (newUser.get('status') === 'invited-pending') {
self.notifications.showWarn('Invitation email was not sent. Please try resending.');
} else {
self.notifications.showSuccess(notificationText);
}
}).catch(function (errors) {
newUser.deleteRecord();
self.notifications.showErrors(errors);
});
}
});
},
confirmReject: function () {
return false;
}
}
});
__exports__["default"] = InviteNewUserController;
});
define("ghost/controllers/modals/leave-editor",
["exports"],
function(__exports__) {
"use strict";
var LeaveEditorController = Ember.Controller.extend({
args: Ember.computed.alias('model'),
actions: {
confirmAccept: function () {
var args = this.get('args'),
editorController,
model,
transition;
if (Ember.isArray(args)) {
editorController = args[0];
transition = args[1];
model = editorController.get('model');
}
if (!transition || !editorController) {
this.notifications.showError('Sorry, there was an error in the application. Please let the Ghost team know what happened.');
return true;
}
// definitely want to clear the data store and post of any unsaved, client-generated tags
model.updateTags();
if (model.get('isNew')) {
// the user doesn't want to save the new, unsaved post, so delete it.
model.deleteRecord();
} else {
// roll back changes on model props
model.rollback();
}
// setting isDirty to false here allows willTransition on the editor route to succeed
editorController.set('isDirty', false);
// since the transition is now certain to complete, we can unset window.onbeforeunload here
window.onbeforeunload = null;
transition.retry();
},
confirmReject: function () {
}
},
confirm: {
accept: {
text: 'Leave',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Stay',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = LeaveEditorController;
});
define("ghost/controllers/modals/transfer-owner",
["exports"],
function(__exports__) {
"use strict";
var TransferOwnerController = Ember.Controller.extend({
actions: {
confirmAccept: function () {
var user = this.get('model'),
url = this.get('ghostPaths.url').api('users', 'owner'),
self = this;
self.get('dropdown').closeDropdowns();
ic.ajax.request(url, {
type: 'PUT',
data: {
owner: [{
id: user.get('id')
}]
}
}).then(function (response) {
// manually update the roles for the users that just changed roles
// because store.pushPayload is not working with embedded relations
if (response && Ember.isArray(response.users)) {
response.users.forEach(function (userJSON) {
var user = self.store.getById('user', userJSON.id),
role = self.store.getById('role', userJSON.roles[0].id);
user.set('role', role);
});
}
self.notifications.showSuccess('Ownership successfully transferred to ' + user.get('name'));
}).catch(function (error) {
self.notifications.showAPIError(error);
});
},
confirmReject: function () {
return false;
}
},
confirm: {
accept: {
text: 'Yep - I\'m sure',
buttonClass: 'btn btn-red'
},
reject: {
text: 'Cancel',
buttonClass: 'btn btn-default btn-minor'
}
}
});
__exports__["default"] = TransferOwnerController;
});
define("ghost/controllers/modals/upload",
["exports"],
function(__exports__) {
"use strict";
var UploadController = Ember.Controller.extend({
acceptEncoding: 'image/*',
actions: {
confirmAccept: function () {
var self = this;
this.get('model').save().then(function (model) {
self.notifications.showSuccess('Saved');
return model;
}).catch(function (err) {
self.notifications.showErrors(err);
});
},
confirmReject: function () {
return false;
}
}
});
__exports__["default"] = UploadController;
});
define("ghost/controllers/post-settings-menu",
["ghost/utils/date-formatting","ghost/models/slug-generator","ghost/utils/bound-one-way","ghost/utils/isNumber","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
/* global moment */
var parseDateString = __dependency1__.parseDateString;
var formatDate = __dependency1__.formatDate;
var SlugGenerator = __dependency2__["default"];
var boundOneWay = __dependency3__["default"];
var isNumber = __dependency4__["default"];
var PostSettingsMenuController = Ember.ObjectController.extend({
// State for if the user is viewing a tab's pane.
needs: 'application',
lastPromise: null,
isViewingSubview: Ember.computed('controllers.application.showSettingsMenu', function (key, value) {
// Not viewing a subview if we can't even see the PSM
if (!this.get('controllers.application.showSettingsMenu')) {
return false;
}
if (arguments.length > 1) {
return value;
}
return false;
}),
selectedAuthor: null,
initializeSelectedAuthor: function () {
var self = this;
return this.get('author').then(function (author) {
self.set('selectedAuthor', author);
return author;
});
}.observes('model'),
changeAuthor: function () {
var author = this.get('author'),
selectedAuthor = this.get('selectedAuthor'),
model = this.get('model'),
self = this;
// return if nothing changed
if (selectedAuthor.get('id') === author.get('id')) {
return;
}
model.set('author', selectedAuthor);
// if this is a new post (never been saved before), don't try to save it
if (this.get('isNew')) {
return;
}
model.save().catch(function (errors) {
self.showErrors(errors);
self.set('selectedAuthor', author);
model.rollback();
});
}.observes('selectedAuthor'),
authors: Ember.computed(function () {
// Loaded asynchronously, so must use promise proxies.
var deferred = {};
deferred.promise = this.store.find('user', {limit: 'all'}).then(function (users) {
return users.rejectBy('id', 'me').sortBy('name');
}).then(function (users) {
return users.filter(function (user) {
return user.get('active');
});
});
return Ember.ArrayProxy
.extend(Ember.PromiseProxyMixin)
.create(deferred);
}),
publishedAtValue: Ember.computed('published_at', function () {
var pubDate = this.get('published_at');
if (pubDate) {
return formatDate(pubDate);
}
return formatDate(moment());
}),
slugValue: boundOneWay('slug'),
// Lazy load the slug generator
slugGenerator: Ember.computed(function () {
return SlugGenerator.create({
ghostPaths: this.get('ghostPaths'),
slugType: 'post'
});
}),
// Requests slug from title
generateAndSetSlug: function (destination) {
var self = this,
title = this.get('titleScratch'),
afterSave = this.get('lastPromise'),
promise;
// Only set an "untitled" slug once per post
if (title === '(Untitled)' && this.get('slug')) {
return;
}
promise = Ember.RSVP.resolve(afterSave).then(function () {
return self.get('slugGenerator').generateSlug(title).then(function (slug) {
self.set(destination, slug);
});
});
this.set('lastPromise', promise);
},
metaTitleScratch: boundOneWay('meta_title'),
metaDescriptionScratch: boundOneWay('meta_description'),
seoTitle: Ember.computed('titleScratch', 'metaTitleScratch', function () {
var metaTitle = this.get('metaTitleScratch') || '';
metaTitle = metaTitle.length > 0 ? metaTitle : this.get('titleScratch');
if (metaTitle.length > 70) {
metaTitle = metaTitle.substring(0, 70).trim();
metaTitle = Ember.Handlebars.Utils.escapeExpression(metaTitle);
metaTitle = new Ember.Handlebars.SafeString(metaTitle + '…');
}
return metaTitle;
}),
seoDescription: Ember.computed('scratch', 'metaDescriptionScratch', function () {
var metaDescription = this.get('metaDescriptionScratch') || '',
el,
html = '',
placeholder;
if (metaDescription.length > 0) {
placeholder = metaDescription;
} else {
el = $('.rendered-markdown');
// Get rendered markdown
if (el !== undefined && el.length > 0) {
html = el.clone();
html.find('.js-drop-zone').remove();
html = html[0].innerHTML;
}
// Strip HTML
placeholder = $('<div />', {html: html}).text();
// Replace new lines and trim
// jscs: disable
placeholder = placeholder.replace(/\n+/g, ' ').trim();
// jscs: enable
}
if (placeholder.length > 156) {
// Limit to 156 characters
placeholder = placeholder.substring(0, 156).trim();
placeholder = Ember.Handlebars.Utils.escapeExpression(placeholder);
placeholder = new Ember.Handlebars.SafeString(placeholder + '…');
}
return placeholder;
}),
seoURL: Ember.computed('slug', function () {
var blogUrl = this.get('config').blogUrl,
seoSlug = this.get('slug') ? this.get('slug') : '',
seoURL = blogUrl + '/' + seoSlug;
// only append a slash to the URL if the slug exists
if (seoSlug) {
seoURL += '/';
}
if (seoURL.length > 70) {
seoURL = seoURL.substring(0, 70).trim();
seoURL = new Ember.Handlebars.SafeString(seoURL + '…');
}
return seoURL;
}),
// observe titleScratch, keeping the post's slug in sync
// with it until saved for the first time.
addTitleObserver: function () {
if (this.get('isNew') || this.get('title') === '(Untitled)') {
this.addObserver('titleScratch', this, 'titleObserver');
}
}.observes('model'),
titleObserver: function () {
var debounceId,
title = this.get('title');
// generate a slug if a post is new and doesn't have a title yet or
// if the title is still '(Untitled)' and the slug is unaltered.
if ((this.get('isNew') && !title) || title === '(Untitled)') {
debounceId = Ember.run.debounce(this, 'generateAndSetSlug', ['slug'], 700);
}
this.set('debounceId', debounceId);
},
showErrors: function (errors) {
errors = Ember.isArray(errors) ? errors : [errors];
this.notifications.showErrors(errors);
},
showSuccess: function (message) {
this.notifications.showSuccess(message);
},
actions: {
togglePage: function () {
var self = this;
this.toggleProperty('page');
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
toggleFeatured: function () {
var self = this;
this.toggleProperty('featured');
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (this.get('isNew')) {
return;
}
this.get('model').save(this.get('saveOptions')).catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
/**
* triggered by user manually changing slug
*/
updateSlug: function (newSlug) {
var slug = this.get('slug'),
self = this;
newSlug = newSlug || slug;
newSlug = newSlug && newSlug.trim();
// Ignore unchanged slugs or candidate slugs that are empty
if (!newSlug || slug === newSlug) {
// reset the input to its previous state
this.set('slugValue', slug);
return;
}
this.get('slugGenerator').generateSlug(newSlug).then(function (serverSlug) {
// If after getting the sanitized and unique slug back from the API
// we end up with a slug that matches the existing slug, abort the change
if (serverSlug === slug) {
return;
}
// Because the server transforms the candidate slug by stripping
// certain characters and appending a number onto the end of slugs
// to enforce uniqueness, there are cases where we can get back a
// candidate slug that is a duplicate of the original except for
// the trailing incrementor (e.g., this-is-a-slug and this-is-a-slug-2)
// get the last token out of the slug candidate and see if it's a number
var slugTokens = serverSlug.split('-'),
check = Number(slugTokens.pop());
// if the candidate slug is the same as the existing slug except
// for the incrementor then the existing slug should be used
if (isNumber(check) && check > 0) {
if (slug === slugTokens.join('-') && serverSlug !== newSlug) {
self.set('slugValue', slug);
return;
}
}
self.set('slug', serverSlug);
if (self.hasObserverFor('titleScratch')) {
self.removeObserver('titleScratch', self, 'titleObserver');
}
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (self.get('isNew')) {
return;
}
return self.get('model').save();
}).catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
/**
* Parse user's set published date.
* Action sent by post settings menu view.
* (#1351)
*/
setPublishedAt: function (userInput) {
var errMessage = '',
newPublishedAt = parseDateString(userInput),
publishedAt = this.get('published_at'),
self = this;
if (!userInput) {
// Clear out the published_at field for a draft
if (this.get('isDraft')) {
this.set('published_at', null);
}
return;
}
// Validate new Published date
if (!newPublishedAt.isValid()) {
errMessage = 'Published Date must be a valid date with format: ' +
'DD MMM YY @ HH:mm (e.g. 6 Dec 14 @ 15:00)';
}
if (newPublishedAt.diff(new Date(), 'h') > 0) {
errMessage = 'Published Date cannot currently be in the future.';
}
// If errors, notify and exit.
if (errMessage) {
this.showErrors(errMessage);
return;
}
// Do nothing if the user didn't actually change the date
if (publishedAt && publishedAt.isSame(newPublishedAt)) {
return;
}
// Validation complete
this.set('published_at', newPublishedAt);
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
setMetaTitle: function (metaTitle) {
var self = this,
currentTitle = this.get('meta_title') || '';
// Only update if the title has changed
if (currentTitle === metaTitle) {
return;
}
this.set('meta_title', metaTitle);
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
});
},
setMetaDescription: function (metaDescription) {
var self = this,
currentDescription = this.get('meta_description') || '';
// Only update if the description has changed
if (currentDescription === metaDescription) {
return;
}
this.set('meta_description', metaDescription);
// If this is a new post. Don't save the model. Defer the save
// to the user pressing the save button
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
});
},
setCoverImage: function (image) {
var self = this;
this.set('image', image);
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
clearCoverImage: function () {
var self = this;
this.set('image', '');
if (this.get('isNew')) {
return;
}
this.get('model').save().catch(function (errors) {
self.showErrors(errors);
self.get('model').rollback();
});
},
showSubview: function () {
this.set('isViewingSubview', true);
},
closeSubview: function () {
this.set('isViewingSubview', false);
}
}
});
__exports__["default"] = PostSettingsMenuController;
});
define("ghost/controllers/post-tags-input",
["exports"],
function(__exports__) {
"use strict";
var PostTagsInputController = Ember.Controller.extend({
tagEnteredOrder: Ember.A(),
tags: Ember.computed('parentController.tags', function () {
var proxyTags = Ember.ArrayProxy.create({
content: this.get('parentController.tags')
}),
temp = proxyTags.get('arrangedContent').slice();
proxyTags.get('arrangedContent').clear();
this.get('tagEnteredOrder').forEach(function (tagName) {
var tag = temp.find(function (tag) {
return tag.get('name') === tagName;
});
if (tag) {
proxyTags.get('arrangedContent').addObject(tag);
temp.removeObject(tag);
}
});
proxyTags.get('arrangedContent').unshiftObjects(temp);
return proxyTags;
}),
suggestions: null,
newTagText: null,
actions: {
// triggered when the view is inserted so that later store.all('tag')
// queries hit a full store cache and we don't see empty or out-of-date
// suggestion lists
loadAllTags: function () {
this.store.find('tag');
},
addNewTag: function () {
var newTagText = this.get('newTagText'),
searchTerm,
existingTags,
newTag;
if (Ember.isEmpty(newTagText) || this.hasTag(newTagText)) {
this.send('reset');
return;
}
newTagText = newTagText.trim();
searchTerm = newTagText.toLowerCase();
// add existing tag if we have a match
existingTags = this.store.all('tag').filter(function (tag) {
return tag.get('name').toLowerCase() === searchTerm;
});
if (existingTags.get('length')) {
this.send('addTag', existingTags.get('firstObject'));
} else {
// otherwise create a new one
newTag = this.store.createRecord('tag');
newTag.set('name', newTagText);
this.send('addTag', newTag);
}
this.send('reset');
},
addTag: function (tag) {
if (!Ember.isEmpty(tag)) {
this.get('tags').addObject(tag);
this.get('tagEnteredOrder').addObject(tag.get('name'));
}
this.send('reset');
},
deleteTag: function (tag) {
if (tag) {
this.get('tags').removeObject(tag);
this.get('tagEnteredOrder').removeObject(tag.get('name'));
}
},
deleteLastTag: function () {
this.send('deleteTag', this.get('tags.lastObject'));
},
selectSuggestion: function (suggestion) {
if (!Ember.isEmpty(suggestion)) {
this.get('suggestions').setEach('selected', false);
suggestion.set('selected', true);
}
},
selectNextSuggestion: function () {
var suggestions = this.get('suggestions'),
selectedSuggestion = this.get('selectedSuggestion'),
currentIndex,
newSelection;
if (!Ember.isEmpty(suggestions)) {
currentIndex = suggestions.indexOf(selectedSuggestion);
if (currentIndex + 1 < suggestions.get('length')) {
newSelection = suggestions[currentIndex + 1];
this.send('selectSuggestion', newSelection);
} else {
suggestions.setEach('selected', false);
}
}
},
selectPreviousSuggestion: function () {
var suggestions = this.get('suggestions'),
selectedSuggestion = this.get('selectedSuggestion'),
currentIndex,
lastIndex,
newSelection;
if (!Ember.isEmpty(suggestions)) {
currentIndex = suggestions.indexOf(selectedSuggestion);
if (currentIndex === -1) {
lastIndex = suggestions.get('length') - 1;
this.send('selectSuggestion', suggestions[lastIndex]);
} else if (currentIndex - 1 >= 0) {
newSelection = suggestions[currentIndex - 1];
this.send('selectSuggestion', newSelection);
} else {
suggestions.setEach('selected', false);
}
}
},
addSelectedSuggestion: function () {
var suggestion = this.get('selectedSuggestion');
if (Ember.isEmpty(suggestion)) {
return;
}
this.send('addTag', suggestion.get('tag'));
},
reset: function () {
this.set('suggestions', null);
this.set('newTagText', null);
}
},
selectedSuggestion: Ember.computed('suggestions.@each.selected', function () {
var suggestions = this.get('suggestions');
if (suggestions && suggestions.get('length')) {
return suggestions.filterBy('selected').get('firstObject');
} else {
return null;
}
}),
updateSuggestionsList: function () {
var searchTerm = this.get('newTagText'),
matchingTags,
// Limit the suggestions number
maxSuggestions = 5,
suggestions = Ember.A();
if (!searchTerm || Ember.isEmpty(searchTerm.trim())) {
this.set('suggestions', null);
return;
}
searchTerm = searchTerm.trim();
matchingTags = this.findMatchingTags(searchTerm);
matchingTags = matchingTags.slice(0, maxSuggestions);
matchingTags.forEach(function (matchingTag) {
var suggestion = this.makeSuggestionObject(matchingTag, searchTerm);
suggestions.pushObject(suggestion);
}, this);
this.set('suggestions', suggestions);
}.observes('newTagText'),
findMatchingTags: function (searchTerm) {
var matchingTags,
self = this,
allTags = this.store.all('tag'),
deDupe = {};
if (allTags.get('length') === 0) {
return [];
}
searchTerm = searchTerm.toLowerCase();
matchingTags = allTags.filter(function (tag) {
var tagNameMatches,
hasAlreadyBeenAdded,
tagName = tag.get('name');
tagNameMatches = tagName.toLowerCase().indexOf(searchTerm) !== -1;
hasAlreadyBeenAdded = self.hasTag(tagName);
if (tagNameMatches && !hasAlreadyBeenAdded) {
if (typeof deDupe[tagName] === 'undefined') {
deDupe[tagName] = 1;
} else {
deDupe[tagName] += 1;
}
}
return deDupe[tagName] === 1;
});
return matchingTags;
},
hasTag: function (tagName) {
return this.get('tags').mapBy('name').contains(tagName);
},
makeSuggestionObject: function (matchingTag, _searchTerm) {
var searchTerm = Ember.Handlebars.Utils.escapeExpression(_searchTerm),
// jscs:disable
regexEscapedSearchTerm = searchTerm.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'),
// jscs:enable
tagName = Ember.Handlebars.Utils.escapeExpression(matchingTag.get('name')),
regex = new RegExp('(' + regexEscapedSearchTerm + ')', 'gi'),
highlightedName,
suggestion = Ember.Object.create();
highlightedName = tagName.replace(regex, '<mark>$1</mark>');
highlightedName = new Ember.Handlebars.SafeString(highlightedName);
suggestion.set('tag', matchingTag);
suggestion.set('highlightedName', highlightedName);
return suggestion;
}
});
__exports__["default"] = PostTagsInputController;
});
define("ghost/controllers/posts",
["ghost/mixins/pagination-controller","exports"],
function(__dependency1__, __exports__) {
"use strict";
var PaginationControllerMixin = __dependency1__["default"];
function publishedAtCompare(item1, item2) {
var published1 = item1.get('published_at'),
published2 = item2.get('published_at');
if (!published1 && !published2) {
return 0;
}
if (!published1 && published2) {
return -1;
}
if (!published2 && published1) {
return 1;
}
return Ember.compare(published1.valueOf(), published2.valueOf());
}
var PostsController = Ember.ArrayController.extend(PaginationControllerMixin, {
// See PostsRoute's shortcuts
postListFocused: Ember.computed.equal('keyboardFocus', 'postList'),
postContentFocused: Ember.computed.equal('keyboardFocus', 'postContent'),
// this will cause the list to re-sort when any of these properties change on any of the models
sortProperties: ['status', 'published_at', 'updated_at'],
// override Ember.SortableMixin
//
// this function will keep the posts list sorted when loading individual/bulk
// models from the server, even if records in between haven't been loaded.
// this can happen when reloading the page on the Editor or PostsPost routes.
//
// a custom sort function is needed in order to sort the posts list the same way the server would:
// status: ASC
// published_at: DESC
// updated_at: DESC
orderBy: function (item1, item2) {
var updated1 = item1.get('updated_at'),
updated2 = item2.get('updated_at'),
statusResult,
updatedAtResult,
publishedAtResult;
// when `updated_at` is undefined, the model is still
// being written to with the results from the server
if (item1.get('isNew') || !updated1) {
return -1;
}
if (item2.get('isNew') || !updated2) {
return 1;
}
statusResult = Ember.compare(item1.get('status'), item2.get('status'));
updatedAtResult = Ember.compare(updated1.valueOf(), updated2.valueOf());
publishedAtResult = publishedAtCompare(item1, item2);
if (statusResult === 0) {
if (publishedAtResult === 0) {
// This should be DESC
return updatedAtResult * -1;
}
// This should be DESC
return publishedAtResult * -1;
}
return statusResult;
},
init: function () {
// let the PaginationControllerMixin know what type of model we will be paginating
// this is necesariy because we do not have access to the model inside the Controller::init method
this._super({modelType: 'post'});
}
});
__exports__["default"] = PostsController;
});
define("ghost/controllers/posts/post",
["exports"],
function(__exports__) {
"use strict";
var PostController = Ember.ObjectController.extend({
isPublished: Ember.computed.equal('status', 'published'),
classNameBindings: ['featured'],
actions: {
toggleFeatured: function () {
var options = {disableNProgress: true},
self = this;
this.toggleProperty('featured');
this.get('model').save(options).catch(function (errors) {
self.notifications.showErrors(errors);
});
},
showPostContent: function () {
this.transitionToRoute('posts.post', this.get('model'));
}
}
});
__exports__["default"] = PostController;
});
define("ghost/controllers/reset",
["ghost/utils/ajax","ghost/mixins/validation-engine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global console*/
/* jshint unused: false */
var ajax = __dependency1__["default"];
var ValidationEngine = __dependency2__["default"];
var ResetController = Ember.Controller.extend(ValidationEngine, {
newPassword: '',
ne2Password: '',
token: '',
submitButtonDisabled: false,
validationType: 'reset',
email: Ember.computed('token', function () {
// The token base64 encodes the email (and some other stuff),
// each section is divided by a '|'. Email comes second.
return atob(this.get('token')).split('|')[1];
}),
// Used to clear sensitive information
clearData: function () {
this.setProperties({
newPassword: '',
ne2Password: '',
token: ''
});
},
actions: {
submit: function () {
var credentials = this.getProperties('newPassword', 'ne2Password', 'token'),
self = this;
this.toggleProperty('submitting');
this.validate({format: false}).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'PUT',
data: {
passwordreset: [credentials]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess(resp.passwordreset[0].message, true);
self.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', {
identification: self.get('email'),
password: credentials.newPassword
});
}).catch(function (response) {
self.notifications.showAPIError(response);
self.toggleProperty('submitting');
});
}).catch(function (error) {
self.toggleProperty('submitting');
self.notifications.showErrors(error);
});
}
}
});
__exports__["default"] = ResetController;
});
define("ghost/controllers/settings",
["exports"],
function(__exports__) {
"use strict";
var SettingsController = Ember.Controller.extend({
showApps: Ember.computed.bool('config.apps'),
showTags: Ember.computed.bool('config.tagsUI')
});
__exports__["default"] = SettingsController;
});
define("ghost/controllers/settings/app",
["exports"],
function(__exports__) {
"use strict";
/*global alert */
var appStates,
SettingsAppController;
appStates = {
active: 'active',
working: 'working',
inactive: 'inactive'
};
SettingsAppController = Ember.ObjectController.extend({
appState: appStates.active,
buttonText: '',
setAppState: function () {
this.set('appState', this.get('active') ? appStates.active : appStates.inactive);
}.on('init'),
buttonTextSetter: function () {
switch (this.get('appState')) {
case appStates.active:
this.set('buttonText', 'Deactivate');
break;
case appStates.inactive:
this.set('buttonText', 'Activate');
break;
case appStates.working:
this.set('buttonText', 'Working');
break;
}
}.observes('appState').on('init'),
activeClass: Ember.computed('appState', function () {
return this.appState === appStates.active ? true : false;
}),
inactiveClass: Ember.computed('appState', function () {
return this.appState === appStates.inactive ? true : false;
}),
actions: {
toggleApp: function (app) {
var self = this;
this.set('appState', appStates.working);
app.set('active', !app.get('active'));
app.save().then(function () {
self.setAppState();
})
.then(function () {
alert('@TODO: Success');
})
.catch(function () {
alert('@TODO: Failure');
});
}
}
});
__exports__["default"] = SettingsAppController;
});
define("ghost/controllers/settings/general",
["exports"],
function(__exports__) {
"use strict";
var SettingsGeneralController = Ember.ObjectController.extend({
isDatedPermalinks: Ember.computed('permalinks', function (key, value) {
// setter
if (arguments.length > 1) {
this.set('permalinks', value ? '/:year/:month/:day/:slug/' : '/:slug/');
}
// getter
var slugForm = this.get('permalinks');
return slugForm !== '/:slug/';
}),
themes: Ember.computed(function () {
return this.get('availableThemes').reduce(function (themes, t) {
var theme = {};
theme.name = t.name;
theme.label = t.package ? t.package.name + ' - ' + t.package.version : t.name;
theme.package = t.package;
theme.active = !!t.active;
themes.push(theme);
return themes;
}, []);
}).readOnly(),
actions: {
save: function () {
var self = this;
return this.get('model').save().then(function (model) {
self.notifications.showSuccess('Settings successfully saved.');
return model;
}).catch(function (errors) {
self.notifications.showErrors(errors);
});
},
checkPostsPerPage: function () {
if (this.get('postsPerPage') < 1 || this.get('postsPerPage') > 1000 || isNaN(this.get('postsPerPage'))) {
this.set('postsPerPage', 5);
}
}
}
});
__exports__["default"] = SettingsGeneralController;
});
define("ghost/controllers/settings/users/index",
["ghost/mixins/pagination-controller","exports"],
function(__dependency1__, __exports__) {
"use strict";
var PaginationControllerMixin = __dependency1__["default"];
var UsersIndexController = Ember.ArrayController.extend(PaginationControllerMixin, {
init: function () {
// let the PaginationControllerMixin know what type of model we will be paginating
// this is necessary because we do not have access to the model inside the Controller::init method
this._super({modelType: 'user'});
},
users: Ember.computed.alias('model'),
activeUsers: Ember.computed.filter('users', function (user) {
return /^active|warn-[1-4]|locked$/.test(user.get('status'));
}),
invitedUsers: Ember.computed.filter('users', function (user) {
var status = user.get('status');
return status === 'invited' || status === 'invited-pending';
})
});
__exports__["default"] = UsersIndexController;
});
define("ghost/controllers/settings/users/user",
["ghost/models/slug-generator","ghost/utils/isNumber","ghost/utils/bound-one-way","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var SlugGenerator = __dependency1__["default"];
var isNumber = __dependency2__["default"];
var boundOneWay = __dependency3__["default"];
var SettingsUserController = Ember.ObjectController.extend({
user: Ember.computed.alias('model'),
email: Ember.computed.readOnly('user.email'),
slugValue: boundOneWay('user.slug'),
lastPromise: null,
coverDefault: Ember.computed('ghostPaths', function () {
return this.get('ghostPaths.url').asset('/shared/img/user-cover.png');
}),
userDefault: Ember.computed('ghostPaths', function () {
return this.get('ghostPaths.url').asset('/shared/img/user-image.png');
}),
cover: Ember.computed('user.cover', 'coverDefault', function () {
var cover = this.get('user.cover');
if (Ember.isBlank(cover)) {
cover = this.get('coverDefault');
}
return 'background-image: url(' + cover + ')';
}),
coverTitle: Ember.computed('user.name', function () {
return this.get('user.name') + '\'s Cover Image';
}),
image: Ember.computed('imageUrl', function () {
return 'background-image: url(' + this.get('imageUrl') + ')';
}),
imageUrl: Ember.computed('user.image', function () {
return this.get('user.image') || this.get('userDefault');
}),
last_login: Ember.computed('user.last_login', function () {
var lastLogin = this.get('user.last_login');
return lastLogin ? lastLogin.fromNow() : '(Never)';
}),
created_at: Ember.computed('user.created_at', function () {
var createdAt = this.get('user.created_at');
return createdAt ? createdAt.fromNow() : '';
}),
// Lazy load the slug generator for slugPlaceholder
slugGenerator: Ember.computed(function () {
return SlugGenerator.create({
ghostPaths: this.get('ghostPaths'),
slugType: 'user'
});
}),
actions: {
changeRole: function (newRole) {
this.set('model.role', newRole);
},
revoke: function () {
var self = this,
model = this.get('model'),
email = this.get('email');
// reload the model to get the most up-to-date user information
model.reload().then(function () {
if (self.get('invited')) {
model.destroyRecord().then(function () {
var notificationText = 'Invitation revoked. (' + email + ')';
self.notifications.showSuccess(notificationText, false);
}).catch(function (error) {
self.notifications.showAPIError(error);
});
} else {
// if the user is no longer marked as "invited", then show a warning and reload the route
self.get('target').send('reload');
self.notifications.showError('This user has already accepted the invitation.', {delayed: 500});
}
});
},
resend: function () {
var self = this;
this.get('model').resendInvite().then(function (result) {
var notificationText = 'Invitation resent! (' + self.get('email') + ')';
// If sending the invitation email fails, the API will still return a status of 201
// but the user's status in the response object will be 'invited-pending'.
if (result.users[0].status === 'invited-pending') {
self.notifications.showWarn('Invitation email was not sent. Please try resending.');
} else {
self.get('model').set('status', result.users[0].status);
self.notifications.showSuccess(notificationText);
}
}).catch(function (error) {
self.notifications.showAPIError(error);
});
},
save: function () {
var user = this.get('user'),
slugValue = this.get('slugValue'),
afterUpdateSlug = this.get('lastPromise'),
promise,
slugChanged,
self = this;
if (user.get('slug') !== slugValue) {
slugChanged = true;
user.set('slug', slugValue);
}
promise = Ember.RSVP.resolve(afterUpdateSlug).then(function () {
return user.save({format: false});
}).then(function (model) {
var currentPath,
newPath;
self.notifications.showSuccess('Settings successfully saved.');
// If the user's slug has changed, change the URL and replace
// the history so refresh and back button still work
if (slugChanged) {
currentPath = window.history.state.path;
newPath = currentPath.split('/');
newPath[newPath.length - 2] = model.get('slug');
newPath = newPath.join('/');
window.history.replaceState({path: newPath}, '', newPath);
}
return model;
}).catch(function (errors) {
self.notifications.showErrors(errors);
});
this.set('lastPromise', promise);
},
password: function () {
var user = this.get('user'),
self = this;
if (user.get('isPasswordValid')) {
user.saveNewPassword().then(function (model) {
// Clear properties from view
user.setProperties({
password: '',
newPassword: '',
ne2Password: ''
});
self.notifications.showSuccess('Password updated.');
return model;
}).catch(function (errors) {
self.notifications.showAPIError(errors);
});
} else {
self.notifications.showErrors(user.get('passwordValidationErrors'));
}
},
updateSlug: function (newSlug) {
var self = this,
afterSave = this.get('lastPromise'),
promise;
promise = Ember.RSVP.resolve(afterSave).then(function () {
var slug = self.get('slug');
newSlug = newSlug || slug;
newSlug = newSlug.trim();
// Ignore unchanged slugs or candidate slugs that are empty
if (!newSlug || slug === newSlug) {
self.set('slugValue', slug);
return;
}
return self.get('slugGenerator').generateSlug(newSlug).then(function (serverSlug) {
// If after getting the sanitized and unique slug back from the API
// we end up with a slug that matches the existing slug, abort the change
if (serverSlug === slug) {
return;
}
// Because the server transforms the candidate slug by stripping
// certain characters and appending a number onto the end of slugs
// to enforce uniqueness, there are cases where we can get back a
// candidate slug that is a duplicate of the original except for
// the trailing incrementor (e.g., this-is-a-slug and this-is-a-slug-2)
// get the last token out of the slug candidate and see if it's a number
var slugTokens = serverSlug.split('-'),
check = Number(slugTokens.pop());
// if the candidate slug is the same as the existing slug except
// for the incrementor then the existing slug should be used
if (isNumber(check) && check > 0) {
if (slug === slugTokens.join('-') && serverSlug !== newSlug) {
self.set('slugValue', slug);
return;
}
}
self.set('slugValue', serverSlug);
});
});
this.set('lastPromise', promise);
}
}
});
__exports__["default"] = SettingsUserController;
});
define("ghost/controllers/setup",
["ghost/utils/ajax","ghost/mixins/validation-engine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ajax = __dependency1__["default"];
var ValidationEngine = __dependency2__["default"];
var SetupController = Ember.ObjectController.extend(ValidationEngine, {
blogTitle: null,
name: null,
email: null,
password: null,
submitting: false,
// ValidationEngine settings
validationType: 'setup',
actions: {
setup: function () {
var self = this,
data = self.getProperties('blogTitle', 'name', 'email', 'password');
self.notifications.closePassive();
this.toggleProperty('submitting');
this.validate({format: false}).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'setup'),
type: 'POST',
data: {
setup: [{
name: data.name,
email: data.email,
password: data.password,
blogTitle: data.blogTitle
}]
}
}).then(function () {
self.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', {
identification: self.get('email'),
password: self.get('password')
});
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp);
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
__exports__["default"] = SetupController;
});
define("ghost/controllers/signin",
["ghost/mixins/validation-engine","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ValidationEngine = __dependency1__["default"];
var SigninController = Ember.Controller.extend(SimpleAuth.AuthenticationControllerMixin, ValidationEngine, {
authenticator: 'simple-auth-authenticator:oauth2-password-grant',
validationType: 'signin',
actions: {
authenticate: function () {
var data = this.getProperties('identification', 'password');
return this._super(data);
},
validateAndAuthenticate: function () {
var self = this;
this.validate({format: false}).then(function () {
self.notifications.closePassive();
self.send('authenticate');
}).catch(function (errors) {
self.notifications.showErrors(errors);
});
}
}
});
__exports__["default"] = SigninController;
});
define("ghost/controllers/signup",
["ghost/utils/ajax","ghost/mixins/validation-engine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ajax = __dependency1__["default"];
var ValidationEngine = __dependency2__["default"];
var SignupController = Ember.ObjectController.extend(ValidationEngine, {
submitting: false,
// ValidationEngine settings
validationType: 'signup',
actions: {
signup: function () {
var self = this,
data = self.getProperties('name', 'email', 'password', 'token');
self.notifications.closePassive();
this.toggleProperty('submitting');
this.validate({format: false}).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'invitation'),
type: 'POST',
dataType: 'json',
data: {
invitation: [{
name: data.name,
email: data.email,
password: data.password,
token: data.token
}]
}
}).then(function () {
self.get('session').authenticate('simple-auth-authenticator:oauth2-password-grant', {
identification: self.get('email'),
password: self.get('password')
});
}, function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp);
});
}, function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
__exports__["default"] = SignupController;
});
define("ghost/docs/js/nav",
[],
function() {
"use strict";
(function(){
// TODO: unbind click events when nav is desktop sized
// Element vars
var menu_button = document.querySelector(".menu-button"),
viewport = document.querySelector(".viewport"),
global_nav = document.querySelector(".global-nav"),
page_content = document.querySelector(".viewport .page-content");
// mediaQuery listener
var mq_max_1025 = window.matchMedia("(max-width: 1025px)");
mq_max_1025.addListener(show_hide_nav);
show_hide_nav(mq_max_1025);
menu_button.addEventListener("click", function(e) {
e.preventDefault();
if (menu_button.getAttribute('data-nav-open')) {
close_nav();
} else {
open_nav();
}
});
page_content.addEventListener("click", function(e) {
e.preventDefault();
console.log("click viewport");
if (viewport.classList.contains("global-nav-expanded")) {
console.log("close nav from viewport");
close_nav();
}
});
var open_nav = function(){
menu_button.setAttribute("data-nav-open", "true");
viewport.classList.add("global-nav-expanded");
global_nav.classList.add("global-nav-expanded");
};
var close_nav = function(){
menu_button.removeAttribute('data-nav-open');
viewport.classList.remove("global-nav-expanded");
global_nav.classList.remove("global-nav-expanded");
};
function show_hide_nav(mq) {
if (mq.matches) {
// Window is 1025px or less
} else {
// Window is 1026px or more
viewport.classList.remove("global-nav-expanded");
global_nav.classList.remove("global-nav-expanded");
}
}
})();
});
define("ghost/helpers/gh-blog-url",
["exports"],
function(__exports__) {
"use strict";
var blogUrl = Ember.Handlebars.makeBoundHelper(function () {
return new Ember.Handlebars.SafeString(this.get('config.blogUrl'));
});
__exports__["default"] = blogUrl;
});
define("ghost/helpers/gh-count-characters",
["exports"],
function(__exports__) {
"use strict";
var countCharacters = Ember.Handlebars.makeBoundHelper(function (content) {
var el = document.createElement('span'),
length = content ? content.length : 0;
el.className = 'word-count';
if (length > 180) {
el.style.color = '#E25440';
} else {
el.style.color = '#9E9D95';
}
el.innerHTML = 200 - length;
return new Ember.Handlebars.SafeString(el.outerHTML);
});
__exports__["default"] = countCharacters;
});
define("ghost/helpers/gh-count-down-characters",
["exports"],
function(__exports__) {
"use strict";
var countDownCharacters = Ember.Handlebars.makeBoundHelper(function (content, maxCharacters) {
var el = document.createElement('span'),
length = content ? content.length : 0;
el.className = 'word-count';
if (length > maxCharacters) {
el.style.color = '#E25440';
} else {
el.style.color = '#9FBB58';
}
el.innerHTML = length;
return new Ember.Handlebars.SafeString(el.outerHTML);
});
__exports__["default"] = countDownCharacters;
});
define("ghost/helpers/gh-count-words",
["ghost/utils/word-count","exports"],
function(__dependency1__, __exports__) {
"use strict";
var counter = __dependency1__["default"];
var countWords = Ember.Handlebars.makeBoundHelper(function (markdown) {
if (/^\s*$/.test(markdown)) {
return '0 words';
}
var count = counter(markdown || '');
return count + (count === 1 ? ' word' : ' words');
});
__exports__["default"] = countWords;
});
define("ghost/helpers/gh-format-html",
["ghost/utils/caja-sanitizers","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global Handlebars, html_sanitize*/
var cajaSanitizers = __dependency1__["default"];
var formatHTML = Ember.Handlebars.makeBoundHelper(function (html) {
var escapedhtml = html || '';
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize HTML
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
__exports__["default"] = formatHTML;
});
define("ghost/helpers/gh-format-markdown",
["ghost/utils/caja-sanitizers","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global Showdown, Handlebars, html_sanitize*/
var cajaSanitizers = __dependency1__["default"];
var showdown,
formatMarkdown;
showdown = new Showdown.converter({extensions: ['ghostimagepreview', 'ghostgfm']});
formatMarkdown = Ember.Handlebars.makeBoundHelper(function (markdown) {
var escapedhtml = '';
// convert markdown to HTML
escapedhtml = showdown.makeHtml(markdown || '');
// replace script and iFrame
// jscs:disable
escapedhtml = escapedhtml.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
'<pre class="js-embed-placeholder">Embedded JavaScript</pre>');
escapedhtml = escapedhtml.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
'<pre class="iframe-embed-placeholder">Embedded iFrame</pre>');
// jscs:enable
// sanitize html
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
escapedhtml = html_sanitize(escapedhtml, cajaSanitizers.url, cajaSanitizers.id);
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
return new Handlebars.SafeString(escapedhtml);
});
__exports__["default"] = formatMarkdown;
});
define("ghost/helpers/gh-format-timeago",
["exports"],
function(__exports__) {
"use strict";
/* global moment */
var formatTimeago = Ember.Handlebars.makeBoundHelper(function (timeago) {
return moment(timeago).fromNow();
// stefanpenner says cool for small number of timeagos.
// For large numbers moment sucks => single Ember.Object based clock better
// https://github.com/manuelmitasch/ghost-admin-ember-demo/commit/fba3ab0a59238290c85d4fa0d7c6ed1be2a8a82e#commitcomment-5396524
});
__exports__["default"] = formatTimeago;
});
define("ghost/helpers/ghost-paths",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
// Handlebars Helper {{gh-path}}
// Usage: Assume 'http://www.myghostblog.org/myblog/'
// {{gh-path}} or {{gh-path ‘blog’}} for Ghost’s root (/myblog/)
// {{gh-path ‘admin’}} for Ghost’s admin root (/myblog/ghost/)
// {{gh-path ‘api’}} for Ghost’s api root (/myblog/ghost/api/v0.1/)
// {{gh-path 'admin' '/assets/hi.png'}} for resolved url (/myblog/ghost/assets/hi.png)
var ghostPaths = __dependency1__["default"];
function ghostPathsHelper(path, url) {
var base,
argsLength = arguments.length,
paths = ghostPaths();
// function is always invoked with at least one parameter, so if
// arguments.length is 1 there were 0 arguments passed in explicitly
if (argsLength === 1) {
path = 'blog';
} else if (argsLength === 2 && !/^(blog|admin|api)$/.test(path)) {
url = path;
path = 'blog';
}
switch (path.toString()) {
case 'blog':
base = paths.blogRoot;
break;
case 'admin':
base = paths.adminRoot;
break;
case 'api':
base = paths.apiRoot;
break;
default:
base = paths.blogRoot;
break;
}
// handle leading and trailing slashes
base = base[base.length - 1] !== '/' ? base + '/' : base;
if (url && url.length > 0) {
if (url[0] === '/') {
url = url.substr(1);
}
base = base + url;
}
return new Ember.Handlebars.SafeString(base);
}
__exports__["default"] = ghostPathsHelper;
});
define("ghost/initializers/authentication",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ghostPaths = __dependency1__["default"];
var Ghost,
AuthenticationInitializer;
Ghost = ghostPaths();
AuthenticationInitializer = {
name: 'authentication',
before: 'simple-auth',
after: 'registerTrailingLocationHistory',
initialize: function (container) {
window.ENV = window.ENV || {};
window.ENV['simple-auth'] = {
authenticationRoute: 'signin',
routeAfterAuthentication: 'content',
authorizer: 'simple-auth-authorizer:oauth2-bearer'
};
SimpleAuth.Session.reopen({
user: Ember.computed(function () {
return container.lookup('store:main').find('user', 'me');
})
});
SimpleAuth.Authenticators.OAuth2.reopen({
serverTokenEndpoint: Ghost.apiRoot + '/authentication/token',
serverTokenRevocationEndpoint: Ghost.apiRoot + '/authentication/revoke',
refreshAccessTokens: true,
makeRequest: function (url, data) {
data.client_id = 'ghost-admin';
return this._super(url, data);
}
});
SimpleAuth.Stores.LocalStorage.reopen({
key: 'ghost' + (Ghost.subdir.indexOf('/') === 0 ? '-' + Ghost.subdir.substr(1) : '') + ':session'
});
}
};
__exports__["default"] = AuthenticationInitializer;
});
define("ghost/initializers/dropdown",
["ghost/utils/dropdown-service","exports"],
function(__dependency1__, __exports__) {
"use strict";
var DropdownService = __dependency1__["default"];
var dropdownInitializer = {
name: 'dropdown',
initialize: function (container, application) {
application.register('dropdown:service', DropdownService);
// Inject dropdowns
application.inject('component:gh-dropdown', 'dropdown', 'dropdown:service');
application.inject('component:gh-dropdown-button', 'dropdown', 'dropdown:service');
application.inject('controller:modals.delete-post', 'dropdown', 'dropdown:service');
application.inject('controller:modals.transfer-owner', 'dropdown', 'dropdown:service');
application.inject('route:application', 'dropdown', 'dropdown:service');
// Inject popovers
application.inject('component:gh-popover', 'dropdown', 'dropdown:service');
application.inject('component:gh-popover-button', 'dropdown', 'dropdown:service');
application.inject('route:application', 'dropdown', 'dropdown:service');
}
};
__exports__["default"] = dropdownInitializer;
});
define("ghost/initializers/ghost-config",
["exports"],
function(__exports__) {
"use strict";
var ConfigInitializer = {
name: 'config',
initialize: function (container, application) {
var apps = $('body').data('apps'),
tagsUI = $('body').data('tagsui'),
fileStorage = $('body').data('filestorage'),
blogUrl = $('body').data('blogurl');
application.register(
'ghost:config', {apps: apps, fileStorage: fileStorage, blogUrl: blogUrl, tagsUI: tagsUI}, {instantiate: false}
);
application.inject('route', 'config', 'ghost:config');
application.inject('controller', 'config', 'ghost:config');
application.inject('component', 'config', 'ghost:config');
}
};
__exports__["default"] = ConfigInitializer;
});
define("ghost/initializers/ghost-paths",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ghostPaths = __dependency1__["default"];
var ghostPathsInitializer = {
name: 'ghost-paths',
after: 'store',
initialize: function (container, application) {
application.register('ghost:paths', ghostPaths(), {instantiate: false});
application.inject('route', 'ghostPaths', 'ghost:paths');
application.inject('model', 'ghostPaths', 'ghost:paths');
application.inject('controller', 'ghostPaths', 'ghost:paths');
}
};
__exports__["default"] = ghostPathsInitializer;
});
define("ghost/initializers/notifications",
["ghost/utils/notifications","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Notifications = __dependency1__["default"];
var injectNotificationsInitializer = {
name: 'injectNotifications',
before: 'authentication',
initialize: function (container, application) {
application.register('notifications:main', Notifications);
application.inject('controller', 'notifications', 'notifications:main');
application.inject('component', 'notifications', 'notifications:main');
application.inject('router', 'notifications', 'notifications:main');
application.inject('route', 'notifications', 'notifications:main');
}
};
__exports__["default"] = injectNotificationsInitializer;
});
define("ghost/initializers/store-injector",
["exports"],
function(__exports__) {
"use strict";
var StoreInjector = {
name: 'store-injector',
after: 'store',
initialize: function (container, application) {
application.inject('component:gh-role-selector', 'store', 'store:main');
}
};
__exports__["default"] = StoreInjector;
});
define("ghost/initializers/trailing-history",
["exports"],
function(__exports__) {
"use strict";
/*global Ember */
var trailingHistory,
registerTrailingLocationHistory;
trailingHistory = Ember.HistoryLocation.extend({
formatURL: function () {
// jscs: disable
return this._super.apply(this, arguments).replace(/\/?$/, '/');
// jscs: enable
}
});
registerTrailingLocationHistory = {
name: 'registerTrailingLocationHistory',
initialize: function (container, application) {
application.register('location:trailing-history', trailingHistory);
}
};
__exports__["default"] = registerTrailingLocationHistory;
});
define("ghost/mixins/body-event-listener",
["exports"],
function(__exports__) {
"use strict";
// Code modified from Addepar/ember-widgets
// https://github.com/Addepar/ember-widgets/blob/master/src/mixins.coffee#L39
var BodyEventListener = Ember.Mixin.create({
bodyElementSelector: 'html',
bodyClick: Ember.K,
init: function () {
this._super();
return Ember.run.next(this, this._setupDocumentHandlers);
},
willDestroy: function () {
this._super();
return this._removeDocumentHandlers();
},
_setupDocumentHandlers: function () {
if (this._clickHandler) {
return;
}
var self = this;
this._clickHandler = function () {
return self.bodyClick();
};
return $(this.get('bodyElementSelector')).on('click', this._clickHandler);
},
_removeDocumentHandlers: function () {
$(this.get('bodyElementSelector')).off('click', this._clickHandler);
this._clickHandler = null;
},
// http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element
click: function (event) {
return event.stopPropagation();
}
});
__exports__["default"] = BodyEventListener;
});
define("ghost/mixins/current-user-settings",
["exports"],
function(__exports__) {
"use strict";
var CurrentUserSettings = Ember.Mixin.create({
currentUser: function () {
return this.store.find('user', 'me');
},
transitionAuthor: function () {
var self = this;
return function (user) {
if (user.get('isAuthor')) {
return self.transitionTo('settings.users.user', user);
}
return user;
};
},
transitionEditor: function () {
var self = this;
return function (user) {
if (user.get('isEditor')) {
return self.transitionTo('settings.users');
}
return user;
};
}
});
__exports__["default"] = CurrentUserSettings;
});
define("ghost/mixins/dropdown-mixin",
["exports"],
function(__exports__) {
"use strict";
/*
Dropdowns and their buttons are evented and do not propagate clicks.
*/
var DropdownMixin = Ember.Mixin.create(Ember.Evented, {
classNameBindings: ['isOpen:open:closed'],
isOpen: false,
click: function (event) {
this._super(event);
return event.stopPropagation();
}
});
__exports__["default"] = DropdownMixin;
});
define("ghost/mixins/editor-base-controller",
["ghost/mixins/marker-manager","ghost/models/post","ghost/utils/bound-one-way","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
/* global console */
var MarkerManager = __dependency1__["default"];
var PostModel = __dependency2__["default"];
var boundOneWay = __dependency3__["default"];
var watchedProps,
EditorControllerMixin;
// this array will hold properties we need to watch
// to know if the model has been changed (`controller.isDirty`)
watchedProps = ['scratch', 'titleScratch', 'model.isDirty', 'tags.[]'];
PostModel.eachAttribute(function (name) {
watchedProps.push('model.' + name);
});
EditorControllerMixin = Ember.Mixin.create(MarkerManager, {
needs: ['post-tags-input', 'post-settings-menu'],
init: function () {
var self = this;
this._super();
window.onbeforeunload = function () {
return self.get('isDirty') ? self.unloadDirtyMessage() : null;
};
},
/**
* By default, a post will not change its publish state.
* Only with a user-set value (via setSaveType action)
* can the post's status change.
*/
willPublish: boundOneWay('isPublished'),
// Make sure editor starts with markdown shown
isPreview: false,
// set by the editor route and `isDirty`. useful when checking
// whether the number of tags has changed for `isDirty`.
previousTagNames: null,
tagNames: Ember.computed('tags.@each.name', function () {
return this.get('tags').mapBy('name');
}),
// compares previousTagNames to tagNames
tagNamesEqual: function () {
var tagNames = this.get('tagNames'),
previousTagNames = this.get('previousTagNames'),
hashCurrent,
hashPrevious;
// beware! even if they have the same length,
// that doesn't mean they're the same.
if (tagNames.length !== previousTagNames.length) {
return false;
}
// instead of comparing with slow, nested for loops,
// perform join on each array and compare the strings
hashCurrent = tagNames.join('');
hashPrevious = previousTagNames.join('');
return hashCurrent === hashPrevious;
},
// a hook created in editor-base-route's setupController
modelSaved: function () {
var model = this.get('model');
// safer to updateTags on save in one place
// rather than in all other places save is called
model.updateTags();
// set previousTagNames to current tagNames for isDirty check
this.set('previousTagNames', this.get('tagNames'));
// `updateTags` triggers `isDirty => true`.
// for a saved model it would otherwise be false.
// if the two "scratch" properties (title and content) match the model, then
// it's ok to set isDirty to false
if (this.get('titleScratch') === model.get('title') &&
this.get('scratch') === model.get('markdown')) {
this.set('isDirty', false);
}
},
// an ugly hack, but necessary to watch all the model's properties
// and more, without having to be explicit and do it manually
isDirty: Ember.computed.apply(Ember, watchedProps.concat(function (key, value) {
if (arguments.length > 1) {
return value;
}
var model = this.get('model'),
markdown = this.get('markdown'),
title = this.get('title'),
titleScratch = this.get('titleScratch'),
scratch = this.getMarkdown().withoutMarkers,
changedAttributes;
if (!this.tagNamesEqual()) {
return true;
}
if (titleScratch !== title) {
return true;
}
// since `scratch` is not model property, we need to check
// it explicitly against the model's markdown attribute
if (markdown !== scratch) {
return true;
}
// models created on the client always return `isDirty: true`,
// so we need to see which properties have actually changed.
if (model.get('isNew')) {
changedAttributes = Ember.keys(model.changedAttributes());
if (changedAttributes.length) {
return true;
}
return false;
}
// even though we use the `scratch` prop to show edits,
// which does *not* change the model's `isDirty` property,
// `isDirty` will tell us if the other props have changed,
// as long as the model is not new (model.isNew === false).
return model.get('isDirty');
})),
// used on window.onbeforeunload
unloadDirtyMessage: function () {
return '==============================\n\n' +
'Hey there! It looks like you\'re in the middle of writing' +
' something and you haven\'t saved all of your content.' +
'\n\nSave before you go!\n\n' +
'==============================';
},
// TODO: This has to be moved to the I18n localization file.
// This structure is supposed to be close to the i18n-localization which will be used soon.
messageMap: {
errors: {
post: {
published: {
published: 'Update failed.',
draft: 'Saving failed.'
},
draft: {
published: 'Publish failed.',
draft: 'Saving failed.'
}
}
},
success: {
post: {
published: {
published: 'Updated.',
draft: 'Saved.'
},
draft: {
published: 'Published!',
draft: 'Saved.'
}
}
}
},
showSaveNotification: function (prevStatus, status, delay) {
var message = this.messageMap.success.post[prevStatus][status];
this.notifications.showSuccess(message, {delayed: delay});
},
showErrorNotification: function (prevStatus, status, errors, delay) {
var message = this.messageMap.errors.post[prevStatus][status];
message += '<br />' + errors[0].message;
this.notifications.showError(message, {delayed: delay});
},
shouldFocusTitle: Ember.computed.alias('model.isNew'),
shouldFocusEditor: Ember.computed.not('model.isNew'),
actions: {
save: function (options) {
var status = this.get('willPublish') ? 'published' : 'draft',
prevStatus = this.get('status'),
isNew = this.get('isNew'),
autoSaveId = this.get('autoSaveId'),
timedSaveId = this.get('timedSaveId'),
self = this,
psmController = this.get('controllers.post-settings-menu'),
promise;
options = options || {};
if (autoSaveId) {
Ember.run.cancel(autoSaveId);
this.set('autoSaveId', null);
}
if (timedSaveId) {
Ember.run.cancel(timedSaveId);
this.set('timedSaveId', null);
}
self.notifications.closePassive();
// ensure an incomplete tag is finalised before save
this.get('controllers.post-tags-input').send('addNewTag');
// Set the properties that are indirected
// set markdown equal to what's in the editor, minus the image markers.
this.set('markdown', this.getMarkdown().withoutMarkers);
this.set('status', status);
// Set a default title
if (!this.get('titleScratch')) {
this.set('titleScratch', '(Untitled)');
}
this.set('title', this.get('titleScratch'));
this.set('meta_title', psmController.get('metaTitleScratch'));
this.set('meta_description', psmController.get('metaDescriptionScratch'));
if (!this.get('slug')) {
// Cancel any pending slug generation that may still be queued in the
// run loop because we need to run it before the post is saved.
Ember.run.cancel(psmController.get('debounceId'));
psmController.generateAndSetSlug('slug');
}
promise = Ember.RSVP.resolve(psmController.get('lastPromise')).then(function () {
return self.get('model').save(options).then(function (model) {
if (!options.silent) {
self.showSaveNotification(prevStatus, model.get('status'), isNew ? true : false);
}
return model;
});
}).catch(function (errors) {
if (!options.silent) {
self.showErrorNotification(prevStatus, self.get('status'), errors);
}
self.set('status', prevStatus);
return Ember.RSVP.reject(errors);
});
psmController.set('lastPromise', promise);
return promise;
},
setSaveType: function (newType) {
if (newType === 'publish') {
this.set('willPublish', true);
} else if (newType === 'draft') {
this.set('willPublish', false);
} else {
console.warn('Received invalid save type; ignoring.');
}
},
// set from a `sendAction` on the codemirror component,
// so that we get a reference for handling uploads.
setCodeMirror: function (codemirrorComponent) {
var codemirror = codemirrorComponent.get('codemirror');
this.set('codemirrorComponent', codemirrorComponent);
this.set('codemirror', codemirror);
},
// fired from the gh-markdown component when an image upload starts
disableCodeMirror: function () {
this.get('codemirrorComponent').disableCodeMirror();
},
// fired from the gh-markdown component when an image upload finishes
enableCodeMirror: function () {
this.get('codemirrorComponent').enableCodeMirror();
},
// Match the uploaded file to a line in the editor, and update that line with a path reference
// ensuring that everything ends up in the correct place and format.
handleImgUpload: function (e, resultSrc) {
var editor = this.get('codemirror'),
line = this.findLine(Ember.$(e.currentTarget).attr('id')),
lineNumber = editor.getLineNumber(line),
// jscs:disable
match = line.text.match(/\([^\n]*\)?/),
// jscs:enable
replacement = '(http://)';
if (match) {
// simple case, we have the parenthesis
editor.setSelection(
{line: lineNumber, ch: match.index + 1},
{line: lineNumber, ch: match.index + match[0].length - 1}
);
} else {
// jscs:disable
match = line.text.match(/\]/);
// jscs:enable
if (match) {
editor.replaceRange(
replacement,
{line: lineNumber, ch: match.index + 1},
{line: lineNumber, ch: match.index + 1}
);
editor.setSelection(
{line: lineNumber, ch: match.index + 2},
{line: lineNumber, ch: match.index + replacement.length}
);
}
}
editor.replaceSelection(resultSrc);
},
togglePreview: function (preview) {
this.set('isPreview', preview);
},
autoSave: function () {
if (this.get('model.isDraft')) {
var autoSaveId,
timedSaveId;
timedSaveId = Ember.run.throttle(this, 'send', 'save', {silent: true, disableNProgress: true}, 60000, false);
this.set('timedSaveId', timedSaveId);
autoSaveId = Ember.run.debounce(this, 'send', 'save', {silent: true, disableNProgress: true}, 3000);
this.set('autoSaveId', autoSaveId);
}
},
autoSaveNew: function () {
if (this.get('isNew')) {
this.send('save', {silent: true, disableNProgress: true});
}
}
}
});
__exports__["default"] = EditorControllerMixin;
});
define("ghost/mixins/editor-base-route",
["ghost/mixins/shortcuts-route","ghost/mixins/style-body","ghost/mixins/loading-indicator","ghost/utils/editor-shortcuts","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var ShortcutsRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var loadingIndicator = __dependency3__["default"];
var editorShortcuts = __dependency4__["default"];
var EditorBaseRoute = Ember.Mixin.create(styleBody, ShortcutsRoute, loadingIndicator, {
classNames: ['editor'],
actions: {
save: function () {
this.get('controller').send('save');
},
publish: function () {
var controller = this.get('controller');
controller.send('setSaveType', 'publish');
controller.send('save');
},
toggleZenMode: function () {
Ember.$('body').toggleClass('zen');
},
// The actual functionality is implemented in utils/codemirror-shortcuts
codeMirrorShortcut: function (options) {
// Only fire editor shortcuts when the editor has focus.
if (Ember.$('.CodeMirror.CodeMirror-focused').length > 0) {
this.get('controller.codemirror').shortcut(options.type);
}
},
willTransition: function (transition) {
var controller = this.get('controller'),
scratch = controller.get('scratch'),
controllerIsDirty = controller.get('isDirty'),
model = controller.get('model'),
state = model.getProperties('isDeleted', 'isSaving', 'isDirty', 'isNew'),
fromNewToEdit,
deletedWithoutChanges;
fromNewToEdit = this.get('routeName') === 'editor.new' &&
transition.targetName === 'editor.edit' &&
transition.intent.contexts &&
transition.intent.contexts[0] &&
transition.intent.contexts[0].id === model.get('id');
deletedWithoutChanges = state.isDeleted &&
(state.isSaving || !state.isDirty);
this.send('closeSettingsMenu');
if (!fromNewToEdit && !deletedWithoutChanges && controllerIsDirty) {
transition.abort();
this.send('openModal', 'leave-editor', [controller, transition]);
return;
}
// The controller may hold model state that will be lost in the transition,
// so we need to apply it now.
if (fromNewToEdit && controllerIsDirty) {
if (scratch !== model.get('markdown')) {
model.set('markdown', scratch);
}
}
if (state.isNew) {
model.deleteRecord();
}
// since the transition is now certain to complete..
window.onbeforeunload = null;
// remove model-related listeners created in editor-base-route
this.detachModelHooks(controller, model);
}
},
renderTemplate: function (controller, model) {
this._super(controller, model);
this.render('post-settings-menu', {
into: 'application',
outlet: 'settings-menu',
model: model
});
},
shortcuts: editorShortcuts,
attachModelHooks: function (controller, model) {
// this will allow us to track when the model is saved and update the controller
// so that we can be sure controller.isDirty is correct, without having to update the
// controller on each instance of `model.save()`.
//
// another reason we can't do this on `model.save().then()` is because the post-settings-menu
// also saves the model, and passing messages is difficult because we have two
// types of editor controllers, and the PSM also exists on the posts.post route.
//
// The reason we can't just keep this functionality in the editor controller is
// because we need to remove these handlers on `willTransition` in the editor route.
model.on('didCreate', controller, controller.get('modelSaved'));
model.on('didUpdate', controller, controller.get('modelSaved'));
},
detachModelHooks: function (controller, model) {
model.off('didCreate', controller, controller.get('modelSaved'));
model.off('didUpdate', controller, controller.get('modelSaved'));
},
setupController: function (controller, model) {
this._super(controller, model);
var tags = model.get('tags');
controller.set('scratch', model.get('markdown'));
controller.set('titleScratch', model.get('title'));
if (tags) {
// used to check if anything has changed in the editor
controller.set('previousTagNames', tags.mapBy('name'));
} else {
controller.set('previousTagNames', []);
}
// attach model-related listeners created in editor-base-route
this.attachModelHooks(controller, model);
}
});
__exports__["default"] = EditorBaseRoute;
});
define("ghost/mixins/editor-base-view",
["ghost/utils/set-scroll-classname","exports"],
function(__dependency1__, __exports__) {
"use strict";
var setScrollClassName = __dependency1__["default"];
var EditorViewMixin = Ember.Mixin.create({
// create a hook for jQuery logic that will run after
// a view and all child views have been rendered,
// since didInsertElement runs only when the view's el
// has rendered, and not necessarily all child views.
//
// http://mavilein.github.io/javascript/2013/08/01/Ember-JS-After-Render-Event/
// http://emberjs.com/api/classes/Ember.run.html#method_next
scheduleAfterRender: function () {
Ember.run.scheduleOnce('afterRender', this, this.afterRenderEvent);
}.on('didInsertElement'),
// all child views will have rendered when this fires
afterRenderEvent: function () {
var $previewViewPort = this.$('.js-entry-preview-content');
// cache these elements for use in other methods
this.set('$previewViewPort', $previewViewPort);
this.set('$previewContent', this.$('.js-rendered-markdown'));
$previewViewPort.scroll(Ember.run.bind($previewViewPort, setScrollClassName, {
target: this.$('.js-entry-preview'),
offset: 10
}));
},
removeScrollHandlers: function () {
this.get('$previewViewPort').off('scroll');
}.on('willDestroyElement'),
// updated when gh-codemirror component scrolls
markdownScrollInfo: null,
// percentage of scroll position to set htmlPreview
scrollPosition: Ember.computed('markdownScrollInfo', function () {
if (!this.get('markdownScrollInfo')) {
return 0;
}
var scrollInfo = this.get('markdownScrollInfo'),
markdownHeight,
previewHeight,
ratio;
markdownHeight = scrollInfo.height - scrollInfo.clientHeight;
previewHeight = this.get('$previewContent').height() - this.get('$previewViewPort').height();
ratio = previewHeight / markdownHeight;
return scrollInfo.top * ratio;
})
});
__exports__["default"] = EditorViewMixin;
});
define("ghost/mixins/loading-indicator",
["exports"],
function(__exports__) {
"use strict";
// mixin used for routes to display a loading indicator when there is network activity
var loaderOptions,
loadingIndicator;
loaderOptions = {
showSpinner: false
};
NProgress.configure(loaderOptions);
loadingIndicator = Ember.Mixin.create({
actions: {
loading: function () {
NProgress.start();
this.router.one('didTransition', function () {
NProgress.done();
});
return true;
},
error: function () {
NProgress.done();
return true;
}
}
});
__exports__["default"] = loadingIndicator;
});
define("ghost/mixins/marker-manager",
["exports"],
function(__exports__) {
"use strict";
var MarkerManager = Ember.Mixin.create({
// jscs:disable
imageMarkdownRegex: /^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim,
markerRegex: /\{<([\w\W]*?)>\}/,
// jscs:enable
uploadId: 1,
// create an object that will be shared amongst instances.
// makes it easier to use helper functions in different modules
markers: {},
// Add markers to the line if it needs one
initMarkers: function (line) {
var imageMarkdownRegex = this.get('imageMarkdownRegex'),
markerRegex = this.get('markerRegex'),
editor = this.get('codemirror'),
isImage = line.text.match(imageMarkdownRegex),
hasMarker = line.text.match(markerRegex);
if (isImage && !hasMarker) {
this.addMarker(line, editor.getLineNumber(line));
}
},
// Get the markdown with all the markers stripped
getMarkdown: function (value) {
var marker, id,
editor = this.get('codemirror'),
markers = this.get('markers'),
markerRegexForId = this.get('markerRegexForId'),
oldValue = value || editor.getValue(),
newValue = oldValue;
for (id in markers) {
if (markers.hasOwnProperty(id)) {
marker = markers[id];
newValue = newValue.replace(markerRegexForId(id), '');
}
}
return {
withMarkers: oldValue,
withoutMarkers: newValue
};
},
// check the given line to see if it has an image, and if it correctly has a marker
// in the special case of lines which were just pasted in, any markers are removed to prevent duplication
checkLine: function (ln, mode) {
var editor = this.get('codemirror'),
line = editor.getLineHandle(ln),
imageMarkdownRegex = this.get('imageMarkdownRegex'),
markerRegex = this.get('markerRegex'),
isImage = line.text.match(imageMarkdownRegex),
hasMarker;
// We care if it is an image
if (isImage) {
hasMarker = line.text.match(markerRegex);
if (hasMarker && (mode === 'paste' || mode === 'undo')) {
// this could be a duplicate, and won't be a real marker
this.stripMarkerFromLine(line);
}
if (!hasMarker) {
this.addMarker(line, ln);
}
}
// TODO: hasMarker but no image?
},
// Add a marker to the given line
// Params:
// line - CodeMirror LineHandle
// ln - line number
addMarker: function (line, ln) {
var marker,
markers = this.get('markers'),
editor = this.get('codemirror'),
uploadPrefix = 'image_upload',
uploadId = this.get('uploadId'),
magicId = '{<' + uploadId + '>}',
newText = magicId + line.text;
editor.replaceRange(
newText,
{line: ln, ch: 0},
{line: ln, ch: newText.length}
);
marker = editor.markText(
{line: ln, ch: 0},
{line: ln, ch: (magicId.length)},
{collapsed: true}
);
markers[uploadPrefix + '_' + uploadId] = marker;
this.set('uploadId', uploadId += 1);
},
// Check each marker to see if it is still present in the editor and if it still corresponds to image markdown
// If it is no longer a valid image, remove it
checkMarkers: function () {
var id, marker, line,
editor = this.get('codemirror'),
markers = this.get('markers'),
imageMarkdownRegex = this.get('imageMarkdownRegex');
for (id in markers) {
if (markers.hasOwnProperty(id)) {
marker = markers[id];
if (marker.find()) {
line = editor.getLineHandle(marker.find().from.line);
if (!line.text.match(imageMarkdownRegex)) {
this.removeMarker(id, marker, line);
}
} else {
this.removeMarker(id, marker);
}
}
}
},
// this is needed for when we transition out of the editor.
// since the markers object is persistent and shared between classes that
// mix in this mixin, we need to make sure markers don't carry over between edits.
clearMarkers: function () {
var markers = this.get('markers'),
id,
marker;
// can't just `this.set('markers', {})`,
// since it wouldn't apply to this mixin,
// but only to the class that mixed this mixin in
for (id in markers) {
if (markers.hasOwnProperty(id)) {
marker = markers[id];
delete markers[id];
marker.clear();
}
}
},
// Remove a marker
// Will be passed a LineHandle if we already know which line the marker is on
removeMarker: function (id, marker, line) {
var markers = this.get('markers');
delete markers[id];
marker.clear();
if (line) {
this.stripMarkerFromLine(line);
} else {
this.findAndStripMarker(id);
}
},
// Removes the marker on the given line if there is one
stripMarkerFromLine: function (line) {
var editor = this.get('codemirror'),
ln = editor.getLineNumber(line),
// jscs:disable
markerRegex = /\{<([\w\W]*?)>\}/,
// jscs:enable
markerText = line.text.match(markerRegex);
if (markerText) {
editor.replaceRange(
'',
{line: ln, ch: markerText.index},
{line: ln, ch: markerText.index + markerText[0].length}
);
}
},
// the regex
markerRegexForId: function (id) {
id = id.replace('image_upload_', '');
return new RegExp('\\{<' + id + '>\\}', 'gmi');
},
// Find a marker in the editor by id & remove it
// Goes line by line to find the marker by it's text if we've lost track of the TextMarker
findAndStripMarker: function (id) {
var self = this,
editor = this.get('codemirror');
editor.eachLine(function (line) {
var markerText = self.markerRegexForId(id).exec(line.text),
ln;
if (markerText) {
ln = editor.getLineNumber(line);
editor.replaceRange(
'',
{line: ln, ch: markerText.index},
{line: ln, ch: markerText.index + markerText[0].length}
);
}
});
},
// Find the line with the marker which matches
findLine: function (resultId) {
var editor = this.get('codemirror'),
markers = this.get('markers');
// try to find the right line to replace
if (markers.hasOwnProperty(resultId) && markers[resultId].find()) {
return editor.getLineHandle(markers[resultId].find().from.line);
}
return false;
}
});
__exports__["default"] = MarkerManager;
});
define("ghost/mixins/nprogress-save",
["exports"],
function(__exports__) {
"use strict";
var NProgressSaveMixin = Ember.Mixin.create({
save: function (options) {
if (options && options.disableNProgress) {
return this._super(options);
}
NProgress.start();
return this._super(options).then(function (value) {
NProgress.done();
return value;
}).catch(function (error) {
NProgress.done();
return Ember.RSVP.reject(error);
});
}
});
__exports__["default"] = NProgressSaveMixin;
});
define("ghost/mixins/pagination-controller",
["ghost/utils/ajax","exports"],
function(__dependency1__, __exports__) {
"use strict";
var getRequestErrorMessage = __dependency1__.getRequestErrorMessage;
var PaginationControllerMixin = Ember.Mixin.create({
// set from PaginationRouteMixin
paginationSettings: null,
// holds the next page to load during infinite scroll
nextPage: null,
// indicates whether we're currently loading the next page
isLoading: null,
/**
*
* @param {object} options: {
* modelType: <String> name of the model that will be paginated
* }
*/
init: function (options) {
this._super();
var metadata = this.store.metadataFor(options.modelType);
this.set('nextPage', metadata.pagination.next);
},
/**
* Takes an ajax response, concatenates any error messages, then generates an error notification.
* @param {jqXHR} response The jQuery ajax reponse object.
* @return
*/
reportLoadError: function (response) {
var message = 'A problem was encountered while loading more records';
if (response) {
// Get message from response
message += ': ' + getRequestErrorMessage(response, true);
} else {
message += '.';
}
this.notifications.showError(message);
},
actions: {
/**
* Loads the next paginated page of posts into the ember-data store. Will cause the posts list UI to update.
* @return
*/
loadNextPage: function () {
var self = this,
store = this.get('store'),
recordType = this.get('model').get('type'),
nextPage = this.get('nextPage'),
paginationSettings = this.get('paginationSettings');
if (nextPage) {
this.set('isLoading', true);
this.set('paginationSettings.page', nextPage);
store.find(recordType, paginationSettings).then(function () {
var metadata = store.metadataFor(recordType);
self.set('nextPage', metadata.pagination.next);
self.set('isLoading', false);
}, function (response) {
self.reportLoadError(response);
});
}
}
}
});
__exports__["default"] = PaginationControllerMixin;
});
define("ghost/mixins/pagination-route",
["exports"],
function(__exports__) {
"use strict";
var defaultPaginationSettings,
PaginationRoute;
defaultPaginationSettings = {
page: 1,
limit: 15
};
PaginationRoute = Ember.Mixin.create({
/**
* Sets up pagination details
* @param {object} settings specifies additional pagination details
*/
setupPagination: function (settings) {
settings = settings || {};
for (var key in defaultPaginationSettings) {
if (defaultPaginationSettings.hasOwnProperty(key)) {
if (!settings.hasOwnProperty(key)) {
settings[key] = defaultPaginationSettings[key];
}
}
}
this.set('paginationSettings', settings);
this.controller.set('paginationSettings', settings);
}
});
__exports__["default"] = PaginationRoute;
});
define("ghost/mixins/pagination-view-infinite-scroll",
["exports"],
function(__exports__) {
"use strict";
var PaginationViewInfiniteScrollMixin = Ember.Mixin.create({
/**
* Determines if we are past a scroll point where we need to fetch the next page
* @param {object} event The scroll event
*/
checkScroll: function (event) {
var element = event.target,
triggerPoint = 100,
controller = this.get('controller'),
isLoading = controller.get('isLoading');
// If we haven't passed our threshold or we are already fetching content, exit
if (isLoading || (element.scrollTop + element.clientHeight + triggerPoint <= element.scrollHeight)) {
return;
}
controller.send('loadNextPage');
},
/**
* Bind to the scroll event once the element is in the DOM
*/
attachCheckScroll: function () {
var el = this.$();
el.on('scroll', Ember.run.bind(this, this.checkScroll));
}.on('didInsertElement'),
/**
* Unbind from the scroll event when the element is no longer in the DOM
*/
detachCheckScroll: function () {
var el = this.$();
el.off('scroll');
}.on('willDestroyElement')
});
__exports__["default"] = PaginationViewInfiniteScrollMixin;
});
define("ghost/mixins/selective-save",
["exports"],
function(__exports__) {
"use strict";
// SelectiveSaveMixin adds a saveOnly method to a DS.Model.
//
// saveOnly provides a way to save one or more properties of a model while
// preserving outstanding changes to other properties.
var SelectiveSaveMixin = Ember.Mixin.create({
saveOnly: function () {
if (arguments.length === 0) {
return Ember.RSVP.resolve();
}
if (arguments.length === 1 && Ember.isArray(arguments[0])) {
return this.saveOnly.apply(this, Array.prototype.slice.call(arguments[0]));
}
var propertiesToSave = Array.prototype.slice.call(arguments),
changed,
hasMany = {},
belongsTo = {},
self = this;
changed = this.changedAttributes();
// disable observers so we can make changes to the model but not have
// them reflected by the UI
this.beginPropertyChanges();
// make a copy of any relations the model may have so they can
// be reapplied later
this.eachRelationship(function (name, meta) {
if (meta.kind === 'hasMany') {
hasMany[name] = self.get(name).slice();
return;
}
if (meta.kind === 'belongsTo') {
belongsTo[name] = self.get(name);
return;
}
});
try {
// roll back all changes to the model and then reapply only those that
// are part of the saveOnly
self.rollback();
propertiesToSave.forEach(function (name) {
if (hasMany.hasOwnProperty(name)) {
self.get(name).clear();
hasMany[name].forEach(function (relatedType) {
self.get(name).pushObject(relatedType);
});
return;
}
if (belongsTo.hasOwnProperty(name)) {
return self.updateBelongsTo(name, belongsTo[name]);
}
if (changed.hasOwnProperty(name)) {
return self.set(name, changed[name][1]);
}
});
}
catch (err) {
// if we were not able to get the model into the correct state
// put it back the way we found it and return a rejected promise
Ember.keys(changed).forEach(function (name) {
self.set(name, changed[name][1]);
});
Ember.keys(hasMany).forEach(function (name) {
self.updateHasMany(name, hasMany[name]);
});
Ember.keys(belongsTo).forEach(function (name) {
self.updateBelongsTo(name, belongsTo[name]);
});
self.endPropertyChanges();
return Ember.RSVP.reject(new Error(err.message || 'Error during saveOnly. Changes NOT saved.'));
}
return this.save().finally(function () {
// reapply any changes that were not part of the save
Ember.keys(changed).forEach(function (name) {
if (propertiesToSave.hasOwnProperty(name)) {
return;
}
self.set(name, changed[name][1]);
});
Ember.keys(hasMany).forEach(function (name) {
if (propertiesToSave.hasOwnProperty(name)) {
return;
}
self.updateHasMany(name, hasMany[name]);
});
Ember.keys(belongsTo).forEach(function (name) {
if (propertiesToSave.hasOwnProperty(name)) {
return;
}
self.updateBelongsTo(name, belongsTo[name]);
});
// signal that we're finished and normal model observation may continue
self.endPropertyChanges();
});
}
});
__exports__["default"] = SelectiveSaveMixin;
});
define("ghost/mixins/shortcuts-route",
["exports"],
function(__exports__) {
"use strict";
/* global key */
// Configure KeyMaster to respond to all shortcuts,
// even inside of
// input, textarea, and select.
key.filter = function () {
return true;
};
key.setScope('default');
/**
* Only routes can implement shortcuts.
* If you need to trigger actions on the controller,
* simply call them with `this.get('controller').send('action')`.
*
* To implement shortcuts, add this mixin to your `extend()`,
* and implement a `shortcuts` hash.
* In this hash, keys are shortcut combinations and values are route action names.
* (see [keymaster docs](https://github.com/madrobby/keymaster/blob/master/README.markdown)),
*
* ```javascript
* shortcuts: {
* 'ctrl+s, command+s': 'save',
* 'ctrl+alt+z': 'toggleZenMode'
* }
* ```
* For more complex actions, shortcuts can instead have their value
* be an object like {action, options}
* ```javascript
* shortcuts: {
* 'ctrl+k': {action: 'markdownShortcut', options: 'createLink'}
* }
* ```
* You can set the scope of your shortcut by passing a scope property.
* ```javascript
* shortcuts : {
* 'enter': {action : 'confirmModal', scope: 'modal'}
* }
* ```
* If you don't specify a scope, we use a default scope called "default".
* To have all your shortcut work in all scopes, give it the scope "all".
* Find out more at the keymaster docs
*/
var ShortcutsRoute = Ember.Mixin.create({
registerShortcuts: function () {
var self = this,
shortcuts = this.get('shortcuts');
Ember.keys(shortcuts).forEach(function (shortcut) {
var scope = shortcuts[shortcut].scope || 'default',
action = shortcuts[shortcut],
options;
if (Ember.typeOf(action) !== 'string') {
options = action.options;
action = action.action;
}
key(shortcut, scope, function (event) {
// stop things like ctrl+s from actually opening a save dialogue
event.preventDefault();
self.send(action, options);
});
});
},
removeShortcuts: function () {
var shortcuts = this.get('shortcuts');
Ember.keys(shortcuts).forEach(function (shortcut) {
key.unbind(shortcut);
});
},
activate: function () {
this._super();
if (!this.shortcuts) {
return;
}
this.registerShortcuts();
},
deactivate: function () {
this._super();
this.removeShortcuts();
}
});
__exports__["default"] = ShortcutsRoute;
});
define("ghost/mixins/style-body",
["exports"],
function(__exports__) {
"use strict";
// mixin used for routes that need to set a css className on the body tag
var styleBody = Ember.Mixin.create({
activate: function () {
this._super();
var cssClasses = this.get('classNames');
if (cssClasses) {
Ember.run.schedule('afterRender', null, function () {
cssClasses.forEach(function (curClass) {
Ember.$('body').addClass(curClass);
});
});
}
},
deactivate: function () {
this._super();
var cssClasses = this.get('classNames');
Ember.run.schedule('afterRender', null, function () {
cssClasses.forEach(function (curClass) {
Ember.$('body').removeClass(curClass);
});
});
}
});
__exports__["default"] = styleBody;
});
define("ghost/mixins/text-input",
["exports"],
function(__exports__) {
"use strict";
var BlurField = Ember.Mixin.create({
selectOnClick: false,
stopEnterKeyDownPropagation: false,
click: function (event) {
if (this.get('selectOnClick')) {
event.currentTarget.select();
}
},
keyDown: function (event) {
// stop event propagation when pressing "enter"
// most useful in the case when undesired (global) keyboard shortcuts are getting triggered while interacting
// with this particular input element.
if (this.get('stopEnterKeyDownPropagation') && event.keyCode === 13) {
event.stopPropagation();
return true;
}
}
});
__exports__["default"] = BlurField;
});
define("ghost/mixins/validation-engine",
["ghost/utils/ajax","ghost/utils/validator-extensions","ghost/validators/post","ghost/validators/setup","ghost/validators/signup","ghost/validators/signin","ghost/validators/forgotten","ghost/validators/setting","ghost/validators/reset","ghost/validators/user","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __exports__) {
"use strict";
var getRequestErrorMessage = __dependency1__.getRequestErrorMessage;
var ValidatorExtensions = __dependency2__["default"];
var PostValidator = __dependency3__["default"];
var SetupValidator = __dependency4__["default"];
var SignupValidator = __dependency5__["default"];
var SigninValidator = __dependency6__["default"];
var ForgotValidator = __dependency7__["default"];
var SettingValidator = __dependency8__["default"];
var ResetValidator = __dependency9__["default"];
var UserValidator = __dependency10__["default"];
// our extensions to the validator library
ValidatorExtensions.init();
// format errors to be used in `notifications.showErrors`.
// result is [{message: 'concatenated error messages'}]
function formatErrors(errors, opts) {
var message = 'There was an error';
opts = opts || {};
if (opts.wasSave && opts.validationType) {
message += ' saving this ' + opts.validationType;
}
if (Ember.isArray(errors)) {
// get the validator's error messages from the array.
// normalize array members to map to strings.
message = errors.map(function (error) {
if (typeof error === 'string') {
return error;
}
return error.message;
}).join('<br />');
} else if (errors instanceof Error) {
message += errors.message || '.';
} else if (typeof errors === 'object') {
// Get messages from server response
message += ': ' + getRequestErrorMessage(errors, true);
} else if (typeof errors === 'string') {
message += ': ' + errors;
} else {
message += '.';
}
// set format for notifications.showErrors
message = [{message: message}];
return message;
}
/**
* The class that gets this mixin will receive these properties and functions.
* It will be able to validate any properties on itself (or the model it passes to validate())
* with the use of a declared validator.
*/
var ValidationEngine = Ember.Mixin.create({
// these validators can be passed a model to validate when the class that
// mixes in the ValidationEngine declares a validationType equal to a key on this object.
// the model is either passed in via `this.validate({ model: object })`
// or by calling `this.validate()` without the model property.
// in that case the model will be the class that the ValidationEngine
// was mixed into, i.e. the controller or Ember Data model.
validators: {
post: PostValidator,
setup: SetupValidator,
signup: SignupValidator,
signin: SigninValidator,
forgotten: ForgotValidator,
setting: SettingValidator,
reset: ResetValidator,
user: UserValidator
},
/**
* Passses the model to the validator specified by validationType.
* Returns a promise that will resolve if validation succeeds, and reject if not.
* Some options can be specified:
*
* `format: false` - doesn't use formatErrors to concatenate errors for notifications.showErrors.
* will return whatever the specified validator returns.
* since notifications are a common usecase, `format` is true by default.
*
* `model: Object` - you can specify the model to be validated, rather than pass the default value of `this`,
* the class that mixes in this mixin.
*/
validate: function (opts) {
var model = opts.model || this,
type = this.get('validationType'),
validator = this.get('validators.' + type);
opts = opts || {};
opts.validationType = type;
return new Ember.RSVP.Promise(function (resolve, reject) {
var validationErrors;
if (!type || !validator) {
validationErrors = ['The validator specified, "' + type + '", did not exist!'];
} else {
validationErrors = validator.check(model);
}
if (Ember.isEmpty(validationErrors)) {
return resolve();
}
if (opts.format !== false) {
validationErrors = formatErrors(validationErrors, opts);
}
return reject(validationErrors);
});
},
/**
* The primary goal of this method is to override the `save` method on Ember Data models.
* This allows us to run validation before actually trying to save the model to the server.
* You can supply options to be passed into the `validate` method, since the ED `save` method takes no options.
*/
save: function (options) {
var self = this,
// this is a hack, but needed for async _super calls.
// ref: https://github.com/emberjs/ember.js/pull/4301
_super = this.__nextSuper;
options = options || {};
options.wasSave = true;
// model.destroyRecord() calls model.save() behind the scenes.
// in that case, we don't need validation checks or error propagation,
// because the model itself is being destroyed.
if (this.get('isDeleted')) {
return this._super();
}
// If validation fails, reject with validation errors.
// If save to the server fails, reject with server response.
return this.validate(options).then(function () {
return _super.call(self, options);
}).catch(function (result) {
// server save failed - validate() would have given back an array
if (!Ember.isArray(result)) {
if (options.format !== false) {
// concatenate all errors into an array with a single object: [{message: 'concatted message'}]
result = formatErrors(result, options);
} else {
// return the array of errors from the server
result = getRequestErrorMessage(result);
}
}
return Ember.RSVP.reject(result);
});
}
});
__exports__["default"] = ValidationEngine;
});
define("ghost/models/notification",
["exports"],
function(__exports__) {
"use strict";
var Notification = DS.Model.extend({
dismissible: DS.attr('boolean'),
location: DS.attr('string'),
status: DS.attr('string'),
type: DS.attr('string'),
message: DS.attr('string')
});
__exports__["default"] = Notification;
});
define("ghost/models/post",
["ghost/mixins/validation-engine","ghost/mixins/nprogress-save","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ValidationEngine = __dependency1__["default"];
var NProgressSaveMixin = __dependency2__["default"];
var Post = DS.Model.extend(NProgressSaveMixin, ValidationEngine, {
validationType: 'post',
uuid: DS.attr('string'),
title: DS.attr('string', {defaultValue: ''}),
slug: DS.attr('string'),
markdown: DS.attr('string', {defaultValue: ''}),
html: DS.attr('string'),
image: DS.attr('string'),
featured: DS.attr('boolean', {defaultValue: false}),
page: DS.attr('boolean', {defaultValue: false}),
status: DS.attr('string', {defaultValue: 'draft'}),
language: DS.attr('string', {defaultValue: 'en_US'}),
meta_title: DS.attr('string'),
meta_description: DS.attr('string'),
author: DS.belongsTo('user', {async: true}),
author_id: DS.attr('number'),
updated_at: DS.attr('moment-date'),
published_at: DS.attr('moment-date'),
published_by: DS.belongsTo('user', {async: true}),
tags: DS.hasMany('tag', {embedded: 'always'}),
// Computed post properties
isPublished: Ember.computed.equal('status', 'published'),
isDraft: Ember.computed.equal('status', 'draft'),
// remove client-generated tags, which have `id: null`.
// Ember Data won't recognize/update them automatically
// when returned from the server with ids.
updateTags: function () {
var tags = this.get('tags'),
oldTags = tags.filterBy('id', null);
tags.removeObjects(oldTags);
oldTags.invoke('deleteRecord');
},
isAuthoredByUser: function (user) {
return parseInt(user.get('id'), 10) === parseInt(this.get('author_id'), 10);
}
});
__exports__["default"] = Post;
});
define("ghost/models/role",
["exports"],
function(__exports__) {
"use strict";
var Role = DS.Model.extend({
uuid: DS.attr('string'),
name: DS.attr('string'),
description: DS.attr('string'),
created_at: DS.attr('moment-date'),
updated_at: DS.attr('moment-date'),
lowerCaseName: Ember.computed('name', function () {
return this.get('name').toLocaleLowerCase();
})
});
__exports__["default"] = Role;
});
define("ghost/models/setting",
["ghost/mixins/validation-engine","ghost/mixins/nprogress-save","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var ValidationEngine = __dependency1__["default"];
var NProgressSaveMixin = __dependency2__["default"];
var Setting = DS.Model.extend(NProgressSaveMixin, ValidationEngine, {
validationType: 'setting',
title: DS.attr('string'),
description: DS.attr('string'),
email: DS.attr('string'),
logo: DS.attr('string'),
cover: DS.attr('string'),
defaultLang: DS.attr('string'),
postsPerPage: DS.attr('number'),
forceI18n: DS.attr('boolean'),
permalinks: DS.attr('string'),
activeTheme: DS.attr('string'),
availableThemes: DS.attr()
});
__exports__["default"] = Setting;
});
define("ghost/models/slug-generator",
["exports"],
function(__exports__) {
"use strict";
var SlugGenerator = Ember.Object.extend({
ghostPaths: null,
slugType: null,
value: null,
toString: function () {
return this.get('value');
},
generateSlug: function (textToSlugify) {
var self = this,
url;
if (!textToSlugify) {
return Ember.RSVP.resolve('');
}
url = this.get('ghostPaths.url').api('slugs', this.get('slugType'), encodeURIComponent(textToSlugify));
return ic.ajax.request(url, {
type: 'GET'
}).then(function (response) {
var slug = response.slugs[0].slug;
self.set('value', slug);
return slug;
});
}
});
__exports__["default"] = SlugGenerator;
});
define("ghost/models/tag",
["exports"],
function(__exports__) {
"use strict";
var Tag = DS.Model.extend({
uuid: DS.attr('string'),
name: DS.attr('string'),
slug: DS.attr('string'),
description: DS.attr('string'),
parent_id: DS.attr('number'),
meta_title: DS.attr('string'),
meta_description: DS.attr('string')
});
__exports__["default"] = Tag;
});
define("ghost/models/user",
["ghost/mixins/validation-engine","ghost/mixins/nprogress-save","ghost/mixins/selective-save","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var ValidationEngine = __dependency1__["default"];
var NProgressSaveMixin = __dependency2__["default"];
var SelectiveSaveMixin = __dependency3__["default"];
var User = DS.Model.extend(NProgressSaveMixin, SelectiveSaveMixin, ValidationEngine, {
validationType: 'user',
uuid: DS.attr('string'),
name: DS.attr('string'),
slug: DS.attr('string'),
email: DS.attr('string'),
image: DS.attr('string'),
cover: DS.attr('string'),
bio: DS.attr('string'),
website: DS.attr('string'),
location: DS.attr('string'),
accessibility: DS.attr('string'),
status: DS.attr('string'),
language: DS.attr('string', {defaultValue: 'en_US'}),
meta_title: DS.attr('string'),
meta_description: DS.attr('string'),
last_login: DS.attr('moment-date'),
created_at: DS.attr('moment-date'),
created_by: DS.attr('number'),
updated_at: DS.attr('moment-date'),
updated_by: DS.attr('number'),
roles: DS.hasMany('role', {embedded: 'always'}),
role: Ember.computed('roles', function (name, value) {
if (arguments.length > 1) {
// Only one role per user, so remove any old data.
this.get('roles').clear();
this.get('roles').pushObject(value);
return value;
}
return this.get('roles.firstObject');
}),
// TODO: Once client-side permissions are in place,
// remove the hard role check.
isAuthor: Ember.computed.equal('role.name', 'Author'),
isEditor: Ember.computed.equal('role.name', 'Editor'),
isAdmin: Ember.computed.equal('role.name', 'Administrator'),
isOwner: Ember.computed.equal('role.name', 'Owner'),
saveNewPassword: function () {
var url = this.get('ghostPaths.url').api('users', 'password');
return ic.ajax.request(url, {
type: 'PUT',
data: {
password: [{
oldPassword: this.get('password'),
newPassword: this.get('newPassword'),
ne2Password: this.get('ne2Password')
}]
}
});
},
resendInvite: function () {
var fullUserData = this.toJSON(),
userData = {
email: fullUserData.email,
roles: fullUserData.roles
};
return ic.ajax.request(this.get('ghostPaths.url').api('users'), {
type: 'POST',
data: JSON.stringify({users: [userData]}),
contentType: 'application/json'
});
},
passwordValidationErrors: Ember.computed('password', 'newPassword', 'ne2Password', function () {
var validationErrors = [];
if (!validator.equals(this.get('newPassword'), this.get('ne2Password'))) {
validationErrors.push({message: 'Your new passwords do not match'});
}
if (!validator.isLength(this.get('newPassword'), 8)) {
validationErrors.push({message: 'Your password is not long enough. It must be at least 8 characters long.'});
}
return validationErrors;
}),
isPasswordValid: Ember.computed.empty('passwordValidationErrors.[]'),
active: function () {
return ['active', 'warn-1', 'warn-2', 'warn-3', 'warn-4', 'locked'].indexOf(this.get('status')) > -1;
}.property('status'),
invited: function () {
return ['invited', 'invited-pending'].indexOf(this.get('status')) > -1;
}.property('status'),
pending: Ember.computed.equal('status', 'invited-pending').property('status')
});
__exports__["default"] = User;
});
define("ghost/router",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
/*global Ember */
var ghostPaths = __dependency1__["default"];
// ensure we don't share routes between all Router instances
var Router = Ember.Router.extend();
Router.reopen({
location: 'trailing-history', // use HTML5 History API instead of hash-tag based URLs
rootURL: ghostPaths().adminRoot, // admin interface lives under sub-directory /ghost
clearNotifications: function () {
this.notifications.closePassive();
this.notifications.displayDelayed();
}.on('didTransition')
});
Router.map(function () {
this.route('setup');
this.route('signin');
this.route('signout');
this.route('signup', {path: '/signup/:token'});
this.route('forgotten');
this.route('reset', {path: '/reset/:token'});
this.resource('posts', {path: '/'}, function () {
this.route('post', {path: ':post_id'});
});
this.resource('editor', function () {
this.route('new', {path: ''});
this.route('edit', {path: ':post_id'});
});
this.resource('settings', function () {
this.route('general');
this.resource('settings.users', {path: '/users'}, function () {
this.route('user', {path: '/:slug'});
});
this.route('about');
this.route('tags');
});
this.route('debug');
// Redirect legacy content to posts
this.route('content');
this.route('error404', {path: '/*path'});
});
__exports__["default"] = Router;
});
define("ghost/routes/application",
["ghost/mixins/shortcuts-route","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global key */
var ShortcutsRoute = __dependency1__["default"];
var ApplicationRoute = Ember.Route.extend(SimpleAuth.ApplicationRouteMixin, ShortcutsRoute, {
afterModel: function (model, transition) {
if (this.get('session').isAuthenticated) {
transition.send('loadServerNotifications');
}
},
shortcuts: {
esc: {action: 'closePopups', scope: 'all'},
enter: {action: 'confirmModal', scope: 'modal'}
},
actions: {
authorizationFailed: function () {
var currentRoute = this.get('controller').get('currentRouteName');
if (currentRoute.split('.')[0] === 'editor') {
this.send('openModal', 'auth-failed-unsaved', this.controllerFor(currentRoute));
return;
}
this._super();
},
toggleGlobalMobileNav: function () {
this.toggleProperty('controller.showGlobalMobileNav');
},
toggleSettingsMenu: function () {
this.toggleProperty('controller.showSettingsMenu');
},
closeSettingsMenu: function () {
this.set('controller.showSettingsMenu', false);
},
closePopups: function () {
this.get('dropdown').closeDropdowns();
this.get('notifications').closeAll();
// Close right outlet if open
this.send('closeSettingsMenu');
this.send('closeModal');
},
signedIn: function () {
this.send('loadServerNotifications', true);
},
sessionAuthenticationFailed: function (error) {
if (error.errors) {
this.notifications.showErrors(error.errors);
} else {
// connection errors don't return proper status message, only req.body
this.notifications.showError('There was a problem on the server.');
}
},
sessionAuthenticationSucceeded: function () {
var self = this;
this.store.find('user', 'me').then(function (user) {
self.send('signedIn', user);
var attemptedTransition = self.get('session').get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
self.get('session').set('attemptedTransition', null);
} else {
self.transitionTo(SimpleAuth.Configuration.routeAfterAuthentication);
}
});
},
sessionInvalidationFailed: function (error) {
this.notifications.showError(error.message);
},
openModal: function (modalName, model, type) {
this.get('dropdown').closeDropdowns();
key.setScope('modal');
modalName = 'modals/' + modalName;
this.set('modalName', modalName);
// We don't always require a modal to have a controller
// so we're skipping asserting if one exists
if (this.controllerFor(modalName, true)) {
this.controllerFor(modalName).set('model', model);
if (type) {
this.controllerFor(modalName).set('imageType', type);
this.controllerFor(modalName).set('src', model.get(type));
}
}
return this.render(modalName, {
into: 'application',
outlet: 'modal'
});
},
confirmModal: function () {
var modalName = this.get('modalName');
this.send('closeModal');
if (this.controllerFor(modalName, true)) {
this.controllerFor(modalName).send('confirmAccept');
}
},
closeModal: function () {
this.disconnectOutlet({
outlet: 'modal',
parentView: 'application'
});
key.setScope('default');
},
loadServerNotifications: function (isDelayed) {
var self = this;
if (this.session.isAuthenticated) {
this.store.findAll('notification').then(function (serverNotifications) {
serverNotifications.forEach(function (notification) {
self.notifications.handleNotification(notification, isDelayed);
});
});
}
},
handleErrors: function (errors) {
var self = this;
this.notifications.clear();
errors.forEach(function (errorObj) {
self.notifications.showError(errorObj.message || errorObj);
if (errorObj.hasOwnProperty('el')) {
errorObj.el.addClass('input-error');
}
});
}
}
});
__exports__["default"] = ApplicationRoute;
});
define("ghost/routes/authenticated",
["exports"],
function(__exports__) {
"use strict";
var AuthenticatedRoute = Ember.Route.extend(SimpleAuth.AuthenticatedRouteMixin);
__exports__["default"] = AuthenticatedRoute;
});
define("ghost/routes/content",
["exports"],
function(__exports__) {
"use strict";
var ContentRoute = Ember.Route.extend({
beforeModel: function () {
this.transitionTo('posts');
}
});
__exports__["default"] = ContentRoute;
});
define("ghost/routes/debug",
["ghost/routes/authenticated","ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var loadingIndicator = __dependency3__["default"];
var DebugRoute = AuthenticatedRoute.extend(styleBody, loadingIndicator, {
classNames: ['settings'],
beforeModel: function (transition) {
this._super(transition);
var self = this;
this.store.find('user', 'me').then(function (user) {
if (user.get('isAuthor') || user.get('isEditor')) {
self.transitionTo('posts');
}
});
},
model: function () {
return this.store.find('setting', {type: 'blog,theme'}).then(function (records) {
return records.get('firstObject');
});
}
});
__exports__["default"] = DebugRoute;
});
define("ghost/routes/editor/edit",
["ghost/routes/authenticated","ghost/mixins/editor-base-route","ghost/utils/isNumber","ghost/utils/isFinite","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var base = __dependency2__["default"];
var isNumber = __dependency3__["default"];
var isFinite = __dependency4__["default"];
var EditorEditRoute = AuthenticatedRoute.extend(base, {
model: function (params) {
var self = this,
post,
postId,
paginationSettings;
postId = Number(params.post_id);
if (!isNumber(postId) || !isFinite(postId) || postId % 1 !== 0 || postId <= 0) {
return this.transitionTo('error404', 'editor/' + params.post_id);
}
post = this.store.getById('post', postId);
if (post) {
return post;
}
paginationSettings = {
id: postId,
status: 'all',
staticPages: 'all'
};
return this.store.find('user', 'me').then(function (user) {
if (user.get('isAuthor')) {
paginationSettings.author = user.get('slug');
}
return self.store.find('post', paginationSettings).then(function (records) {
var post = records.get('firstObject');
if (user.get('isAuthor') && post.isAuthoredByUser(user)) {
// do not show the post if they are an author but not this posts author
post = null;
}
if (post) {
return post;
}
return self.transitionTo('posts.index');
});
});
}
});
__exports__["default"] = EditorEditRoute;
});
define("ghost/routes/editor/index",
["exports"],
function(__exports__) {
"use strict";
var EditorRoute = Ember.Route.extend({
beforeModel: function () {
this.transitionTo('editor.new');
}
});
__exports__["default"] = EditorRoute;
});
define("ghost/routes/editor/new",
["ghost/routes/authenticated","ghost/mixins/editor-base-route","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var base = __dependency2__["default"];
var EditorNewRoute = AuthenticatedRoute.extend(base, {
model: function () {
var self = this;
return this.get('session.user').then(function (user) {
return self.store.createRecord('post', {
author: user
});
});
},
setupController: function (controller, model) {
var psm = this.controllerFor('post-settings-menu');
// make sure there are no titleObserver functions hanging around
// from previous posts
psm.removeObserver('titleScratch', psm, 'titleObserver');
this._super(controller, model);
}
});
__exports__["default"] = EditorNewRoute;
});
define("ghost/routes/error404",
["exports"],
function(__exports__) {
"use strict";
var Error404Route = Ember.Route.extend({
controllerName: 'error',
templateName: 'error',
model: function () {
return {
status: 404
};
}
});
__exports__["default"] = Error404Route;
});
define("ghost/routes/forgotten",
["ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var styleBody = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var ForgottenRoute = Ember.Route.extend(styleBody, loadingIndicator, {
classNames: ['ghost-forgotten']
});
__exports__["default"] = ForgottenRoute;
});
define("ghost/routes/mobile-index-route",
["ghost/utils/mobile","exports"],
function(__dependency1__, __exports__) {
"use strict";
var mobileQuery = __dependency1__["default"];
// Routes that extend MobileIndexRoute need to implement
// desktopTransition, a function which is called when
// the user resizes to desktop levels.
var MobileIndexRoute = Ember.Route.extend({
desktopTransition: Ember.K,
activate: function attachDesktopTransition() {
this._super();
mobileQuery.addListener(this.desktopTransitionMQ);
},
deactivate: function removeDesktopTransition() {
this._super();
mobileQuery.removeListener(this.desktopTransitionMQ);
},
setDesktopTransitionMQ: function () {
var self = this;
this.set('desktopTransitionMQ', function desktopTransitionMQ() {
if (!mobileQuery.matches) {
self.desktopTransition();
}
});
}.on('init')
});
__exports__["default"] = MobileIndexRoute;
});
define("ghost/routes/posts",
["ghost/routes/authenticated","ghost/mixins/style-body","ghost/mixins/shortcuts-route","ghost/mixins/loading-indicator","ghost/mixins/pagination-route","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var ShortcutsRoute = __dependency3__["default"];
var loadingIndicator = __dependency4__["default"];
var PaginationRouteMixin = __dependency5__["default"];
var paginationSettings,
PostsRoute;
paginationSettings = {
status: 'all',
staticPages: 'all',
page: 1
};
PostsRoute = AuthenticatedRoute.extend(ShortcutsRoute, styleBody, loadingIndicator, PaginationRouteMixin, {
classNames: ['manage'],
model: function () {
var self = this;
return this.store.find('user', 'me').then(function (user) {
if (user.get('isAuthor')) {
paginationSettings.author = user.get('slug');
}
// using `.filter` allows the template to auto-update when new models are pulled in from the server.
// we just need to 'return true' to allow all models by default.
return self.store.filter('post', paginationSettings, function (post) {
if (user.get('isAuthor')) {
return post.isAuthoredByUser(user);
}
return true;
});
});
},
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
stepThroughPosts: function (step) {
var currentPost = this.get('controller.currentPost'),
posts = this.get('controller.arrangedContent'),
length = posts.get('length'),
newPosition;
newPosition = posts.indexOf(currentPost) + step;
// if we are on the first or last item
// just do nothing (desired behavior is to not
// loop around)
if (newPosition >= length) {
return;
} else if (newPosition < 0) {
return;
}
this.transitionTo('posts.post', posts.objectAt(newPosition));
},
scrollContent: function (amount) {
var content = Ember.$('.js-content-preview'),
scrolled = content.scrollTop();
content.scrollTop(scrolled + 50 * amount);
},
shortcuts: {
'up, k': 'moveUp',
'down, j': 'moveDown',
left: 'focusList',
right: 'focusContent',
c: 'newPost'
},
actions: {
focusList: function () {
this.controller.set('keyboardFocus', 'postList');
},
focusContent: function () {
this.controller.set('keyboardFocus', 'postContent');
},
newPost: function () {
this.transitionTo('editor.new');
},
moveUp: function () {
if (this.controller.get('postContentFocused')) {
this.scrollContent(-1);
} else {
this.stepThroughPosts(-1);
}
},
moveDown: function () {
if (this.controller.get('postContentFocused')) {
this.scrollContent(1);
} else {
this.stepThroughPosts(1);
}
}
}
});
__exports__["default"] = PostsRoute;
});
define("ghost/routes/posts/index",
["ghost/routes/mobile-index-route","ghost/mixins/loading-indicator","ghost/utils/mobile","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var MobileIndexRoute = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var mobileQuery = __dependency3__["default"];
var PostsIndexRoute = MobileIndexRoute.extend(SimpleAuth.AuthenticatedRouteMixin, loadingIndicator, {
noPosts: false,
// Transition to a specific post if we're not on mobile
beforeModel: function () {
if (!mobileQuery.matches) {
return this.goToPost();
}
},
setupController: function (controller, model) {
/*jshint unused:false*/
controller.set('noPosts', this.get('noPosts'));
},
goToPost: function () {
var self = this,
// the store has been populated by PostsRoute
posts = this.store.all('post'),
post;
return this.store.find('user', 'me').then(function (user) {
post = posts.find(function (post) {
// Authors can only see posts they've written
if (user.get('isAuthor')) {
return post.isAuthoredByUser(user);
}
return true;
});
if (post) {
return self.transitionTo('posts.post', post);
}
self.set('noPosts', true);
});
},
// Mobile posts route callback
desktopTransition: function () {
this.goToPost();
}
});
__exports__["default"] = PostsIndexRoute;
});
define("ghost/routes/posts/post",
["ghost/routes/authenticated","ghost/mixins/loading-indicator","ghost/mixins/shortcuts-route","ghost/utils/isNumber","ghost/utils/isFinite","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var ShortcutsRoute = __dependency3__["default"];
var isNumber = __dependency4__["default"];
var isFinite = __dependency5__["default"];
var PostsPostRoute = AuthenticatedRoute.extend(loadingIndicator, ShortcutsRoute, {
model: function (params) {
var self = this,
post,
postId,
paginationSettings;
postId = Number(params.post_id);
if (!isNumber(postId) || !isFinite(postId) || postId % 1 !== 0 || postId <= 0) {
return this.transitionTo('error404', params.post_id);
}
post = this.store.getById('post', postId);
if (post) {
return post;
}
paginationSettings = {
id: postId,
status: 'all',
staticPages: 'all'
};
return this.store.find('user', 'me').then(function (user) {
if (user.get('isAuthor')) {
paginationSettings.author = user.get('slug');
}
return self.store.find('post', paginationSettings).then(function (records) {
var post = records.get('firstObject');
if (user.get('isAuthor') && !post.isAuthoredByUser(user)) {
// do not show the post if they are an author but not this posts author
post = null;
}
if (post) {
return post;
}
return self.transitionTo('posts.index');
});
});
},
setupController: function (controller, model) {
this._super(controller, model);
this.controllerFor('posts').set('currentPost', model);
},
shortcuts: {
'enter, o': 'openEditor',
'command+backspace, ctrl+backspace': 'deletePost'
},
actions: {
openEditor: function () {
this.transitionTo('editor.edit', this.get('controller.model'));
},
deletePost: function () {
this.send('openModal', 'delete-post', this.get('controller.model'));
}
}
});
__exports__["default"] = PostsPostRoute;
});
define("ghost/routes/reset",
["ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var styleBody = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var ResetRoute = Ember.Route.extend(styleBody, loadingIndicator, {
classNames: ['ghost-reset'],
beforeModel: function () {
if (this.get('session').isAuthenticated) {
this.notifications.showWarn('You can\'t reset your password while you\'re signed in.', {delayed: true});
this.transitionTo(SimpleAuth.Configuration.routeAfterAuthentication);
}
},
setupController: function (controller, params) {
controller.token = params.token;
},
// Clear out any sensitive information
deactivate: function () {
this._super();
this.controller.clearData();
}
});
__exports__["default"] = ResetRoute;
});
define("ghost/routes/settings",
["ghost/routes/authenticated","ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var loadingIndicator = __dependency3__["default"];
var SettingsRoute = AuthenticatedRoute.extend(styleBody, loadingIndicator, {
classNames: ['settings']
});
__exports__["default"] = SettingsRoute;
});
define("ghost/routes/settings/about",
["ghost/routes/authenticated","ghost/mixins/loading-indicator","ghost/mixins/style-body","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var styleBody = __dependency3__["default"];
var SettingsAboutRoute = AuthenticatedRoute.extend(styleBody, loadingIndicator, {
classNames: ['settings-view-about'],
cachedConfig: false,
model: function () {
var cachedConfig = this.get('cachedConfig'),
self = this;
if (cachedConfig) {
return cachedConfig;
}
return ic.ajax.request(this.get('ghostPaths.url').api('configuration'))
.then(function (configurationResponse) {
var configKeyValues = configurationResponse.configuration;
cachedConfig = {};
configKeyValues.forEach(function (configKeyValue) {
cachedConfig[configKeyValue.key] = configKeyValue.value;
});
self.set('cachedConfig', cachedConfig);
return cachedConfig;
});
}
});
__exports__["default"] = SettingsAboutRoute;
});
define("ghost/routes/settings/apps",
["ghost/routes/authenticated","ghost/mixins/current-user-settings","ghost/mixins/style-body","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var CurrentUserSettings = __dependency2__["default"];
var styleBody = __dependency3__["default"];
var AppsRoute = AuthenticatedRoute.extend(styleBody, CurrentUserSettings, {
classNames: ['settings-view-apps'],
beforeModel: function () {
if (!this.get('config.apps')) {
return this.transitionTo('settings.general');
}
return this.currentUser()
.then(this.transitionAuthor())
.then(this.transitionEditor());
},
model: function () {
return this.store.find('app');
}
});
__exports__["default"] = AppsRoute;
});
define("ghost/routes/settings/general",
["ghost/routes/authenticated","ghost/mixins/loading-indicator","ghost/mixins/current-user-settings","ghost/mixins/style-body","ghost/mixins/shortcuts-route","ghost/utils/ctrl-or-cmd","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var CurrentUserSettings = __dependency3__["default"];
var styleBody = __dependency4__["default"];
var ShortcutsRoute = __dependency5__["default"];
var ctrlOrCmd = __dependency6__["default"];
var shortcuts = {},
SettingsGeneralRoute;
shortcuts[ctrlOrCmd + '+s'] = {action: 'save'};
SettingsGeneralRoute = AuthenticatedRoute.extend(styleBody, loadingIndicator, CurrentUserSettings, ShortcutsRoute, {
classNames: ['settings-view-general'],
beforeModel: function () {
return this.currentUser()
.then(this.transitionAuthor())
.then(this.transitionEditor());
},
model: function () {
return this.store.find('setting', {type: 'blog,theme'}).then(function (records) {
return records.get('firstObject');
});
},
shortcuts: shortcuts,
actions: {
save: function () {
this.get('controller').send('save');
}
}
});
__exports__["default"] = SettingsGeneralRoute;
});
define("ghost/routes/settings/index",
["ghost/routes/mobile-index-route","ghost/mixins/current-user-settings","ghost/utils/mobile","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var MobileIndexRoute = __dependency1__["default"];
var CurrentUserSettings = __dependency2__["default"];
var mobileQuery = __dependency3__["default"];
var SettingsIndexRoute = MobileIndexRoute.extend(SimpleAuth.AuthenticatedRouteMixin, CurrentUserSettings, {
// Redirect users without permission to view settings,
// and show the settings.general route unless the user
// is mobile
beforeModel: function () {
var self = this;
return this.currentUser()
.then(this.transitionAuthor())
.then(this.transitionEditor())
.then(function () {
if (!mobileQuery.matches) {
self.transitionTo('settings.general');
}
});
},
desktopTransition: function () {
this.transitionTo('settings.general');
}
});
__exports__["default"] = SettingsIndexRoute;
});
define("ghost/routes/settings/tags",
["ghost/routes/authenticated","ghost/mixins/current-user-settings","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var CurrentUserSettings = __dependency2__["default"];
var TagsRoute = AuthenticatedRoute.extend(CurrentUserSettings, {
beforeModel: function () {
if (!this.get('config.tagsUI')) {
return this.transitionTo('settings.general');
}
return this.currentUser()
.then(this.transitionAuthor());
},
model: function () {
return this.store.find('tag');
}
});
__exports__["default"] = TagsRoute;
});
define("ghost/routes/settings/users",
["ghost/routes/authenticated","ghost/mixins/current-user-settings","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var CurrentUserSettings = __dependency2__["default"];
var UsersRoute = AuthenticatedRoute.extend(CurrentUserSettings, {
beforeModel: function () {
return this.currentUser()
.then(this.transitionAuthor());
}
});
__exports__["default"] = UsersRoute;
});
define("ghost/routes/settings/users/index",
["ghost/routes/authenticated","ghost/mixins/pagination-route","ghost/mixins/style-body","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var PaginationRouteMixin = __dependency2__["default"];
var styleBody = __dependency3__["default"];
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor') || user === currentUser;
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
__exports__["default"] = UsersIndexRoute;
});
define("ghost/routes/settings/users/user",
["ghost/routes/authenticated","ghost/mixins/style-body","ghost/mixins/shortcuts-route","ghost/utils/ctrl-or-cmd","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var ShortcutsRoute = __dependency3__["default"];
var ctrlOrCmd = __dependency4__["default"];
var shortcuts = {},
SettingsUserRoute;
shortcuts[ctrlOrCmd + '+s'] = {action: 'save'};
SettingsUserRoute = AuthenticatedRoute.extend(styleBody, ShortcutsRoute, {
classNames: ['settings-view-user'],
model: function (params) {
var self = this;
// TODO: Make custom user adapter that uses /api/users/:slug endpoint
// return this.store.find('user', { slug: params.slug });
// Instead, get all the users and then find by slug
return this.store.find('user').then(function (result) {
var user = result.findBy('slug', params.slug);
if (!user) {
return self.transitionTo('error404', 'settings/users/' + params.slug);
}
return user;
});
},
afterModel: function (user) {
var self = this;
this.store.find('user', 'me').then(function (currentUser) {
var isOwnProfile = user.get('id') === currentUser.get('id'),
isAuthor = currentUser.get('isAuthor'),
isEditor = currentUser.get('isEditor');
if (isAuthor && !isOwnProfile) {
self.transitionTo('settings.users.user', currentUser);
} else if (isEditor && !isOwnProfile && !user.get('isAuthor')) {
self.transitionTo('settings.users');
}
});
},
deactivate: function () {
var model = this.modelFor('settings.users.user');
// we want to revert any unsaved changes on exit
if (model && model.get('isDirty')) {
model.rollback();
}
this._super();
},
shortcuts: shortcuts,
actions: {
save: function () {
this.get('controller').send('save');
}
}
});
__exports__["default"] = SettingsUserRoute;
});
define("ghost/routes/setup",
["ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var styleBody = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var SetupRoute = Ember.Route.extend(styleBody, loadingIndicator, {
classNames: ['ghost-setup'],
// use the beforeModel hook to check to see whether or not setup has been
// previously completed. If it has, stop the transition into the setup page.
beforeModel: function () {
var self = this;
// If user is logged in, setup has already been completed.
if (this.get('session').isAuthenticated) {
this.transitionTo(SimpleAuth.Configuration.routeAfterAuthentication);
return;
}
// If user is not logged in, check the state of the setup process via the API
return ic.ajax.request(this.get('ghostPaths.url').api('authentication/setup'), {
type: 'GET'
}).then(function (result) {
var setup = result.setup[0].status;
if (setup) {
return self.transitionTo('signin');
}
});
}
});
__exports__["default"] = SetupRoute;
});
define("ghost/routes/signin",
["ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var styleBody = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var SigninRoute = Ember.Route.extend(styleBody, loadingIndicator, {
classNames: ['ghost-login'],
beforeModel: function () {
if (this.get('session').isAuthenticated) {
this.transitionTo(SimpleAuth.Configuration.routeAfterAuthentication);
}
},
// the deactivate hook is called after a route has been exited.
deactivate: function () {
this._super();
// clear the properties that hold the credentials from the controller
// when we're no longer on the signin screen
this.controllerFor('signin').setProperties({identification: '', password: ''});
}
});
__exports__["default"] = SigninRoute;
});
define("ghost/routes/signout",
["ghost/routes/authenticated","ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __exports__) {
"use strict";
var AuthenticatedRoute = __dependency1__["default"];
var styleBody = __dependency2__["default"];
var loadingIndicator = __dependency3__["default"];
var SignoutRoute = AuthenticatedRoute.extend(styleBody, loadingIndicator, {
classNames: ['ghost-signout'],
afterModel: function (model, transition) {
this.notifications.clear();
if (Ember.canInvoke(transition, 'send')) {
transition.send('invalidateSession');
transition.abort();
} else {
this.send('invalidateSession');
}
}
});
__exports__["default"] = SignoutRoute;
});
define("ghost/routes/signup",
["ghost/mixins/style-body","ghost/mixins/loading-indicator","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var styleBody = __dependency1__["default"];
var loadingIndicator = __dependency2__["default"];
var SignupRoute = Ember.Route.extend(styleBody, loadingIndicator, {
classNames: ['ghost-signup'],
beforeModel: function () {
if (this.get('session').isAuthenticated) {
this.notifications.showWarn('You need to sign out to register as a new user.', {delayed: true});
this.transitionTo(SimpleAuth.Configuration.routeAfterAuthentication);
}
},
model: function (params) {
var self = this,
tokenText,
email,
model = {},
re = /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/;
return new Ember.RSVP.Promise(function (resolve) {
if (!re.test(params.token)) {
self.notifications.showError('Invalid token.', {delayed: true});
return resolve(self.transitionTo('signin'));
}
tokenText = atob(params.token);
email = tokenText.split('|')[1];
model.email = email;
model.token = params.token;
return ic.ajax.request({
url: self.get('ghostPaths.url').api('authentication', 'invitation'),
type: 'GET',
dataType: 'json',
data: {
email: email
}
}).then(function (response) {
if (response && response.invitation && response.invitation[0].valid === false) {
self.notifications.showError('The invitation does not exist or is no longer valid.', {delayed: true});
return resolve(self.transitionTo('signin'));
}
resolve(model);
}).catch(function () {
resolve(model);
});
});
},
deactivate: function () {
this._super();
// clear the properties that hold the sensitive data from the controller
this.controllerFor('signup').setProperties({email: '', password: '', token: ''});
}
});
__exports__["default"] = SignupRoute;
});
define("ghost/serializers/application",
["exports"],
function(__exports__) {
"use strict";
var ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function (hash, type, record, options) {
// Our API expects an id on the posted object
options = options || {};
options.includeId = true;
// We have a plural root in the API
var root = Ember.String.pluralize(type.typeKey),
data = this.serialize(record, options);
// Don't ever pass uuid's
delete data.uuid;
hash[root] = [data];
}
});
__exports__["default"] = ApplicationSerializer;
});
define("ghost/serializers/post",
["ghost/serializers/application","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ApplicationSerializer = __dependency1__["default"];
var PostSerializer = ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
// settings for the EmbeddedRecordsMixin.
attrs: {
tags: {embedded: 'always'}
},
normalize: function (type, hash) {
// this is to enable us to still access the raw author_id
// without requiring an extra get request (since it is an
// async relationship).
hash.author_id = hash.author;
return this._super(type, hash);
},
extractSingle: function (store, primaryType, payload) {
var root = this.keyForAttribute(primaryType.typeKey),
pluralizedRoot = Ember.String.pluralize(primaryType.typeKey);
// make payload { post: { title: '', tags: [obj, obj], etc. } }.
// this allows ember-data to pull the embedded tags out again,
// in the function `updatePayloadWithEmbeddedHasMany` of the
// EmbeddedRecordsMixin (line: `if (!partial[attribute])`):
// https://github.com/emberjs/data/blob/master/packages/activemodel-adapter/lib/system/embedded_records_mixin.js#L499
payload[root] = payload[pluralizedRoot][0];
delete payload[pluralizedRoot];
return this._super.apply(this, arguments);
},
keyForAttribute: function (attr) {
return attr;
},
keyForRelationship: function (relationshipName) {
// this is a hack to prevent Ember-Data from deleting our `tags` reference.
// ref: https://github.com/emberjs/data/issues/2051
// @TODO: remove this once the situation becomes clearer what to do.
if (relationshipName === 'tags') {
return 'tag';
}
return relationshipName;
},
serializeIntoHash: function (hash, type, record, options) {
options = options || {};
// We have a plural root in the API
var root = Ember.String.pluralize(type.typeKey),
data = this.serialize(record, options);
// Don't ever pass uuid's
delete data.uuid;
// Don't send HTML
delete data.html;
hash[root] = [data];
}
});
__exports__["default"] = PostSerializer;
});
define("ghost/serializers/setting",
["ghost/serializers/application","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ApplicationSerializer = __dependency1__["default"];
var SettingSerializer = ApplicationSerializer.extend({
serializeIntoHash: function (hash, type, record, options) {
// Settings API does not want ids
options = options || {};
options.includeId = false;
var root = Ember.String.pluralize(type.typeKey),
data = this.serialize(record, options),
payload = [];
delete data.id;
Object.keys(data).forEach(function (k) {
payload.push({key: k, value: data[k]});
});
hash[root] = payload;
},
extractArray: function (store, type, _payload) {
var payload = {id: '0'};
_payload.settings.forEach(function (setting) {
payload[setting.key] = setting.value;
});
return [payload];
},
extractSingle: function (store, type, payload) {
return this.extractArray(store, type, payload).pop();
}
});
__exports__["default"] = SettingSerializer;
});
define("ghost/serializers/user",
["ghost/serializers/application","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ApplicationSerializer = __dependency1__["default"];
var UserSerializer = ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
roles: {embedded: 'always'}
},
extractSingle: function (store, primaryType, payload) {
var root = this.keyForAttribute(primaryType.typeKey),
pluralizedRoot = Ember.String.pluralize(primaryType.typeKey);
payload[root] = payload[pluralizedRoot][0];
delete payload[pluralizedRoot];
return this._super.apply(this, arguments);
},
keyForAttribute: function (attr) {
return attr;
},
keyForRelationship: function (relationshipName) {
// this is a hack to prevent Ember-Data from deleting our `tags` reference.
// ref: https://github.com/emberjs/data/issues/2051
// @TODO: remove this once the situation becomes clearer what to do.
if (relationshipName === 'roles') {
return 'role';
}
return relationshipName;
}
});
__exports__["default"] = UserSerializer;
});
define("ghost/transforms/moment-date",
["exports"],
function(__exports__) {
"use strict";
/* global moment */
var MomentDate = DS.Transform.extend({
deserialize: function (serialized) {
if (serialized) {
return moment(serialized);
}
return serialized;
},
serialize: function (deserialized) {
if (deserialized) {
return moment(deserialized).toDate();
}
return deserialized;
}
});
__exports__["default"] = MomentDate;
});
define("ghost/utils/ajax",
["exports"],
function(__exports__) {
"use strict";
/* global ic */
var ajax = window.ajax = function () {
return ic.ajax.request.apply(null, arguments);
};
// Used in API request fail handlers to parse a standard api error
// response json for the message to display
function getRequestErrorMessage(request, performConcat) {
var message,
msgDetail;
// Can't really continue without a request
if (!request) {
return null;
}
// Seems like a sensible default
message = request.statusText;
// If a non 200 response
if (request.status !== 200) {
try {
// Try to parse out the error, or default to 'Unknown'
if (request.responseJSON.errors && Ember.isArray(request.responseJSON.errors)) {
message = request.responseJSON.errors.map(function (errorItem) {
return errorItem.message;
});
} else {
message = request.responseJSON.error || 'Unknown Error';
}
} catch (e) {
msgDetail = request.status ? request.status + ' - ' + request.statusText : 'Server was not available';
message = 'The server returned an error (' + msgDetail + ').';
}
}
if (performConcat && Ember.isArray(message)) {
message = message.join('<br />');
}
// return an array of errors by default
if (!performConcat && typeof message === 'string') {
message = [message];
}
return message;
}
__exports__.getRequestErrorMessage = getRequestErrorMessage;
__exports__.ajax = ajax;
__exports__["default"] = ajax;
});
define("ghost/utils/bind",
["exports"],
function(__exports__) {
"use strict";
var slice = Array.prototype.slice;
function bind(/* func, args, thisArg */) {
var args = slice.call(arguments),
func = args.shift(),
thisArg = args.pop();
function bound() {
return func.apply(thisArg, args);
}
return bound;
}
__exports__["default"] = bind;
});
define("ghost/utils/bound-one-way",
["exports"],
function(__exports__) {
"use strict";
/**
* Defines a property similarly to `Ember.computed.oneway`,
* save that while a `oneway` loses its binding upon being set,
* the `BoundOneWay` will continue to listen for upstream changes.
*
* This is an ideal tool for working with values inside of {{input}}
* elements.
* @param {*} upstream
* @param {function} transform a function to transform the **upstream** value.
*/
var BoundOneWay = function (upstream, transform) {
if (typeof transform !== 'function') {
// default to the identity function
transform = function (value) { return value; };
}
return Ember.computed(upstream, function (key, value) {
return arguments.length > 1 ? value : transform(this.get(upstream));
});
};
__exports__["default"] = BoundOneWay;
});
define("ghost/utils/caja-sanitizers",
["exports"],
function(__exports__) {
"use strict";
/**
* google-caja uses url() and id() to verify if the values are allowed.
*/
var url,
id;
/**
* Check if URL is allowed
* URLs are allowed if they start with http://, https://, or /.
*/
url = function (url) {
// jscs:disable
url = url.toString().replace(/['"]+/g, '');
if (/^https?:\/\//.test(url) || /^\//.test(url)) {
return url;
}
// jscs:enable
};
/**
* Check if ID is allowed
* All ids are allowed at the moment.
*/
id = function (id) {
return id;
};
__exports__["default"] = {
url: url,
id: id
};
});
define("ghost/utils/codemirror-mobile",
["ghost/assets/lib/touch-editor","exports"],
function(__dependency1__, __exports__) {
"use strict";
/*global CodeMirror, device, FastClick*/
var createTouchEditor = __dependency1__["default"];
var setupMobileCodeMirror,
TouchEditor,
init;
setupMobileCodeMirror = function setupMobileCodeMirror() {
var noop = function () {},
key;
for (key in CodeMirror) {
if (CodeMirror.hasOwnProperty(key)) {
CodeMirror[key] = noop;
}
}
CodeMirror.fromTextArea = function (el, options) {
return new TouchEditor(el, options);
};
CodeMirror.keyMap = {basic: {}};
};
init = function init() {
// Codemirror does not function on mobile devices, or on any iDevice
if (device.mobile() || (device.tablet() && device.ios())) {
$('body').addClass('touch-editor');
Ember.touchEditor = true;
// initialize FastClick to remove touch delays
Ember.run.scheduleOnce('afterRender', null, function () {
FastClick.attach(document.body);
});
TouchEditor = createTouchEditor();
setupMobileCodeMirror();
}
};
__exports__["default"] = {
createIfMobile: init
};
});
define("ghost/utils/codemirror-shortcuts",
["ghost/utils/titleize","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global CodeMirror, moment, Showdown */
// jscs:disable disallowSpacesInsideParentheses
/** Set up a shortcut function to be called via router actions.
* See editor-base-route
*/
var titleize = __dependency1__["default"];
function init() {
// remove predefined `ctrl+h` shortcut
delete CodeMirror.keyMap.emacsy['Ctrl-H'];
// Used for simple, noncomputational replace-and-go! shortcuts.
// See default case in shortcut function below.
CodeMirror.prototype.simpleShortcutSyntax = {
bold: '**$1**',
italic: '*$1*',
strike: '~~$1~~',
code: '`$1`',
link: '[$1](http://)',
image: '',
blockquote: '> $1'
};
CodeMirror.prototype.shortcut = function (type) {
var text = this.getSelection(),
cursor = this.getCursor(),
line = this.getLine(cursor.line),
fromLineStart = {line: cursor.line, ch: 0},
toLineEnd = {line: cursor.line, ch: line.length},
md, letterCount, textIndex, position, converter,
generatedHTML, match, currentHeaderLevel, hashPrefix,
replacementLine;
switch (type) {
case 'cycleHeaderLevel':
match = line.match(/^#+/);
if (!match) {
currentHeaderLevel = 1;
} else {
currentHeaderLevel = match[0].length;
}
if (currentHeaderLevel > 2) {
currentHeaderLevel = 1;
}
hashPrefix = new Array(currentHeaderLevel + 2).join('#');
// jscs:disable
replacementLine = hashPrefix + ' ' + line.replace(/^#* /, '');
// jscs:enable
this.replaceRange(replacementLine, fromLineStart, toLineEnd);
this.setCursor(cursor.line, cursor.ch + replacementLine.length);
break;
case 'link':
md = this.simpleShortcutSyntax.link.replace('$1', text);
this.replaceSelection(md, 'end');
if (!text) {
this.setCursor(cursor.line, cursor.ch + 1);
} else {
textIndex = line.indexOf(text, cursor.ch - text.length);
position = textIndex + md.length - 1;
this.setSelection({
line: cursor.line,
ch: position - 7
}, {
line: cursor.line,
ch: position
});
}
return;
case 'image':
md = this.simpleShortcutSyntax.image.replace('$1', text);
if (line !== '') {
md = '\n\n' + md;
}
this.replaceSelection(md, 'end');
cursor = this.getCursor();
this.setSelection({line: cursor.line, ch: cursor.ch - 8}, {line: cursor.line, ch: cursor.ch - 1});
return;
case 'list':
// jscs:disable
md = text.replace(/^(\s*)(\w\W*)/gm, '$1* $2');
// jscs:enable
this.replaceSelection(md, 'end');
return;
case 'currentDate':
md = moment(new Date()).format('D MMMM YYYY');
this.replaceSelection(md, 'end');
return;
case 'uppercase':
md = text.toLocaleUpperCase();
break;
case 'lowercase':
md = text.toLocaleLowerCase();
break;
case 'titlecase':
md = titleize(text);
break;
case 'copyHTML':
converter = new Showdown.converter();
if (text) {
generatedHTML = converter.makeHtml(text);
} else {
generatedHTML = converter.makeHtml(this.getValue());
}
// Talk to Ember
this.component.sendAction('openModal', 'copy-html', {generatedHTML: generatedHTML});
break;
default:
if (this.simpleShortcutSyntax[type]) {
md = this.simpleShortcutSyntax[type].replace('$1', text);
}
}
if (md) {
this.replaceSelection(md, 'end');
if (!text) {
letterCount = md.length;
this.setCursor({
line: cursor.line,
ch: cursor.ch + (letterCount / 2)
});
}
}
};
}
__exports__["default"] = {
init: init
};
});
define("ghost/utils/ctrl-or-cmd",
["exports"],
function(__exports__) {
"use strict";
var ctrlOrCmd = navigator.userAgent.indexOf('Mac') !== -1 ? 'command' : 'ctrl';
__exports__["default"] = ctrlOrCmd;
});
define("ghost/utils/date-formatting",
["exports"],
function(__exports__) {
"use strict";
/* global moment */
// jscs: disable disallowSpacesInsideParentheses
var parseDateFormats,
displayDateFormat,
verifyTimeStamp,
parseDateString,
formatDate;
parseDateFormats = ['DD MMM YY @ HH:mm', 'DD MMM YY HH:mm',
'DD MMM YYYY @ HH:mm', 'DD MMM YYYY HH:mm',
'DD/MM/YY @ HH:mm', 'DD/MM/YY HH:mm',
'DD/MM/YYYY @ HH:mm', 'DD/MM/YYYY HH:mm',
'DD-MM-YY @ HH:mm', 'DD-MM-YY HH:mm',
'DD-MM-YYYY @ HH:mm', 'DD-MM-YYYY HH:mm',
'YYYY-MM-DD @ HH:mm', 'YYYY-MM-DD HH:mm',
'DD MMM @ HH:mm', 'DD MMM HH:mm'];
displayDateFormat = 'DD MMM YY @ HH:mm';
// Add missing timestamps
verifyTimeStamp = function (dateString) {
if (dateString && !dateString.slice(-5).match(/\d+:\d\d/)) {
dateString += ' 12:00';
}
return dateString;
};
// Parses a string to a Moment
parseDateString = function (value) {
return value ? moment(verifyTimeStamp(value), parseDateFormats, true) : undefined;
};
// Formats a Date or Moment
formatDate = function (value) {
return verifyTimeStamp(value ? moment(value).format(displayDateFormat) : '');
};
__exports__.parseDateString = parseDateString;
__exports__.formatDate = formatDate;
});
define("ghost/utils/dropdown-service",
["ghost/mixins/body-event-listener","exports"],
function(__dependency1__, __exports__) {
"use strict";
// This is used by the dropdown initializer (and subsequently popovers) to manage closing & toggling
var BodyEventListener = __dependency1__["default"];
var DropdownService = Ember.Object.extend(Ember.Evented, BodyEventListener, {
bodyClick: function (event) {
/*jshint unused:false */
this.closeDropdowns();
},
closeDropdowns: function () {
this.trigger('close');
},
toggleDropdown: function (dropdownName, dropdownButton) {
this.trigger('toggle', {target: dropdownName, button: dropdownButton});
}
});
__exports__["default"] = DropdownService;
});
define("ghost/utils/editor-shortcuts",
["ghost/utils/ctrl-or-cmd","exports"],
function(__dependency1__, __exports__) {
"use strict";
var ctrlOrCmd = __dependency1__["default"];
var shortcuts = {};
// General editor shortcuts
shortcuts[ctrlOrCmd + '+s'] = 'save';
shortcuts[ctrlOrCmd + '+alt+p'] = 'publish';
shortcuts['alt+shift+z'] = 'toggleZenMode';
// CodeMirror Markdown Shortcuts
// Text
shortcuts['ctrl+alt+u'] = {action: 'codeMirrorShortcut', options: {type: 'strike'}};
shortcuts[ctrlOrCmd + '+b'] = {action: 'codeMirrorShortcut', options: {type: 'bold'}};
shortcuts[ctrlOrCmd + '+i'] = {action: 'codeMirrorShortcut', options: {type: 'italic'}};
shortcuts['ctrl+u'] = {action: 'codeMirrorShortcut', options: {type: 'uppercase'}};
shortcuts['ctrl+shift+u'] = {action: 'codeMirrorShortcut', options: {type: 'lowercase'}};
shortcuts['ctrl+alt+shift+u'] = {action: 'codeMirrorShortcut', options: {type: 'titlecase'}};
shortcuts[ctrlOrCmd + '+shift+c'] = {action: 'codeMirrorShortcut', options: {type: 'copyHTML'}};
shortcuts[ctrlOrCmd + '+h'] = {action: 'codeMirrorShortcut', options: {type: 'cycleHeaderLevel'}};
// Formatting
shortcuts['ctrl+q'] = {action: 'codeMirrorShortcut', options: {type: 'blockquote'}};
shortcuts['ctrl+l'] = {action: 'codeMirrorShortcut', options: {type: 'list'}};
// Insert content
shortcuts['ctrl+shift+1'] = {action: 'codeMirrorShortcut', options: {type: 'currentDate'}};
shortcuts[ctrlOrCmd + '+k'] = {action: 'codeMirrorShortcut', options: {type: 'link'}};
shortcuts[ctrlOrCmd + '+shift+i'] = {action: 'codeMirrorShortcut', options: {type: 'image'}};
shortcuts[ctrlOrCmd + '+shift+k'] = {action: 'codeMirrorShortcut', options: {type: 'code'}};
__exports__["default"] = shortcuts;
});
define("ghost/utils/ghost-paths",
["exports"],
function(__exports__) {
"use strict";
var makeRoute = function (root, args) {
var parts = Array.prototype.slice.call(args, 0).join('/'),
route = [root, parts].join('/');
if (route.slice(-1) !== '/') {
route += '/';
}
return route;
};
function ghostPaths() {
var path = window.location.pathname,
subdir = path.substr(0, path.search('/ghost/')),
adminRoot = subdir + '/ghost',
apiRoot = subdir + '/ghost/api/v0.1';
function assetUrl(src) {
return subdir + src;
}
return {
subdir: subdir,
blogRoot: subdir + '/',
adminRoot: adminRoot,
apiRoot: apiRoot,
url: {
admin: function () {
return makeRoute(adminRoot, arguments);
},
api: function () {
return makeRoute(apiRoot, arguments);
},
asset: assetUrl
}
};
}
__exports__["default"] = ghostPaths;
});
define("ghost/utils/isFinite",
["exports"],
function(__exports__) {
"use strict";
/* globals window */
// isFinite function from lodash
function isFinite(value) {
return window.isFinite(value) && !window.isNaN(parseFloat(value));
}
__exports__["default"] = isFinite;
});
define("ghost/utils/isNumber",
["exports"],
function(__exports__) {
"use strict";
// isNumber function from lodash
var toString = Object.prototype.toString;
function isNumber(value) {
return typeof value === 'number' ||
value && typeof value === 'object' && toString.call(value) === '[object Number]' || false;
}
__exports__["default"] = isNumber;
});
define("ghost/utils/link-view",
[],
function() {
"use strict";
Ember.LinkView.reopen({
active: Ember.computed('resolvedParams', 'routeArgs', function () {
var isActive = this._super();
Ember.set(this, 'alternateActive', isActive);
return isActive;
}),
activeClass: Ember.computed('tagName', function () {
return this.get('tagName') === 'button' ? '' : 'active';
})
});
});
define("ghost/utils/mobile",
["exports"],
function(__exports__) {
"use strict";
var mobileQuery = matchMedia('(max-width: 900px)');
__exports__["default"] = mobileQuery;
});
define("ghost/utils/notifications",
["ghost/models/notification","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Notification = __dependency1__["default"];
var Notifications = Ember.ArrayProxy.extend({
delayedNotifications: [],
content: Ember.A(),
timeout: 3000,
pushObject: function (object) {
// object can be either a DS.Model or a plain JS object, so when working with
// it, we need to handle both cases.
// make sure notifications have all the necessary properties set.
if (typeof object.toJSON === 'function') {
// working with a DS.Model
if (object.get('location') === '') {
object.set('location', 'bottom');
}
} else {
if (!object.location) {
object.location = 'bottom';
}
}
this._super(object);
},
handleNotification: function (message, delayed) {
if (!message.status) {
message.status = 'passive';
}
if (!delayed) {
this.pushObject(message);
} else {
this.delayedNotifications.push(message);
}
},
showError: function (message, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
this.handleNotification({
type: 'error',
message: message
}, options.delayed);
},
showErrors: function (errors, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
for (var i = 0; i < errors.length; i += 1) {
this.showError(errors[i].message || errors[i], {doNotClosePassive: true});
}
},
showAPIError: function (resp, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
options.defaultErrorText = options.defaultErrorText || 'There was a problem on the server, please try again.';
if (resp && resp.jqXHR && resp.jqXHR.responseJSON && resp.jqXHR.responseJSON.error) {
this.showError(resp.jqXHR.responseJSON.error, options);
} else if (resp && resp.jqXHR && resp.jqXHR.responseJSON && resp.jqXHR.responseJSON.errors) {
this.showErrors(resp.jqXHR.responseJSON.errors, options);
} else if (resp && resp.jqXHR && resp.jqXHR.responseJSON && resp.jqXHR.responseJSON.message) {
this.showError(resp.jqXHR.responseJSON.message, options);
} else {
this.showError(options.defaultErrorText, {doNotClosePassive: true});
}
},
showInfo: function (message, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
this.handleNotification({
type: 'info',
message: message
}, options.delayed);
},
showSuccess: function (message, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
this.handleNotification({
type: 'success',
message: message
}, options.delayed);
},
showWarn: function (message, options) {
options = options || {};
if (!options.doNotClosePassive) {
this.closePassive();
}
this.handleNotification({
type: 'warn',
message: message
}, options.delayed);
},
displayDelayed: function () {
var self = this;
self.delayedNotifications.forEach(function (message) {
self.pushObject(message);
});
self.delayedNotifications = [];
},
closeNotification: function (notification) {
var self = this;
if (notification instanceof Notification) {
notification.deleteRecord();
notification.save().finally(function () {
self.removeObject(notification);
});
} else {
this.removeObject(notification);
}
},
closePassive: function () {
this.set('content', this.rejectBy('status', 'passive'));
},
closePersistent: function () {
this.set('content', this.rejectBy('status', 'persistent'));
},
closeAll: function () {
this.clear();
}
});
__exports__["default"] = Notifications;
});
define("ghost/utils/set-scroll-classname",
["exports"],
function(__exports__) {
"use strict";
// ## scrollShadow
// This adds a 'scroll' class to the targeted element when the element is scrolled
// `this` is expected to be a jQuery-wrapped element
// **target:** The element in which the class is applied. Defaults to scrolled element.
// **class-name:** The class which is applied.
// **offset:** How far the user has to scroll before the class is applied.
var setScrollClassName = function (options) {
var $target = options.target || this,
offset = options.offset,
className = options.className || 'scrolling';
if (this.scrollTop() > offset) {
$target.addClass(className);
} else {
$target.removeClass(className);
}
};
__exports__["default"] = setScrollClassName;
});
define("ghost/utils/text-field",
[],
function() {
"use strict";
Ember.TextField.reopen({
attributeBindings: ['autofocus']
});
});
define("ghost/utils/titleize",
["exports"],
function(__exports__) {
"use strict";
var lowerWords = ['of', 'a', 'the', 'and', 'an', 'or', 'nor', 'but', 'is', 'if',
'then', 'else', 'when', 'at', 'from', 'by', 'on', 'off', 'for',
'in', 'out', 'over', 'to', 'into', 'with'];
function titleize(input) {
var words = input.split(' ').map(function (word, index) {
if (index === 0 || lowerWords.indexOf(word) === -1) {
word = Ember.String.capitalize(word);
}
return word;
});
return words.join(' ');
}
__exports__["default"] = titleize;
});
define("ghost/utils/validator-extensions",
["exports"],
function(__exports__) {
"use strict";
function init() {
// Provide a few custom validators
//
validator.extend('empty', function (str) {
return Ember.isBlank(str);
});
validator.extend('notContains', function (str, badString) {
return str.indexOf(badString) === -1;
});
}
__exports__["default"] = {
init: init
};
});
define("ghost/utils/word-count",
["exports"],
function(__exports__) {
"use strict";
// jscs: disable
function wordCount(s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ''); // exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, ' '); // 2 or more space to 1
s = s.replace(/\n /gi, '\n'); // exclude newline with a start spacing
s = s.replace(/\n+/gi, '\n');
return s.split(/ |\n/).length;
}
__exports__["default"] = wordCount;
});
define("ghost/validators/forgotten",
["exports"],
function(__exports__) {
"use strict";
var ForgotValidator = Ember.Object.create({
check: function (model) {
var data = model.getProperties('email'),
validationErrors = [];
if (!validator.isEmail(data.email)) {
validationErrors.push({
message: 'Invalid email address'
});
}
return validationErrors;
}
});
__exports__["default"] = ForgotValidator;
});
define("ghost/validators/new-user",
["exports"],
function(__exports__) {
"use strict";
var NewUserValidator = Ember.Object.extend({
check: function (model) {
var data = model.getProperties('name', 'email', 'password'),
validationErrors = [];
if (!validator.isLength(data.name, 1)) {
validationErrors.push({
message: 'Please enter a name.'
});
}
if (!validator.isEmail(data.email)) {
validationErrors.push({
message: 'Invalid Email.'
});
}
if (!validator.isLength(data.password, 8)) {
validationErrors.push({
message: 'Password must be at least 8 characters long.'
});
}
return validationErrors;
}
});
__exports__["default"] = NewUserValidator;
});
define("ghost/validators/post",
["exports"],
function(__exports__) {
"use strict";
var PostValidator = Ember.Object.create({
check: function (model) {
var validationErrors = [],
data = model.getProperties('title', 'meta_title', 'meta_description');
if (validator.empty(data.title)) {
validationErrors.push({
message: 'You must specify a title for the post.'
});
}
if (!validator.isLength(data.meta_title, 0, 150)) {
validationErrors.push({
message: 'Meta Title cannot be longer than 150 characters.'
});
}
if (!validator.isLength(data.meta_description, 0, 200)) {
validationErrors.push({
message: 'Meta Description cannot be longer than 200 characters.'
});
}
return validationErrors;
}
});
__exports__["default"] = PostValidator;
});
define("ghost/validators/reset",
["exports"],
function(__exports__) {
"use strict";
var ResetValidator = Ember.Object.create({
check: function (model) {
var p1 = model.get('newPassword'),
p2 = model.get('ne2Password'),
validationErrors = [];
if (!validator.equals(p1, p2)) {
validationErrors.push({
message: 'The two new passwords don\'t match.'
});
}
if (!validator.isLength(p1, 8)) {
validationErrors.push({
message: 'The password is not long enough.'
});
}
return validationErrors;
}
});
__exports__["default"] = ResetValidator;
});
define("ghost/validators/setting",
["exports"],
function(__exports__) {
"use strict";
var SettingValidator = Ember.Object.create({
check: function (model) {
var validationErrors = [],
title = model.get('title'),
description = model.get('description'),
email = model.get('email'),
postsPerPage = model.get('postsPerPage');
if (!validator.isLength(title, 0, 150)) {
validationErrors.push({message: 'Title is too long'});
}
if (!validator.isLength(description, 0, 200)) {
validationErrors.push({message: 'Description is too long'});
}
if (!validator.isEmail(email) || !validator.isLength(email, 0, 254)) {
validationErrors.push({message: 'Supply a valid email address'});
}
if (postsPerPage > 1000) {
validationErrors.push({message: 'The maximum number of posts per page is 1000'});
}
if (postsPerPage < 1) {
validationErrors.push({message: 'The minimum number of posts per page is 1'});
}
if (!validator.isInt(postsPerPage)) {
validationErrors.push({message: 'Posts per page must be a number'});
}
return validationErrors;
}
});
__exports__["default"] = SettingValidator;
});
define("ghost/validators/setup",
["ghost/validators/new-user","exports"],
function(__dependency1__, __exports__) {
"use strict";
var NewUserValidator = __dependency1__["default"];
var SetupValidator = NewUserValidator.extend({
check: function (model) {
var data = model.getProperties('blogTitle'),
validationErrors = this._super(model);
if (!validator.isLength(data.blogTitle, 1)) {
validationErrors.push({
message: 'Please enter a blog title.'
});
}
return validationErrors;
}
}).create();
__exports__["default"] = SetupValidator;
});
define("ghost/validators/signin",
["exports"],
function(__exports__) {
"use strict";
var SigninValidator = Ember.Object.create({
check: function (model) {
var data = model.getProperties('identification', 'password'),
validationErrors = [];
if (!validator.isEmail(data.identification)) {
validationErrors.push('Invalid Email');
}
if (!validator.isLength(data.password || '', 1)) {
validationErrors.push('Please enter a password');
}
return validationErrors;
}
});
__exports__["default"] = SigninValidator;
});
define("ghost/validators/signup",
["ghost/validators/new-user","exports"],
function(__dependency1__, __exports__) {
"use strict";
var NewUserValidator = __dependency1__["default"];
__exports__["default"] = NewUserValidator.create();
});
define("ghost/validators/user",
["exports"],
function(__exports__) {
"use strict";
var UserValidator = Ember.Object.create({
check: function (model) {
var validator = this.validators[model.get('status')];
if (typeof validator !== 'function') {
return [];
}
return validator(model);
},
validators: {
invited: function (model) {
var validationErrors = [],
email = model.get('email'),
roles = model.get('roles');
if (!validator.isEmail(email)) {
validationErrors.push({message: 'Please supply a valid email address'});
}
if (roles.length < 1) {
validationErrors.push({message: 'Please select a role'});
}
return validationErrors;
},
active: function (model) {
var validationErrors = [],
name = model.get('name'),
bio = model.get('bio'),
email = model.get('email'),
location = model.get('location'),
website = model.get('website');
if (!validator.isLength(name, 0, 150)) {
validationErrors.push({message: 'Name is too long'});
}
if (!validator.isLength(bio, 0, 200)) {
validationErrors.push({message: 'Bio is too long'});
}
if (!validator.isEmail(email)) {
validationErrors.push({message: 'Please supply a valid email address'});
}
if (!validator.isLength(location, 0, 150)) {
validationErrors.push({message: 'Location is too long'});
}
if (!Ember.isEmpty(website) &&
(!validator.isURL(website, {require_protocol: false}) ||
!validator.isLength(website, 0, 2000))) {
validationErrors.push({message: 'Website is not a valid url'});
}
return validationErrors;
}
}
});
__exports__["default"] = UserValidator;
});
define("ghost/views/application",
["ghost/utils/mobile","ghost/utils/bind","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var mobileQuery = __dependency1__["default"];
var bind = __dependency2__["default"];
var ApplicationView = Ember.View.extend({
elementId: 'container',
setupGlobalMobileNav: function () {
// #### Navigating within the sidebar closes it.
var self = this;
$('body').on('click tap', '.js-nav-item', function () {
if (mobileQuery.matches) {
self.set('controller.showGlobalMobileNav', false);
}
});
// #### Close the nav if mobile and clicking outside of the nav or not the burger toggle
$('.js-nav-cover').on('click tap', function () {
var isOpen = self.get('controller.showGlobalMobileNav');
if (isOpen) {
self.set('controller.showGlobalMobileNav', false);
}
});
// #### Listen to the viewport and change user-menu dropdown triangle classes accordingly
mobileQuery.addListener(this.swapUserMenuDropdownTriangleClasses);
this.swapUserMenuDropdownTriangleClasses(mobileQuery);
}.on('didInsertElement'),
swapUserMenuDropdownTriangleClasses: function (mq) {
if (mq.matches) {
$('.js-user-menu-dropdown-menu').removeClass('dropdown-triangle-top-right ').addClass('dropdown-triangle-bottom');
} else {
$('.js-user-menu-dropdown-menu').removeClass('dropdown-triangle-bottom').addClass('dropdown-triangle-top-right');
}
},
showGlobalMobileNavObserver: function () {
if (this.get('controller.showGlobalMobileNav')) {
$('body').addClass('global-nav-expanded');
} else {
$('body').removeClass('global-nav-expanded');
}
}.observes('controller.showGlobalMobileNav'),
setupCloseNavOnDesktop: function () {
this.set('closeGlobalMobileNavOnDesktop', bind(function closeGlobalMobileNavOnDesktop(mq) {
if (!mq.matches) {
// Is desktop sized
this.set('controller.showGlobalMobileNav', false);
}
}, this));
mobileQuery.addListener(this.closeGlobalMobileNavOnDesktop);
}.on('didInsertElement'),
removeCloseNavOnDesktop: function () {
mobileQuery.removeListener(this.closeGlobalMobileNavOnDesktop);
}.on('willDestroyElement'),
toggleSettingsMenuBodyClass: function () {
$('body').toggleClass('settings-menu-expanded', this.get('controller.showSettingsMenu'));
}.observes('controller.showSettingsMenu')
});
__exports__["default"] = ApplicationView;
});
define("ghost/views/content-preview-content-view",
["ghost/utils/set-scroll-classname","exports"],
function(__dependency1__, __exports__) {
"use strict";
var setScrollClassName = __dependency1__["default"];
var PostContentView = Ember.View.extend({
classNames: ['content-preview-content'],
didInsertElement: function () {
var el = this.$();
el.on('scroll', Ember.run.bind(el, setScrollClassName, {
target: el.closest('.content-preview'),
offset: 10
}));
},
contentObserver: function () {
this.$().closest('.content-preview').scrollTop(0);
}.observes('controller.content'),
willDestroyElement: function () {
var el = this.$();
el.off('scroll');
}
});
__exports__["default"] = PostContentView;
});
define("ghost/views/editor-save-button",
["exports"],
function(__exports__) {
"use strict";
var EditorSaveButtonView = Ember.View.extend({
templateName: 'editor-save-button',
tagName: 'section',
classNames: ['splitbtn', 'js-publish-splitbutton'],
// Tracks whether we're going to change the state of the post on save
isDangerous: Ember.computed('controller.isPublished', 'controller.willPublish', function () {
return this.get('controller.isPublished') !== this.get('controller.willPublish');
}),
publishText: Ember.computed('controller.isPublished', function () {
return this.get('controller.isPublished') ? 'Update Post' : 'Publish Now';
}),
draftText: Ember.computed('controller.isPublished', function () {
return this.get('controller.isPublished') ? 'Unpublish' : 'Save Draft';
}),
saveText: Ember.computed('controller.willPublish', function () {
return this.get('controller.willPublish') ? this.get('publishText') : this.get('draftText');
})
});
__exports__["default"] = EditorSaveButtonView;
});
define("ghost/views/editor/edit",
["ghost/mixins/editor-base-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EditorViewMixin = __dependency1__["default"];
var EditorView = Ember.View.extend(EditorViewMixin, {
tagName: 'section',
classNames: ['entry-container']
});
__exports__["default"] = EditorView;
});
define("ghost/views/editor/new",
["ghost/mixins/editor-base-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var EditorViewMixin = __dependency1__["default"];
var EditorNewView = Ember.View.extend(EditorViewMixin, {
tagName: 'section',
templateName: 'editor/edit',
classNames: ['entry-container']
});
__exports__["default"] = EditorNewView;
});
define("ghost/views/item-view",
["exports"],
function(__exports__) {
"use strict";
var ItemView = Ember.View.extend({
classNameBindings: ['active'],
active: Ember.computed('childViews.firstObject.active', function () {
return this.get('childViews.firstObject.active');
})
});
__exports__["default"] = ItemView;
});
define("ghost/views/mobile/content-view",
["ghost/utils/mobile","exports"],
function(__dependency1__, __exports__) {
"use strict";
var mobileQuery = __dependency1__["default"];
var MobileContentView = Ember.View.extend({
// Ensure that loading this view brings it into view on mobile
showContent: function () {
if (mobileQuery.matches) {
this.get('parentView').showContent();
}
}.on('didInsertElement')
});
__exports__["default"] = MobileContentView;
});
define("ghost/views/mobile/index-view",
["ghost/utils/mobile","exports"],
function(__dependency1__, __exports__) {
"use strict";
var mobileQuery = __dependency1__["default"];
var MobileIndexView = Ember.View.extend({
// Ensure that going to the index brings the menu into view on mobile.
showMenu: function () {
if (mobileQuery.matches) {
this.get('parentView').showMenu();
}
}.on('didInsertElement')
});
__exports__["default"] = MobileIndexView;
});
define("ghost/views/mobile/parent-view",
["ghost/utils/mobile","exports"],
function(__dependency1__, __exports__) {
"use strict";
var mobileQuery = __dependency1__["default"];
// A mobile parent view needs to implement three methods,
// showContent, showAll, and showMenu
// Which are called by MobileIndex and MobileContent views
var MobileParentView = Ember.View.extend({
showContent: Ember.K,
showMenu: Ember.K,
showAll: Ember.K,
setChangeLayout: function () {
var self = this;
this.set('changeLayout', function changeLayout() {
if (mobileQuery.matches) {
// transitioned to mobile layout, so show content
self.showContent();
} else {
// went from mobile to desktop
self.showAll();
}
});
}.on('init'),
attachChangeLayout: function () {
mobileQuery.addListener(this.changeLayout);
}.on('didInsertElement'),
detachChangeLayout: function () {
mobileQuery.removeListener(this.changeLayout);
}.on('willDestroyElement')
});
__exports__["default"] = MobileParentView;
});
define("ghost/views/paginated-scroll-box",
["ghost/utils/set-scroll-classname","ghost/mixins/pagination-view-infinite-scroll","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var setScrollClassName = __dependency1__["default"];
var PaginationViewMixin = __dependency2__["default"];
var PaginatedScrollBox = Ember.View.extend(PaginationViewMixin, {
attachScrollClassHandler: function () {
var el = this.$();
el.on('scroll', Ember.run.bind(el, setScrollClassName, {
target: el.closest('.content-list'),
offset: 10
}));
}.on('didInsertElement'),
detachScrollClassHandler: function () {
this.$().off('scroll');
}.on('willDestroyElement')
});
__exports__["default"] = PaginatedScrollBox;
});
define("ghost/views/post-item-view",
["ghost/views/item-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var itemView = __dependency1__["default"];
var PostItemView = itemView.extend({
classNameBindings: ['isFeatured:featured', 'isPage:page'],
isFeatured: Ember.computed.alias('controller.model.featured'),
isPage: Ember.computed.alias('controller.model.page'),
doubleClick: function () {
this.get('controller').send('openEditor');
},
click: function () {
this.get('controller').send('showPostContent');
}
});
__exports__["default"] = PostItemView;
});
define("ghost/views/post-settings-menu",
["ghost/utils/date-formatting","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global moment */
var formatDate = __dependency1__.formatDate;
var PostSettingsMenuView = Ember.View.extend({
templateName: 'post-settings-menu',
publishedAtBinding: Ember.Binding.oneWay('controller.publishedAt'),
datePlaceholder: Ember.computed('controller.publishedAt', function () {
return formatDate(moment());
})
});
__exports__["default"] = PostSettingsMenuView;
});
define("ghost/views/post-tags-input",
["exports"],
function(__exports__) {
"use strict";
var PostTagsInputView = Ember.View.extend({
tagName: 'section',
elementId: 'entry-tags',
classNames: 'publish-bar-inner',
classNameBindings: ['hasFocus:focused'],
templateName: 'post-tags-input',
hasFocus: false,
keys: {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
ESCAPE: 27,
UP: 38,
DOWN: 40,
NUMPAD_ENTER: 108,
COMMA: 188
},
didInsertElement: function () {
this.get('controller').send('loadAllTags');
},
willDestroyElement: function () {
this.get('controller').send('reset');
},
overlayStyles: Ember.computed('hasFocus', 'controller.suggestions.length', function () {
var styles = [],
leftPos;
if (this.get('hasFocus') && this.get('controller.suggestions.length')) {
leftPos = this.$().find('#tags').position().left;
styles.push('display: block');
styles.push('left: ' + leftPos + 'px');
} else {
styles.push('display: none');
styles.push('left', 0);
}
return styles.join(';');
}),
tagInputView: Ember.TextField.extend({
focusIn: function () {
this.get('parentView').set('hasFocus', true);
},
focusOut: function () {
this.get('parentView').set('hasFocus', false);
},
keyDown: function (event) {
var controller = this.get('parentView.controller'),
keys = this.get('parentView.keys'),
hasValue;
switch (event.keyCode) {
case keys.UP:
event.preventDefault();
controller.send('selectPreviousSuggestion');
break;
case keys.DOWN:
event.preventDefault();
controller.send('selectNextSuggestion');
break;
case keys.TAB:
case keys.ENTER:
case keys.NUMPAD_ENTER:
case keys.COMMA:
if (event.keyCode === keys.COMMA && event.shiftKey) {
break;
}
if (controller.get('selectedSuggestion')) {
event.preventDefault();
controller.send('addSelectedSuggestion');
} else {
// allow user to tab out of field if input is empty
hasValue = !Ember.isEmpty(this.get('value'));
if (hasValue || event.keyCode !== keys.TAB) {
event.preventDefault();
controller.send('addNewTag');
}
}
break;
case keys.BACKSPACE:
if (Ember.isEmpty(this.get('value'))) {
event.preventDefault();
controller.send('deleteLastTag');
}
break;
case keys.ESCAPE:
event.preventDefault();
controller.send('reset');
break;
}
}
}),
suggestionView: Ember.View.extend({
tagName: 'li',
classNameBindings: 'suggestion.selected',
suggestion: null,
// we can't use the 'click' event here as the focusOut event on the
// input will fire first
mouseDown: function (event) {
event.preventDefault();
},
mouseUp: function (event) {
event.preventDefault();
this.get('parentView.controller').send('addTag',
this.get('suggestion.tag'));
}
}),
actions: {
deleteTag: function (tag) {
// The view wants to keep focus on the input after a click on a tag
Ember.$('.js-tag-input').focus();
// Make the controller do the actual work
this.get('controller').send('deleteTag', tag);
}
}
});
__exports__["default"] = PostTagsInputView;
});
define("ghost/views/posts",
["ghost/views/mobile/parent-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileParentView = __dependency1__["default"];
var PostsView = MobileParentView.extend({
classNames: ['content-view-container'],
tagName: 'section',
// Mobile parent view callbacks
showMenu: function () {
$('.js-content-list').addClass('show-menu').removeClass('show-content');
$('.js-content-preview').addClass('show-menu').removeClass('show-content');
},
showContent: function () {
$('.js-content-list').addClass('show-content').removeClass('show-menu');
$('.js-content-preview').addClass('show-content').removeClass('show-menu');
},
showAll: function () {
$('.js-content-list, .js-content-preview').removeClass('show-menu show-content');
}
});
__exports__["default"] = PostsView;
});
define("ghost/views/posts/index",
["ghost/views/mobile/index-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileIndexView = __dependency1__["default"];
var PostsIndexView = MobileIndexView.extend({
classNames: ['no-posts-box']
});
__exports__["default"] = PostsIndexView;
});
define("ghost/views/posts/post",
["ghost/views/mobile/content-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileContentView = __dependency1__["default"];
var PostsPostView = MobileContentView.extend();
__exports__["default"] = PostsPostView;
});
define("ghost/views/settings",
["ghost/views/mobile/parent-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileParentView = __dependency1__["default"];
var SettingsView = MobileParentView.extend({
// MobileParentView callbacks
showMenu: function () {
$('.js-settings-header-inner').css('display', 'none');
$('.js-settings-menu').css({right: '0', left: '0', 'margin-right': '0'});
$('.js-settings-content').css({right: '-100%', left: '100%', 'margin-left': '15'});
},
showContent: function () {
$('.js-settings-menu').css({right: '100%', left: '-110%', 'margin-right': '15px'});
$('.js-settings-content').css({right: '0', left: '0', 'margin-left': '0'});
$('.js-settings-header-inner').css('display', 'block');
},
showAll: function () {
$('.js-settings-menu, .js-settings-content').removeAttr('style');
}
});
__exports__["default"] = SettingsView;
});
define("ghost/views/settings/about",
["ghost/views/settings/content-base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BaseView = __dependency1__["default"];
var SettingsAboutView = BaseView.extend();
__exports__["default"] = SettingsAboutView;
});
define("ghost/views/settings/apps",
["ghost/views/settings/content-base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BaseView = __dependency1__["default"];
var SettingsAppsView = BaseView.extend();
__exports__["default"] = SettingsAppsView;
});
define("ghost/views/settings/content-base",
["ghost/views/mobile/content-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileContentView = __dependency1__["default"];
/**
* All settings views other than the index should inherit from this base class.
* It ensures that the correct screen is showing when a mobile user navigates
* to a `settings.someRouteThatIsntIndex` route.
*/
var SettingsContentBaseView = MobileContentView.extend({
tagName: 'section',
classNames: ['settings-content', 'js-settings-content', 'fade-in']
});
__exports__["default"] = SettingsContentBaseView;
});
define("ghost/views/settings/general",
["ghost/views/settings/content-base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BaseView = __dependency1__["default"];
var SettingsGeneralView = BaseView.extend();
__exports__["default"] = SettingsGeneralView;
});
define("ghost/views/settings/index",
["ghost/views/mobile/index-view","exports"],
function(__dependency1__, __exports__) {
"use strict";
var MobileIndexView = __dependency1__["default"];
var SettingsIndexView = MobileIndexView.extend();
__exports__["default"] = SettingsIndexView;
});
define("ghost/views/settings/tags",
["ghost/views/settings/content-base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BaseView = __dependency1__["default"];
var SettingsTagsView = BaseView.extend();
__exports__["default"] = SettingsTagsView;
});
define("ghost/views/settings/users",
["ghost/views/settings/content-base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var BaseView = __dependency1__["default"];
var SettingsUsersView = BaseView.extend();
__exports__["default"] = SettingsUsersView;
});
define("ghost/views/settings/users/user",
["exports"],
function(__exports__) {
"use strict";
var SettingsUserView = Ember.View.extend({
currentUser: Ember.computed.alias('controller.session.user'),
isNotOwnProfile: Ember.computed('controller.user.id', 'currentUser.id', function () {
return this.get('controller.user.id') !== this.get('currentUser.id');
}),
isNotOwnersProfile: Ember.computed.not('controller.user.isOwner'),
canAssignRoles: Ember.computed.or('currentUser.isAdmin', 'currentUser.isOwner'),
canMakeOwner: Ember.computed.and('currentUser.isOwner', 'isNotOwnProfile', 'controller.user.isAdmin'),
rolesDropdownIsVisible: Ember.computed.and('isNotOwnProfile', 'canAssignRoles', 'isNotOwnersProfile'),
deleteUserActionIsVisible: Ember.computed('currentUser', 'canAssignRoles', 'controller.user', function () {
if ((this.get('canAssignRoles') && this.get('isNotOwnProfile') && !this.get('controller.user.isOwner')) ||
(this.get('currentUser.isEditor') && (this.get('isNotOwnProfile') ||
this.get('controller.user.isAuthor')))) {
return true;
}
}),
userActionsAreVisible: Ember.computed.or('deleteUserActionIsVisible', 'canMakeOwner')
});
__exports__["default"] = SettingsUserView;
});
define("ghost/views/settings/users/users-list-view",
["ghost/mixins/pagination-view-infinite-scroll","exports"],
function(__dependency1__, __exports__) {
"use strict";
var PaginationViewMixin = __dependency1__["default"];
var UsersListView = Ember.View.extend(PaginationViewMixin, {
classNames: ['settings-users']
});
__exports__["default"] = UsersListView;
});
// Loader to create the Ember.js application
/*global require */
window.App = require('ghost/app')['default'].create();
//# sourceMappingURL=ghost-dev.js.map |
/*
* grunt-kunstmaan-generate
* https://github.com/sambellen/grunt-kunstmaan-generate
*
* Copyright (c) 2013 Sam Bellen for Kunstmaan
* Licensed under the MIT license.
*/
'use strict';
debugger;
module.exports = function(grunt) {
// Variables
var _ = grunt.util._,
fs = require('fs'),
prompt = require('prompt'),
kumaGenerator,
isDefined,
// Check if the variable is defined
isDefined = function(val, empty) {
var _defined = false;
// If empty is not given or not a boolean
if (typeof empty === 'undefined' || !_.isBoolean(empty)) {
empty = false;
}
// If the value is not givven or if it can be an empty string
if (typeof val !== 'undefined' && val !== null) {
if((val === '' && empty === true) || val !== '') {
_defined = true;
}
}
return _defined;
};
// The Kunstmaan Generator
kumaGenerator = function(type, name, subDir, config) {
// this
var _this = this;
// Getters
var getTypePath,
getImportPath,
getTypeContenttype,
getFilePath;
/*
* Setters
*/
// Set the type
_this.setType = function(val) {
_this.type = val;
// Set the the path of the generated file type
_this.typePath = getTypePath();
};
// Set the name
_this.setName = function(val) {
_this.name = val;
};
// Set the subdirectory
_this.setSubDir = function(val) {
_this.subDir = val;
};
// Set the prompt value
_this.setPromptValue = function(val) {
_this.promptValue = val;
}
// Set the comment that gets printed on top of the file
_this.setComment = function() {
_this.comment = '/* ==========================================================================\n ';
if(isDefined(_this.name)) {
// Capitalise the first letter
_this.comment += _this.name.charAt(0).toUpperCase() + _this.name.slice(1) + '\n';
}
if (isDefined(_this.config.config.comment)) {
_this.comment += '\n ' + _this.config.config.comment;
}
_this.comment += '\n ========================================================================== */\n\n';
};
/*
* Set the variables
*/
// Set the Type of the generated file
_this.type = type;
// Set the name of the generated file
_this.name = name;
// Set the subdirectory of the generated file
_this.subDir = subDir + '/';
if (!isDefined(subDir)) {
_this.setSubDir('');
}
// Set the config of the generator
_this.config = config;
// Set the base path
if (isDefined(_this.config.config.path)) {
_this.path = _this.config.config.path;
} else {
_this.path = _this.config.cwd;
}
// Set the available file types for the generator
if (isDefined(_this.config.config.types) && _this.config.config.types.length > 0) {
_this.types = _this.config.config.types;
} else {
grunt.warn('Please set some file types in the grunt config.');
}
// Set the extension of the generated file
_this.extension = '.scss';
/*
* Helper functions
*/
// Check if the given type is in the config
_this.isType = function(val) {
var i, _type = false;
for (i = 0; i < _this.config.config.types.length; i++) {
if (_this.config.config.types[i].name === val) {
_type = true;
}
}
return _type;
};
// Check if a file already exists
_this.fileExists = function(val) {
// var _exists = false;
// console.log('file', getFilePath());
// if (fs.statSync(getFilePath())) {
// _exists = true;
// }
// return _exists;
};
// Prompt the user for data
_this.promptUser = function(message, type, fn) {
prompt.start();
prompt.message = message;
prompt.get([type], function(err, result){
// Execute the callback function
fn(result[type]);
});
};
/*
* Getters
*/
// Get the path of the generated file type
getTypePath = function() {
var _typePath, i;
if (_this.isType(_this.type)) {
for (i = 0; i < _this.types.length; i++) {
if (isDefined(_this.types[i].path) && _this.types[i].name === _this.type) {
_typePath = _this.types[i].path;
break;
} else {
_typePath = _this.type + '/';
}
}
} else {
_typePath = _this.type + '/';
}
return _typePath;
};
// Get the content type of the generated file type
getTypeContenttype = function() {
var _typeContentType, i;
if (_this.isType(_this.type)) {
for (i = 0; i < _this.types.length; i++) {
if (isDefined(_this.types[i].type) && _this.types[i].name === _this.type) {
_typeContentType = _this.types[i].type;
} else {
_typeContentType = 'component';
}
}
}
return _typeContentType;
}
// Get the path to the generated file
getFilePath = function() {
return _this.path + _this.typePath + _this.subDir + '_' + _this.name + _this.extension;
};
// Get the path to the generated file
getImportPath = function() {
return _this.path + _this.typePath + _this.type + _this.extension;
};
// Save the new file
_this.save = function(done) {
_this.setComment();
var _data = _this.comment;
if (_this.type === 'mixins') {
_data += '@mixin ' + _this.name + '() {\n\n}';
} else if (_this.type === 'placeholders') {
_data += '%' + _this.name + ' {\n\n}';
} else {
_data += '.' +_this.name + ' {\n\n}'
}
fs.writeFile(getFilePath(), _data, function(err) {
if (err) {
throw err;
}
grunt.log.ok('Generated ' + getFilePath());
var _import = '@import "' + _this.name + '";\n';
fs.appendFile(getImportPath(), _import, function(err) {
if (err) {
throw err;
}
grunt.log.ok('Appended @import "' + _this.name + '"; to ' + _this.type + '.scss');
done();
});
});
};
return {
'type': _this.type,
'name': _this.name,
'subDir': _this.subDir,
'types': _this.types,
'prompt': _this.promptUser,
'promptValue' : _this.promptValue,
'isType': _this.isType,
'setType': _this.setType,
'setName': _this.setName,
'setSubDir': _this.setSubDir,
'save': _this.save
}
};
// Register the task
grunt.registerTask('kg', 'Easily create new SCSS modules within a kumaGenerator project.', function(type, name, subDir) {
var done = this.async(),
_config,
_promptType,
_promptName,
generator,
_this = this;
_config = {
config : grunt.config.data.kg,
cwd : process.cwd()
};
generator = new kumaGenerator(type, name, subDir, _config);
if (!isDefined(subDir)) {
subDir = '';
}
// Check if the type is given, and prompt if nececary
_this.promptType = function(val) {
if (!isDefined(val) || !generator.isType(val)) {
grunt.log.ok('\nPlease provide a valid type, choose one of the following:');
var i;
for (i = 0; i < generator.types.length; i++) {
console.log(' - ' + generator.types[i].name);
}
generator.prompt('Please enter a type','type', function(val) {
_this.promptType(val);
});
} else {
generator.setType(val);
_this.promptName(name);
}
};
// Check if the name is given, and prompt if nececary
_this.promptName = function(val) {
if (!isDefined(val)) {
grunt.log.ok('\nPlease choose a name for the generated file:');
generator.prompt('Enter a valid name','name', function(val) {
if (isDefined(val)) {
generator.setName(val);
_this.promptName(val);
} else {
console.log('Error setting name!');
}
});
} else {
generator.save(done);
}
};
// Start wizard
if (isDefined(_config) && isDefined(_config.config) && isDefined(_config.config.types)) {
_this.promptType(type);
} else {
grunt.warn('Error getting the config');
}
});
}; |
/**
* Util functions
*
* @since 1.0.0
*/
/**
* Get client IP address
*
* Will return 127.0.0.1 when testing locally
* Useful when you need the user ip for geolocation or serving localized content
*
* @param {Object} request
* @returns {string} ip
*/
exports.getClientIp = (request) => {
// workaround to get real client IP
// most likely because our app will be behind a [reverse] proxy or load balancer
const clientIp = request.headers['x-client-ip'];
// x-forwarded-for
// (typically when your node app is behind a load-balancer (eg. AWS ELB) or proxy)
//
// x-forwarded-for may return multiple IP addresses in the format:
// "client IP, proxy 1 IP, proxy 2 IP"
// Therefore, the right-most IP address is the IP address of the most recent proxy
// and the left-most IP address is the IP address of the originating client.
// source: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
const forwardedForAlt = request.headers['x-forwarded-for'];
// x-real-ip
// (default nginx proxy/fcgi)
// alternative to x-forwarded-for, used by some proxies
const realIp = request.headers['x-real-ip'];
// more obsure ones below
const clusterClientIp = request.headers['x-cluster-client-ip'];
const forwardedAlt = request.headers['x-forwarded'];
const forwardedFor = request.headers['forwarded-for'];
const { forwarded } = request.headers;
// remote address check
const reqConnectionRemoteAddress = request.connection ? request.connection.remoteAddress : null;
const reqSocketRemoteAddress = request.socket ? request.socket.remoteAddress : null;
// remote address checks
const reqConnectionSocketRemoteAddress = (request.connection && request.connection.socket)
? request.connection.socket.remoteAddress : null;
const reqInfoRemoteAddress = request.info ? request.info.remoteAddress : null;
return clientIp
|| (forwardedForAlt && forwardedForAlt.split(',')[0])
|| realIp
|| clusterClientIp
|| forwardedAlt
|| forwardedFor
|| forwarded
|| reqConnectionRemoteAddress
|| reqSocketRemoteAddress
|| reqConnectionSocketRemoteAddress
|| reqInfoRemoteAddress;
};
const regex = /([>=<]{1,2})([0-9a-zA-Z\-.]+)*/g;
const getComparator = (conditionStr) => {
let result = conditionStr.charAt(0);
if ('<>'.includes(result)) {
result = '~';
}
return result;
};
const parsers = {
'*': () => ({ comparator: '*' }),
'=': (cond) => {
let execResult;
if ((execResult = regex.exec(cond)) !== null) {
return { comparator: '=', version: execResult[2] };
}
return false;
},
'~': (cond) => {
const resultItem = { comparator: '~' };
let execResult;
while ((execResult = regex.exec(cond)) !== null) {
if (execResult[1] === '>=') {
[,, resultItem.versionStart] = execResult;
} else if (execResult[1] === '<') {
[,, resultItem.versionEnd] = execResult;
}
}
if (resultItem.versionStart || resultItem.versionEnd) {
return resultItem;
}
return false;
},
};
const stringifier = {
'*': () => '*',
'=': cond => `=${cond.version}`,
'~': cond => `${cond.versionStart ? `>=${cond.versionStart}` : ''} ${cond.versionEnd ? `<${cond.versionEnd}` : ''}`,
};
/**
* Parse below "limited" formatted Semantic Version to an array for UI expression
* - equals: "=2.3", "=2", "=4.3.3"
* - range: ">=1.2.3 <3.0", ">=1.2.3", "<3.0.0" (only permitted gte(>=) and lt(<) for ranges)
* - all: "*"
* - mixed (by OR): ">=1.2.3 <3.0.0 || <0.1.2 || >=5.1"
* @param {string} conditionString
* @return {Array}
*/
exports.parseSemVersion = (semVerString) => {
if (!semVerString) {
return [{ comparator: '*' }]; // default
}
const conditions = semVerString.split('||').map(cond => cond.trim()); // OR 연산을 기준으로 분리
const result = [];
conditions.forEach((cond) => {
regex.lastIndex = 0; // reset find index
const comparator = getComparator(cond);
const parsedObj = parsers[comparator](cond);
if (parsedObj) {
result.push(parsedObj);
}
});
return result;
};
/**
* Stringify parsed version conditions to SemVer representation
* @param {Array} parsedConditions
* @return {string}
*/
exports.stringifySemVersion = (parsedConditions) => {
const result = parsedConditions.map((cond) => {
if (stringifier[cond.comparator]) {
return stringifier[cond.comparator](cond);
}
return '';
});
if (result.includes('*')) {
return '*';
}
return result.filter(cond => !!cond).join(' || ').replace(/\s\s/g, ' ').trim();
};
/**
* Replace camelCase string to snake_case
* @param {string} str
* @returns {string}
*/
exports.camel2snake = (str) => {
if (typeof str === 'string') {
// ignore first occurrence of underscore(_) and capital
return str.replace(/^_/, '')
.replace(/^([A-Z])/, $1 => `${$1.toLowerCase()}`)
.replace(/([A-Z])/g, $1 => `_${$1.toLowerCase()}`);
}
return str;
};
/**
* Replace camelCase string to snake_case on the property names in objects
* @param {Array|Object} object
* @returns {*}
*/
exports.camel2snakeObject = (object) => {
if (object instanceof Array) {
return object.map(value => exports.camel2snakeObject(value));
}
if (object && typeof object === 'object') {
const result = {};
Object.keys(object).forEach((key) => {
result[exports.camel2snake(key)] = exports.camel2snakeObject(object[key]);
});
return result;
}
return object;
};
/**
* Replace snake_case string to camelCase
* @param {string} str
* @returns {string}
*/
exports.snake2camel = (str) => {
if (typeof str === 'string') {
// ignore first occurrence of underscore(_)
return str.replace(/^_/, '').replace(/_([a-z0-9]?)/g, ($1, $2) => `${$2.toUpperCase()}`);
}
return str;
};
/**
* Replace snake_case string to camelCase on the property names in objects
* @param {Array|Object} object
* @returns {*}
*/
exports.snake2camelObject = (object) => {
if (object instanceof Array) {
return object.map(value => exports.snake2camelObject(value));
}
if (object && typeof object === 'object') {
const result = {};
Object.keys(object).forEach((key) => {
result[exports.snake2camel(key)] = exports.snake2camelObject(object[key]);
});
return result;
}
return object;
};
|
import { Globals } from 'vizart-core';
import getSortDef from '../helper/get-sort-def';
const sortData = (_data, _options) => {
if (_options.hasOwnProperty('ordering')) {
let _field = getSortDef(_options);
let _accessor = _field.accessor;
if (_accessor !== undefined && _accessor !== null) {
switch (_field.type) {
case Globals.DataType.STRING:
_data.sort((a, b) => {
return _options.ordering.direction === 'asc'
? a[_accessor].localeCompare(b[_accessor])
: b[_accessor].localeCompare(a[_accessor]);
});
break;
default:
_data.sort((a, b) => {
return _options.ordering.direction === 'asc'
? a[_accessor] - b[_accessor]
: b[_accessor] - a[_accessor];
});
break;
}
}
}
};
export default sortData;
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the JobDeleteMethodOptions class.
* @constructor
* Additional parameters for the deleteMethod operation.
* @member {number} [timeout] The maximum time that the server can spend
* processing the request, in seconds. The default is 30 seconds. Default
* value: 30 .
*
* @member {string} [clientRequestId] The caller-generated request identity,
* in the form of a GUID with no decoration such as curly braces, e.g.
* 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
*
* @member {boolean} [returnClientRequestId] Whether the server should return
* the client-request-id identifier in the response.
*
* @member {date} [ocpDate] The time the request was issued. If not specified,
* this header will be automatically populated with the current system clock
* time.
*
* @member {string} [ifMatch] An ETag is specified. Specify this header to
* perform the operation only if the resource's ETag is an exact match as
* specified.
*
* @member {string} [ifNoneMatch] An ETag is specified. Specify this header to
* perform the operation only if the resource's ETag does not match the
* specified ETag.
*
* @member {date} [ifModifiedSince] Specify this header to perform the
* operation only if the resource has been modified since the specified
* date/time.
*
* @member {date} [ifUnmodifiedSince] Specify this header to perform the
* operation only if the resource has not been modified since the specified
* date/time.
*
*/
function JobDeleteMethodOptions() {
}
/**
* Defines the metadata of JobDeleteMethodOptions
*
* @returns {object} metadata of JobDeleteMethodOptions
*
*/
JobDeleteMethodOptions.prototype.mapper = function () {
return {
required: false,
type: {
name: 'Composite',
className: 'JobDeleteMethodOptions',
modelProperties: {
timeout: {
required: false,
defaultValue: 30,
type: {
name: 'Number'
}
},
clientRequestId: {
required: false,
type: {
name: 'String'
}
},
returnClientRequestId: {
required: false,
type: {
name: 'Boolean'
}
},
ocpDate: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifMatch: {
required: false,
type: {
name: 'String'
}
},
ifNoneMatch: {
required: false,
type: {
name: 'String'
}
},
ifModifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
},
ifUnmodifiedSince: {
required: false,
type: {
name: 'DateTimeRfc1123'
}
}
}
}
};
};
module.exports = JobDeleteMethodOptions;
|
function testSpeed(input) {
if (input.length < 1 || input === undefined) {
return;
}
var speed = +input[0],
area = input[1],
cityLimit = 50,
motorwayLimit = 130,
interstateLimit = 90,
residentalLimit = 20,
overSpeeding = 20,
overExcessiveSpeeding = 40,
city = 'city',
residential = 'residential',
interstate = 'interstate',
motorway = 'motorway',
speeding = 'speeding',
excessiveSpeeding = 'excessive speeding',
recklessDriving = 'reckless driving';
switch (area) {
case city:
if (speed > cityLimit) {
if (speed <= cityLimit + overSpeeding) {
console.log(speeding);
} else if (speed <= cityLimit + overExcessiveSpeeding) {
console.log(excessiveSpeeding);
} else {
console.log(recklessDriving);
}
}
break;
case residential:
if (speed > residentalLimit) {
if (speed <= residentalLimit + overSpeeding) {
console.log(speeding);
} else if (speed <= residentalLimit + overExcessiveSpeeding) {
console.log(excessiveSpeeding);
} else {
console.log(recklessDriving);
}
}
break;
case interstate:
if (speed > interstateLimit) {
if (speed <= interstateLimit + overSpeeding) {
console.log(speeding);
} else if (speed <= interstateLimit + overExcessiveSpeeding) {
console.log(excessiveSpeeding);
} else {
console.log(recklessDriving);
}
}
break;
case motorway:
if (speed > motorwayLimit) {
if (speed <= motorwayLimit + overSpeeding) {
console.log(speeding);
} else if (speed <= motorwayLimit + overExcessiveSpeeding) {
console.log(excessiveSpeeding);
} else {
console.log(recklessDriving);
}
}
break;
default:
return;
}
}
testSpeed([70, 'city']); |
'use strict'
const Container = require('../formats/Container')
const Keys = require('../formats/Keys')
/**
* Saves the grid layer for laye into a PNG file
* @param {WeightedColorGrid} colorGrid the color grid you want to export
* @returns {Promise<void>} a promise returning when finished
*/
function toGridContainer (colorGrid) {
const container = new Container()
// build sprites
const layers = new Map()
const borders = {
initialized: false,
minY: null,
maxY: null
}
colorGrid.forEach(function (x, y, z, color) {
let sprite = null
if (layers.has(y)) {
const data = layers.get(y)
data.minX = Math.min(data.minX, x)
data.minZ = Math.min(data.minZ, z)
sprite = data.sprite
} else {
sprite = container.addSprite()
layers.set(y, {
minX: x,
minZ: z,
sprite: sprite
})
}
const value = color.weight > 0
? color.value
: ((0x80 << 24) >>> 0)
sprite.setPixel(x, z, value)
if (borders.initialized) {
borders.minY = Math.min(borders.minY, y)
borders.maxY = Math.max(borders.maxY, y)
} else {
borders.initialized = true
borders.minY = y
borders.maxY = y
}
})
// build meta model
if (!borders.initialized) {
throw new Error('Color grid did not seem to have color information!')
}
let model = {
format: 'grid-1.0.0',
layers: []
}
for (let y = borders.maxY; y >= borders.minY; y--) {
if (layers.has(y)) {
const data = layers.get(y)
model.layers.push({
spriteId: data.sprite.id,
targetX: data.minX,
targetY: data.minZ
})
} else {
model.layers.push(null)
}
}
container.setMetaObject(Keys.ModelKey, model)
// return container
return container
}
module.exports = toGridContainer
|
/*
* Level Controller
*/
import Event from '../events';
import EventHandler from '../event-handler';
import {logger} from '../utils/logger';
import {ErrorTypes, ErrorDetails} from '../errors';
import BufferHelper from '../helper/buffer-helper';
class LevelController extends EventHandler {
constructor(hls) {
super(hls,
Event.MANIFEST_LOADED,
Event.LEVEL_LOADED,
Event.FRAG_LOADED,
Event.ERROR);
this.ontick = this.tick.bind(this);
this._manualLevel = -1;
}
destroy() {
this.cleanTimer();
this._manualLevel = -1;
}
cleanTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
startLoad() {
this.canload = true;
let levels = this._levels;
// clean up live level details to force reload them, and reset load errors
if(levels) {
levels.forEach(level => {
level.loadError = 0;
const levelDetails = level.details;
if (levelDetails && levelDetails.live) {
level.details = undefined;
}
});
}
// speed up live playlist refresh if timer exists
if (this.timer) {
this.tick();
}
}
stopLoad() {
this.canload = false;
}
onManifestLoaded(data) {
var levels0 = [],
levels = [],
bitrateStart,
bitrateSet = {},
videoCodecFound = false,
audioCodecFound = false,
hls = this.hls,
brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()),
checkSupported = function(type,codec) { return MediaSource.isTypeSupported(`${type}/mp4;codecs=${codec}`);};
// regroup redundant level together
data.levels.forEach(level => {
if(level.videoCodec) {
videoCodecFound = true;
}
// erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio
if(brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
level.audioCodec = undefined;
}
if(level.audioCodec || (level.attrs && level.attrs.AUDIO)) {
audioCodecFound = true;
}
let redundantLevelId = bitrateSet[level.bitrate];
if (redundantLevelId === undefined) {
bitrateSet[level.bitrate] = levels0.length;
level.url = [level.url];
level.urlId = 0;
levels0.push(level);
} else {
levels0[redundantLevelId].url.push(level.url);
}
});
// remove audio-only level if we also have levels with audio+video codecs signalled
if(videoCodecFound && audioCodecFound) {
levels0.forEach(level => {
if(level.videoCodec) {
levels.push(level);
}
});
} else {
levels = levels0;
}
// only keep level with supported audio/video codecs
levels = levels.filter(function(level) {
let audioCodec = level.audioCodec, videoCodec = level.videoCodec;
return (!audioCodec || checkSupported('audio',audioCodec)) &&
(!videoCodec || checkSupported('video',videoCodec));
});
if(levels.length) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate;
// sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels;
// find index of first level in sorted levels
for (let i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);
break;
}
}
hls.trigger(Event.MANIFEST_PARSED, {levels: levels, firstLevel: this._firstLevel, stats: data.stats, audio : audioCodecFound, video : videoCodecFound, altAudio : data.audioTracks.length > 0});
} else {
hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest'});
}
return;
}
get levels() {
return this._levels;
}
get level() {
return this._level;
}
set level(newLevel) {
let levels = this._levels;
if (levels && levels.length > newLevel) {
if (this._level !== newLevel || levels[newLevel].details === undefined) {
this.setLevelInternal(newLevel);
}
}
}
setLevelInternal(newLevel) {
const levels = this._levels;
const hls = this.hls;
// check if level idx is valid
if (newLevel >= 0 && newLevel < levels.length) {
// stopping live reloading timer if any
this.cleanTimer();
if (this._level !== newLevel) {
logger.log(`switching to level ${newLevel}`);
this._level = newLevel;
var levelProperties = levels[newLevel];
levelProperties.level = newLevel;
// LEVEL_SWITCH to be deprecated in next major release
hls.trigger(Event.LEVEL_SWITCH, levelProperties);
hls.trigger(Event.LEVEL_SWITCHING, levelProperties);
}
var level = levels[newLevel], levelDetails = level.details;
// check if we need to load playlist for this level
if (!levelDetails || levelDetails.live === true) {
// level not retrieved yet, or live playlist we need to (re)load it
var urlId = level.urlId;
hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: newLevel, id: urlId});
}
} else {
// invalid level id given, trigger error
hls.trigger(Event.ERROR, {type : ErrorTypes.OTHER_ERROR, details: ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx'});
}
}
get manualLevel() {
return this._manualLevel;
}
set manualLevel(newLevel) {
this._manualLevel = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
get firstLevel() {
return this._firstLevel;
}
set firstLevel(newLevel) {
this._firstLevel = newLevel;
}
get startLevel() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
let configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
}
set startLevel(newLevel) {
this._startLevel = newLevel;
}
onError(data) {
if(data.fatal) {
if (data.type === ErrorTypes.NETWORK_ERROR) {
this.cleanTimer();
}
return;
}
let details = data.details, hls = this.hls, levelId, level, levelError = false;
// try to recover not fatal errors
switch(details) {
case ErrorDetails.FRAG_LOAD_ERROR:
case ErrorDetails.FRAG_LOAD_TIMEOUT:
case ErrorDetails.FRAG_LOOP_LOADING_ERROR:
case ErrorDetails.KEY_LOAD_ERROR:
case ErrorDetails.KEY_LOAD_TIMEOUT:
levelId = data.frag.level;
break;
case ErrorDetails.LEVEL_LOAD_ERROR:
case ErrorDetails.LEVEL_LOAD_TIMEOUT:
levelId = data.context.level;
levelError = true;
break;
case ErrorDetails.REMUX_ALLOC_ERROR:
levelId = data.level;
break;
default:
break;
}
/* try to switch to a redundant stream if any available.
* if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
* otherwise, we cannot recover this network error ...
*/
if (levelId !== undefined) {
level = this._levels[levelId];
if(!level.loadError) {
level.loadError = 1;
} else {
level.loadError++;
}
// if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load.
// if level.loadError reaches nbRedundantLevel it means that we tried them all, no hope => let's switch down
const nbRedundantLevel = level.url.length;
if (nbRedundantLevel > 1 && level.loadError < nbRedundantLevel) {
level.urlId = (level.urlId + 1) % nbRedundantLevel;
level.details = undefined;
logger.warn(`level controller,${details} for level ${levelId}: switching to redundant stream id ${level.urlId}`);
} else {
// we could try to recover if in auto mode and current level not lowest level (0)
let recoverable = ((this._manualLevel === -1) && levelId);
if (recoverable) {
logger.warn(`level controller,${details}: switch-down for next fragment`);
hls.nextAutoLevel = Math.max(0,levelId-1);
} else if(level && level.details && level.details.live) {
logger.warn(`level controller,${details} on live stream, discard`);
if (levelError) {
// reset this._level so that another call to set level() will retrigger a frag load
this._level = undefined;
}
// other errors are handled by stream controller
} else if (details === ErrorDetails.LEVEL_LOAD_ERROR ||
details === ErrorDetails.LEVEL_LOAD_TIMEOUT) {
let media = hls.media,
// 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
mediaBuffered = media && BufferHelper.isBuffered(media,media.currentTime) && BufferHelper.isBuffered(media,media.currentTime+0.5);
if (mediaBuffered) {
let retryDelay = hls.config.levelLoadingRetryDelay;
logger.warn(`level controller,${details}, but media buffered, retry in ${retryDelay}ms`);
this.timer = setTimeout(this.ontick,retryDelay);
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
data.levelRetry = true;
} else {
logger.error(`cannot recover ${details} error`);
this._level = undefined;
// stopping live reloading timer if any
this.cleanTimer();
// switch error to fatal
data.fatal = true;
}
}
}
}
}
// reset level load error counter on successful frag loaded
onFragLoaded(data) {
const fragLoaded = data.frag;
if (fragLoaded && fragLoaded.type === 'main') {
const level = this._levels[fragLoaded.level];
if (level) {
level.loadError = 0;
}
}
}
onLevelLoaded(data) {
const levelId = data.level;
// only process level loaded events matching with expected level
if (levelId === this._level) {
let curLevel = this._levels[levelId];
// reset level load error counter on successful level loaded
curLevel.loadError = 0;
let newDetails = data.details;
// if current playlist is a live playlist, arm a timer to reload it
if (newDetails.live) {
let reloadInterval = 1000*( newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
curDetails = curLevel.details;
if (curDetails && newDetails.endSN === curDetails.endSN) {
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
reloadInterval /=2;
logger.log(`same live playlist, reload twice faster`);
}
// decrement reloadInterval with level loading delay
reloadInterval -= performance.now() - data.stats.trequest;
// in any case, don't reload more than every second
reloadInterval = Math.max(1000,Math.round(reloadInterval));
logger.log(`live playlist, reload in ${reloadInterval} ms`);
this.timer = setTimeout(this.ontick,reloadInterval);
} else {
this.timer = null;
}
}
}
tick() {
var levelId = this._level;
if (levelId !== undefined && this.canload) {
var level = this._levels[levelId];
if (level && level.url) {
var urlId = level.urlId;
this.hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: levelId, id: urlId});
}
}
}
get nextLoadLevel() {
if (this._manualLevel !== -1) {
return this._manualLevel;
} else {
return this.hls.nextAutoLevel;
}
}
set nextLoadLevel(nextLevel) {
this.level = nextLevel;
if (this._manualLevel === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}
export default LevelController;
|
import _ from 'underscore';
import { diffModes } from '~/ide/constants';
import {
LINE_POSITION_LEFT,
LINE_POSITION_RIGHT,
TEXT_DIFF_POSITION_TYPE,
LEGACY_DIFF_NOTE_TYPE,
DIFF_NOTE_TYPE,
NEW_LINE_TYPE,
OLD_LINE_TYPE,
MATCH_LINE_TYPE,
LINES_TO_BE_RENDERED_DIRECTLY,
MAX_LINES_TO_BE_RENDERED,
} from '../constants';
export function findDiffFile(files, hash) {
return files.filter(file => file.file_hash === hash)[0];
}
export const getReversePosition = linePosition => {
if (linePosition === LINE_POSITION_RIGHT) {
return LINE_POSITION_LEFT;
}
return LINE_POSITION_RIGHT;
};
export function getFormData(params) {
const {
commit,
note,
noteableType,
noteableData,
diffFile,
noteTargetLine,
diffViewType,
linePosition,
positionType,
} = params;
const position = JSON.stringify({
base_sha: diffFile.diff_refs.base_sha,
start_sha: diffFile.diff_refs.start_sha,
head_sha: diffFile.diff_refs.head_sha,
old_path: diffFile.old_path,
new_path: diffFile.new_path,
position_type: positionType || TEXT_DIFF_POSITION_TYPE,
old_line: noteTargetLine ? noteTargetLine.old_line : null,
new_line: noteTargetLine ? noteTargetLine.new_line : null,
x: params.x,
y: params.y,
width: params.width,
height: params.height,
});
const postData = {
view: diffViewType,
line_type: linePosition === LINE_POSITION_RIGHT ? NEW_LINE_TYPE : OLD_LINE_TYPE,
merge_request_diff_head_sha: diffFile.diff_refs.head_sha,
in_reply_to_discussion_id: '',
note_project_id: '',
target_type: noteableData.targetType,
target_id: noteableData.id,
return_discussion: true,
note: {
note,
position,
noteable_type: noteableType,
noteable_id: noteableData.id,
commit_id: commit && commit.id,
type:
diffFile.diff_refs.start_sha && diffFile.diff_refs.head_sha
? DIFF_NOTE_TYPE
: LEGACY_DIFF_NOTE_TYPE,
line_code: noteTargetLine ? noteTargetLine.line_code : null,
},
};
return postData;
}
export function getNoteFormData(params) {
const data = getFormData(params);
return {
endpoint: params.noteableData.create_note_path,
data,
};
}
export const findIndexInInlineLines = (lines, lineNumbers) => {
const { oldLineNumber, newLineNumber } = lineNumbers;
return _.findIndex(
lines,
line => line.old_line === oldLineNumber && line.new_line === newLineNumber,
);
};
export const findIndexInParallelLines = (lines, lineNumbers) => {
const { oldLineNumber, newLineNumber } = lineNumbers;
return _.findIndex(
lines,
line =>
line.left &&
line.right &&
line.left.old_line === oldLineNumber &&
line.right.new_line === newLineNumber,
);
};
export function removeMatchLine(diffFile, lineNumbers, bottom) {
const indexForInline = findIndexInInlineLines(diffFile.highlighted_diff_lines, lineNumbers);
const indexForParallel = findIndexInParallelLines(diffFile.parallel_diff_lines, lineNumbers);
const factor = bottom ? 1 : -1;
diffFile.highlighted_diff_lines.splice(indexForInline + factor, 1);
diffFile.parallel_diff_lines.splice(indexForParallel + factor, 1);
}
export function addLineReferences(lines, lineNumbers, bottom) {
const { oldLineNumber, newLineNumber } = lineNumbers;
const lineCount = lines.length;
let matchLineIndex = -1;
const linesWithNumbers = lines.map((l, index) => {
if (l.type === MATCH_LINE_TYPE) {
matchLineIndex = index;
} else {
Object.assign(l, {
old_line: bottom ? oldLineNumber + index + 1 : oldLineNumber + index - lineCount,
new_line: bottom ? newLineNumber + index + 1 : newLineNumber + index - lineCount,
});
}
return l;
});
if (matchLineIndex > -1) {
const line = linesWithNumbers[matchLineIndex];
const targetLine = bottom
? linesWithNumbers[matchLineIndex - 1]
: linesWithNumbers[matchLineIndex + 1];
Object.assign(line, {
meta_data: {
old_pos: targetLine.old_line,
new_pos: targetLine.new_line,
},
});
}
return linesWithNumbers;
}
export function addContextLines(options) {
const { inlineLines, parallelLines, contextLines, lineNumbers } = options;
const normalizedParallelLines = contextLines.map(line => ({
left: line,
right: line,
}));
if (options.bottom) {
inlineLines.push(...contextLines);
parallelLines.push(...normalizedParallelLines);
} else {
const inlineIndex = findIndexInInlineLines(inlineLines, lineNumbers);
const parallelIndex = findIndexInParallelLines(parallelLines, lineNumbers);
inlineLines.splice(inlineIndex, 0, ...contextLines);
parallelLines.splice(parallelIndex, 0, ...normalizedParallelLines);
}
}
/**
* Trims the first char of the `richText` property when it's either a space or a diff symbol.
* @param {Object} line
* @returns {Object}
*/
export function trimFirstCharOfLineContent(line = {}) {
// eslint-disable-next-line no-param-reassign
delete line.text;
// eslint-disable-next-line no-param-reassign
line.discussions = [];
const parsedLine = Object.assign({}, line);
if (line.rich_text) {
const firstChar = parsedLine.rich_text.charAt(0);
if (firstChar === ' ' || firstChar === '+' || firstChar === '-') {
parsedLine.rich_text = line.rich_text.substring(1);
}
}
return parsedLine;
}
function getLineCode({ left, right }, index) {
if (left && left.line_code) {
return left.line_code;
} else if (right && right.line_code) {
return right.line_code;
}
return index;
}
// This prepares and optimizes the incoming diff data from the server
// by setting up incremental rendering and removing unneeded data
export function prepareDiffData(diffData) {
const filesLength = diffData.diff_files.length;
let showingLines = 0;
for (let i = 0; i < filesLength; i += 1) {
const file = diffData.diff_files[i];
if (file.parallel_diff_lines) {
const linesLength = file.parallel_diff_lines.length;
for (let u = 0; u < linesLength; u += 1) {
const line = file.parallel_diff_lines[u];
line.line_code = getLineCode(line, u);
if (line.left) {
line.left = trimFirstCharOfLineContent(line.left);
line.left.hasForm = false;
}
if (line.right) {
line.right = trimFirstCharOfLineContent(line.right);
line.right.hasForm = false;
}
}
}
if (file.highlighted_diff_lines) {
const linesLength = file.highlighted_diff_lines.length;
for (let u = 0; u < linesLength; u += 1) {
const line = file.highlighted_diff_lines[u];
Object.assign(line, { ...trimFirstCharOfLineContent(line), hasForm: false });
}
showingLines += file.parallel_diff_lines.length;
}
Object.assign(file, {
renderIt: showingLines < LINES_TO_BE_RENDERED_DIRECTLY,
collapsed: file.text && showingLines > MAX_LINES_TO_BE_RENDERED,
discussions: [],
});
}
}
export function getDiffPositionByLineCode(diffFiles) {
return diffFiles.reduce((acc, diffFile) => {
// We can only use highlightedDiffLines to create the map of diff lines because
// highlightedDiffLines will also include every parallel diff line in it.
if (diffFile.highlighted_diff_lines) {
diffFile.highlighted_diff_lines.forEach(line => {
if (line.line_code) {
acc[line.line_code] = {
base_sha: diffFile.diff_refs.base_sha,
head_sha: diffFile.diff_refs.head_sha,
start_sha: diffFile.diff_refs.start_sha,
new_path: diffFile.new_path,
old_path: diffFile.old_path,
old_line: line.old_line,
new_line: line.new_line,
line_code: line.line_code,
position_type: 'text',
};
}
});
}
return acc;
}, {});
}
// This method will check whether the discussion is still applicable
// to the diff line in question regarding different versions of the MR
export function isDiscussionApplicableToLine({ discussion, diffPosition, latestDiff }) {
const { line_code, ...diffPositionCopy } = diffPosition;
if (discussion.original_position && discussion.position) {
const originalRefs = discussion.original_position;
const refs = discussion.position;
return _.isEqual(refs, diffPositionCopy) || _.isEqual(originalRefs, diffPositionCopy);
}
// eslint-disable-next-line
return latestDiff && discussion.active && line_code === discussion.line_code;
}
export const generateTreeList = files =>
files.reduce(
(acc, file) => {
const split = file.new_path.split('/');
split.forEach((name, i) => {
const parent = acc.treeEntries[split.slice(0, i).join('/')];
const path = `${parent ? `${parent.path}/` : ''}${name}`;
if (!acc.treeEntries[path]) {
const type = path === file.new_path ? 'blob' : 'tree';
acc.treeEntries[path] = {
key: path,
path,
name,
type,
tree: [],
};
const entry = acc.treeEntries[path];
if (type === 'blob') {
Object.assign(entry, {
changed: true,
tempFile: file.new_file,
deleted: file.deleted_file,
fileHash: file.file_hash,
addedLines: file.added_lines,
removedLines: file.removed_lines,
});
} else {
Object.assign(entry, {
opened: true,
});
}
(parent ? parent.tree : acc.tree).push(entry);
}
});
return acc;
},
{ treeEntries: {}, tree: [] },
);
export const getDiffMode = diffFile => {
const diffModeKey = Object.keys(diffModes).find(key => diffFile[`${key}_file`]);
return (
diffModes[diffModeKey] ||
(diffFile.mode_changed && diffModes.mode_changed) ||
diffModes.replaced
);
};
|
/*
*
* DepartmentListContainer
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import makeSelectDepartmentListContainer from './selectors';
import { requestDepartment, selectSection } from './actions';
import DepartmentList from '../../components/DepartmentList';
export class DepartmentListContainer extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
storeName: PropTypes.string.isRequired,
departmentName: PropTypes.string.isRequired,
requestDepartment: PropTypes.func.isRequired,
selectSection: PropTypes.func.isRequired,
}
componentWillMount() {
this.props.requestDepartment(this.props.storeName, this.props.departmentName);
}
render() {
return (
<div>
<DepartmentList {...this.props} />
</div>
);
}
}
const mapStateToProps = makeSelectDepartmentListContainer();
function mapDispatchToProps(dispatch) {
return {
requestDepartment: (storeName, departmentName) =>
dispatch(requestDepartment(storeName, departmentName)),
selectSection: (departmentSlug, sectionId, floorSlug) =>
dispatch(selectSection(departmentSlug, sectionId, floorSlug)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(DepartmentListContainer);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.