text
stringlengths 7
3.69M
|
|---|
const bcrypt = require("bcryptjs");
module.exports = {
async register(req, res) {
const { username, password, email } = req.body;
console.log(req.body);
const db = req.app.get("db");
const user = db.auth.find_email(email);
if (user[0])
return res.status(200).send({ message: "lol this email is being used" });
salt = bcrypt.genSaltSync(10);
hash = bcrypt.hashSync(password, salt);
const userId = await db.auth.add_user({ username, email });
console.log(userId[0].id);
db.auth.add_hash({ user_id: userId[0].id, hash }).catch(err => {
return res.sendStatus(503);
});
req.session.user = {
username,
email,
userId: userId[0].id,
isAdmin: false
};
res.status(201).send({ user: req.session.user });
},
async login(req, res) {
const db = req.app.get('db')
const {username, password} = req.body
console.log(username, password);
const user = await db.auth.find_user(username)
if(!user[0]) return res.status(200).send({message: 'User not found'})
const result = bcrypt.compareSync(password, user[0].hash)
if(!result) return res.status(200).send({message: 'Incorrect Password'})
const {is_admin: isAdmin, id: id, email } = user[0]
req.session.user = { username, email, id, isAdmin }
res.status(200).send({message: 'yeet', user: req.session.user})
},
logout(req,res) {
req.session.destroy()
res.status(200).send('yeet')
}
};
|
/**
* Copyright(c) 2012-2016 weizoom
*/
"use strict";
var debug = require('debug')('m:outline.data:ProductModel');
var React = require('react');
var ReactDOM = require('react-dom');
var Reactman = require('reactman');
var FormInput = Reactman.FormInput;
var Action = require('./Action');
var Constant = require('./Constant')
var ProductModel = React.createClass({
getInitialState: function() {
var model = this.props.value;
debug(model);
return {
index: this.props.index,
name: model.name,
stocks: model.stocks
};
},
onChange: function(value, event) {
var property = event.target.getAttribute('name');
this.state[property] = value;
if (this.props.onChange) {
this.props.onChange(this.state, event);
}
},
onClickDelete: function(event) {
if (this.props.onDelete) {
this.props.onDelete(this.props.index);
}
},
render:function(){
var model = this.props.value;
var autoFocus = !model.name;
return (
<div>
<FormInput label="规格名:" type="text" name="name" validate="require-string" placeholder="" value={model.name} onChange={this.onChange} autoFocus={autoFocus} />
<FormInput label="库存:" type="text" name="stocks" validate="require-int" placeholder="" value={model.stocks} onChange={this.onChange} />
<a className="btn btn-default ml20" style={{'verticalAlign':'top'}} onClick={this.onClickDelete}><span className="glyphicon glyphicon-remove"></span></a>
</div>
)
}
})
module.exports = ProductModel;
|
import Ember from 'ember';
import C from 'ui/utils/constants';
export default Ember.Route.extend({
model: function() {
var me = this.get(`session.${C.SESSION.ACCOUNT_ID}`);
return Ember.RSVP.hash({
account: this.get('userStore').findAll('apikey', null, {filter: {accountId: me}, url: 'apikeys', forceReload: true}),
environment: this.get('store').findAll('apikey', null, {forceReload: true}),
});
},
});
|
export default function formatDate(date) {
if (date === null) return;
const event = new Date(date);
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
return event.toLocaleString('en-GB', options);
}
|
/* Chunky Monkey
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
Here are some helpful links:
Array.prototype.push()
Array.prototype.slice()
*/
function chunkArrayInGroups(arr, size) {
var chunk = [];
while (arr.length) {
chunk.push(arr.splice(0, size));
}
return chunk;
}
/*
Array.prototype.push() - The push() method adds one or more elements to the end of an array and returns the new length of the array.
Array.prototype.splice() - The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
*/
chunkArrayInGroups(["a", "b", "c", "d"], 2);
|
import React from 'react';
import ExerciceDisplayer from './ExerciceDisplayer';
import PropTypes from 'prop-types';
import connect from 'react-redux/es/connect/connect';
import { postQuestion } from '../../../../redux/question/actions/post';
import { deleteQuestion } from '../../../../redux/question/actions/delete';
import { patchQuestion } from '../../../../redux/question/actions/patch';
import { getExam } from '../../../../redux/exams/actions/getSingle';
import { arrayMove } from 'react-sortable-hoc';
class Exercice extends React.Component {
static propTypes = {
exercices: PropTypes.object,
handleInputExercice: PropTypes.func,
saveNewExercice: PropTypes.func,
saveNewExerciceEnter: PropTypes.func,
id: PropTypes.string,
index: PropTypes.number
};
constructor(props) {
super(props);
this.state = {
question: {},
questions: props.exercices.questions
};
}
componentDidMount() {}
/**
* Add a new question related to an exercice.
*/
addQuestion = async () => {
let questions = this.state.questions;
let maxOrder = questions ? questions.length : 0;
await this.props.fetchNewQuestion(
this.props.exam._id,
this.props.exercices._id,
{
title: 'Nouvelle Question',
order: maxOrder + 1,
scale: 0
}
);
await this.props.fetchExam(this.props.exam._id);
this.setState({
questions: this.props.exercices.questions
});
};
moveQuestion = async ({ oldIndex, newIndex, collection }) => {
const questions = arrayMove(this.state.questions, oldIndex, newIndex);
const orderedQuestions = questions.map((q, i) => {
return {
...q,
order: i
};
});
await this.setState({
questions: orderedQuestions
});
await this.state.questions.map(async question => {
await this.props.fetchPatchQuestion(
this.props.exam._id,
this.props.exercices._id,
question._id,
question
);
});
await this.props.fetchExam(this.props.exam._id);
};
/**
* Put input value in state with name of the input as name of the variable
* @param {Object} e
*/
handleInputQuestion = e => {
const question = this.props.exercices.questions.find(
q => q._id === e.target.id
);
const questionCopy = { ...question };
const { name } = e.target;
switch (name) {
case 'questionTitle':
questionCopy.title = e.target.value;
this.setState({ question: questionCopy });
break;
case 'questionScale':
questionCopy.scale = e.target.value;
this.setState({ question: questionCopy });
break;
case 'questionCorrection':
questionCopy.correction = e.target.value;
this.setState({ question: questionCopy });
break;
case 'questionEstimatedTime':
let time = e.target.value * 60;
questionCopy.estimatedTime = time;
this.setState({ question: questionCopy });
break;
default:
break;
}
};
/**
* Delete a question related to an exercice.
*
* We can't delete the first question.
*
* @param {Object} v
*/
deleteQuestion = async v => {
const question = this.props.exercices.questions.find(
q => q._id === v.target.value
);
const idQuestion = question._id;
let idExo = this.props.exercices._id;
const listOfQuestions = this.props.exercices.questions.filter(
q => q._id !== question._id
);
this.setState({ question: listOfQuestions });
await this.props.fetchDeleteQuestion(this.props.id, idExo, idQuestion);
await this.props.fetchExam(this.props.id);
};
saveNewQuestion = async e => {
const question = this.state.question;
await this.props.fetchPatchQuestion(
this.props.id,
this.props.exercices._id,
question._id,
question
);
await this.props.fetchExam(this.props.id);
};
saveQuestionEnter = async e => {
if (e.keyCode === 13 || e.keyCode === 9) {
const question = this.state.question;
await this.props.fetchPatchQuestion(
this.props.id,
this.props.exercices._id,
question._id,
question
);
}
await this.props.fetchExam(this.props.id);
};
render() {
return (
<div>
<ExerciceDisplayer
handleInputQuestion={this.handleInputQuestion}
handleInputExercice={this.props.handleInputExercice}
saveNewExercice={this.props.saveNewExercice}
saveNewExerciceEnter={this.props.saveNewExerciceEnter}
addQuestion={this.addQuestion}
exercices={this.props.exercices}
deleteQuestion={this.deleteQuestion}
moveQuestion={this.moveQuestion}
deleteExercice={this.props.deleteExercice}
saveQuestion={this.saveNewQuestion}
saveQuestionEnter={this.saveQuestionEnter}
question={this.state.questions}
index={this.props.index}
id={this.props.id}
/>
</div>
);
}
}
export default connect(
(state, ownProps) => ({
exercice: state.exercices.exercices,
exam: state.exams.exams,
loading: state.exercices.loading,
err: state.exercices.errorMessage
}),
(dispatch, ownProps) => ({
fetchNewQuestion: (idExam, idExercice, questionToAdd) =>
dispatch(postQuestion(idExam, idExercice, questionToAdd)),
fetchDeleteQuestion: (idExam, idExercice, idQuestion, questionToAdd) =>
dispatch(deleteQuestion(idExam, idExercice, idQuestion, questionToAdd)),
fetchPatchQuestion: (idExam, idExercice, idQuestion, questionToAdd) =>
dispatch(patchQuestion(idExam, idExercice, idQuestion, questionToAdd)),
fetchExam: id => dispatch(getExam(id))
})
)(Exercice);
|
import MeshPointMap from './MeshPointMap'
export default MeshPointMap
|
import React, {
Component,
PropTypes,
StyleSheet,
Text,
View,
} from 'react-native'
class Watermark extends Component {
static propTypes = {
};
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>{this.props.name}</Text>
</View>
)
}
}
export default Watermark
const styles = StyleSheet.create({
container: {position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center'},
text: {fontSize: 80, color: '#eee', fontWeight: 'bold', textAlign: 'center'},
})
|
/**
* Created by Ziv on 2017/3/10.
*/
/**
* 将输入的字符串变为驼峰法表示。
* @param str
* @returns {string|void|XML|*}
*/
//my solution
function toCamelCase(str) {
return str.replace(/[_-]\w/ig, function (match) {
return match.charAt(1).toUpperCase();
})
}
// returns "theStealthWarrior"
toCamelCase("the-stealth-warrior");
|
"use strict";
document.addEventListener("DOMContentLoaded", function () {
if (Neo.init()) {
if (!navigator.userAgent.match("Electron")) {
Neo.start();
}
}
});
var Neo = function () {};
Neo.version = "1.5.11";
Neo.painter;
Neo.fullScreen = false;
Neo.uploaded = false;
Neo.viewer = false;
Neo.toolSide = false;
Neo.config = {
width: 300,
height: 300,
colors: [
"#000000",
"#FFFFFF",
"#B47575",
"#888888",
"#FA9696",
"#C096C0",
"#FFB6FF",
"#8080FF",
"#25C7C9",
"#E7E58D",
"#E7962D",
"#99CB7B",
"#FCECE2",
"#F9DDCF",
],
};
Neo.reservePen = {};
Neo.reserveEraser = {};
Neo.SLIDERTYPE_RED = 0;
Neo.SLIDERTYPE_GREEN = 1;
Neo.SLIDERTYPE_BLUE = 2;
Neo.SLIDERTYPE_ALPHA = 3;
Neo.SLIDERTYPE_SIZE = 4;
document.neo = Neo;
Neo.init = function () {
var applets = document.getElementsByTagName("applet");
if (applets.length == 0) {
applets = document.getElementsByTagName("applet-dummy");
}
for (var i = 0; i < applets.length; i++) {
var applet = applets[i];
var name = applet.attributes.name.value;
if (name == "paintbbs" || name == "pch") {
Neo.applet = applet;
if (name == "paintbbs") {
Neo.initConfig(applet);
Neo.createContainer(applet);
Neo.init2();
} else {
Neo.viewer = true;
Neo.initConfig(applet);
var filename = Neo.getFilename();
var pch = Neo.getPCH(filename, function (pch) {
if (pch) {
Neo.createViewer(applet);
Neo.config.width = pch.width;
Neo.config.height = pch.height;
Neo.initViewer(pch);
Neo.startViewer();
}
});
}
return true;
}
}
return false;
};
Neo.init2 = function () {
var pageview = document.getElementById("pageView");
pageview.style.width = Neo.config.applet_width + "px";
pageview.style.height = Neo.config.applet_height + "px";
Neo.canvas = document.getElementById("canvas");
Neo.container = document.getElementById("container");
Neo.toolsWrapper = document.getElementById("toolsWrapper");
Neo.painter = new Neo.Painter();
Neo.painter.build(Neo.canvas, Neo.config.width, Neo.config.height);
Neo.container.oncontextmenu = function () {
return false;
};
// 動画記録
Neo.animation = Neo.config.thumbnail_type == "animation";
// 続きから描く
Neo.storage = Neo.isMobile() ? localStorage : sessionStorage;
var filename = Neo.getFilename();
var message =
!filename || filename.slice(-4).toLowerCase() != ".pch"
? "描きかけの画像があります。復元しますか?"
: "描きかけの画像があります。動画の読み込みを中止して復元しますか?";
if (Neo.storage.getItem("timestamp") && confirm(Neo.translate(message))) {
var oe = Neo.painter;
setTimeout(function () {
oe.loadSession(function () {
oe._pushUndo();
oe._actionMgr.restore();
});
}, 1);
} else if (filename) {
if (filename.slice(-4).toLowerCase() == ".pch") {
Neo.painter.loadAnimation(filename);
} else {
Neo.painter.loadImage(filename);
}
}
window.addEventListener(
"pagehide",
function (e) {
if (!Neo.uploaded && Neo.painter.isDirty()) {
Neo.painter.saveSession();
} else {
Neo.painter.clearSession();
}
},
false
);
};
Neo.initConfig = function (applet) {
if (applet) {
var name = applet.attributes.name.value || "neo";
var appletWidth = applet.attributes.width;
var appletHeight = applet.attributes.height;
if (appletWidth) Neo.config.applet_width = parseInt(appletWidth.value);
if (appletHeight) Neo.config.applet_height = parseInt(appletHeight.value);
var params = applet.getElementsByTagName("param");
for (var i = 0; i < params.length; i++) {
var p = params[i];
Neo.config[p.name] = Neo.fixConfig(p.value);
if (p.name == "image_width") Neo.config.width = parseInt(p.value);
if (p.name == "image_height") Neo.config.height = parseInt(p.value);
}
var emulationMode = Neo.config.neo_emulation_mode || "2.22_8x";
Neo.config.neo_alt_translation = emulationMode.slice(-1).match(/x/i);
if (Neo.viewer && !Neo.config.color_bar) {
Neo.config.color_bar = "#eeeeff";
}
Neo.readStyles();
Neo.applyStyle("color_bk", "#ccccff");
Neo.applyStyle("color_bk2", "#bbbbff");
Neo.applyStyle("color_tool_icon", "#e8dfae");
Neo.applyStyle("color_icon", "#ccccff");
Neo.applyStyle("color_iconselect", "#ffaaaa");
Neo.applyStyle("color_text", "#666699");
Neo.applyStyle("color_bar", "#6f6fae");
Neo.applyStyle("tool_color_button", "#e8dfae");
Neo.applyStyle("tool_color_button2", "#f8daaa");
Neo.applyStyle("tool_color_text", "#773333");
Neo.applyStyle("tool_color_bar", "#ddddff");
Neo.applyStyle("tool_color_frame", "#000000");
// viewer用
if (Neo.viewer) {
Neo.applyStyle("color_back", "#ccccff");
Neo.applyStyle("color_bar_select", "#407675");
}
var e = document.getElementById("container");
Neo.config.inherit_color = Neo.getInheritColor(e);
if (!Neo.config.color_frame) Neo.config.color_frame = Neo.config.color_text;
if (
Neo.config.neo_tool_side == "left" ||
Neo.config.neo_tool_side == "true"
) {
Neo.toolSide = true;
}
}
Neo.config.reserves = [
{
size: 1,
color: "#000000",
alpha: 1.0,
tool: Neo.Painter.TOOLTYPE_PEN,
drawType: Neo.Painter.DRAWTYPE_FREEHAND,
},
{
size: 5,
color: "#FFFFFF",
alpha: 1.0,
tool: Neo.Painter.TOOLTYPE_ERASER,
drawType: Neo.Painter.DRAWTYPE_FREEHAND,
},
{
size: 10,
color: "#FFFFFF",
alpha: 1.0,
tool: Neo.Painter.TOOLTYPE_ERASER,
drawType: Neo.Painter.DRAWTYPE_FREEHAND,
},
];
Neo.reservePen = Neo.clone(Neo.config.reserves[0]);
Neo.reserveEraser = Neo.clone(Neo.config.reserves[1]);
};
Neo.fixConfig = function (value) {
// javaでは"#12345"を色として解釈するがjavascriptでは"#012345"に変換しないとだめ
if (value.match(/^#[0-9a-fA-F]{5}$/)) {
value = "#0" + value.slice(1);
}
return value;
};
Neo.getStyleSheet = function () {
var style = document.createElement("style");
document.head.appendChild(style);
return style.sheet;
};
Neo.initSkin = function () {
Neo.styleSheet = Neo.getStyleSheet();
var lightBorder = Neo.multColor(Neo.config.color_icon, 1.3);
var darkBorder = Neo.multColor(Neo.config.color_icon, 0.7);
var lightBar = Neo.multColor(Neo.config.color_bar, 1.3);
var darkBar = Neo.multColor(Neo.config.color_bar, 0.7);
var bgImage = Neo.painter ? Neo.backgroundImage() : "";
Neo.addRule(".NEO #container", "background-image", "url(" + bgImage + ")");
Neo.addRule(".NEO .colorSlider .label", "color", Neo.config.tool_color_text);
Neo.addRule(".NEO .sizeSlider .label", "color", Neo.config.tool_color_text);
Neo.addRule(
".NEO .layerControl .label1",
"color",
Neo.config.tool_color_text
);
Neo.addRule(
".NEO .layerControl .label0",
"color",
Neo.config.tool_color_text
);
Neo.addRule(".NEO .toolTipOn .label", "color", Neo.config.tool_color_text);
Neo.addRule(".NEO .toolTipOff .label", "color", Neo.config.tool_color_text);
Neo.addRule(".NEO #toolSet", "background-color", Neo.config.color_bk);
Neo.addRule(".NEO #tools", "color", Neo.config.tool_color_text);
Neo.addRule(
".NEO .layerControl .bg",
"border-bottom",
"1px solid " + Neo.config.tool_color_text
);
Neo.addRule(".NEO .buttonOn", "color", Neo.config.color_text);
Neo.addRule(".NEO .buttonOff", "color", Neo.config.color_text);
Neo.addRule(".NEO .buttonOff", "background-color", Neo.config.color_icon);
Neo.addRule(
".NEO .buttonOff",
"border-top",
"1px solid ",
Neo.config.color_icon
);
Neo.addRule(
".NEO .buttonOff",
"border-left",
"1px solid ",
Neo.config.color_icon
);
Neo.addRule(
".NEO .buttonOff",
"box-shadow",
"0 0 0 1px " +
Neo.config.color_icon +
", 0 0 0 2px " +
Neo.config.color_frame
);
Neo.addRule(
".NEO .buttonOff:hover",
"background-color",
Neo.config.color_icon
);
Neo.addRule(
".NEO .buttonOff:hover",
"border-top",
"1px solid " + lightBorder
);
Neo.addRule(
".NEO .buttonOff:hover",
"border-left",
"1px solid " + lightBorder
);
Neo.addRule(
".NEO .buttonOff:hover",
"box-shadow",
"0 0 0 1px " +
Neo.config.color_iconselect +
", 0 0 0 2px " +
Neo.config.color_frame
);
Neo.addRule(
".NEO .buttonOff:active, .NEO .buttonOn",
"background-color",
darkBorder
);
Neo.addRule(
".NEO .buttonOff:active, .NEO .buttonOn",
"border-top",
"1px solid " + darkBorder
);
Neo.addRule(
".NEO .buttonOff:active, .NEO .buttonOn",
"border-left",
"1px solid " + darkBorder
);
Neo.addRule(
".NEO .buttonOff:active, .NEO .buttonOn",
"box-shadow",
"0 0 0 1px " +
Neo.config.color_iconselect +
", 0 0 0 2px " +
Neo.config.color_frame
);
Neo.addRule(".NEO #canvas", "border", "1px solid " + Neo.config.color_frame);
Neo.addRule(
".NEO #scrollH, .NEO #scrollV",
"background-color",
Neo.config.color_icon
);
Neo.addRule(
".NEO #scrollH, .NEO #scrollV",
"box-shadow",
"0 0 0 1px white" + ", 0 0 0 2px " + Neo.config.color_frame
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"background-color",
Neo.config.color_bar
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"box-shadow",
"0 0 0 1px " + Neo.config.color_icon
);
Neo.addRule(
".NEO #scrollH div:hover, .NEO #scrollV div:hover",
"box-shadow",
"0 0 0 1px " + Neo.config.color_iconselect
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"border-top",
"1px solid " + lightBar
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"border-left",
"1px solid " + lightBar
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"border-right",
"1px solid " + darkBar
);
Neo.addRule(
".NEO #scrollH div, .NEO #scrollV div",
"border-bottom",
"1px solid " + darkBar
);
Neo.addRule(
".NEO .toolTipOn",
"background-color",
Neo.multColor(Neo.config.tool_color_button, 0.7)
);
Neo.addRule(
".NEO .toolTipOff",
"background-color",
Neo.config.tool_color_button
);
Neo.addRule(
".NEO .toolTipFixed",
"background-color",
Neo.config.tool_color_button2
);
Neo.addRule(
".NEO .colorSlider, .NEO .sizeSlider",
"background-color",
Neo.config.tool_color_bar
);
Neo.addRule(
".NEO .reserveControl",
"background-color",
Neo.config.tool_color_bar
);
Neo.addRule(
".NEO .reserveControl",
"background-color",
Neo.config.tool_color_bar
);
Neo.addRule(
".NEO .layerControl",
"background-color",
Neo.config.tool_color_bar
);
Neo.addRule(
".NEO .colorTipOn, .NEO .colorTipOff",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .toolTipOn, .NEO .toolTipOff",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .toolTipFixed",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .colorSlider, .NEO .sizeSlider",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .reserveControl",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .layerControl",
"box-shadow",
"0 0 0 1px " + Neo.config.tool_color_frame
);
Neo.addRule(
".NEO .reserveControl .reserve",
"border",
"1px solid " + Neo.config.tool_color_frame
);
if (navigator.language.indexOf("ja") != 0) {
var labels = ["Fixed", "On", "Off"];
for (var i = 0; i < labels.length; i++) {
var selector = ".NEO .toolTip" + labels[i] + " .label";
Neo.addRule(selector, "letter-spacing", "0px !important");
}
}
Neo.setToolSide(Neo.toolSide);
};
Neo.addRule = function (selector, styleName, value, sheet) {
if (!sheet) sheet = Neo.styleSheet;
if (sheet.addRule) {
sheet.addRule(selector, styleName + ":" + value, sheet.rules.length);
} else if (sheet.insertRule) {
var rule = selector + "{" + styleName + ":" + value + "}";
var index = sheet.cssRules.length;
sheet.insertRule(rule, index);
}
};
Neo.readStyles = function () {
Neo.rules = {};
for (var i = 0; i < document.styleSheets.length; i++) {
Neo.readStyle(document.styleSheets[i]);
}
};
Neo.readStyle = function (sheet) {
try {
var rules = sheet.cssRules;
for (var i = 0; i < rules.length; i++) {
var rule = rules[i];
if (rule.styleSheet) {
Neo.readStyle(rule.styleSheet);
continue;
}
var selector = rule.selectorText;
if (selector) {
selector = selector.replace(/^(.NEO\s+)?\./, "");
var css = rule.cssText || rule.style.cssText;
var result = css.match(/color:\s*(.*)\s*;/);
if (result) {
var hex = Neo.colorNameToHex(result[1]);
if (hex) {
Neo.rules[selector] = hex;
}
}
}
}
} catch (e) {}
};
Neo.applyStyle = function (name, defaultColor) {
if (Neo.config[name] == undefined) {
Neo.config[name] = Neo.rules[name] || defaultColor;
}
};
Neo.getInheritColor = function (e) {
var result = "#000000";
while (e && e.style) {
if (e.style.color != "") {
result = e.style.color;
break;
}
if (e.attributes["text"]) {
result = e.attributes["text"].value;
break;
}
e = e.parentNode;
}
return result;
};
Neo.backgroundImage = function () {
var c1 = Neo.painter.getColor(Neo.config.color_bk) | 0xff000000;
var c2 = Neo.painter.getColor(Neo.config.color_bk2) | 0xff000000;
var bgCanvas = document.createElement("canvas");
bgCanvas.width = 16;
bgCanvas.height = 16;
var ctx = bgCanvas.getContext("2d");
var imageData = ctx.getImageData(0, 0, 16, 16);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var index = 0;
for (var y = 0; y < 16; y++) {
for (var x = 0; x < 16; x++) {
buf32[index++] = x == 14 || y == 14 ? c2 : c1;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
return bgCanvas.toDataURL("image/png");
};
Neo.multColor = function (c, scale) {
var r = Math.round(parseInt(c.substr(1, 2), 16) * scale);
var g = Math.round(parseInt(c.substr(3, 2), 16) * scale);
var b = Math.round(parseInt(c.substr(5, 2), 16) * scale);
r = ("0" + Math.min(Math.max(r, 0), 255).toString(16)).substr(-2);
g = ("0" + Math.min(Math.max(g, 0), 255).toString(16)).substr(-2);
b = ("0" + Math.min(Math.max(b, 0), 255).toString(16)).substr(-2);
return "#" + r + g + b;
};
Neo.colorNameToHex = function (name) {
var colors = {
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgrey: "#d3d3d3",
lightgreen: "#90ee90",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370d8",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#d87093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
rebeccapurple: "#663399",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32",
};
var rgb = name.toLowerCase().match(/rgb\((.*),(.*),(.*)\)/);
if (rgb) {
var r = ("0" + parseInt(rgb[1]).toString(16)).slice(-2);
var g = ("0" + parseInt(rgb[2]).toString(16)).slice(-2);
var b = ("0" + parseInt(rgb[3]).toString(16)).slice(-2);
return "#" + r + g + b;
}
if (typeof colors[name.toLowerCase()] != "undefined") {
return colors[name.toLowerCase()];
}
return false;
};
Neo.initComponents = function () {
var copyright = document.getElementById("copyright");
if (copyright) copyright.innerHTML += "v" + Neo.version;
// アプレットのborderの動作をエミュレート
if (navigator.userAgent.search("FireFox") > -1) {
var container = document.getElementById("container");
container.addEventListener(
"mousedown",
function (e) {
container.style.borderColor = Neo.config.inherit_color;
e.stopPropagation();
},
false
);
document.addEventListener(
"mousedown",
function (e) {
container.style.borderColor = "transparent";
},
false
);
}
// ドラッグしたまま画面外に移動した時
document.addEventListener(
"mouseup",
function (e) {
if (Neo.painter && !Neo.painter.isContainer(e.target)) {
Neo.painter.cancelTool(e.target);
}
},
false
);
// 投稿に失敗する可能性があるときは警告を表示する
Neo.showWarning();
if (Neo.styleSheet) {
Neo.addRule("*", "user-select", "none");
Neo.addRule("*", "-webkit-user-select", "none");
Neo.addRule("*", "-ms-user-select", "none");
}
};
Neo.initButtons = function () {
new Neo.Button().init("undo").onmouseup = function () {
new Neo.UndoCommand(Neo.painter).execute();
};
new Neo.Button().init("redo").onmouseup = function () {
new Neo.RedoCommand(Neo.painter).execute();
};
new Neo.Button().init("window").onmouseup = function () {
new Neo.WindowCommand(Neo.painter).execute();
};
new Neo.Button().init("copyright").onmouseup = function () {
new Neo.CopyrightCommand(Neo.painter).execute();
};
new Neo.Button().init("zoomPlus").onmouseup = function () {
new Neo.ZoomPlusCommand(Neo.painter).execute();
};
new Neo.Button().init("zoomMinus").onmouseup = function () {
new Neo.ZoomMinusCommand(Neo.painter).execute();
};
Neo.submitButton = new Neo.Button().init("submit");
Neo.submitButton.onmouseup = function () {
Neo.submitButton.disable(5000);
new Neo.SubmitCommand(Neo.painter).execute();
};
Neo.fillButton = new Neo.FillButton().init("fill");
Neo.rightButton = new Neo.RightButton().init("right");
if (Neo.isMobile()) {
Neo.rightButton.element.style.display = "block";
}
// toolTip
Neo.penTip = new Neo.PenTip().init("pen");
Neo.pen2Tip = new Neo.Pen2Tip().init("pen2");
Neo.effectTip = new Neo.EffectTip().init("effect");
Neo.effect2Tip = new Neo.Effect2Tip().init("effect2");
Neo.eraserTip = new Neo.EraserTip().init("eraser");
Neo.drawTip = new Neo.DrawTip().init("draw");
Neo.maskTip = new Neo.MaskTip().init("mask");
Neo.toolButtons = [
Neo.fillButton,
Neo.penTip,
Neo.pen2Tip,
Neo.effectTip,
Neo.effect2Tip,
Neo.drawTip,
Neo.eraserTip,
];
// colorTip
for (var i = 1; i <= 14; i++) {
new Neo.ColorTip().init("color" + i, { index: i });
}
// colorSlider
Neo.sliders[Neo.SLIDERTYPE_RED] = new Neo.ColorSlider().init("sliderRed", {
type: Neo.SLIDERTYPE_RED,
});
Neo.sliders[Neo.SLIDERTYPE_GREEN] = new Neo.ColorSlider().init(
"sliderGreen",
{ type: Neo.SLIDERTYPE_GREEN }
);
Neo.sliders[Neo.SLIDERTYPE_BLUE] = new Neo.ColorSlider().init("sliderBlue", {
type: Neo.SLIDERTYPE_BLUE,
});
Neo.sliders[Neo.SLIDERTYPE_ALPHA] = new Neo.ColorSlider().init(
"sliderAlpha",
{ type: Neo.SLIDERTYPE_ALPHA }
);
// sizeSlider
Neo.sliders[Neo.SLIDERTYPE_SIZE] = new Neo.SizeSlider().init("sliderSize", {
type: Neo.SLIDERTYPE_SIZE,
});
// reserveControl
for (var i = 1; i <= 3; i++) {
new Neo.ReserveControl().init("reserve" + i, { index: i });
}
new Neo.LayerControl().init("layerControl");
new Neo.ScrollBarButton().init("scrollH");
new Neo.ScrollBarButton().init("scrollV");
};
Neo.start = function (isApp) {
if (Neo.viewer) return;
Neo.initSkin();
Neo.initComponents();
Neo.initButtons();
Neo.isApp = isApp;
if (Neo.applet) {
var name = Neo.applet.attributes.name.value || "paintbbs";
Neo.applet.outerHTML = "";
document[name] = Neo;
Neo.resizeCanvas();
Neo.container.style.visibility = "visible";
if (Neo.isApp) {
var ipc = require("electron").ipcRenderer;
ipc.sendToHost("neo-status", "ok");
} else {
if (document.paintBBSCallback) {
document.paintBBSCallback("start");
}
}
}
};
Neo.isIE = function () {
var ms = false;
if (/MSIE 10/i.test(navigator.userAgent)) {
ms = true; // This is internet explorer 10
}
if (
/MSIE 9/i.test(navigator.userAgent) ||
/rv:11.0/i.test(navigator.userAgent)
) {
ms = true; // This is internet explorer 9 or 11
}
return ms;
};
Neo.isMobile = function () {
if (navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) return true;
if (navigator.maxTouchPoints && navigator.maxTouchPoints > 1) return true;
return false;
};
Neo.showWarning = function () {
var futaba = location.hostname.match(/2chan.net/i);
var samplebbs = location.hostname.match(/neo.websozai.jp/i);
var chrome = navigator.userAgent.match(/Chrome\/(\d+)/i);
if (chrome && chrome.length > 1) chrome = chrome[1];
var edge = navigator.userAgent.match(/Edge\/(\d+)/i);
if (edge && edge.length > 1) edge = edge[1];
var ms = Neo.isIE();
var str = "";
if (futaba || samplebbs) {
if (ms || (edge && edge < 15)) {
str = Neo.translate(
"このブラウザでは<br>投稿に失敗することがあります<br>"
);
}
}
// もし<PARAM NAME="neo_warning" VALUE="...">があれば表示する
if (Neo.config.neo_warning) {
str += Neo.config.neo_warning;
}
var warning = document.getElementById("neoWarning");
if (warning) {
warning.innerHTML = str;
setTimeout(function () {
warning.style.opacity = "0";
}, 15000);
}
};
/*
-----------------------------------------------------------------------
UIの更新
-----------------------------------------------------------------------
*/
Neo.updateUI = function () {
var current = Neo.painter.tool.getToolButton();
for (var i = 0; i < Neo.toolButtons.length; i++) {
var toolTip = Neo.toolButtons[i];
if (current) {
if (current == toolTip) {
toolTip.setSelected(true);
toolTip.update();
} else {
toolTip.setSelected(false);
}
}
}
if (Neo.drawTip) {
Neo.drawTip.update();
}
Neo.updateUIColor(true, false);
};
Neo.updateUIColor = function (updateSlider, updateColorTip) {
for (var i = 0; i < Neo.toolButtons.length; i++) {
var toolTip = Neo.toolButtons[i];
toolTip.update();
}
if (updateSlider) {
for (var i = 0; i < Neo.sliders.length; i++) {
var slider = Neo.sliders[i];
slider.update();
}
}
// パレットを変更するとき
if (updateColorTip) {
var colorTip = Neo.ColorTip.getCurrent();
if (colorTip) {
colorTip.setColor(Neo.painter.foregroundColor);
}
}
};
/*
-----------------------------------------------------------------------
リサイズ対応
-----------------------------------------------------------------------
*/
Neo.updateWindow = function () {
if (Neo.fullScreen) {
document.getElementById("windowView").style.display = "block";
document.getElementById("windowView").appendChild(Neo.container);
} else {
document.getElementById("windowView").style.display = "none";
document.getElementById("pageView").appendChild(Neo.container);
}
Neo.resizeCanvas();
};
Neo.resizeCanvas = function () {
var appletWidth = Neo.container.clientWidth;
var appletHeight = Neo.container.clientHeight;
var canvasWidth = Neo.painter.canvasWidth;
var canvasHeight = Neo.painter.canvasHeight;
var width0 = canvasWidth * Neo.painter.zoom;
var height0 = canvasHeight * Neo.painter.zoom;
var width = width0 < appletWidth - 100 ? width0 : appletWidth - 100;
var height = height0 < appletHeight - 120 ? height0 : appletHeight - 120;
//width, heightは偶数でないと誤差が出るため
width = Math.floor(width / 2) * 2;
height = Math.floor(height / 2) * 2;
if (Neo.viewer) {
width = canvasWidth;
height = canvasHeight;
}
Neo.painter.destWidth = width;
Neo.painter.destHeight = height;
Neo.painter.destCanvas.width = width;
Neo.painter.destCanvas.height = height;
Neo.painter.destCanvasCtx = Neo.painter.destCanvas.getContext("2d");
Neo.painter.destCanvasCtx.imageSmoothingEnabled = false;
//Neo.painter.destCanvasCtx.mozImageSmoothingEnabled = false;
Neo.canvas.style.width = width + "px";
Neo.canvas.style.height = height + "px";
if (Neo.toolsWrapper) {
var top = (Neo.container.clientHeight - toolsWrapper.clientHeight) / 2;
Neo.toolsWrapper.style.top = (top > 0 ? top : 0) + "px";
if (top < 0) {
var s = Neo.container.clientHeight / toolsWrapper.clientHeight;
Neo.toolsWrapper.style.transform =
"translate(0, " + top + "px) scale(1," + s + ")";
} else {
Neo.toolsWrapper.style.transform = "";
}
}
Neo.painter.setZoom(Neo.painter.zoom);
Neo.painter.updateDestCanvas(0, 0, canvasWidth, canvasHeight);
};
/*
-----------------------------------------------------------------------
投稿
-----------------------------------------------------------------------
*/
Neo.clone = function (src) {
var dst = {};
for (var k in src) {
dst[k] = src[k];
}
return dst;
};
Neo.getSizeString = function (len) {
var result = String(len);
while (result.length < 8) {
result = "0" + result;
}
return result;
};
Neo.openURL = function (url) {
if (Neo.isApp) {
require("electron").shell.openExternal(url);
} else {
window.open(url, "_blank");
}
};
Neo.getAbsoluteURL = function (board, url) {
if (url.indexOf('://') > 0 || url.indexOf('//') === 0) {
return url;
} else {
return board + url;
}
}
Neo.submit = function (board, blob, thumbnail, thumbnail2) {
var url = Neo.getAbsoluteURL(board, Neo.config.url_save);
var headerString = Neo.str_header || "";
if (document.paintBBSCallback) {
var result = document.paintBBSCallback("check");
if (result == 0 || result == "false") {
return;
}
result = document.paintBBSCallback("header");
if (result && typeof result == "string") {
headerString = result;
}
}
if (!headerString) headerString = Neo.config.send_header || "";
var imageType = Neo.config.send_header_image_type;
if (imageType && imageType == "true") {
headerString = "image_type=png&" + headerString;
}
var count = Neo.painter.securityCount;
var timer = new Date() - Neo.painter.securityTimer;
if (Neo.config.send_header_count == "true") {
headerString = "count=" + count + "&" + headerString;
}
if (Neo.config.send_header_timer == "true") {
headerString = "timer=" + timer + "&" + headerString;
}
console.log("header: " + headerString);
if (Neo.config.neo_emulate_security_error == "true") {
var securityError = false;
if (Neo.config.security_click) {
if (count - parseInt(Neo.config.security_click || 0) < 0) {
securityError = true;
}
}
if (Neo.config.security_timer) {
if (timer - parseInt(Neo.config.security_timer || 0) * 1000 < 0) {
securityError = true;
}
}
if (securityError && Neo.config.security_url) {
if (Neo.config.security_post == "true") {
url = Neo.config.security_url;
} else {
location.href = Neo.config.security_url;
return;
}
}
}
// console.log("submit url=" + url + " header=" + headerString);
var header = new Blob([headerString]);
var headerLength = this.getSizeString(header.size);
var imgLength = this.getSizeString(blob.size);
var array = [
"P", // PaintBBS
headerLength,
header,
imgLength,
"\r\n",
blob,
];
if (thumbnail) {
var thumbnailLength = this.getSizeString(thumbnail.size);
array.push(thumbnailLength, thumbnail);
}
if (thumbnail2) {
var thumbnail2Length = this.getSizeString(thumbnail2.size);
array.push(thumbnail2Length, thumbnail2);
}
var futaba = location.hostname.match(/2chan.net/i);
var subtype = futaba ? "octet-binary" : "octet-stream"; // 念のため
var body = new Blob(array, { type: "application/" + subtype });
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.onload = function (e) {
console.log(request.response, "status=", request.status);
var errorMessage = null;
if (request.status / 100 != 2) {
errorMessage = request.response.replace(/<[^>]*>?/gm, '');
} else if (request.response.match(/^error\n/m)) {
errorMessage = request.response.replace(/^error\n/m, '');
} else {
Neo.uploaded = true;
}
var exitURL = Neo.getAbsoluteURL(board, Neo.config.url_exit);
var responseURL = request.response.replace(/&/g, "&");
// ふたばではresponseの文字列をそのままURLとして解釈する
if (responseURL.match(/painttmp=/)) {
exitURL = responseURL;
}
// responseが "URL:〜" の形だった場合はそのURLへ
if (responseURL.match(/^URL:/)) {
exitURL = responseURL.replace(/^URL:/, "");
}
if (Neo.uploaded) {
location.href = exitURL;
} else {
alert(errorMessage);
Neo.submitButton.enable();
}
};
request.onerror = function (e) {
console.log("error");
Neo.submitButton.enable();
};
request.onabort = function (e) {
console.log("abort");
Neo.submitButton.enable();
};
request.ontimeout = function (e) {
console.log("timeout");
Neo.submitButton.enable();
};
request.send(body);
};
/*
-----------------------------------------------------------------------
LiveConnect
-----------------------------------------------------------------------
*/
Neo.getColors = function () {
console.log("getColors");
console.log("defaultColors==", Neo.config.colors.join("\n"));
var array = [];
for (var i = 0; i < 14; i++) {
array.push(Neo.colorTips[i].color);
}
return array.join("\n");
// return Neo.config.colors.join('\n');
};
Neo.setColors = function (colors) {
console.log("setColors");
var array = colors.split("\n");
for (var i = 0; i < 14; i++) {
var color = array[i];
Neo.config.colors[i] = color;
Neo.colorTips[i].setColor(color);
}
};
Neo.pExit = function () {
new Neo.SubmitCommand(Neo.painter).execute();
};
Neo.str_header = "";
/*
-----------------------------------------------------------------------
DOMツリーの作成
-----------------------------------------------------------------------
*/
Neo.createContainer = function (applet) {
var neo = document.createElement("div");
neo.className = "NEO";
neo.id = "NEO";
var html =
'<div id="pageView" style="margin:auto; width:450px; height:470px;">' +
'<div id="container" style="visibility:hidden;" class="o">' +
'<div id="center" class="o">' +
'<div id="painterContainer" class="o">' +
'<div id="painterWrapper" class="o">' +
'<div id="upper" class="o">' +
'<div id="redo">[やり直し]</div> ' +
'<div id="undo">[元に戻す]</div> ' +
'<div id="fill">[塗り潰し]</div> ' +
'<div id="right" style="display:none;">[右]</div> ' +
"</div>" +
'<div id="painter">' +
'<div id="canvas">' +
'<div id="scrollH"></div>' +
'<div id="scrollV"></div>' +
'<div id="zoomPlusWrapper">' +
'<div id="zoomPlus">+</div>' +
"</div>" +
'<div id="zoomMinusWrapper">' +
'<div id="zoomMinus">-</div>' +
"</div>" +
'<div id="neoWarning"></div>' +
"</div>" +
"</div>" +
'<div id="lower" class="o">' +
"</div>" +
"</div>" +
'<div id="toolsWrapper">' +
'<div id="tools">' +
'<div id="toolSet">' +
'<div id="pen"></div>' +
'<div id="pen2"></div>' +
'<div id="effect"></div>' +
'<div id="effect2"></div>' +
'<div id="eraser"></div>' +
'<div id="draw"></div>' +
'<div id="mask"></div>' +
'<div class="colorTips">' +
'<div id="color2"></div><div id="color1"></div><br>' +
'<div id="color4"></div><div id="color3"></div><br>' +
'<div id="color6"></div><div id="color5"></div><br>' +
'<div id="color8"></div><div id="color7"></div><br>' +
'<div id="color10"></div><div id="color9"></div><br>' +
'<div id="color12"></div><div id="color11"></div><br>' +
'<div id="color14"></div><div id="color13"></div>' +
"</div>" +
'<div id="sliderRed"></div>' +
'<div id="sliderGreen"></div>' +
'<div id="sliderBlue"></div>' +
'<div id="sliderAlpha"></div>' +
'<div id="sliderSize"></div>' +
'<div class="reserveControl" style="margin-top:4px;">' +
'<div id="reserve1"></div>' +
'<div id="reserve2"></div>' +
'<div id="reserve3"></div>' +
"</div>" +
'<div id="layerControl" style="margin-top:6px;"></div>' +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
'<div id="headerButtons">' +
'<div id="window">[窓]</div>' +
"</div>" +
'<div id="footerButtons">' +
'<div id="submit">[投稿]</div> ' +
'<div id="copyright">[(C)しぃちゃん PaintBBS NEO]</div> ' +
"</div>" +
"</div>" +
"</div>" +
'<div id="windowView" style="display: none;">' +
"</div>";
neo.innerHTML = html.replace(/\[(.*?)\]/g, function (match, str) {
return Neo.translate(str);
});
var parent = applet.parentNode;
parent.appendChild(neo);
parent.insertBefore(neo, applet);
// applet.style.display = "none";
// NEOを組み込んだURLをアプリ版で開くとDOMツリーが2重にできて格好悪いので消しておく
setTimeout(function () {
var tmp = document.getElementsByClassName("NEO");
if (tmp.length > 1) {
for (var i = 1; i < tmp.length; i++) {
tmp[i].style.display = "none";
}
}
}, 0);
};
Neo.tintImage = function (ctx, c) {
c = Neo.painter.getColor(c) & 0xffffff;
var imageData = ctx.getImageData(0, 0, 46, 18);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
for (var i = 0; i < buf32.length; i++) {
var a = buf32[i] & 0xff000000;
if (a) {
buf32[i] = (buf32[i] & a) | c;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
};
Neo.setToolSide = function (side) {
if (side === "left") side = true;
if (side === "right") side = false;
Neo.toolSide = !!side;
if (!Neo.toolSide) {
Neo.addRule(".NEO #toolsWrapper", "right", "-3px");
Neo.addRule(".NEO #toolsWrapper", "left", "auto");
Neo.addRule(".NEO #painterWrapper", "padding", "0 55px 0 0 !important");
Neo.addRule(".NEO #upper", "padding-right", "75px !important");
} else {
Neo.addRule(".NEO #toolsWrapper", "right", "auto");
Neo.addRule(".NEO #toolsWrapper", "left", "-1px");
Neo.addRule(".NEO #painterWrapper", "padding", "0 0 0 55px !important");
Neo.addRule(".NEO #upper", "padding-right", "20px !important");
}
};
"use strict";
Neo.dictionary = {
ja: {},
en: {
やり直し: "Redo",
元に戻す: "Undo",
塗り潰し: "Paint",
窓: "F ",
投稿: "Send",
"(C)しぃちゃん PaintBBS NEO": "(C)shi-chan PaintBBS NEO",
鉛筆: "Solid",
水彩: "WaterC",
テキスト: "Text",
トーン: "Tone",
ぼかし: "ShadeOff",
覆い焼き: "HLight",
焼き込み: "Dark",
消しペン: "White",
消し四角: "WhiteRect",
全消し: "Clear",
四角: "Rect",
線四角: "LineRect",
楕円: "Oval",
線楕円: "LineOval",
コピー: "Copy",
レイヤ結合: "lay-unif",
角取り: "Antialias",
左右反転: "reverseL",
上下反転: "reverseU",
傾け: "lie",
通常: "Normal",
マスク: "Mask",
逆マスク: "ReMask",
加算: "And",
逆加算: "Div",
手書き: "FreeLine",
直線: "Straight",
BZ曲線: "Bezie",
"ページビュー?": "Page view?",
"ウィンドウビュー?": "Window view?",
"描きかけの画像があります。復元しますか?": "Restore session?",
右: "Right Click",
"PaintBBS NEOは、お絵描きしぃ掲示板 PaintBBS (©2000-2004 しぃちゃん) をhtml5化するプロジェクトです。\n\nPaintBBS NEOのホームページを表示しますか?":
"PaintBBS NEO is an HTML5 port of Oekaki Shi-BBS PaintBBS (©2000-2004 shi-chan). Show the project page?",
"このブラウザでは<br>投稿に失敗することがあります<br>":
"This browser may fail to send your picture.<br>",
"画像を投稿しますか?<br>投稿に成功後、編集を終了します。":
"Is the picture contributed?<br>if contribution completed, you jump to the comment page.",
"描きかけの画像があります。動画の読み込みを中止して復元しますか?":
"Discard animation data and restore session?",
最: "Mx",
早: "H",
既: "M",
鈍: "L",
},
enx: {
やり直し: "Redo",
元に戻す: "Undo",
塗り潰し: "Fill",
窓: "Float",
投稿: "Send",
"(C)しぃちゃん PaintBBS NEO": "©shi-cyan PaintBBS NEO",
鉛筆: "Solid",
水彩: "WaterCo",
テキスト: "Text",
トーン: "Halftone",
ぼかし: "Blur",
覆い焼き: "Light",
焼き込み: "Dark",
消しペン: "White",
消し四角: "WhiteRe",
全消し: "Clear",
四角: "Rect",
線四角: "LineRect",
楕円: "Oval",
線楕円: "LineOval",
コピー: "Copy",
レイヤ結合: "layerUnit",
角取り: "antiAlias",
左右反転: "flipHorita",
上下反転: "flipVertic",
傾け: "rotate",
通常: "Normal",
マスク: "Mask",
逆マスク: "ReMask",
加算: "And",
逆加算: "Divide",
手書き: "Freehan",
直線: "Line",
BZ曲線: "Bezier",
Layer0: "LayerBG",
Layer1: "LayerFG",
"ページビュー?": "Page view?",
"ウィンドウビュー?": "Window view?",
"描きかけの画像があります。復元しますか?": "Restore session?",
右: "Right Click",
"PaintBBS NEOは、お絵描きしぃ掲示板 PaintBBS (©2000-2004 しぃちゃん) をhtml5化するプロジェクトです。\n\nPaintBBS NEOのホームページを表示しますか?":
"PaintBBS NEO is an HTML5 port of Oekaki Shi-BBS PaintBBS (©2000-2004 shi-chan). Show the project page?",
"このブラウザでは<br>投稿に失敗することがあります<br>":
"This browser may fail to send your picture.<br>",
"画像を投稿しますか?<br>投稿に成功後、編集を終了します。":
"Send this picture and end session?",
"描きかけの画像があります。動画の読み込みを中止して復元しますか?":
"Discard animation data and restore session?",
最: "Mx",
早: "H",
既: "M",
鈍: "L",
},
es: {
やり直し: "Rehacer",
元に戻す: "Deshacer",
塗り潰し: "Llenar",
窓: "Ventana",
投稿: "Enviar",
"(C)しぃちゃん PaintBBS NEO": "©shi-cyan PaintBBS NEO",
鉛筆: "Lápiz",
水彩: "Acuarela",
テキスト: "Texto",
トーン: "Tono",
ぼかし: "Gradación",
覆い焼き: "Sobreexp.",
焼き込み: "Quemar",
消しペン: "Goma",
消し四角: "GomaRect",
全消し: "Borrar",
四角: "Rect",
線四角: "LíneaRect",
楕円: "Óvalo",
線楕円: "LíneaÓvalo",
コピー: "Copiar",
レイヤ結合: "UnirCapa",
角取り: "Antialias",
左右反転: "Inv.Izq/Der",
上下反転: "Inv.Arr/Aba",
傾け: "Inclinar",
通常: "Normal",
マスク: "Masc.",
逆マスク: "Masc.Inv",
加算: "Adición",
逆加算: "Subtrac",
手書き: "Libre",
直線: "Línea",
BZ曲線: "Curva",
Layer0: "Capa0",
Layer1: "Capa1",
"ページビュー?": "¿Vista de página?",
"ウィンドウビュー?": "¿Vista de ventana?",
"描きかけの画像があります。復元しますか?": "¿Restaurar sesión anterior?",
右: "Clic derecho",
"PaintBBS NEOは、お絵描きしぃ掲示板 PaintBBS (©2000-2004 しぃちゃん) をhtml5化するプロジェクトです。\n\nPaintBBS NEOのホームページを表示しますか?":
"PaintBBS NEO es una versión para HTML5 de Oekaki Shi-BBS PaintBBS (© 2000-2004 shi-chan). ¿Mostrar la página del proyecto?",
"このブラウザでは<br>投稿に失敗することがあります<br>":
"Este navegador podría no enviar su imagen.<br>",
"画像を投稿しますか?<br>投稿に成功後、編集を終了します。":
"¿Enviar esta imagen y finalizar sesión?",
"描きかけの画像があります。動画の読み込みを中止して復元しますか?":
"¿Desechar datos de animación y restaurar sesión?",
最: "Mx",
早: "H",
既: "M",
鈍: "L",
},
};
Neo.translate = (function () {
var language =
(window.navigator.languages && window.navigator.languages[0]) ||
window.navigator.language ||
window.navigator.userLanguage ||
window.navigator.browserLanguage;
var lang = "en";
for (var key in Neo.dictionary) {
if (language.indexOf(key) == 0) {
lang = key;
break;
}
}
return function (string) {
if (Neo.config.neo_alt_translation) {
if (lang == "en") lang = "enx";
} else {
if (lang != "ja") lang = "en";
}
return Neo.dictionary[lang][string] || string;
};
})();
"use strict";
Neo.Painter = function () {
this._undoMgr = new Neo.UndoManager(50);
this._actionMgr = new Neo.ActionManager();
};
Neo.Painter.prototype.container;
Neo.Painter.prototype._undoMgr;
Neo.Painter.prototype._actionMgr;
Neo.Painter.prototype.tool;
Neo.Painter.prototype.inputText;
//Canvas Info
Neo.Painter.prototype.canvasWidth;
Neo.Painter.prototype.canvasHeight;
Neo.Painter.prototype.canvas = [];
Neo.Painter.prototype.canvasCtx = [];
Neo.Painter.prototype.visible = [];
Neo.Painter.prototype.current = 0;
//Temp Canvas Info
Neo.Painter.prototype.tempCanvas;
Neo.Painter.prototype.tempCanvasCtx;
Neo.Painter.prototype.tempX = 0;
Neo.Painter.prototype.tempY = 0;
//Destination Canvas for display
Neo.Painter.prototype.destCanvas;
Neo.Painter.prototype.destCanvasCtx;
Neo.Painter.prototype.backgroundColor = "#ffffff";
Neo.Painter.prototype.foregroundColor = "#000000";
Neo.Painter.prototype.lineWidth = 1;
Neo.Painter.prototype.alpha = 1;
Neo.Painter.prototype.zoom = 1;
Neo.Painter.prototype.zoomX = 0;
Neo.Painter.prototype.zoomY = 0;
Neo.Painter.prototype.isMouseDown;
Neo.Painter.prototype.isMouseDownRight;
Neo.Painter.prototype.prevMouseX;
Neo.Painter.prototype.prevMouseY;
Neo.Painter.prototype.mouseX;
Neo.Painter.prototype.mouseY;
//Neo.Painter.prototype.slowX = 0;
//Neo.Painter.prototype.slowY = 0;
//Neo.Painter.prototype.stab = null;
Neo.Painter.prototype.isShiftDown = false;
Neo.Painter.prototype.isCtrlDown = false;
Neo.Painter.prototype.isAltDown = false;
//Neo.Painter.prototype.touchModifier = null;
Neo.Painter.prototype.virtualRight = false;
Neo.Painter.prototype.virtualShift = false;
//Neo.Painter.prototype.onUpdateCanvas;
Neo.Painter.prototype._roundData = [];
Neo.Painter.prototype._toneData = [];
Neo.Painter.prototype.toolStack = [];
Neo.Painter.prototype.maskType = 0;
Neo.Painter.prototype.drawType = 0;
Neo.Painter.prototype.maskColor = "#000000";
Neo.Painter.prototype._currentColor = [];
Neo.Painter.prototype._currentMask = [];
Neo.Painter.prototype.aerr;
Neo.Painter.prototype.dirty = false;
Neo.Painter.prototype.busy = false;
Neo.Painter.prototype.busySkipped = false;
Neo.Painter.LINETYPE_NONE = 0;
Neo.Painter.LINETYPE_PEN = 1;
Neo.Painter.LINETYPE_ERASER = 2;
Neo.Painter.LINETYPE_BRUSH = 3;
Neo.Painter.LINETYPE_TONE = 4;
Neo.Painter.LINETYPE_DODGE = 5;
Neo.Painter.LINETYPE_BURN = 6;
Neo.Painter.LINETYPE_BLUR = 7;
Neo.Painter.MASKTYPE_NONE = 0;
Neo.Painter.MASKTYPE_NORMAL = 1;
Neo.Painter.MASKTYPE_REVERSE = 2;
Neo.Painter.MASKTYPE_ADD = 3;
Neo.Painter.MASKTYPE_SUB = 4;
Neo.Painter.DRAWTYPE_FREEHAND = 0;
Neo.Painter.DRAWTYPE_LINE = 1;
Neo.Painter.DRAWTYPE_BEZIER = 2;
Neo.Painter.ALPHATYPE_NONE = 0;
Neo.Painter.ALPHATYPE_PEN = 1;
Neo.Painter.ALPHATYPE_FILL = 2;
Neo.Painter.ALPHATYPE_BRUSH = 3;
Neo.Painter.TOOLTYPE_NONE = 0;
Neo.Painter.TOOLTYPE_PEN = 1;
Neo.Painter.TOOLTYPE_ERASER = 2;
Neo.Painter.TOOLTYPE_HAND = 3;
Neo.Painter.TOOLTYPE_SLIDER = 4;
Neo.Painter.TOOLTYPE_FILL = 5;
Neo.Painter.TOOLTYPE_MASK = 6;
Neo.Painter.TOOLTYPE_ERASEALL = 7;
Neo.Painter.TOOLTYPE_ERASERECT = 8;
Neo.Painter.TOOLTYPE_COPY = 9;
Neo.Painter.TOOLTYPE_PASTE = 10;
Neo.Painter.TOOLTYPE_MERGE = 11;
Neo.Painter.TOOLTYPE_FLIP_H = 12;
Neo.Painter.TOOLTYPE_FLIP_V = 13;
Neo.Painter.TOOLTYPE_BRUSH = 14;
Neo.Painter.TOOLTYPE_TEXT = 15;
Neo.Painter.TOOLTYPE_TONE = 16;
Neo.Painter.TOOLTYPE_BLUR = 17;
Neo.Painter.TOOLTYPE_DODGE = 18;
Neo.Painter.TOOLTYPE_BURN = 19;
Neo.Painter.TOOLTYPE_RECT = 20;
Neo.Painter.TOOLTYPE_RECTFILL = 21;
Neo.Painter.TOOLTYPE_ELLIPSE = 22;
Neo.Painter.TOOLTYPE_ELLIPSEFILL = 23;
Neo.Painter.TOOLTYPE_BLURRECT = 24;
Neo.Painter.TOOLTYPE_TURN = 25;
Neo.Painter.prototype.build = function (div, width, height) {
this.container = div;
this._initCanvas(div, width, height);
this._initRoundData();
this._initToneData();
this._initInputText();
this.setTool(new Neo.PenTool());
};
Neo.Painter.prototype.setTool = function (tool) {
if (this.tool && this.tool.saveStates) this.tool.saveStates();
if (this.tool && this.tool.kill) {
this.tool.kill();
}
this.tool = tool;
tool.init();
if (this.tool && this.tool.loadStates) this.tool.loadStates();
};
Neo.Painter.prototype.pushTool = function (tool) {
this.toolStack.push(this.tool);
this.tool = tool;
tool.init();
};
Neo.Painter.prototype.popTool = function () {
var tool = this.tool;
if (tool && tool.kill) {
tool.kill();
}
this.tool = this.toolStack.pop();
};
Neo.Painter.prototype.getCurrentTool = function () {
if (this.tool) {
var tool = this.tool;
if (tool && tool.type == Neo.Painter.TOOLTYPE_SLIDER) {
var stack = this.toolStack;
if (stack.length > 0) {
tool = stack[stack.length - 1];
}
}
return tool;
}
return null;
};
Neo.Painter.prototype.setToolByType = function (toolType) {
switch (parseInt(toolType)) {
case Neo.Painter.TOOLTYPE_PEN:
this.setTool(new Neo.PenTool());
break;
case Neo.Painter.TOOLTYPE_ERASER:
this.setTool(new Neo.EraserTool());
break;
case Neo.Painter.TOOLTYPE_HAND:
this.setTool(new Neo.HandTool());
break;
case Neo.Painter.TOOLTYPE_FILL:
this.setTool(new Neo.FillTool());
break;
case Neo.Painter.TOOLTYPE_ERASEALL:
this.setTool(new Neo.EraseAllTool());
break;
case Neo.Painter.TOOLTYPE_ERASERECT:
this.setTool(new Neo.EraseRectTool());
break;
case Neo.Painter.TOOLTYPE_COPY:
this.setTool(new Neo.CopyTool());
break;
case Neo.Painter.TOOLTYPE_PASTE:
this.setTool(new Neo.PasteTool());
break;
case Neo.Painter.TOOLTYPE_MERGE:
this.setTool(new Neo.MergeTool());
break;
case Neo.Painter.TOOLTYPE_FLIP_H:
this.setTool(new Neo.FlipHTool());
break;
case Neo.Painter.TOOLTYPE_FLIP_V:
this.setTool(new Neo.FlipVTool());
break;
case Neo.Painter.TOOLTYPE_BRUSH:
this.setTool(new Neo.BrushTool());
break;
case Neo.Painter.TOOLTYPE_TEXT:
this.setTool(new Neo.TextTool());
break;
case Neo.Painter.TOOLTYPE_TONE:
this.setTool(new Neo.ToneTool());
break;
case Neo.Painter.TOOLTYPE_BLUR:
this.setTool(new Neo.BlurTool());
break;
case Neo.Painter.TOOLTYPE_DODGE:
this.setTool(new Neo.DodgeTool());
break;
case Neo.Painter.TOOLTYPE_BURN:
this.setTool(new Neo.BurnTool());
break;
case Neo.Painter.TOOLTYPE_RECT:
this.setTool(new Neo.RectTool());
break;
case Neo.Painter.TOOLTYPE_RECTFILL:
this.setTool(new Neo.RectFillTool());
break;
case Neo.Painter.TOOLTYPE_ELLIPSE:
this.setTool(new Neo.EllipseTool());
break;
case Neo.Painter.TOOLTYPE_ELLIPSEFILL:
this.setTool(new Neo.EllipseFillTool());
break;
case Neo.Painter.TOOLTYPE_BLURRECT:
this.setTool(new Neo.BlurRectTool());
break;
case Neo.Painter.TOOLTYPE_TURN:
this.setTool(new Neo.TurnTool());
break;
default:
console.log("unknown toolType " + toolType);
break;
}
};
Neo.Painter.prototype._initCanvas = function (div, width, height) {
width = parseInt(width);
height = parseInt(height);
var destWidth = parseInt(div.clientWidth);
var destHeight = parseInt(div.clientHeight);
this.destWidth = width;
this.destHeight = height;
this.canvasWidth = width;
this.canvasHeight = height;
this.zoomX = width * 0.5;
this.zoomY = height * 0.5;
this.securityTimer = new Date() - 0;
this.securityCount = 0;
for (var i = 0; i < 2; i++) {
this.canvas[i] = document.createElement("canvas");
this.canvas[i].width = width;
this.canvas[i].height = height;
this.canvasCtx[i] = this.canvas[i].getContext("2d");
this.canvas[i].style.imageRendering = "pixelated";
this.canvasCtx[i].imageSmoothingEnabled = false;
this.canvasCtx[i].mozImageSmoothingEnabled = false;
this.visible[i] = true;
}
this.tempCanvas = document.createElement("canvas");
this.tempCanvas.width = width;
this.tempCanvas.height = height;
this.tempCanvasCtx = this.tempCanvas.getContext("2d");
this.tempCanvas.style.position = "absolute";
this.tempCanvas.enabled = false;
var array = this.container.getElementsByTagName("canvas");
if (array.length > 0) {
this.destCanvas = array[0];
} else {
this.destCanvas = document.createElement("canvas");
this.container.appendChild(this.destCanvas);
}
this.destCanvasCtx = this.destCanvas.getContext("2d");
this.destCanvas.width = destWidth;
this.destCanvas.height = destHeight;
this.destCanvas.style.imageRendering = "pixelated";
this.destCanvasCtx.imageSmoothingEnabled = false;
this.destCanvasCtx.mozImageSmoothingEnabled = false;
var ref = this;
if (!Neo.viewer) {
var container = document.getElementById("container");
container.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
container.onmousemove = function (e) {
ref._mouseMoveHandler(e);
};
container.onmouseup = function (e) {
ref._mouseUpHandler(e);
};
container.onmouseover = function (e) {
ref._rollOverHandler(e);
};
container.onmouseout = function (e) {
ref._rollOutHandler(e);
};
container.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
},
false
);
container.addEventListener(
"touchmove",
function (e) {
ref._mouseMoveHandler(e);
},
false
);
container.addEventListener(
"touchend",
function (e) {
ref._mouseUpHandler(e);
},
false
);
document.onkeydown = function (e) {
ref._keyDownHandler(e);
};
document.onkeyup = function (e) {
ref._keyUpHandler(e);
};
}
if (Neo.config.neo_confirm_unload == "true") {
window.onbeforeunload = function () {
if (!Neo.uploaded && Neo.painter.isDirty()) {
return false;
}
};
}
this.updateDestCanvas(0, 0, this.canvasWidth, this.canvasHeight);
};
Neo.Painter.prototype._initRoundData = function () {
for (var r = 1; r <= 30; r++) {
this._roundData[r] = new Uint8Array(r * r);
var mask = this._roundData[r];
var d = Math.floor(r / 2.0);
var index = 0;
for (var x = 0; x < r; x++) {
for (var y = 0; y < r; y++) {
var xx = x + 0.5 - r / 2.0;
var yy = y + 0.5 - r / 2.0;
mask[index++] = xx * xx + yy * yy <= (r * r) / 4 ? 1 : 0;
}
}
}
this._roundData[3][0] = 0;
this._roundData[3][2] = 0;
this._roundData[3][6] = 0;
this._roundData[3][8] = 0;
this._roundData[5][1] = 0;
this._roundData[5][3] = 0;
this._roundData[5][5] = 0;
this._roundData[5][9] = 0;
this._roundData[5][15] = 0;
this._roundData[5][19] = 0;
this._roundData[5][21] = 0;
this._roundData[5][23] = 0;
};
Neo.Painter.prototype._initToneData = function () {
var pattern = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
for (var i = 0; i < 16; i++) {
this._toneData[i] = new Uint8Array(16);
for (var j = 0; j < 16; j++) {
this._toneData[i][j] = i >= pattern[j] ? 1 : 0;
}
}
};
Neo.Painter.prototype.getToneData = function (alpha) {
var alphaTable = [
23,
47,
69,
92,
114,
114,
114,
138,
161,
184,
184,
207,
230,
230,
253,
];
for (var i = 0; i < alphaTable.length; i++) {
if (alpha < alphaTable[i]) {
return this._toneData[i];
}
}
return this._toneData[i];
};
Neo.Painter.prototype._initInputText = function () {
var text = document.getElementById("inputtext");
if (!text) {
text = document.createElement("div");
}
text.id = "inputext";
text.setAttribute("contentEditable", true);
text.spellcheck = false;
text.className = "inputText";
text.innerHTML = "";
text.style.display = "none";
// text.style.userSelect = "none";
Neo.painter.container.appendChild(text);
this.inputText = text;
this.updateInputText();
};
Neo.Painter.prototype.hideInputText = function () {
var text = this.inputText;
text.blur();
text.style.display = "none";
};
Neo.Painter.prototype.updateInputText = function () {
var text = this.inputText;
var d = this.lineWidth;
var fontSize = Math.round((d * 55) / 28 + 7);
var height = Math.round((d * 68) / 28 + 12);
text.style.fontSize = fontSize + "px";
text.style.lineHeight = fontSize + "px";
text.style.height = fontSize + "px";
text.style.marginTop = -fontSize + "px";
};
/*
-----------------------------------------------------------------------
Mouse Event Handling
-----------------------------------------------------------------------
*/
Neo.Painter.prototype._keyDownHandler = function (e) {
this.isShiftDown = e.shiftKey;
this.isCtrlDown = e.ctrlKey;
this.isAltDown = e.altKey;
if (e.keyCode == 32) this.isSpaceDown = true;
if (!this.isShiftDown && this.isCtrlDown) {
if (!this.isAltDown) {
if (e.keyCode == 90 || e.keyCode == 85) this.undo(); //Ctrl+Z,Ctrl.U
if (e.keyCode == 89) this.redo(); //Ctrl+Y
} else {
if (e.keyCode == 90) this.redo(); //Ctrl+Alt+Z
}
}
if (!this.isShiftDown && !this.isCtrlDown && !this.isAltDown) {
if (e.keyCode == 107) new Neo.ZoomPlusCommand(this).execute(); // +
if (e.keyCode == 109) new Neo.ZoomMinusCommand(this).execute(); // -
}
if (this.tool.keyDownHandler) {
this.tool.keyDownHandler(e);
}
//スペース・Shift+スペースででスクロールしないように
// if (document.activeElement != this.inputText) e.preventDefault();
// console.log(document.activeElement.tagName)
if (
document.activeElement != this.inputText &&
!(document.activeElement.tagName == "INPUT")
) {
e.preventDefault();
}
};
Neo.Painter.prototype._keyUpHandler = function (e) {
this.isShiftDown = e.shiftKey;
this.isCtrlDown = e.ctrlKey;
this.isAltDown = e.altKey;
if (e.keyCode == 32) this.isSpaceDown = false;
if (this.tool.keyUpHandler) {
this.tool.keyUpHandler(oe);
}
};
Neo.Painter.prototype._rollOverHandler = function (e) {
if (this.tool.rollOverHandler) {
this.tool.rollOverHandler(this);
}
};
Neo.Painter.prototype._rollOutHandler = function (e) {
if (this.tool.rollOutHandler) {
this.tool.rollOutHandler(this);
}
};
Neo.Painter.prototype._mouseDownHandler = function (e) {
if (this.busy) {
// loadAnimation実行中は何もしない
if (e.target == Neo.painter.destCanvas) {
this.busySkipped = true;
}
return;
}
if (e.target == Neo.painter.destCanvas) {
//よくわからないがChromeでドラッグの時カレットが出るのを防ぐ
//http://stackoverflow.com/questions/2745028/chrome-sets-cursor-to-text-while-dragging-why
e.preventDefault();
}
if (e.type == "touchstart" && e.touches.length > 1) return;
if (e.button == 2 || this.virtualRight) {
this.isMouseDownRight = true;
} else {
if (!e.shiftKey && e.ctrlKey && e.altKey) {
this.isMouseDown = true;
} else {
if (e.ctrlKey || e.altKey) {
this.isMouseDownRight = true;
} else {
this.isMouseDown = true;
}
}
}
this._updateMousePosition(e);
this.prevMouseX = this.mouseX;
this.prevMouseY = this.mouseY;
this.securityCount++;
if (this.isMouseDownRight) {
this.isMouseDownRight = false;
if (!this.isWidget(e.target)) {
this.pickColor(this.mouseX, this.mouseY);
return;
}
}
if (!this.isUIPaused()) {
if (e.target["data-bar"]) {
this.pushTool(new Neo.HandTool());
} else if (this.isSpaceDown && document.activeElement != this.inputText) {
this.pushTool(new Neo.HandTool());
this.tool.reverse = true;
} else if (e.target["data-slider"] != undefined) {
this.pushTool(new Neo.SliderTool());
this.tool.target = e.target;
} else if (e.ctrlKey && e.altKey && !e.shiftKey) {
this.pushTool(new Neo.SliderTool());
this.tool.target = Neo.sliders[Neo.SLIDERTYPE_SIZE].element;
this.tool.alt = true;
} else if (this.isWidget(e.target)) {
this.isMouseDown = false;
this.pushTool(new Neo.DummyTool());
}
}
// console.warn("down -" + e.target.id + e.target.className)
if (!(e.target.className == "o" && e.type == "touchdown")) {
this.tool.downHandler(this);
}
// var ref = this;
// document.onmouseup = function(e) {
// ref._mouseUpHandler(e)
// };
};
Neo.Painter.prototype._mouseUpHandler = function (e) {
this.isMouseDown = false;
this.isMouseDownRight = false;
this.tool.upHandler(this);
// document.onmouseup = undefined;
if (e.target.id != "right") {
this.virtualRight = false;
Neo.RightButton.clear();
}
// if (e.changedTouches) {
// for (var i = 0; i < e.changedTouches.length; i++) {
// var touch = e.changedTouches[i];
// if (touch.identifier == this.touchModifier) {
// this.touchModifier = null;
// }
// }
// }
};
Neo.Painter.prototype._mouseMoveHandler = function (e) {
this._updateMousePosition(e);
if (e.type == "touchmove" && e.touches.length > 1) return;
if (this.isMouseDown || this.isMouseDownRight) {
this.tool.moveHandler(this);
} else {
if (this.tool.upMoveHandler) {
this.tool.upMoveHandler(this);
}
}
this.prevMouseX = this.mouseX;
this.prevMouseY = this.mouseY;
// 画面外をタップした時スクロール可能にするため
// console.warn("move -" + e.target.id + e.target.className)
if (!(e.target.className == "o" && e.type == "touchmove")) {
e.preventDefault();
}
};
Neo.Painter.prototype.getPosition = function (e) {
if (e.clientX !== undefined) {
return { x: e.clientX, y: e.clientY, e: e.type };
} else {
var touch = e.changedTouches[0];
return { x: touch.clientX, y: touch.clientY, e: e.type };
// for (var i = 0; i < e.changedTouches.length; i++) {
// var touch = e.changedTouches[i];
// if (!this.touchModifier || this.touchModifier != touch.identifier) {
// return {x: touch.clientX, y: touch.clientY, e: e.type};
// }
// }
// console.log("getPosition error");
// return {x:0, y:0};
}
};
Neo.Painter.prototype._updateMousePosition = function (e) {
var rect = this.destCanvas.getBoundingClientRect();
// var x = (e.clientX !== undefined) ? e.clientX : e.touches[0].clientX;
// var y = (e.clientY !== undefined) ? e.clientY : e.touches[0].clientY;
var pos = this.getPosition(e);
var x = pos.x;
var y = pos.y;
if (this.zoom <= 0) this.zoom = 1; //なぜか0になることがあるので
this.mouseX =
(x - rect.left) / this.zoom +
this.zoomX -
(this.destCanvas.width * 0.5) / this.zoom;
this.mouseY =
(y - rect.top) / this.zoom +
this.zoomY -
(this.destCanvas.height * 0.5) / this.zoom;
if (isNaN(this.prevMouseX)) {
this.prevMouseX = this.mouseX;
}
if (isNaN(this.prevMouseY)) {
this.prevMosueY = this.mouseY;
}
/*
this.slowX = this.slowX * 0.8 + this.mouseX * 0.2;
this.slowY = this.slowY * 0.8 + this.mouseY * 0.2;
var now = new Date().getTime();
if (this.stab) {
var pause = this.stab[3];
if (pause) {
// ポーズ中
if (now > pause) {
this.stab = [this.slowX, this.slowY, now];
}
} else {
// ポーズされていないとき
var prev = this.stab[2];
if (now - prev > 150) { // 150ms以上止まっていたらポーズをオンにする
this.stab[3] = now + 200 // 200msペンの位置を固定
} else {
this.stab = [this.slowX, this.slowY, now];
}
}
} else {
this.stab = [this.slowX, this.slowY, now];
}
*/
this.rawMouseX = x;
this.rawMouseY = y;
this.clipMouseX = Math.max(Math.min(this.canvasWidth, this.mouseX), 0);
this.clipMouseY = Math.max(Math.min(this.canvasHeight, this.mouseY), 0);
};
Neo.Painter.prototype._beforeUnloadHandler = function (e) {
// quick save
};
/*
Neo.Painter.prototype.getStabilized = function() {
return this.stab;
};
*/
/*
-------------------------------------------------------------------------
Undo
-------------------------------------------------------------------------
*/
Neo.Painter.prototype.undo = function () {
var undoItem = this._undoMgr.popUndo();
if (undoItem) {
this._pushRedo();
this._actionMgr.back();
this.canvasCtx[0].putImageData(undoItem.data[0], undoItem.x, undoItem.y);
this.canvasCtx[1].putImageData(undoItem.data[1], undoItem.x, undoItem.y);
this.updateDestCanvas(
undoItem.x,
undoItem.y,
undoItem.width,
undoItem.height
);
}
};
Neo.Painter.prototype.redo = function () {
var undoItem = this._undoMgr.popRedo();
if (undoItem) {
this._actionMgr.forward();
this._pushUndo(0, 0, this.canvasWidth, this.canvasHeight, true);
this.canvasCtx[0].putImageData(undoItem.data[0], undoItem.x, undoItem.y);
this.canvasCtx[1].putImageData(undoItem.data[1], undoItem.x, undoItem.y);
this.updateDestCanvas(
undoItem.x,
undoItem.y,
undoItem.width,
undoItem.height
);
}
};
//Neo.Painter.prototype.hasUndo = function() {
// return true;
//};
Neo.Painter.prototype._pushUndo = function (x, y, w, h, holdRedo) {
x = x === undefined ? 0 : x;
y = y === undefined ? 0 : y;
w = w === undefined ? this.canvasWidth : w;
h = h === undefined ? this.canvasHeight : h;
var undoItem = new Neo.UndoItem();
undoItem.x = 0;
undoItem.y = 0;
undoItem.width = w;
undoItem.height = h;
undoItem.data = [
this.canvasCtx[0].getImageData(x, y, w, h),
this.canvasCtx[1].getImageData(x, y, w, h),
];
this._undoMgr.pushUndo(undoItem, holdRedo);
if (!holdRedo) {
this._actionMgr.step();
}
this.dirty = true;
};
Neo.Painter.prototype._pushRedo = function (x, y, w, h) {
x = x === undefined ? 0 : x;
y = y === undefined ? 0 : y;
w = w === undefined ? this.canvasWidth : w;
h = h === undefined ? this.canvasHeight : h;
var undoItem = new Neo.UndoItem();
undoItem.x = 0;
undoItem.y = 0;
undoItem.width = w;
undoItem.height = h;
undoItem.data = [
this.canvasCtx[0].getImageData(x, y, w, h),
this.canvasCtx[1].getImageData(x, y, w, h),
];
this._undoMgr.pushRedo(undoItem);
};
/*
-------------------------------------------------------------------------
Data Cache for Undo / Redo
-------------------------------------------------------------------------
*/
Neo.UndoManager = function (_maxStep) {
this._maxStep = _maxStep;
this._undoItems = [];
this._redoItems = [];
};
Neo.UndoManager.prototype._maxStep;
Neo.UndoManager.prototype._redoItems;
Neo.UndoManager.prototype._undoItems;
//アクションをしてUndo情報を更新
Neo.UndoManager.prototype.pushUndo = function (undoItem, holdRedo) {
this._undoItems.push(undoItem);
if (this._undoItems.length > this._maxStep) {
this._undoItems.shift();
}
if (!holdRedo == true) {
this._redoItems = [];
}
};
Neo.UndoManager.prototype.popUndo = function () {
return this._undoItems.pop();
};
Neo.UndoManager.prototype.pushRedo = function (undoItem) {
this._redoItems.push(undoItem);
};
Neo.UndoManager.prototype.popRedo = function () {
return this._redoItems.pop();
};
Neo.UndoItem = function () {};
Neo.UndoItem.prototype.data;
Neo.UndoItem.prototype.x;
Neo.UndoItem.prototype.y;
Neo.UndoItem.prototype.width;
Neo.UndoItem.prototype.height;
/*
-------------------------------------------------------------------------
Zoom Controller
-------------------------------------------------------------------------
*/
Neo.Painter.prototype.setZoom = function (value) {
this.zoom = value;
var container = document.getElementById("container");
var width = this.canvasWidth * this.zoom;
var height = this.canvasHeight * this.zoom;
if (width > container.clientWidth - 100) width = container.clientWidth - 100;
if (height > container.clientHeight - 130)
height = container.clientHeight - 130;
this.destWidth = width;
this.destHeight = height;
this.updateDestCanvas(0, 0, this.canvasWidth, this.canvasHeight, false);
this.setZoomPosition(this.zoomX, this.zoomY);
};
Neo.Painter.prototype.setZoomPosition = function (x, y) {
var minx = (this.destCanvas.width / this.zoom) * 0.5;
var maxx = this.canvasWidth - minx;
var miny = (this.destCanvas.height / this.zoom) * 0.5;
var maxy = this.canvasHeight - miny;
x = Math.round(Math.max(Math.min(maxx, x), minx));
y = Math.round(Math.max(Math.min(maxy, y), miny));
this.zoomX = x;
this.zoomY = y;
this.updateDestCanvas(0, 0, this.canvasWidth, this.canvasHeight, false);
this.scrollBarX = maxx == minx ? 0 : (x - minx) / (maxx - minx);
this.scrollBarY = maxy == miny ? 0 : (y - miny) / (maxy - miny);
this.scrollWidth = maxx - minx;
this.scrollHeight = maxy - miny;
if (Neo.scrollH) Neo.scrollH.update(this);
if (Neo.scrollV) Neo.scrollV.update(this);
this.hideInputText();
};
/*
-------------------------------------------------------------------------
Drawing Helper
-------------------------------------------------------------------------
*/
Neo.Painter.prototype.submit = function (board) {
if (Neo.animation) {
// neo_save_layers
var items = this._actionMgr._items;
if (items.length > 0 && items[items.length - 1][0] != "restore") {
this._pushUndo();
this._actionMgr.restore();
}
}
var thumbnail = null;
var thumbnail2 = null;
if (Neo.config.thumbnail_type == "animation" || this.useThumbnail()) {
thumbnail = this.getThumbnail(Neo.config.thumbnail_type || "png");
}
if (Neo.config.thumbnail_type2 && this.useThumbnail()) {
thumbnail2 = this.getThumbnail(Neo.config.thumbnail_type2);
}
/*
if (this.useThumbnail()) {
thumbnail = this.getThumbnail(Neo.config.thumbnail_type || "png");
if (Neo.config.thumbnail_type2) {
thumbnail2 = this.getThumbnail(Neo.config.thumbnail_type2);
}
}*/
Neo.submit(board, this.getPNG(), thumbnail2, thumbnail);
};
Neo.Painter.prototype.useThumbnail = function () {
var thumbnailWidth = this.getThumbnailWidth();
var thumbnailHeight = this.getThumbnailHeight();
if (thumbnailWidth && thumbnailHeight) {
if (
thumbnailWidth < this.canvasWidth ||
thumbnailHeight < this.canvasHeight
) {
return true;
}
}
return false;
};
Neo.Painter.prototype.dataURLtoBlob = function (dataURL) {
var byteString;
if (dataURL.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataURL.split(",")[1]);
} else {
byteString = unescape(dataURL.split(",")[1]);
}
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: "image/png" });
};
Neo.Painter.prototype.getImage = function (imageWidth, imageHeight) {
var width = this.canvasWidth;
var height = this.canvasHeight;
imageWidth = imageWidth || width;
imageHeight = imageHeight || height;
var pngCanvas = document.createElement("canvas");
pngCanvas.width = imageWidth;
pngCanvas.height = imageHeight;
var pngCanvasCtx = pngCanvas.getContext("2d");
pngCanvasCtx.fillStyle = "#ffffff";
pngCanvasCtx.fillRect(0, 0, imageWidth, imageHeight);
if (this.visible[0]) {
pngCanvasCtx.drawImage(
this.canvas[0],
0,
0,
width,
height,
0,
0,
imageWidth,
imageHeight
);
}
if (this.visible[1]) {
pngCanvasCtx.drawImage(
this.canvas[1],
0,
0,
width,
height,
0,
0,
imageWidth,
imageHeight
);
}
return pngCanvas;
};
Neo.Painter.prototype.getPNG = function () {
var image = this.getImage();
var dataURL = image.toDataURL("image/png");
return this.dataURLtoBlob(dataURL);
};
Neo.Painter.prototype.getThumbnail = function (type) {
if (type != "animation") {
var thumbnailWidth = this.getThumbnailWidth();
var thumbnailHeight = this.getThumbnailHeight();
if (thumbnailWidth || thumbnailHeight) {
var width = this.canvasWidth;
var height = this.canvasHeight;
if (thumbnailWidth == 0) {
thumbnailWidth = (thumbnailHeight * width) / height;
}
if (thumbnailHeight == 0) {
thumbnailHeight = (thumbnailWidth * height) / width;
}
} else {
thumbnailWidth = thumbnailHeight = null;
}
console.log("get thumbnail", thumbnailWidth, thumbnailHeight);
var image = this.getImage(thumbnailWidth, thumbnailHeight);
var dataURL = image.toDataURL("image/" + type);
return this.dataURLtoBlob(dataURL);
} else {
var data = JSON.stringify(this._actionMgr._items);
data = LZString.compressToUint8Array(data);
var magic = "NEO ";
var w = this.canvasWidth;
var h = this.canvasHeight;
return new Blob([
magic,
new Uint8Array([w % 0x100, Math.floor(w / 0x100)]),
new Uint8Array([h % 0x100, Math.floor(h / 0x100)]),
new Uint8Array(4),
data,
]);
}
};
Neo.Painter.prototype.getThumbnailWidth = function () {
var width = Neo.config.thumbnail_width;
if (width) {
if (width.match(/%$/)) {
return Math.floor(this.canvasWidth * (parseInt(width) / 100.0));
} else {
return parseInt(width);
}
}
return 0;
};
Neo.Painter.prototype.getThumbnailHeight = function () {
var height = Neo.config.thumbnail_height;
if (height) {
if (height.match(/%$/)) {
return Math.floor(this.canvasHeight * (parseInt(height) / 100.0));
} else {
return parseInt(height);
}
}
return 0;
};
Neo.Painter.prototype.clearCanvas = function (doConfirm) {
if (!doConfirm || confirm("全消しします")) {
//Register undo first;
this._pushUndo();
this._actionMgr.clearCanvas();
/*
this.canvasCtx[0].clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.canvasCtx[1].clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.updateDestCanvas(0, 0, this.canvasWidth, this.canvasHeight);
*/
}
};
Neo.Painter.prototype.updateDestCanvas = function (
x,
y,
width,
height,
useTemp
) {
var canvasWidth = this.canvasWidth;
var canvasHeight = this.canvasHeight;
var updateAll = false;
if (x == 0 && y == 0 && width == canvasWidth && height == canvasHeight) {
updateAll = true;
}
if (x + width > this.canvasWidth) width = this.canvasWidth - x;
if (y + height > this.canvasHeight) height = this.canvasHeight - y;
if (x < 0) x = 0;
if (y < 0) y = 0;
if (width <= 0 || height <= 0) return;
var ctx = this.destCanvasCtx;
ctx.save();
ctx.fillStyle = "#ffffff";
var fillWidth = width;
var fillHeight = height;
if (updateAll) {
ctx.fillRect(0, 0, this.destCanvas.width, this.destCanvas.height);
} else {
//カーソルの描画ゴミが残るのをごまかすため
if (x + width == this.canvasWidth) fillWidth = width + 1;
if (y + height == this.canvasHeight) fillHeight = height + 1;
}
ctx.translate(this.destCanvas.width * 0.5, this.destCanvas.height * 0.5);
ctx.scale(this.zoom, this.zoom);
ctx.translate(-this.zoomX, -this.zoomY);
ctx.globalAlpha = 1.0;
ctx.msImageSmoothingEnabled = 0;
if (!updateAll) {
ctx.fillRect(x, y, fillWidth, fillHeight);
}
if (this.visible[0]) {
ctx.drawImage(this.canvas[0], x, y, width, height, x, y, width, height);
}
if (this.visible[1]) {
ctx.drawImage(this.canvas[1], x, y, width, height, x, y, width, height);
}
if (useTemp) {
ctx.globalAlpha = 1.0; //this.alpha;
ctx.drawImage(
this.tempCanvas,
x,
y,
width,
height,
x + this.tempX,
y + this.tempY,
width,
height
);
}
ctx.restore();
};
Neo.Painter.prototype.getBound = function (x0, y0, x1, y1, r) {
var left = Math.floor(x0 < x1 ? x0 : x1);
var top = Math.floor(y0 < y1 ? y0 : y1);
var width = Math.ceil(Math.abs(x0 - x1));
var height = Math.ceil(Math.abs(y0 - y1));
r = Math.ceil(r + 1);
if (!r) {
width += 1;
height += 1;
} else {
left -= r;
top -= r;
width += r * 2;
height += r * 2;
}
return [left, top, width, height];
};
Neo.Painter.prototype.getColor = function (c) {
if (!c) c = this.foregroundColor;
var r = parseInt(c.substr(1, 2), 16);
var g = parseInt(c.substr(3, 2), 16);
var b = parseInt(c.substr(5, 2), 16);
var a = Math.floor(this.alpha * 255);
return (a << 24) | (b << 16) | (g << 8) | r;
};
Neo.Painter.prototype.getColorString = function (c) {
var rgb = ("000000" + (c & 0xffffff).toString(16)).substr(-6);
return "#" + rgb;
};
Neo.Painter.prototype.setColor = function (c) {
if (typeof c != "string") c = this.getColorString(c);
this.foregroundColor = c;
Neo.updateUI();
};
Neo.Painter.prototype.getAlpha = function (type) {
var a1 = this._currentColor[3] / 255.0; //this.alpha;
switch (type) {
case Neo.Painter.ALPHATYPE_PEN:
if (a1 > 0.5) {
a1 = 1.0 / 16 + ((a1 - 0.5) * 30.0) / 16;
} else {
a1 = Math.sqrt(2 * a1) / 16.0;
}
a1 = Math.min(1, Math.max(0, a1));
break;
case Neo.Painter.ALPHATYPE_FILL:
a1 = -0.00056 * a1 + 0.0042 / (1.0 - a1) - 0.0042;
a1 = Math.min(1.0, Math.max(0, a1 * 10));
break;
case Neo.Painter.ALPHATYPE_BRUSH:
a1 = -0.00056 * a1 + 0.0042 / (1.0 - a1) - 0.0042;
a1 = Math.min(1.0, Math.max(0, a1));
break;
}
// アルファが小さい時は適当に点を抜いて見た目の濃度を合わせる
if (a1 < 1.0 / 255) {
this.aerr += a1;
a1 = 0;
while (this.aerr > 1.0 / 255) {
a1 = 1.0 / 255;
this.aerr -= 1.0 / 255;
}
}
return a1;
};
Neo.Painter.prototype.prepareDrawing = function () {
var r = parseInt(this.foregroundColor.substr(1, 2), 16);
var g = parseInt(this.foregroundColor.substr(3, 2), 16);
var b = parseInt(this.foregroundColor.substr(5, 2), 16);
var a = Math.floor(this.alpha * 255);
var maskR = parseInt(this.maskColor.substr(1, 2), 16);
var maskG = parseInt(this.maskColor.substr(3, 2), 16);
var maskB = parseInt(this.maskColor.substr(5, 2), 16);
this._currentColor = [r, g, b, a];
this._currentMask = [maskR, maskG, maskB];
this._currentWidth = this.lineWidth;
this._currentMaskType = this.maskType;
};
Neo.Painter.prototype.isMasked = function (buf8, index) {
var r = this._currentMask[0];
var g = this._currentMask[1];
var b = this._currentMask[2];
var r1 = this._currentColor[0];
var g1 = this._currentColor[1];
var b1 = this._currentColor[2];
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3];
if (a0 == 0) {
r0 = 0xff;
g0 = 0xff;
b0 = 0xff;
}
var type = this._currentMaskType; //this.maskType;
//TODO
//いろいろ試したのですが半透明で描画するときの加算・逆加算を再現する方法がわかりません。
//とりあえず単純に無視しています。
if (type == Neo.Painter.MASKTYPE_ADD || type == Neo.Painter.MASKTYPE_SUB) {
if (this._currentColor[3] < 250) {
type = Neo.Painter.MASKTYPE_NONE;
}
}
switch (type) {
case Neo.Painter.MASKTYPE_NONE:
return;
case Neo.Painter.MASKTYPE_NORMAL:
return r0 == r && g0 == g && b0 == b ? true : false;
case Neo.Painter.MASKTYPE_REVERSE:
return r0 != r || g0 != g || b0 != b ? true : false;
case Neo.Painter.MASKTYPE_ADD:
if (a0 > 0) {
var sort = this.sortColor(r0, g0, b0);
for (var i = 0; i < 3; i++) {
var c = sort[i];
if (buf8[index + c] < this._currentColor[c]) return true;
}
return false;
} else {
return false;
}
case Neo.Painter.MASKTYPE_SUB:
if (a0 > 0) {
var sort = this.sortColor(r0, g0, b0);
for (var i = 0; i < 3; i++) {
var c = sort[i];
if (buf8[index + c] > this._currentColor[c]) return true;
}
return false;
} else {
return true;
}
}
};
Neo.Painter.prototype.setPoint = function (
buf8,
bufWidth,
x0,
y0,
left,
top,
type
) {
var x = x0 - left;
var y = y0 - top;
switch (type) {
case Neo.Painter.LINETYPE_PEN:
this.setPenPoint(buf8, bufWidth, x, y);
break;
case Neo.Painter.LINETYPE_BRUSH:
this.setBrushPoint(buf8, bufWidth, x, y);
break;
case Neo.Painter.LINETYPE_TONE:
this.setTonePoint(buf8, bufWidth, x, y, x0, y0);
break;
case Neo.Painter.LINETYPE_ERASER:
this.setEraserPoint(buf8, bufWidth, x, y);
break;
case Neo.Painter.LINETYPE_BLUR:
this.setBlurPoint(buf8, bufWidth, x, y, x0, y0);
break;
case Neo.Painter.LINETYPE_DODGE:
this.setDodgePoint(buf8, bufWidth, x, y);
break;
case Neo.Painter.LINETYPE_BURN:
this.setBurnPoint(buf8, bufWidth, x, y);
break;
default:
break;
}
};
Neo.Painter.prototype.setPenPoint = function (buf8, width, x, y) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var index = (y * width + x) * 4;
var shape = this._roundData[d];
var shapeIndex = 0;
var r1 = this._currentColor[0];
var g1 = this._currentColor[1];
var b1 = this._currentColor[2];
var a1 = this.getAlpha(Neo.Painter.ALPHATYPE_PEN);
if (a1 == 0) return;
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3] / 255.0;
var a = a0 + a1 - a0 * a1;
if (a > 0) {
var a1x = Math.max(a1, 1.0 / 255);
var r = (r1 * a1x + r0 * a0 * (1 - a1x)) / a;
var g = (g1 * a1x + g0 * a0 * (1 - a1x)) / a;
var b = (b1 * a1x + b0 * a0 * (1 - a1x)) / a;
r = r1 > r0 ? Math.ceil(r) : Math.floor(r);
g = g1 > g0 ? Math.ceil(g) : Math.floor(g);
b = b1 > b0 ? Math.ceil(b) : Math.floor(b);
}
var tmp = a * 255;
a = Math.ceil(tmp);
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
}
index += 4;
}
index += (width - d) * 4;
}
};
Neo.Painter.prototype.setBrushPoint = function (buf8, width, x, y) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var index = (y * width + x) * 4;
var shape = this._roundData[d];
var shapeIndex = 0;
var r1 = this._currentColor[0];
var g1 = this._currentColor[1];
var b1 = this._currentColor[2];
var a1 = this.getAlpha(Neo.Painter.ALPHATYPE_BRUSH);
if (a1 == 0) return;
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3] / 255.0;
var a = a0 + a1 - a0 * a1;
if (a > 0) {
var a1x = Math.max(a1, 1.0 / 255);
var r = (r1 * a1x + r0 * a0) / (a0 + a1x);
var g = (g1 * a1x + g0 * a0) / (a0 + a1x);
var b = (b1 * a1x + b0 * a0) / (a0 + a1x);
r = r1 > r0 ? Math.ceil(r) : Math.floor(r);
g = g1 > g0 ? Math.ceil(g) : Math.floor(g);
b = b1 > b0 ? Math.ceil(b) : Math.floor(b);
}
var tmp = a * 255;
a = Math.ceil(tmp);
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
}
index += 4;
}
index += (width - d) * 4;
}
};
Neo.Painter.prototype.setTonePoint = function (buf8, width, x, y, x0, y0) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
x0 -= r0;
y0 -= r0;
var shape = this._roundData[d];
var shapeIndex = 0;
var index = (y * width + x) * 4;
var r = this._currentColor[0];
var g = this._currentColor[1];
var b = this._currentColor[2];
var a = this._currentColor[3];
var toneData = this.getToneData(a);
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
if (toneData[((y0 + i) % 4) + ((x0 + j) % 4) * 4]) {
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = 255;
}
}
index += 4;
}
index += (width - d) * 4;
}
};
Neo.Painter.prototype.setEraserPoint = function (buf8, width, x, y) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var shape = this._roundData[d];
var shapeIndex = 0;
var index = (y * width + x) * 4;
var a = Math.floor(this._currentColor[3]); //this.alpha * 255);
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var k = (buf8[index + 3] / 255.0) * (1.0 - a / 255.0);
buf8[index + 3] -= a / ((d * (255.0 - a)) / 255.0);
}
index += 4;
}
index += (width - d) * 4;
}
};
Neo.Painter.prototype.setBlurPoint = function (buf8, width, x, y, x0, y0) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var shape = this._roundData[d];
var shapeIndex = 0;
var height = buf8.length / (width * 4);
// var a1 = this.getAlpha(Neo.Painter.ALPHATYPE_BRUSH);
// var a1 = this.alpha / 12;
var a1 = this._currentColor[3] / 255.0 / 12;
if (a1 == 0) return;
var blur = a1;
var tmp = new Uint8ClampedArray(buf8.length);
for (var i = 0; i < buf8.length; i++) {
tmp[i] = buf8[i];
}
var left = x0 - x - r0;
var top = y0 - y - r0;
var xstart = 0,
xend = d;
var ystart = 0,
yend = d;
if (xstart > left) xstart = -left;
if (ystart > top) ystart = -top;
if (xend > this.canvasWidth - left) xend = this.canvasWidth - left;
if (yend > this.canvasHeight - top) yend = this.canvasHeight - top;
for (var j = ystart; j < yend; j++) {
var index = (j * width + xstart) * 4;
for (var i = xstart; i < xend; i++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var rgba = [0, 0, 0, 0, 0];
this.addBlur(tmp, index, 1.0 - blur * 4, rgba);
if (i > xstart) this.addBlur(tmp, index - 4, blur, rgba);
if (i < xend - 1) this.addBlur(tmp, index + 4, blur, rgba);
if (j > ystart) this.addBlur(tmp, index - width * 4, blur, rgba);
if (j < yend - 1) this.addBlur(tmp, index + width * 4, blur, rgba);
buf8[index + 0] = Math.round(rgba[0]);
buf8[index + 1] = Math.round(rgba[1]);
buf8[index + 2] = Math.round(rgba[2]);
buf8[index + 3] = Math.round((rgba[3] / rgba[4]) * 255.0);
}
index += 4;
}
}
};
Neo.Painter.prototype.setDodgePoint = function (buf8, width, x, y) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var index = (y * width + x) * 4;
var shape = this._roundData[d];
var shapeIndex = 0;
var a1 = this.getAlpha(Neo.Painter.ALPHATYPE_BRUSH);
if (a1 == 0) return;
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3] / 255.0;
if (a1 != 255.0) {
var r1 = (r0 * 255) / (255 - a1);
var g1 = (g0 * 255) / (255 - a1);
var b1 = (b0 * 255) / (255 - a1);
} else {
var r1 = 255.0;
var g1 = 255.0;
var b1 = 255.0;
}
var r = Math.ceil(r1);
var g = Math.ceil(g1);
var b = Math.ceil(b1);
var a = a0;
var tmp = a * 255;
a = Math.ceil(tmp);
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
}
index += 4;
}
index += (width - d) * 4;
}
};
Neo.Painter.prototype.setBurnPoint = function (buf8, width, x, y) {
var d = this._currentWidth;
var r0 = Math.floor(d / 2);
x -= r0;
y -= r0;
var index = (y * width + x) * 4;
var shape = this._roundData[d];
var shapeIndex = 0;
var a1 = this.getAlpha(Neo.Painter.ALPHATYPE_BRUSH);
if (a1 == 0) return;
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
if (shape[shapeIndex++] && !this.isMasked(buf8, index)) {
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3] / 255.0;
if (a1 != 255.0) {
var r1 = 255 - ((255 - r0) * 255) / (255 - a1);
var g1 = 255 - ((255 - g0) * 255) / (255 - a1);
var b1 = 255 - ((255 - b0) * 255) / (255 - a1);
} else {
var r1 = 0;
var g1 = 0;
var b1 = 0;
}
var r = Math.floor(r1);
var g = Math.floor(g1);
var b = Math.floor(b1);
var a = a0;
var tmp = a * 255;
a = Math.ceil(tmp);
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
}
index += 4;
}
index += (width - d) * 4;
}
};
//////////////////////////////////////////////////////////////////////
Neo.Painter.prototype.xorPixel = function (buf32, bufWidth, x, y, c) {
var index = y * bufWidth + x;
if (!c) c = 0xffffff;
buf32[index] ^= c;
};
Neo.Painter.prototype.getBezierPoint = function (
t,
x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3
) {
var a0 = (1 - t) * (1 - t) * (1 - t);
var a1 = (1 - t) * (1 - t) * t * 3;
var a2 = (1 - t) * t * t * 3;
var a3 = t * t * t;
var x = x0 * a0 + x1 * a1 + x2 * a2 + x3 * a3;
var y = y0 * a0 + y1 * a1 + y2 * a2 + y3 * a3;
return [x, y];
};
Neo.Painter.prototype.drawBezier = function (
ctx,
x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3,
type,
isReplay,
isPreview
) {
var points = [
[x0, y0],
[x1, y1],
[x2, y2],
[x3, y3],
];
var that = this;
this.draw(ctx, points, function (left, top, width, height, buf8, imageData) {
var n = Math.ceil((width + height) * 2.5);
var oType = that._currentMaskType;
var oAlpha = that._currentColor[3];
if (isPreview) {
that._currentMaskType = Neo.Painter.MASKTYPE_NONE;
that._currentColor[3] = 255;
}
for (var i = 0; i < n; i++) {
var t = (i * 1.0) / n;
var p = that.getBezierPoint(t, x0, y0, x1, y1, x2, y2, x3, y3);
p[0] = Math.round(p[0]);
p[1] = Math.round(p[1]);
that.plot(p, function (x, y) {
that.setPoint(buf8, imageData.width, x, y, left, top, type);
});
}
that._currentMaskType = oType;
that._currentColor[3] = oAlpha;
that.prevLine = null;
});
};
Neo.Painter.prototype.prevLine = null; // 始点または終点が2度プロットされることがあるので
Neo.Painter.prototype.drawLine = function (ctx, x0, y0, x1, y1, type) {
var points = [
[x0, y0],
[x1, y1],
];
var that = this;
this.aerr = 0;
this.draw(ctx, points, function (left, top, width, height, buf8, imageData) {
that.bresenham(points, function (x, y) {
that.setPoint(buf8, imageData.width, x, y, left, top, type);
});
});
this.prevLine = points;
};
Neo.Painter.prototype.draw = function (ctx, points, callback) {
var xs = [],
ys = [];
for (var i = 0; i < points.length; i++) {
var point = points[i];
xs.push(Math.round(point[0]));
ys.push(Math.round(point[1]));
}
var xmin = Math.min.apply(null, xs);
var xmax = Math.max.apply(null, xs);
var ymin = Math.min.apply(null, ys);
var ymax = Math.max.apply(null, ys);
var r = Math.ceil(this._currentWidth / 2);
var left = xmin - r;
var top = ymin - r;
var width = xmax - xmin;
var height = ymax - ymin;
var imageData = ctx.getImageData(left, top, width + r * 2, height + r * 2);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
callback(left, top, width, height, buf8, imageData);
imageData.data.set(buf8);
ctx.putImageData(imageData, left, top);
};
Neo.Painter.prototype.bresenham = function (points, callback) {
var x0 = points[0][0];
var y0 = points[0][1];
var x1 = points[1][0];
var y1 = points[1][1];
var dx = Math.abs(x1 - x0),
sx = x0 < x1 ? 1 : -1;
var dy = Math.abs(y1 - y0),
sy = y0 < y1 ? 1 : -1;
var err = (dx > dy ? dx : -dy) / 2;
while (true) {
if (
this.prevLine == null ||
!(
(this.prevLine[0][0] == x0 && this.prevLine[0][1] == y0) ||
(this.prevLine[1][0] == x0 && this.prevLine[1][1] == y0)
)
) {
callback(x0, y0);
}
if (x0 === x1 && y0 === y1) break;
var e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
this.prevLine = points;
};
Neo.Painter.prototype.plot = function (point, callback) {
var x0 = point[0];
var y0 = point[1];
if (
this.prevLine == null ||
!(this.prevLine[0][0] == x0 && this.prevLine[0][1] == y0)
) {
callback(x0, y0);
}
this.prevLine = [point, point];
};
Neo.Painter.prototype.drawPoint = function (ctx, x, y, type) {
this.drawLine(ctx, x, y, x, y, type);
};
Neo.Painter.prototype.xorRect = function (
buf32,
bufWidth,
x,
y,
width,
height,
c
) {
var index = y * bufWidth + x;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
buf32[index] ^= c;
index++;
}
index += width - bufWidth;
}
};
Neo.Painter.prototype.drawXORRect = function (
ctx,
x,
y,
width,
height,
isFill,
c
) {
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
if (width == 0 || height == 0) return;
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var index = 0;
if (!c) c = 0xffffff;
if (isFill) {
this.xorRect(buf32, width, 0, 0, width, height, c);
} else {
for (var i = 0; i < width; i++) {
//top
buf32[index] = buf32[index] ^= c;
index++;
}
if (height > 1) {
index = width;
for (var i = 1; i < height; i++) {
//left
buf32[index] = buf32[index] ^= c;
index += width;
}
if (width > 1) {
index = width * 2 - 1;
for (var i = 1; i < height - 1; i++) {
//right
buf32[index] = buf32[index] ^= c;
index += width;
}
index = width * (height - 1) + 1;
for (var i = 1; i < width; i++) {
// bottom
buf32[index] = buf32[index] ^= c;
index++;
}
}
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.drawXOREllipse = function (
ctx,
x,
y,
width,
height,
isFill,
c
) {
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
if (width == 0 || height == 0) return;
if (!c) c = 0xffffff;
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var a = width - 1,
b = height - 1,
b1 = b & 1; /* values of diameter */
var dx = 4 * (1 - a) * b * b,
dy = 4 * (b1 + 1) * a * a; /* error increment */
var err = dx + dy + b1 * a * a,
e2; /* error of 1.step */
var x0 = x;
var y0 = y;
var x1 = x0 + a;
var y1 = y0 + b;
if (x0 > x1) {
x0 = x1;
x1 += a;
}
if (y0 > y1) y0 = y1;
y0 += Math.floor((b + 1) / 2);
y1 = y0 - b1; /* starting pixel */
a *= 8 * a;
b1 = 8 * b * b;
var ymin = y0 - 1;
do {
if (isFill) {
if (ymin < y0) {
this.xorRect(buf32, width, x0 - x, y0 - y, x1 - x0, 1, c);
if (y0 != y1) {
this.xorRect(buf32, width, x0 - x, y1 - y, x1 - x0, 1, c);
}
ymin = y0;
}
} else {
this.xorPixel(buf32, width, x1 - x, y0 - y, c);
if (x0 != x1) {
this.xorPixel(buf32, width, x0 - x, y0 - y, c);
}
if (y0 != y1) {
this.xorPixel(buf32, width, x0 - x, y1 - y, c);
if (x0 != x1) {
this.xorPixel(buf32, width, x1 - x, y1 - y, c);
}
}
}
e2 = 2 * err;
if (e2 <= dy) {
y0++;
y1--;
err += dy += a;
} /* y step */
if (e2 >= dx || 2 * err > dy) {
x0++;
x1--;
err += dx += b1;
} /* x step */
} while (x0 <= x1);
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.drawXORLine = function (ctx, x0, y0, x1, y1, c) {
x0 = Math.round(x0);
x1 = Math.round(x1);
y0 = Math.round(y0);
y1 = Math.round(y1);
var width = Math.abs(x1 - x0);
var height = Math.abs(y1 - y0);
var left = x0 < x1 ? x0 : x1;
var top = y0 < y1 ? y0 : y1;
// console.log("left:"+left+" top:"+top+" width:"+width+" height:"+height);
var imageData = ctx.getImageData(left, top, width + 1, height + 1);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var dx = width,
sx = x0 < x1 ? 1 : -1;
var dy = height,
sy = y0 < y1 ? 1 : -1;
var err = (dx > dy ? dx : -dy) / 2;
while (true) {
if (
this.prevLine == null ||
!(
(this.prevLine[0] == x0 && this.prevLine[1] == y0) ||
(this.prevLine[2] == x0 && this.prevLine[3] == y0)
)
) {
this.xorPixel(buf32, imageData.width, x0 - left, y0 - top, c);
}
if (x0 === x1 && y0 === y1) break;
var e2 = err;
if (e2 > -dx) {
err -= dy;
x0 += sx;
}
if (e2 < dy) {
err += dx;
y0 += sy;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, left, top);
};
Neo.Painter.prototype.eraseRect = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var index = 0;
var a = 1.0 - this._currentColor[3] / 255.0; //this.alpha;
if (a != 0) {
a = Math.ceil(2.0 / a);
} else {
a = 255;
}
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
if (!this.isMasked(buf8, index)) {
buf8[index + 3] -= a;
}
index += 4;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.flipH = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var half = Math.floor(width / 2);
for (var j = 0; j < height; j++) {
var index = j * width;
var index2 = index + (width - 1);
for (var i = 0; i < half; i++) {
var value = buf32[index + i];
buf32[index + i] = buf32[index2 - i];
buf32[index2 - i] = value;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.flipV = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var half = Math.floor(height / 2);
for (var j = 0; j < half; j++) {
var index = j * width;
var index2 = (height - 1 - j) * width;
for (var i = 0; i < width; i++) {
var value = buf32[index + i];
buf32[index + i] = buf32[index2 + i];
buf32[index2 + i] = value;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.merge = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
var imageData = [];
var buf32 = [];
var buf8 = [];
for (var i = 0; i < 2; i++) {
imageData[i] = this.canvasCtx[i].getImageData(x, y, width, height);
buf32[i] = new Uint32Array(imageData[i].data.buffer);
buf8[i] = new Uint8ClampedArray(imageData[i].data.buffer);
}
var dst = layer;
var src = dst == 1 ? 0 : 1;
var size = width * height;
var index = 0;
for (var i = 0; i < size; i++) {
var r0 = buf8[0][index + 0];
var g0 = buf8[0][index + 1];
var b0 = buf8[0][index + 2];
var a0 = buf8[0][index + 3] / 255.0;
var r1 = buf8[1][index + 0];
var g1 = buf8[1][index + 1];
var b1 = buf8[1][index + 2];
var a1 = buf8[1][index + 3] / 255.0;
var a = a0 + a1 - a0 * a1;
if (a > 0) {
var r = Math.floor((r1 * a1 + r0 * a0 * (1 - a1)) / a + 0.5);
var g = Math.floor((g1 * a1 + g0 * a0 * (1 - a1)) / a + 0.5);
var b = Math.floor((b1 * a1 + b0 * a0 * (1 - a1)) / a + 0.5);
}
buf8[src][index + 0] = 0;
buf8[src][index + 1] = 0;
buf8[src][index + 2] = 0;
buf8[src][index + 3] = 0;
buf8[dst][index + 0] = r;
buf8[dst][index + 1] = g;
buf8[dst][index + 2] = b;
buf8[dst][index + 3] = Math.floor(a * 255 + 0.5);
index += 4;
}
for (var i = 0; i < 2; i++) {
imageData[i].data.set(buf8[i]);
this.canvasCtx[i].putImageData(imageData[i], x, y);
}
};
Neo.Painter.prototype.blurRect = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
height = Math.round(height);
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var tmp = new Uint8ClampedArray(buf8.length);
for (var i = 0; i < buf8.length; i++) tmp[i] = buf8[i];
var index = 0;
var a1 = this._currentColor[3] / 255.0 / 12; //this.alpha / 12;
var blur = a1;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
var rgba = [0, 0, 0, 0, 0];
this.addBlur(tmp, index, 1.0 - blur * 4, rgba);
if (i > 0) this.addBlur(tmp, index - 4, blur, rgba);
if (i < width - 1) this.addBlur(tmp, index + 4, blur, rgba);
if (j > 0) this.addBlur(tmp, index - width * 4, blur, rgba);
if (j < height - 1) this.addBlur(tmp, index + width * 4, blur, rgba);
var w = rgba[4];
buf8[index + 0] = Math.round(rgba[0]);
buf8[index + 1] = Math.round(rgba[1]);
buf8[index + 2] = Math.round(rgba[2]);
buf8[index + 3] = Math.ceil((rgba[3] / w) * 255.0);
index += 4;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.addBlur = function (buffer, index, a, rgba) {
var r0 = rgba[0];
var g0 = rgba[1];
var b0 = rgba[2];
var a0 = rgba[3];
var r1 = buffer[index + 0];
var g1 = buffer[index + 1];
var b1 = buffer[index + 2];
var a1 = (buffer[index + 3] / 255.0) * a;
rgba[4] += a;
var a = a0 + a1;
if (a > 0) {
rgba[0] = (r1 * a1 + r0 * a0) / (a0 + a1);
rgba[1] = (g1 * a1 + g0 * a0) / (a0 + a1);
rgba[2] = (b1 * a1 + b0 * a0) / (a0 + a1);
rgba[3] = a;
}
};
Neo.Painter.prototype.pickColor = function (x, y) {
var r = 0xff,
g = 0xff,
b = 0xff,
a;
x = Math.floor(x);
y = Math.floor(y);
if (x >= 0 && x < this.canvasWidth && y >= 0 && y < this.canvasHeight) {
for (var i = 0; i < 2; i++) {
if (this.visible[i]) {
var ctx = this.canvasCtx[i];
var imageData = ctx.getImageData(x, y, 1, 1);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var a = buf8[3] / 255.0;
r = r * (1.0 - a) + buf8[2] * a;
g = g * (1.0 - a) + buf8[1] * a;
b = b * (1.0 - a) + buf8[0] * a;
}
}
r = Math.max(Math.min(Math.round(r), 255), 0);
g = Math.max(Math.min(Math.round(g), 255), 0);
b = Math.max(Math.min(Math.round(b), 255), 0);
var result = r | (g << 8) | (b << 16);
}
this.setColor(result);
if (this.current > 0) {
if (a == 0 && (result == 0xffffff || this.getEmulationMode() < 2.16)) {
this.setToolByType(Neo.eraserTip.tools[Neo.eraserTip.mode]);
} else {
if (Neo.eraserTip.selected) {
this.setToolByType(Neo.penTip.tools[Neo.penTip.mode]);
}
}
}
};
Neo.Painter.prototype.fillHorizontalLine = function (buf32, x0, x1, y, color) {
var index = y * this.canvasWidth + x0;
for (var x = x0; x <= x1; x++) {
buf32[index++] = color;
}
};
Neo.Painter.prototype.scanLine = function (x0, x1, y, baseColor, buf32, stack) {
var width = this.canvasWidth;
for (var x = x0; x <= x1; x++) {
stack.push({ x: x, y: y });
}
};
Neo.Painter.prototype.doFloodFill = function (layer, x, y, fillColor) {
x = Math.round(x);
y = Math.round(y);
var ctx = this.canvasCtx[layer];
if (x < 0 || x >= this.canvasWidth || y < 0 || y >= this.canvasHeight) {
return;
}
var imageData = ctx.getImageData(0, 0, this.canvasWidth, this.canvasHeight);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var width = imageData.width;
var stack = [{ x: x, y: y }];
var baseColor = buf32[y * width + x];
if ((baseColor & 0xff000000) == 0 || baseColor != fillColor) {
while (stack.length > 0) {
if (stack.length > 1000000) {
console.log("too much stack");
break;
}
var point = stack.pop();
var x = point.x;
var y = point.y;
var x0 = x;
var x1 = x;
if (buf32[y * width + x] == fillColor) continue;
if (buf32[y * width + x] != baseColor) continue;
for (; 0 < x0; x0--) {
if (buf32[y * width + (x0 - 1)] != baseColor) break;
}
for (; x1 < this.canvasWidth - 1; x1++) {
if (buf32[y * width + (x1 + 1)] != baseColor) break;
}
this.fillHorizontalLine(buf32, x0, x1, y, fillColor);
if (y + 1 < this.canvasHeight) {
this.scanLine(x0, x1, y + 1, baseColor, buf32, stack);
}
if (y - 1 >= 0) {
this.scanLine(x0, x1, y - 1, baseColor, buf32, stack);
}
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
// this.updateDestCanvas(0, 0, this.canvasWidth, this.canvasHeight);
};
Neo.Painter.prototype.copy = function (layer, x, y, width, height) {
this.tempX = 0;
this.tempY = 0;
this.tempCanvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
var imageData = this.canvasCtx[layer].getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
this.temp = new Uint32Array(buf32.length);
for (var i = 0; i < buf32.length; i++) {
this.temp[i] = buf32[i];
}
//tempCanvasに乗せる画像を作る
imageData = this.tempCanvasCtx.getImageData(x, y, width, height);
buf32 = new Uint32Array(imageData.data.buffer);
buf8 = new Uint8ClampedArray(imageData.data.buffer);
for (var i = 0; i < buf32.length; i++) {
if (this.temp[i] >> 24) {
buf32[i] = this.temp[i] | 0xff000000;
} else {
buf32[i] = 0xffffffff;
}
}
imageData.data.set(buf8);
this.tempCanvasCtx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.paste = function (layer, x, y, width, height, dx, dy) {
var ctx = this.canvasCtx[layer];
// console.log(this.tempX, this.tempY);
var imageData = ctx.getImageData(x + dx, y + dy, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
if (this.temp) {
for (var i = 0; i < buf32.length; i++) {
buf32[i] = this.temp[i];
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x + dx, y + dy);
}
this.temp = null;
this.tempX = 0;
this.tempY = 0;
this.tempCanvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
};
Neo.Painter.prototype.turn = function (layer, x, y, width, height) {
var ctx = this.canvasCtx[layer];
// 傾けツールのバグを再現するため一番上のラインで対象領域を埋める
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var temp = new Uint32Array(buf32.length);
var index = 0;
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
temp[index] = buf32[index];
if (index >= width) {
buf32[index] = buf32[index % width];
}
index++;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
// 90度回転させて貼り付け
imageData = ctx.getImageData(x, y, height, width);
buf32 = new Uint32Array(imageData.data.buffer);
buf8 = new Uint8ClampedArray(imageData.data.buffer);
index = 0;
for (var j = height - 1; j >= 0; j--) {
for (var i = 0; i < width; i++) {
buf32[i * height + j] = temp[index++];
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.getMaskFunc = function (type) {
switch (type) {
case Neo.Painter.TOOLTYPE_RECT:
return this.rectMask;
case Neo.Painter.TOOLTYPE_RECTFILL:
return this.rectFillMask;
case Neo.Painter.TOOLTYPE_ELLIPSE:
return this.ellipseMask;
case Neo.Painter.TOOLTYPE_ELLIPSEFILL:
return this.ellipseFillMask;
}
return null;
};
Neo.Painter.prototype.doFill = function (layer, x, y, width, height, type) {
var ctx = this.canvasCtx[layer];
var maskFunc = this.getMaskFunc(type);
var imageData = ctx.getImageData(x, y, width, height);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var index = 0;
var r1 = this._currentColor[0];
var g1 = this._currentColor[1];
var b1 = this._currentColor[2];
var a1 = this.getAlpha(Neo.ALPHATYPE_FILL);
for (var j = 0; j < height; j++) {
for (var i = 0; i < width; i++) {
if (maskFunc && maskFunc.call(this, i, j, width, height)) {
//なぜか加算逆加算は適用されない
if (
this._currentMaskType >= Neo.Painter.MASKTYPE_ADD ||
!this.isMasked(buf8, index)
) {
var r0 = buf8[index + 0];
var g0 = buf8[index + 1];
var b0 = buf8[index + 2];
var a0 = buf8[index + 3] / 255.0;
var a = a0 + a1 - a0 * a1;
if (a > 0) {
var a1x = a1;
var ax = 1 + a0 * (1 - a1x);
var r = (r1 + r0 * a0 * (1 - a1x)) / ax;
var g = (g1 + g0 * a0 * (1 - a1x)) / ax;
var b = (b1 + b0 * a0 * (1 - a1x)) / ax;
r = r1 > r0 ? Math.ceil(r) : Math.floor(r);
g = g1 > g0 ? Math.ceil(g) : Math.floor(g);
b = b1 > b0 ? Math.ceil(b) : Math.floor(b);
}
var tmp = a * 255;
a = Math.ceil(tmp);
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
}
}
index += 4;
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, x, y);
};
Neo.Painter.prototype.rectFillMask = function (x, y, width, height) {
return true;
};
Neo.Painter.prototype.rectMask = function (x, y, width, height) {
var d = this._currentWidth;
// var d = this.lineWidth;
return x < d || x > width - 1 - d || y < d || y > height - 1 - d
? true
: false;
};
Neo.Painter.prototype.ellipseFillMask = function (x, y, width, height) {
var cx = (width - 1) / 2.0;
var cy = (height - 1) / 2.0;
x = (x - cx) / (cx + 1);
y = (y - cy) / (cy + 1);
return x * x + y * y < 1 ? true : false;
};
Neo.Painter.prototype.ellipseMask = function (x, y, width, height) {
var d = this._currentWidth;
// var d = this.lineWidth;
var cx = (width - 1) / 2.0;
var cy = (height - 1) / 2.0;
if (cx <= d || cy <= d) return this.ellipseFillMask(x, y, width, height);
var x2 = (x - cx) / (cx - d + 1);
var y2 = (y - cy) / (cy - d + 1);
x = (x - cx) / (cx + 1);
y = (y - cy) / (cy + 1);
if (x * x + y * y < 1) {
if (x2 * x2 + y2 * y2 >= 1) {
return true;
}
}
return false;
};
/*
-----------------------------------------------------------------------
*/
Neo.Painter.prototype.getDestCanvasPosition = function (
mx,
my,
isClip,
isCenter
) {
var mx = Math.floor(mx); //Math.round(mx);
var my = Math.floor(my); //Math.round(my);
if (isCenter) {
mx += 0.499;
my += 0.499;
}
var x =
(mx - this.zoomX + (this.destCanvas.width * 0.5) / this.zoom) * this.zoom;
var y =
(my - this.zoomY + (this.destCanvas.height * 0.5) / this.zoom) * this.zoom;
if (isClip) {
x = Math.max(Math.min(x, this.destCanvas.width), 0);
y = Math.max(Math.min(y, this.destCanvas.height), 0);
}
return { x: x, y: y };
};
Neo.Painter.prototype.isWidget = function (element) {
while (1) {
if (element == null || element.id == "canvas" || element.id == "container")
break;
if (
element.id == "tools" ||
element.className == "buttonOn" ||
element.className == "buttonOff" ||
element.className == "inputText"
) {
return true;
}
element = element.parentNode;
}
return false;
};
Neo.Painter.prototype.isContainer = function (element) {
while (1) {
if (element == null) break;
if (element.id == "container") return true;
element = element.parentNode;
}
return false;
};
Neo.Painter.prototype.cancelTool = function (e) {
if (this.tool) {
this.isMouseDown = false;
this.tool.upHandler(this);
// switch (this.tool.type) {
// case Neo.Painter.TOOLTYPE_HAND:
// case Neo.Painter.TOOLTYPE_SLIDER:
// this.isMouseDown = false;
// this.tool.upHandler(this);
// }
}
};
Neo.Painter.prototype.loadImage = function (filename) {
console.log("loadImage " + filename);
var img = new Image();
img.src = filename;
img.onload = function () {
var oe = Neo.painter;
oe.canvasCtx[0].drawImage(img, 0, 0);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
};
};
Neo.Painter.prototype.loadAnimation = function (filename) {
console.log("loadAnimation " + filename);
Neo.painter.busy = true;
Neo.painter.busySkipped = false;
Neo.getPCH(filename, function (pch) {
//console.log(pch);
Neo.painter._actionMgr._items = pch.data;
Neo.painter._actionMgr._mark = pch.data.length;
Neo.painter._actionMgr.play();
});
};
Neo.Painter.prototype.loadSession = function (callback) {
if (Neo.storage) {
var img0 = new Image();
img0.src = Neo.storage.getItem("layer0");
img0.onload = function () {
var img1 = new Image();
img1.src = Neo.storage.getItem("layer1");
img1.onload = function () {
var oe = Neo.painter;
oe.canvasCtx[0].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.canvasCtx[1].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.canvasCtx[0].drawImage(img0, 0, 0);
oe.canvasCtx[1].drawImage(img1, 0, 0);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
if (callback) callback();
};
};
}
};
Neo.Painter.prototype.saveSession = function () {
if (Neo.storage) {
Neo.storage.setItem("timestamp", +new Date());
Neo.storage.setItem("layer0", this.canvas[0].toDataURL("image/png"));
Neo.storage.setItem("layer1", this.canvas[1].toDataURL("image/png"));
}
};
Neo.Painter.prototype.clearSession = function () {
if (Neo.storage) {
Neo.storage.removeItem("timestamp");
Neo.storage.removeItem("layer0");
Neo.storage.removeItem("layer1");
}
};
Neo.Painter.prototype.sortColor = function (r0, g0, b0) {
var min = r0 < g0 ? (r0 < b0 ? 0 : 2) : g0 < b0 ? 1 : 2;
var max = r0 > g0 ? (r0 > b0 ? 0 : 2) : g0 > b0 ? 1 : 2;
var mid = min + max == 1 ? 2 : min + max == 2 ? 1 : 0;
return [min, mid, max];
};
Neo.Painter.prototype.doText = function (
layer,
x,
y,
color,
alpha,
string,
fontSize,
fontFamily
) {
//テキスト描画
if (string.length <= 0) return;
//描画位置がずれるので適当に調整
var offset = parseInt(fontSize, 10);
var ctx = this.tempCanvasCtx;
ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
ctx.save();
ctx.translate(x, y);
ctx.font = fontSize + " " + fontFamily;
ctx.fillStyle = 0;
ctx.fillText(string, 0, 0);
ctx.restore();
// 適当に二値化
var r = color & 0xff;
var g = (color & 0xff00) >> 8;
var b = (color & 0xff0000) >> 16;
var a = Math.round(alpha * 255.0);
var imageData = ctx.getImageData(0, 0, this.canvasWidth, this.canvasHeight);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var length = this.canvasWidth * this.canvasHeight;
var index = 0;
for (var i = 0; i < length; i++) {
if (buf8[index + 3] >= 0x60) {
buf8[index + 0] = r;
buf8[index + 1] = g;
buf8[index + 2] = b;
buf8[index + 3] = a;
} else {
buf8[index + 0] = 0;
buf8[index + 1] = 0;
buf8[index + 2] = 0;
buf8[index + 3] = 0;
}
index += 4;
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
//キャンバスに貼り付け
ctx = this.canvasCtx[layer];
ctx.globalAlpha = 1.0;
ctx.drawImage(
this.tempCanvas,
0,
0,
this.canvasWidth,
this.canvasHeight,
0,
0,
this.canvasWidth,
this.canvasHeight
);
this.tempCanvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
};
Neo.Painter.prototype.isUIPaused = function () {
if (this.drawType == Neo.Painter.DRAWTYPE_BEZIER) {
if (this.tool.step && this.tool.step > 0) {
return true;
}
}
return false;
};
Neo.Painter.prototype.getEmulationMode = function () {
return parseFloat(Neo.config.neo_emulation_mode || 2.22);
};
/*
-------------------------------------------------------------------------
Recorder Test
-------------------------------------------------------------------------
*/
Neo.Painter.prototype.play = function (wait) {
if (this._actionMgr) {
this._actionMgr.clearCanvas();
this.prevLine = null;
//console.log('[play]');
this._actionMgr._head = 0;
this._actionMgr._index = 0;
this._actionMgr._mark = this._actionMgr._items.length;
this._actionMgr._pause = false;
this._actionMgr.play(wait);
}
};
Neo.Painter.prototype.onrewind = function () {
if (this._actionMgr) {
this._actionMgr.clearCanvas();
this._actionMgr._head = 0;
this._actionMgr._index = 0;
this.prevLine = null;
}
if (Neo.viewerBar) Neo.viewerBar.update();
if (!this._actionMgr._pause) {
this._actionMgr.play();
}
};
Neo.Painter.prototype.onmark = function () {
if (Neo.viewerBar) Neo.viewerBar.update();
if (!this._actionMgr._pause) {
if (this._actionMgr._head > this._actionMgr._mark) {
this.onrewind();
} else {
this.onplay();
}
}
};
Neo.Painter.prototype.onplay = function () {
Neo.viewerPlay.setSelected(true);
Neo.viewerStop.setSelected(false);
this._actionMgr._pause = false;
this._actionMgr.play();
};
Neo.Painter.prototype.onstop = function () {
Neo.viewerPlay.setSelected(false);
Neo.viewerStop.setSelected(true);
this._actionMgr._pause = true;
};
Neo.Painter.prototype.onspeed = function () {
var mgr = Neo.painter._actionMgr;
var mode = (mgr._speedMode + 1) % 4;
mgr._speedMode = mode;
mgr._speed = mgr._speedTable[mode];
// console.log('speed=', mgr._speed);
};
Neo.Painter.prototype.setCurrent = function (item) {
var color = this._currentColor;
var mask = this._currentMask;
var width = this._currentWidth;
var type = this._currentMaskType;
item.push(color[0], color[1], color[2], color[3]);
item.push(mask[0], mask[1], mask[2]);
item.push(width);
item.push(type);
};
Neo.Painter.prototype.getCurrent = function (item) {
this._currentColor = [item[2], item[3], item[4], item[5]];
this._currentMask = [item[6], item[7], item[8]];
this._currentWidth = item[9];
this._currentMaskType = item[10];
};
Neo.Painter.prototype.isDirty = function () {
return this.dirty;
};
"use strict";
Neo.ToolBase = function () {};
Neo.ToolBase.prototype.startX;
Neo.ToolBase.prototype.startY;
Neo.ToolBase.prototype.init = function (oe) {};
Neo.ToolBase.prototype.kill = function (oe) {};
Neo.ToolBase.prototype.lineType = Neo.Painter.LINETYPE_NONE;
Neo.ToolBase.prototype.downHandler = function (oe) {
this.startX = oe.mouseX;
this.startY = oe.mouseY;
};
Neo.ToolBase.prototype.upHandler = function (oe) {};
Neo.ToolBase.prototype.moveHandler = function (oe) {};
Neo.ToolBase.prototype.transformForZoom = function (oe) {
var ctx = oe.destCanvasCtx;
ctx.translate(oe.canvasWidth * 0.5, oe.canvasHeight * 0.5);
ctx.scale(oe.zoom, oe.zoom);
ctx.translate(-oe.zoomX, -oe.zoomY);
};
Neo.ToolBase.prototype.getType = function () {
return this.type;
};
Neo.ToolBase.prototype.getToolButton = function () {
switch (this.type) {
case Neo.Painter.TOOLTYPE_PEN:
case Neo.Painter.TOOLTYPE_BRUSH:
case Neo.Painter.TOOLTYPE_TEXT:
return Neo.penTip;
case Neo.Painter.TOOLTYPE_TONE:
case Neo.Painter.TOOLTYPE_BLUR:
case Neo.Painter.TOOLTYPE_DODGE:
case Neo.Painter.TOOLTYPE_BURN:
return Neo.pen2Tip;
case Neo.Painter.TOOLTYPE_RECT:
case Neo.Painter.TOOLTYPE_RECTFILL:
case Neo.Painter.TOOLTYPE_ELLIPSE:
case Neo.Painter.TOOLTYPE_ELLIPSEFILL:
return Neo.effectTip;
case Neo.Painter.TOOLTYPE_COPY:
case Neo.Painter.TOOLTYPE_MERGE:
case Neo.Painter.TOOLTYPE_BLURRECT:
case Neo.Painter.TOOLTYPE_FLIP_H:
case Neo.Painter.TOOLTYPE_FLIP_V:
case Neo.Painter.TOOLTYPE_TURN:
return Neo.effect2Tip;
case Neo.Painter.TOOLTYPE_ERASER:
case Neo.Painter.TOOLTYPE_ERASEALL:
case Neo.Painter.TOOLTYPE_ERASERECT:
return Neo.eraserTip;
case Neo.Painter.TOOLTYPE_FILL:
return Neo.fillButton;
}
return null;
};
Neo.ToolBase.prototype.getReserve = function () {
switch (this.type) {
case Neo.Painter.TOOLTYPE_ERASER:
return Neo.reserveEraser;
case Neo.Painter.TOOLTYPE_PEN:
case Neo.Painter.TOOLTYPE_BRUSH:
case Neo.Painter.TOOLTYPE_TONE:
case Neo.Painter.TOOLTYPE_ERASERECT:
case Neo.Painter.TOOLTYPE_ERASEALL:
case Neo.Painter.TOOLTYPE_COPY:
case Neo.Painter.TOOLTYPE_MERGE:
case Neo.Painter.TOOLTYPE_FIP_H:
case Neo.Painter.TOOLTYPE_FIP_V:
case Neo.Painter.TOOLTYPE_DODGE:
case Neo.Painter.TOOLTYPE_BURN:
case Neo.Painter.TOOLTYPE_BLUR:
case Neo.Painter.TOOLTYPE_BLURRECT:
case Neo.Painter.TOOLTYPE_TEXT:
case Neo.Painter.TOOLTYPE_TURN:
case Neo.Painter.TOOLTYPE_RECT:
case Neo.Painter.TOOLTYPE_RECTFILL:
case Neo.Painter.TOOLTYPE_ELLIPSE:
case Neo.Painter.TOOLTYPE_ELLIPSEFILL:
return Neo.reservePen;
}
return null;
};
Neo.ToolBase.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.updateUI();
}
};
Neo.ToolBase.prototype.saveStates = function () {
var reserve = this.getReserve();
if (reserve) {
reserve.size = Neo.painter.lineWidth;
}
};
/*
-------------------------------------------------------------------------
DrawToolBase(描画ツールのベースクラス)
-------------------------------------------------------------------------
*/
Neo.DrawToolBase = function () {};
Neo.DrawToolBase.prototype = new Neo.ToolBase();
Neo.DrawToolBase.prototype.isUpMove = false;
Neo.DrawToolBase.prototype.step = 0;
Neo.DrawToolBase.prototype.init = function () {
this.step = 0;
this.isUpMove = true;
};
Neo.DrawToolBase.prototype.downHandler = function (oe) {
switch (oe.drawType) {
case Neo.Painter.DRAWTYPE_FREEHAND:
this.freeHandDownHandler(oe);
break;
case Neo.Painter.DRAWTYPE_LINE:
this.lineDownHandler(oe);
break;
case Neo.Painter.DRAWTYPE_BEZIER:
this.bezierDownHandler(oe);
break;
}
};
Neo.DrawToolBase.prototype.upHandler = function (oe) {
switch (oe.drawType) {
case Neo.Painter.DRAWTYPE_FREEHAND:
this.freeHandUpHandler(oe);
break;
case Neo.Painter.DRAWTYPE_LINE:
this.lineUpHandler(oe);
break;
case Neo.Painter.DRAWTYPE_BEZIER:
this.bezierUpHandler(oe);
break;
}
};
Neo.DrawToolBase.prototype.moveHandler = function (oe) {
switch (oe.drawType) {
case Neo.Painter.DRAWTYPE_FREEHAND:
this.freeHandMoveHandler(oe);
break;
case Neo.Painter.DRAWTYPE_LINE:
this.lineMoveHandler(oe);
break;
case Neo.Painter.DRAWTYPE_BEZIER:
this.bezierMoveHandler(oe);
break;
}
};
Neo.DrawToolBase.prototype.upMoveHandler = function (oe) {
switch (oe.drawType) {
case Neo.Painter.DRAWTYPE_FREEHAND:
this.freeHandUpMoveHandler(oe);
break;
case Neo.Painter.DRAWTYPE_LINE:
this.lineUpMoveHandler(oe);
break;
case Neo.Painter.DRAWTYPE_BEZIER:
this.bezierUpMoveHandler(oe);
break;
}
};
Neo.DrawToolBase.prototype.keyDownHandler = function (e) {
switch (Neo.painter.drawType) {
case Neo.Painter.DRAWTYPE_BEZIER:
this.bezierKeyDownHandler(e);
break;
}
};
Neo.DrawToolBase.prototype.rollOverHandler = function (oe) {};
Neo.DrawToolBase.prototype.rollOutHandler = function (oe) {
if (!oe.isMouseDown && !oe.isMouseDownRight) {
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
}
};
Neo.DrawToolBase.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 1.0;
Neo.updateUI();
}
};
/* FreeHand (手書き) */
Neo.DrawToolBase.prototype.freeHandDownHandler = function (oe) {
//Register undo first;
oe._pushUndo();
oe.prepareDrawing();
this.isUpMove = false;
var ctx = oe.canvasCtx[oe.current];
if (oe.alpha >= 1 || this.lineType != Neo.Painter.LINETYPE_BRUSH) {
var x0 = Math.floor(oe.mouseX);
var y0 = Math.floor(oe.mouseY);
oe._actionMgr.freeHand(x0, y0, this.lineType);
// oe.drawLine(ctx, x0, y0, x0, y0, this.lineType);
}
if (oe.cursorRect) {
var rect = oe.cursorRect;
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
oe.cursorRect = null;
}
if (oe.alpha >= 1) {
var r = Math.ceil(oe.lineWidth / 2);
var rect = oe.getBound(oe.mouseX, oe.mouseY, oe.mouseX, oe.mouseY, r);
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
}
};
Neo.DrawToolBase.prototype.freeHandUpHandler = function (oe) {
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
if (oe.cursorRect) {
var rect = oe.cursorRect;
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
oe.cursorRect = null;
}
// oe.updateDestCanvas(0,0,oe.canvasWidth, oe.canvasHeight, true);
// this.drawCursor(oe);
oe.prevLine = null;
};
Neo.DrawToolBase.prototype.freeHandMoveHandler = function (oe) {
var ctx = oe.canvasCtx[oe.current];
var x0 = Math.floor(oe.mouseX);
var y0 = Math.floor(oe.mouseY);
var x1 = Math.floor(oe.prevMouseX);
var y1 = Math.floor(oe.prevMouseY);
// oe.drawLine(ctx, x0, y0, x1, y1, this.lineType);
oe._actionMgr.freeHandMove(x0, y0, x1, y1, this.lineType);
if (oe.cursorRect) {
var rect = oe.cursorRect;
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
oe.cursorRect = null;
}
var r = Math.ceil(oe.lineWidth / 2);
var rect = oe.getBound(oe.mouseX, oe.mouseY, oe.prevMouseX, oe.prevMouseY, r);
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
};
Neo.DrawToolBase.prototype.freeHandUpMoveHandler = function (oe) {
this.isUpMove = true;
if (oe.cursorRect) {
var rect = oe.cursorRect;
oe.updateDestCanvas(rect[0], rect[1], rect[2], rect[3], true);
oe.cursorRect = null;
}
this.drawCursor(oe);
};
Neo.DrawToolBase.prototype.drawCursor = function (oe) {
if (oe.lineWidth <= 8) return;
var mx = oe.mouseX;
var my = oe.mouseY;
var d = oe.lineWidth;
var x = (mx - oe.zoomX + (oe.destCanvas.width * 0.5) / oe.zoom) * oe.zoom;
var y = (my - oe.zoomY + (oe.destCanvas.height * 0.5) / oe.zoom) * oe.zoom;
var r = d * 0.5 * oe.zoom;
if (
!(
x > -r &&
y > -r &&
x < oe.destCanvas.width + r &&
y < oe.destCanvas.height + r
)
)
return;
var ctx = oe.destCanvasCtx;
ctx.save();
this.transformForZoom(oe);
var c = this.type == Neo.Painter.TOOLTYPE_ERASER ? 0x0000ff : 0xffff7f;
oe.drawXOREllipse(ctx, x - r, y - r, r * 2, r * 2, false, c);
ctx.restore();
oe.cursorRect = oe.getBound(mx, my, mx, my, Math.ceil(d / 2));
};
/* Line (直線) */
Neo.DrawToolBase.prototype.lineDownHandler = function (oe) {
this.isUpMove = false;
this.startX = Math.floor(oe.mouseX);
this.startY = Math.floor(oe.mouseY);
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
};
Neo.DrawToolBase.prototype.lineUpHandler = function (oe) {
if (this.isUpMove == false) {
this.isUpMove = true;
oe._pushUndo();
oe.prepareDrawing();
var x0 = Math.floor(oe.mouseX);
var y0 = Math.floor(oe.mouseY);
oe._actionMgr.line(x0, y0, this.startX, this.startY, this.lineType);
/*
var ctx = oe.canvasCtx[oe.current];
var x0 = Math.floor(oe.mouseX);
var y0 = Math.floor(oe.mouseY);
oe.drawLine(ctx, x0, y0, this.startX, this.startY, this.lineType);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
*/
}
};
Neo.DrawToolBase.prototype.lineMoveHandler = function (oe) {
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
this.drawLineCursor(oe);
};
Neo.DrawToolBase.prototype.lineUpMoveHandler = function (oe) {};
Neo.DrawToolBase.prototype.drawLineCursor = function (oe, mx, my) {
if (!mx) mx = Math.floor(oe.mouseX);
if (!my) my = Math.floor(oe.mouseY);
var nx = this.startX;
var ny = this.startY;
var ctx = oe.destCanvasCtx;
ctx.save();
this.transformForZoom(oe);
var x0 =
(mx + 0.499 - oe.zoomX + (oe.destCanvas.width * 0.5) / oe.zoom) * oe.zoom;
var y0 =
(my + 0.499 - oe.zoomY + (oe.destCanvas.height * 0.5) / oe.zoom) * oe.zoom;
var x1 =
(nx + 0.499 - oe.zoomX + (oe.destCanvas.width * 0.5) / oe.zoom) * oe.zoom;
var y1 =
(ny + 0.499 - oe.zoomY + (oe.destCanvas.height * 0.5) / oe.zoom) * oe.zoom;
oe.drawXORLine(ctx, x0, y0, x1, y1);
ctx.restore();
};
/* Bezier (BZ曲線) */
Neo.DrawToolBase.prototype.bezierDownHandler = function (oe) {
this.isUpMove = false;
if (this.step == 0) {
this.startX = this.x0 = Math.floor(oe.mouseX);
this.startY = this.y0 = Math.floor(oe.mouseY);
}
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
};
Neo.DrawToolBase.prototype.bezierUpHandler = function (oe) {
if (this.isUpMove == false) {
this.isUpMove = true;
} else return; // 枠外からベジェを開始したときdownを通らずにupが呼ばれてエラーになる
this.step++;
switch (this.step) {
case 1:
oe.prepareDrawing();
this.x3 = Math.floor(oe.mouseX);
this.y3 = Math.floor(oe.mouseY);
break;
case 2:
this.x1 = Math.floor(oe.mouseX);
this.y1 = Math.floor(oe.mouseY);
break;
case 3:
this.x2 = Math.floor(oe.mouseX);
this.y2 = Math.floor(oe.mouseY);
oe._pushUndo();
oe._actionMgr.bezier(
this.x0,
this.y0,
this.x1,
this.y1,
this.x2,
this.y2,
this.x3,
this.y3,
this.lineType
);
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
/*oe.drawBezier(oe.canvasCtx[oe.current],
this.x0, this.y0, this.x1, this.y1,
this.x2, this.y2, this.x3, this.y3, this.lineType);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);*/
this.step = 0;
break;
default:
this.step = 0;
break;
}
};
Neo.DrawToolBase.prototype.bezierMoveHandler = function (oe) {
switch (this.step) {
case 0:
if (!this.isUpMove) {
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, false);
this.drawLineCursor(oe);
}
break;
case 1:
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, false);
this.drawBezierCursor1(oe);
break;
case 2:
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, false);
this.drawBezierCursor2(oe);
break;
}
};
Neo.DrawToolBase.prototype.bezierUpMoveHandler = function (oe) {
this.bezierMoveHandler(oe);
};
Neo.DrawToolBase.prototype.bezierKeyDownHandler = function (e) {
if (e.keyCode == 27) {
//Escでキャンセル
this.step = 0;
var oe = Neo.painter;
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
}
};
Neo.DrawToolBase.prototype.drawBezierCursor1 = function (oe) {
var ctx = oe.destCanvasCtx;
var x = oe.mouseX; //Math.floor(oe.mouseX);
var y = oe.mouseY; //Math.floor(oe.mouseY);
/*
var stab = oe.getStabilized();
var x = Math.floor(stab[0]);
var y = Math.floor(stab[1]);
*/
var p = oe.getDestCanvasPosition(x, y, false, true);
var p0 = oe.getDestCanvasPosition(this.x0, this.y0, false, true);
var p3 = oe.getDestCanvasPosition(this.x3, this.y3, false, true);
// handle
oe.drawXORLine(ctx, p0.x, p0.y, p.x, p.y);
oe.drawXOREllipse(ctx, p.x - 4, p.y - 4, 8, 8);
oe.drawXOREllipse(ctx, p0.x - 4, p0.y - 4, 8, 8);
// preview
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.drawBezier(
oe.tempCanvasCtx,
this.x0,
this.y0,
x,
y,
x,
y,
this.x3,
this.y3,
Neo.Painter.LINETYPE_PEN, //this.lineType,
false,
true
);
ctx.save();
ctx.translate(oe.destCanvas.width * 0.5, oe.destCanvas.height * 0.5);
ctx.scale(oe.zoom, oe.zoom);
ctx.translate(-oe.zoomX, -oe.zoomY);
ctx.drawImage(
oe.tempCanvas,
0,
0,
oe.canvasWidth,
oe.canvasHeight,
0,
0,
oe.canvasWidth,
oe.canvasHeight
);
ctx.restore();
};
Neo.DrawToolBase.prototype.drawBezierCursor2 = function (oe) {
var ctx = oe.destCanvasCtx;
var x = oe.mouseX; //Math.floor(oe.mouseX);
var y = oe.mouseY; //Math.floor(oe.mouseY);
/*
var stab = oe.getStabilized();
var x = Math.floor(stab[0]);
var y = Math.floor(stab[1]);
*/
var p = oe.getDestCanvasPosition(oe.mouseX, oe.mouseY, false, true);
var p0 = oe.getDestCanvasPosition(this.x0, this.y0, false, true);
var p1 = oe.getDestCanvasPosition(this.x1, this.y1, false, true);
var p3 = oe.getDestCanvasPosition(this.x3, this.y3, false, true);
// handle
oe.drawXORLine(ctx, p3.x, p3.y, p.x, p.y);
oe.drawXOREllipse(ctx, p.x - 4, p.y - 4, 8, 8);
oe.drawXORLine(ctx, p0.x, p0.y, p1.x, p1.y);
oe.drawXOREllipse(ctx, p1.x - 4, p1.y - 4, 8, 8);
oe.drawXOREllipse(ctx, p0.x - 4, p0.y - 4, 8, 8);
// preview
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.drawBezier(
oe.tempCanvasCtx,
this.x0,
this.y0,
this.x1,
this.y1,
x,
y,
this.x3,
this.y3,
Neo.Painter.LINETYPE_PEN, //this.lineType,
false,
true
);
ctx.save();
ctx.translate(oe.destCanvas.width * 0.5, oe.destCanvas.height * 0.5);
ctx.scale(oe.zoom, oe.zoom);
ctx.translate(-oe.zoomX, -oe.zoomY);
ctx.drawImage(
oe.tempCanvas,
0,
0,
oe.canvasWidth,
oe.canvasHeight,
0,
0,
oe.canvasWidth,
oe.canvasHeight
);
ctx.restore();
};
/*
-------------------------------------------------------------------------
Pen(鉛筆)
-------------------------------------------------------------------------
*/
Neo.PenTool = function () {};
Neo.PenTool.prototype = new Neo.DrawToolBase();
Neo.PenTool.prototype.type = Neo.Painter.TOOLTYPE_PEN;
Neo.PenTool.prototype.lineType = Neo.Painter.LINETYPE_PEN;
Neo.PenTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 1.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Brush(水彩)
-------------------------------------------------------------------------
*/
Neo.BrushTool = function () {};
Neo.BrushTool.prototype = new Neo.DrawToolBase();
Neo.BrushTool.prototype.type = Neo.Painter.TOOLTYPE_BRUSH;
Neo.BrushTool.prototype.lineType = Neo.Painter.LINETYPE_BRUSH;
Neo.BrushTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = this.getAlpha();
Neo.updateUI();
}
};
Neo.BrushTool.prototype.getAlpha = function () {
var alpha = 241 - Math.floor(Neo.painter.lineWidth / 2) * 6;
return alpha / 255.0;
};
/*
-------------------------------------------------------------------------
Tone(トーン)
-------------------------------------------------------------------------
*/
Neo.ToneTool = function () {};
Neo.ToneTool.prototype = new Neo.DrawToolBase();
Neo.ToneTool.prototype.type = Neo.Painter.TOOLTYPE_TONE;
Neo.ToneTool.prototype.lineType = Neo.Painter.LINETYPE_TONE;
Neo.ToneTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 23 / 255.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Eraser(消しペン)
-------------------------------------------------------------------------
*/
Neo.EraserTool = function () {};
Neo.EraserTool.prototype = new Neo.DrawToolBase();
Neo.EraserTool.prototype.type = Neo.Painter.TOOLTYPE_ERASER;
Neo.EraserTool.prototype.lineType = Neo.Painter.LINETYPE_ERASER;
/*
-------------------------------------------------------------------------
Blur(ぼかし)
-------------------------------------------------------------------------
*/
Neo.BlurTool = function () {};
Neo.BlurTool.prototype = new Neo.DrawToolBase();
Neo.BlurTool.prototype.type = Neo.Painter.TOOLTYPE_BLUR;
Neo.BlurTool.prototype.lineType = Neo.Painter.LINETYPE_BLUR;
Neo.BlurTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 128 / 255.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Dodge(覆い焼き)
-------------------------------------------------------------------------
*/
Neo.DodgeTool = function () {};
Neo.DodgeTool.prototype = new Neo.DrawToolBase();
Neo.DodgeTool.prototype.type = Neo.Painter.TOOLTYPE_DODGE;
Neo.DodgeTool.prototype.lineType = Neo.Painter.LINETYPE_DODGE;
Neo.DodgeTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 128 / 255.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Burn(焼き込み)
-------------------------------------------------------------------------
*/
Neo.BurnTool = function () {};
Neo.BurnTool.prototype = new Neo.DrawToolBase();
Neo.BurnTool.prototype.type = Neo.Painter.TOOLTYPE_BURN;
Neo.BurnTool.prototype.lineType = Neo.Painter.LINETYPE_BURN;
Neo.BurnTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 128 / 255.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Hand(スクロール)
-------------------------------------------------------------------------
*/
Neo.HandTool = function () {};
Neo.HandTool.prototype = new Neo.ToolBase();
Neo.HandTool.prototype.type = Neo.Painter.TOOLTYPE_HAND;
Neo.HandTool.prototype.isUpMove = false;
Neo.HandTool.prototype.reverse = false;
Neo.HandTool.prototype.downHandler = function (oe) {
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
this.isDrag = true;
this.startX = oe.rawMouseX;
this.startY = oe.rawMouseY;
};
Neo.HandTool.prototype.upHandler = function (oe) {
this.isDrag = false;
oe.popTool();
};
Neo.HandTool.prototype.moveHandler = function (oe) {
if (this.isDrag) {
var dx = this.startX - oe.rawMouseX;
var dy = this.startY - oe.rawMouseY;
var ax = oe.destCanvas.width / (oe.canvasWidth * oe.zoom);
var ay = oe.destCanvas.height / (oe.canvasHeight * oe.zoom);
var barWidth = oe.destCanvas.width * ax;
var barHeight = oe.destCanvas.height * ay;
var scrollWidthInScreen = oe.destCanvas.width - barWidth - 2;
var scrollHeightInScreen = oe.destCanvas.height - barHeight - 2;
dx *= oe.scrollWidth / scrollWidthInScreen;
dy *= oe.scrollHeight / scrollHeightInScreen;
if (this.reverse) {
dx *= -1;
dy *= -1;
}
oe.setZoomPosition(oe.zoomX - dx, oe.zoomY - dy);
this.startX = oe.rawMouseX;
this.startY = oe.rawMouseY;
}
};
Neo.HandTool.prototype.upMoveHandler = function (oe) {};
Neo.HandTool.prototype.rollOverHandler = function (oe) {};
Neo.HandTool.prototype.rollOutHandler = function (oe) {};
/*
-------------------------------------------------------------------------
Slider(色やサイズのスライダを操作している時)
-------------------------------------------------------------------------
*/
Neo.SliderTool = function () {};
Neo.SliderTool.prototype = new Neo.ToolBase();
Neo.SliderTool.prototype.type = Neo.Painter.TOOLTYPE_SLIDER;
Neo.SliderTool.prototype.isUpMove = false;
Neo.SliderTool.prototype.alt = false;
Neo.SliderTool.prototype.downHandler = function (oe) {
if (!oe.isShiftDown) this.isDrag = true;
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
var rect = this.target.getBoundingClientRect();
var sliderType = this.alt ? Neo.SLIDERTYPE_SIZE : this.target["data-slider"];
Neo.sliders[sliderType].downHandler(
oe.rawMouseX - rect.left,
oe.rawMouseY - rect.top
);
};
Neo.SliderTool.prototype.upHandler = function (oe) {
this.isDrag = false;
oe.popTool();
var rect = this.target.getBoundingClientRect();
var sliderType = this.alt ? Neo.SLIDERTYPE_SIZE : this.target["data-slider"];
Neo.sliders[sliderType].upHandler(
oe.rawMouseX - rect.left,
oe.rawMouseY - rect.top
);
};
Neo.SliderTool.prototype.moveHandler = function (oe) {
if (this.isDrag) {
var rect = this.target.getBoundingClientRect();
var sliderType = this.alt
? Neo.SLIDERTYPE_SIZE
: this.target["data-slider"];
Neo.sliders[sliderType].moveHandler(
oe.rawMouseX - rect.left,
oe.rawMouseY - rect.top
);
}
};
Neo.SliderTool.prototype.upMoveHandler = function (oe) {};
Neo.SliderTool.prototype.rollOverHandler = function (oe) {};
Neo.SliderTool.prototype.rollOutHandler = function (oe) {};
/*
-------------------------------------------------------------------------
Fill(塗り潰し)
-------------------------------------------------------------------------
*/
Neo.FillTool = function () {};
Neo.FillTool.prototype = new Neo.ToolBase();
Neo.FillTool.prototype.type = Neo.Painter.TOOLTYPE_FILL;
Neo.FillTool.prototype.isUpMove = false;
Neo.FillTool.prototype.downHandler = function (oe) {
var x = Math.floor(oe.mouseX);
var y = Math.floor(oe.mouseY);
var layer = oe.current;
var color = oe.getColor();
oe._pushUndo();
oe._actionMgr.floodFill(layer, x, y, color);
//oe.doFloodFill(layer, x, y, color);
};
Neo.FillTool.prototype.upHandler = function (oe) {};
Neo.FillTool.prototype.moveHandler = function (oe) {};
Neo.FillTool.prototype.rollOutHandler = function (oe) {};
Neo.FillTool.prototype.upMoveHandler = function (oe) {};
Neo.FillTool.prototype.rollOverHandler = function (oe) {};
/*
-------------------------------------------------------------------------
EraseAll(全消し)
-------------------------------------------------------------------------
*/
Neo.EraseAllTool = function () {};
Neo.EraseAllTool.prototype = new Neo.ToolBase();
Neo.EraseAllTool.prototype.type = Neo.Painter.TOOLTYPE_ERASEALL;
Neo.EraseAllTool.prototype.isUpMove = false;
Neo.EraseAllTool.prototype.downHandler = function (oe) {
oe._pushUndo();
oe._actionMgr.eraseAll();
/*oe.prepareDrawing();
oe.canvasCtx[oe.current].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);*/
};
Neo.EraseAllTool.prototype.upHandler = function (oe) {};
Neo.EraseAllTool.prototype.moveHandler = function (oe) {};
Neo.EraseAllTool.prototype.rollOutHandler = function (oe) {};
Neo.EraseAllTool.prototype.upMoveHandler = function (oe) {};
Neo.EraseAllTool.prototype.rollOverHandler = function (oe) {};
/*
-------------------------------------------------------------------------
EffectToolBase(エフェックトツールのベースクラス)
-------------------------------------------------------------------------
*/
Neo.EffectToolBase = function () {};
Neo.EffectToolBase.prototype = new Neo.ToolBase();
Neo.EffectToolBase.prototype.isUpMove = false;
Neo.EffectToolBase.prototype.downHandler = function (oe) {
this.isUpMove = false;
this.startX = this.endX = oe.clipMouseX;
this.startY = this.endY = oe.clipMouseY;
};
Neo.EffectToolBase.prototype.upHandler = function (oe) {
if (this.isUpMove) return;
this.isUpMove = true;
this.startX = Math.floor(this.startX);
this.startY = Math.floor(this.startY);
this.endX = Math.floor(this.endX);
this.endY = Math.floor(this.endY);
var x = this.startX < this.endX ? this.startX : this.endX;
var y = this.startY < this.endY ? this.startY : this.endY;
var width = Math.abs(this.startX - this.endX) + 1;
var height = Math.abs(this.startY - this.endY) + 1;
var ctx = oe.canvasCtx[oe.current];
if (x < 0) x = 0;
if (y < 0) y = 0;
if (x + width > oe.canvasWidth) width = oe.canvasWidth - x;
if (y + height > oe.canvasHeight) height = oe.canvasHeight - y;
if (width > 0 && height > 0) {
oe._pushUndo();
oe.prepareDrawing();
this.doEffect(oe, x, y, width, height);
}
if (oe.tool.type != Neo.Painter.TOOLTYPE_PASTE) {
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
}
};
Neo.EffectToolBase.prototype.moveHandler = function (oe) {
this.endX = oe.clipMouseX;
this.endY = oe.clipMouseY;
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
this.drawCursor(oe);
};
Neo.EffectToolBase.prototype.rollOutHandler = function (oe) {};
Neo.EffectToolBase.prototype.upMoveHandler = function (oe) {};
Neo.EffectToolBase.prototype.rollOverHandler = function (oe) {};
Neo.EffectToolBase.prototype.drawCursor = function (oe) {
var ctx = oe.destCanvasCtx;
ctx.save();
this.transformForZoom(oe);
var start = oe.getDestCanvasPosition(this.startX, this.startY, true);
var end = oe.getDestCanvasPosition(this.endX, this.endY, true);
var x = start.x < end.x ? start.x : end.x;
var y = start.y < end.y ? start.y : end.y;
var width = Math.abs(start.x - end.x) + oe.zoom;
var height = Math.abs(start.y - end.y) + oe.zoom;
if (this.isEllipse) {
oe.drawXOREllipse(ctx, x, y, width, height, this.isFill);
} else {
oe.drawXORRect(ctx, x, y, width, height, this.isFill);
}
ctx.restore();
};
Neo.EffectToolBase.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = this.defaultAlpha || 1.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
EraseRect(消し四角)
-------------------------------------------------------------------------
*/
Neo.EraseRectTool = function () {};
Neo.EraseRectTool.prototype = new Neo.EffectToolBase();
Neo.EraseRectTool.prototype.type = Neo.Painter.TOOLTYPE_ERASERECT;
Neo.EraseRectTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.eraseRect(ctx, x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.eraseRect2(x, y, width, height);
};
/*
-------------------------------------------------------------------------
FlipH(左右反転)
-------------------------------------------------------------------------
*/
Neo.FlipHTool = function () {};
Neo.FlipHTool.prototype = new Neo.EffectToolBase();
Neo.FlipHTool.prototype.type = Neo.Painter.TOOLTYPE_FLIP_H;
Neo.FlipHTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.flipH(ctx, x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.flipH(x, y, width, height);
};
/*
-------------------------------------------------------------------------
FlipV(上下反転)
-------------------------------------------------------------------------
*/
Neo.FlipVTool = function () {};
Neo.FlipVTool.prototype = new Neo.EffectToolBase();
Neo.FlipVTool.prototype.type = Neo.Painter.TOOLTYPE_FLIP_V;
Neo.FlipVTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.flipV(ctx, x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.flipV(x, y, width, height);
};
/*
-------------------------------------------------------------------------
DodgeRect(角取り)
-------------------------------------------------------------------------
*/
Neo.BlurRectTool = function () {};
Neo.BlurRectTool.prototype = new Neo.EffectToolBase();
Neo.BlurRectTool.prototype.type = Neo.Painter.TOOLTYPE_BLURRECT;
Neo.BlurRectTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.blurRect(ctx, x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.blurRect(x, y, width, height);
};
Neo.BlurRectTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 0.5;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Turn(傾け)
-------------------------------------------------------------------------
*/
Neo.TurnTool = function () {};
Neo.TurnTool.prototype = new Neo.EffectToolBase();
Neo.TurnTool.prototype.type = Neo.Painter.TOOLTYPE_TURN;
Neo.TurnTool.prototype.upHandler = function (oe) {
this.isUpMove = true;
this.startX = Math.floor(this.startX);
this.startY = Math.floor(this.startY);
this.endX = Math.floor(this.endX);
this.endY = Math.floor(this.endY);
var x = this.startX < this.endX ? this.startX : this.endX;
var y = this.startY < this.endY ? this.startY : this.endY;
var width = Math.abs(this.startX - this.endX) + 1;
var height = Math.abs(this.startY - this.endY) + 1;
if (width > 0 && height > 0) {
oe._pushUndo();
// oe.turn(x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.turn(x, y, width, height);
}
};
/*
-------------------------------------------------------------------------
Merge(レイヤー結合)
-------------------------------------------------------------------------
*/
Neo.MergeTool = function () {};
Neo.MergeTool.prototype = new Neo.EffectToolBase();
Neo.MergeTool.prototype.type = Neo.Painter.TOOLTYPE_MERGE;
Neo.MergeTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.merge(ctx, x, y, width, height);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.merge(x, y, width, height);
};
/*
-------------------------------------------------------------------------
Copy(コピー)
-------------------------------------------------------------------------
*/
Neo.CopyTool = function () {};
Neo.CopyTool.prototype = new Neo.EffectToolBase();
Neo.CopyTool.prototype.type = Neo.Painter.TOOLTYPE_COPY;
Neo.CopyTool.prototype.doEffect = function (oe, x, y, width, height) {
// oe.copy(oe.current, x, y, width, height);
oe._actionMgr.copy(x, y, width, height);
oe.setToolByType(Neo.Painter.TOOLTYPE_PASTE);
oe.tool.x = x;
oe.tool.y = y;
oe.tool.width = width;
oe.tool.height = height;
};
/*
-------------------------------------------------------------------------
Paste(ペースト)
-------------------------------------------------------------------------
*/
Neo.PasteTool = function () {};
Neo.PasteTool.prototype = new Neo.ToolBase();
Neo.PasteTool.prototype.type = Neo.Painter.TOOLTYPE_PASTE;
Neo.PasteTool.prototype.downHandler = function (oe) {
this.startX = oe.mouseX;
this.startY = oe.mouseY;
this.drawCursor(oe);
};
Neo.PasteTool.prototype.upHandler = function (oe) {
oe._pushUndo();
var dx = oe.tempX;
var dy = oe.tempY;
// oe.paste(oe.current, this.x, this.y, this.width, this.height, dx, dy);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.paste(this.x, this.y, this.width, this.height, dx, dy);
oe.setToolByType(Neo.Painter.TOOLTYPE_COPY);
};
Neo.PasteTool.prototype.moveHandler = function (oe) {
var dx = Math.floor(oe.mouseX - this.startX);
var dy = Math.floor(oe.mouseY - this.startY);
oe.tempX = dx;
oe.tempY = dy;
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
// this.drawCursor(oe);
};
Neo.PasteTool.prototype.keyDownHandler = function (e) {
if (e.keyCode == 27) {
//Escでキャンセル
var oe = Neo.painter;
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe.setToolByType(Neo.Painter.TOOLTYPE_COPY);
}
};
Neo.PasteTool.prototype.kill = function () {
var oe = Neo.painter;
oe.tempCanvasCtx.clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
};
Neo.PasteTool.prototype.drawCursor = function (oe) {
var ctx = oe.destCanvasCtx;
ctx.save();
this.transformForZoom(oe);
var start = oe.getDestCanvasPosition(this.x, this.y, true);
var end = oe.getDestCanvasPosition(
this.x + this.width,
this.y + this.height,
true
);
var x = start.x + oe.tempX * oe.zoom;
var y = start.y + oe.tempY * oe.zoom;
var width = Math.abs(start.x - end.x);
var height = Math.abs(start.y - end.y);
oe.drawXORRect(ctx, x, y, width, height);
ctx.restore();
};
/*
-------------------------------------------------------------------------
Rect(線四角)
-------------------------------------------------------------------------
*/
Neo.RectTool = function () {};
Neo.RectTool.prototype = new Neo.EffectToolBase();
Neo.RectTool.prototype.type = Neo.Painter.TOOLTYPE_RECT;
Neo.RectTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.doFill(ctx, x, y, width, height, this.type); //oe.rectMask);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.fill(x, y, width, height, this.type);
};
/*
-------------------------------------------------------------------------
RectFill(四角)
-------------------------------------------------------------------------
*/
Neo.RectFillTool = function () {};
Neo.RectFillTool.prototype = new Neo.EffectToolBase();
Neo.RectFillTool.prototype.type = Neo.Painter.TOOLTYPE_RECTFILL;
Neo.RectFillTool.prototype.isFill = true;
Neo.RectFillTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.doFill(ctx, x, y, width, height, this.type); //oe.rectFillMask);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.fill(x, y, width, height, this.type);
};
/*
-------------------------------------------------------------------------
Ellipse(線楕円)
-------------------------------------------------------------------------
*/
Neo.EllipseTool = function () {};
Neo.EllipseTool.prototype = new Neo.EffectToolBase();
Neo.EllipseTool.prototype.type = Neo.Painter.TOOLTYPE_ELLIPSE;
Neo.EllipseTool.prototype.isEllipse = true;
Neo.EllipseTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.doFill(ctx, x, y, width, height, this.type); //oe.ellipseMask);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.fill(x, y, width, height, this.type);
};
/*
-------------------------------------------------------------------------
EllipseFill(楕円)
-------------------------------------------------------------------------
*/
Neo.EllipseFillTool = function () {};
Neo.EllipseFillTool.prototype = new Neo.EffectToolBase();
Neo.EllipseFillTool.prototype.type = Neo.Painter.TOOLTYPE_ELLIPSEFILL;
Neo.EllipseFillTool.prototype.isEllipse = true;
Neo.EllipseFillTool.prototype.isFill = true;
Neo.EllipseFillTool.prototype.doEffect = function (oe, x, y, width, height) {
// var ctx = oe.canvasCtx[oe.current];
// oe.doFill(ctx, x, y, width, height, this.type); //oe.ellipseFillMask);
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
oe._actionMgr.fill(x, y, width, height, this.type);
};
/*
-------------------------------------------------------------------------
Text(テキスト)
-------------------------------------------------------------------------
*/
Neo.TextTool = function () {};
Neo.TextTool.prototype = new Neo.ToolBase();
Neo.TextTool.prototype.type = Neo.Painter.TOOLTYPE_TEXT;
Neo.TextTool.prototype.isUpMove = false;
Neo.TextTool.prototype.downHandler = function (oe) {
this.startX = oe.mouseX;
this.startY = oe.mouseY;
if (Neo.painter.inputText) {
Neo.painter.updateInputText();
var rect = oe.container.getBoundingClientRect();
var text = Neo.painter.inputText;
var x = oe.rawMouseX - rect.left - 5;
var y = oe.rawMouseY - rect.top - 5;
text.style.left = x + "px";
text.style.top = y + "px";
text.style.display = "block";
text.focus();
}
};
Neo.TextTool.prototype.upHandler = function (oe) {};
Neo.TextTool.prototype.moveHandler = function (oe) {};
Neo.TextTool.prototype.upMoveHandler = function (oe) {};
Neo.TextTool.prototype.rollOverHandler = function (oe) {};
Neo.TextTool.prototype.rollOutHandler = function (oe) {};
Neo.TextTool.prototype.keyDownHandler = function (e) {
if (e.keyCode == 13) {
// Returnで確定
e.preventDefault();
var oe = Neo.painter;
var text = oe.inputText;
if (text) {
oe._pushUndo();
//this.drawText(oe);
//oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
var string = text.textContent || text.innerText;
var size = text.style.fontSize;
var family = text.style.fontFamily || "Arial";
var layer = oe.current;
var color = oe.getColor();
var alpha = oe.alpha;
var x = this.startX;
var y = this.startY;
//oe.doText(layer, this.startX, this.startY, color, string, size, family);
oe._actionMgr.text(
this.startX,
this.startY,
color,
alpha,
string,
size,
family
);
text.style.display = "none";
text.blur();
}
}
};
Neo.TextTool.prototype.kill = function (oe) {
Neo.painter.hideInputText();
};
/*
Neo.TextTool.prototype.drawText = function(oe) {
var text = oe.inputText;
var string = text.textContent || text.innerText;
var size = text.style.fontSize;
var family = text.style.fontFamily || "Arial";
var layer = oe.current;
var color = oe.getColor();
var alpha = oe.alpha;
var x = this.startX;
var y = this.startY;
//oe.doText(layer, this.startX, this.startY, color, string, size, family);
oe._actionMgr.doText(layer, this.startX, this.startY,
color, alpha, string, size, family);
};
*/
Neo.TextTool.prototype.loadStates = function () {
var reserve = this.getReserve();
if (reserve) {
Neo.painter.lineWidth = reserve.size;
Neo.painter.alpha = 1.0;
Neo.updateUI();
}
};
/*
-------------------------------------------------------------------------
Dummy(何もしない時)
-------------------------------------------------------------------------
*/
Neo.DummyTool = function () {};
Neo.DummyTool.prototype = new Neo.ToolBase();
Neo.DummyTool.prototype.type = Neo.Painter.TOOLTYPE_NONE;
Neo.DummyTool.prototype.isUpMove = false;
Neo.DummyTool.prototype.downHandler = function (oe) {};
Neo.DummyTool.prototype.upHandler = function (oe) {
oe.popTool();
};
Neo.DummyTool.prototype.moveHandler = function (oe) {};
Neo.DummyTool.prototype.upMoveHandler = function (oe) {};
Neo.DummyTool.prototype.rollOverHandler = function (oe) {};
Neo.DummyTool.prototype.rollOutHandler = function (oe) {};
"use strict";
Neo.CommandBase = function () {};
Neo.CommandBase.prototype.data;
Neo.CommandBase.prototype.execute = function () {};
/*
---------------------------------------------------
ZOOM
---------------------------------------------------
*/
Neo.ZoomPlusCommand = function (data) {
this.data = data;
};
Neo.ZoomPlusCommand.prototype = new Neo.CommandBase();
Neo.ZoomPlusCommand.prototype.execute = function () {
if (this.data.zoom < 12) {
this.data.setZoom(this.data.zoom + 1);
}
Neo.resizeCanvas();
Neo.painter.updateDestCanvas();
};
Neo.ZoomMinusCommand = function (data) {
this.data = data;
};
Neo.ZoomMinusCommand.prototype = new Neo.CommandBase();
Neo.ZoomMinusCommand.prototype.execute = function () {
if (this.data.zoom >= 2) {
this.data.setZoom(this.data.zoom - 1);
}
Neo.resizeCanvas();
Neo.painter.updateDestCanvas();
};
/*
---------------------------------------------------
UNDO
---------------------------------------------------
*/
Neo.UndoCommand = function (data) {
this.data = data;
};
Neo.UndoCommand.prototype = new Neo.CommandBase();
Neo.UndoCommand.prototype.execute = function () {
this.data.undo();
};
Neo.RedoCommand = function (data) {
this.data = data;
};
Neo.RedoCommand.prototype = new Neo.CommandBase();
Neo.RedoCommand.prototype.execute = function () {
this.data.redo();
};
Neo.WindowCommand = function (data) {
this.data = data;
};
Neo.WindowCommand.prototype = new Neo.CommandBase();
Neo.WindowCommand.prototype.execute = function () {
if (Neo.fullScreen) {
if (confirm(Neo.translate("ページビュー?"))) {
Neo.fullScreen = false;
Neo.updateWindow();
}
} else {
if (confirm(Neo.translate("ウィンドウビュー?"))) {
Neo.fullScreen = true;
Neo.updateWindow();
}
}
};
Neo.SubmitCommand = function (data) {
this.data = data;
};
Neo.SubmitCommand.prototype = new Neo.CommandBase();
Neo.SubmitCommand.prototype.execute = function () {
var board = location.href.replace(/[^/]*$/, "");
this.data.submit(board);
};
Neo.CopyrightCommand = function (data) {
this.data = data;
};
Neo.CopyrightCommand.prototype = new Neo.CommandBase();
Neo.CopyrightCommand.prototype.execute = function () {
var url = "http://github.com/funige/neo/";
if (
confirm(
Neo.translate(
"PaintBBS NEOは、お絵描きしぃ掲示板 PaintBBS (©2000-2004 しぃちゃん) をhtml5化するプロジェクトです。\n\nPaintBBS NEOのホームページを表示しますか?"
) + "\n"
)
) {
Neo.openURL(url);
}
};
"use strict";
/*
-----------------------------------------------------------------------
Action Manager
-----------------------------------------------------------------------
*/
Neo.ActionManager = function () {
this._items = [];
this._head = 0;
this._index = 0;
this._pause = false;
this._mark = 0;
this._speedTable = [-1, 0, 1, 11];
this._speed = parseInt(Neo.config.speed || 0);
this._speedMode = this.generateSpeedTable();
this._prevSpeed = this._speed; // freeHandの途中で速度が変わると困るので
};
Neo.ActionManager.prototype.generateSpeedTable = function () {
var speed = this._speed;
var mode = 0;
if (speed < 0) {
mode = 0;
} else if (speed == 0) {
mode = 1;
} else if (speed <= 10) {
mode = 2;
} else {
mode = 3;
}
this._speedTable[mode] = speed;
return mode;
};
Neo.ActionManager.prototype.step = function () {
if (!Neo.animation) return;
if (this._items.length > this._head) {
this._items.length = this._head;
}
this._items.push([]);
this._head++;
this._index = 0;
};
Neo.ActionManager.prototype.back = function () {
if (!Neo.animation) return;
if (this._head > 0) {
this._head--;
}
};
Neo.ActionManager.prototype.forward = function () {
if (!Neo.animation) return;
if (this._head < this._items.length) {
this._head++;
}
};
Neo.ActionManager.prototype.push = function () {
if (!Neo.animation) return;
var head = this._items[this._head - 1];
for (var i = 0; i < arguments.length; i++) {
head.push(arguments[i]);
}
};
Neo.ActionManager.prototype.pushCurrent = function () {
if (!Neo.animation) return;
var oe = Neo.painter;
var head = this._items[this._head - 1];
var color = oe._currentColor;
var mask = oe._currentMask;
var width = oe._currentWidth;
var type = oe._currentMaskType;
head.push(color[0], color[1], color[2], color[3]);
head.push(mask[0], mask[1], mask[2]);
head.push(width);
head.push(type);
};
Neo.ActionManager.prototype.getCurrent = function (item) {
var oe = Neo.painter;
oe._currentColor = [item[2], item[3], item[4], item[5]];
oe._currentMask = [item[6], item[7], item[8]];
oe._currentWidth = item[9];
oe._currentMaskType = item[10];
};
Neo.ActionManager.prototype.skip = function (wait) {
for (var i = 0; i < this._items.length; i++) {
if (this._items[i][0] == "restore") {
this._head = i;
}
}
};
Neo.ActionManager.prototype.play = function (wait) {
if (!wait) {
wait = this._prevSpeed < 0 ? 0 : this._prevSpeed;
wait *= 1; //2
}
if (Neo.viewerBar) Neo.viewerBar.update();
if (this._pause) {
console.log("suspend viewer");
return;
}
if (this._head < this._items.length && this._head < this._mark) {
var item = this._items[this._head];
if (!Neo.viewer) {
Neo.painter._pushUndo(
0,
0,
Neo.painter.canvasWidth,
Neo.painter.canvasHeight,
true
);
}
if (Neo.viewer && Neo.viewerBar) {
console.log("play", item[0], this._head + 1, this._items.length);
}
var that = this;
var func = item[0] && this[item[0]] ? item[0] : "dummy";
this[func](item, function (result) {
if (result) {
if (
Neo.painter.busySkipped &&
that._head < that._mark - 2 &&
that._mark - 2 >= 0 &&
that._items[that._mark - 1][0] == "restore"
) {
that._head = that._mark - 2;
} else {
that._head++;
}
that._index = 0;
that._prevSpeed = that._speed;
}
if (that._prevSpeed < 0 && that._head % 10 != 0) {
Neo.painter._actionMgr.play();
} else {
setTimeout(function () {
Neo.painter._actionMgr.play();
}, wait);
}
});
} else {
Neo.painter.dirty = false;
Neo.painter.busy = false;
if (Neo.painter.bushSkipped) {
Neo.painter.busySkipped = false;
console.log("animation skipped");
} else {
console.log("animation finished");
}
}
};
/*
-------------------------------------------------------------------------
Action
-------------------------------------------------------------------------
*/
Neo.ActionManager.prototype.clearCanvas = function () {
if (typeof arguments[0] != "object") {
this.push("clearCanvas");
}
var oe = Neo.painter;
oe.canvasCtx[0].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.canvasCtx[1].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.floodFill = function (layer, x, y, color) {
if (typeof layer != "object") {
this.push("floodFill", layer, x, y, color);
} else {
var item = layer;
layer = item[1];
x = item[2];
y = item[3];
color = item[4];
}
var oe = Neo.painter;
oe.doFloodFill(layer, x, y, color);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.eraseAll = function () {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("eraseAll", layer);
} else {
var item = arguments[0];
layer = item[1];
}
var oe = Neo.painter;
oe.canvasCtx[layer].clearRect(0, 0, oe.canvasWidth, oe.canvasHeight);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.freeHand = function (x0, y0, lineType) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("freeHand", layer);
this.pushCurrent();
this.push(lineType, x0, y0, x0, y0);
oe.drawLine(oe.canvasCtx[layer], x0, y0, x0, y0, lineType);
} else if (!Neo.viewer || this._prevSpeed <= 0) {
this.freeHandFast(arguments[0], arguments[1]);
} else {
var item = arguments[0];
layer = item[1];
lineType = item[11];
this.getCurrent(item);
var i = this._index;
if (i == 0) {
i = 12;
} else {
i += 2;
}
var x1 = item[i + 0];
var y1 = item[i + 1];
x0 = item[i + 2];
y0 = item[i + 3];
oe.drawLine(oe.canvasCtx[layer], x0, y0, x1, y1, lineType);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
this._index = i;
var result = i + 2 + 3 >= item.length;
if (!result) {
oe.prevLine = null;
}
var callback = arguments[1];
if (callback && typeof callback == "function") {
callback(result);
}
}
};
Neo.ActionManager.prototype.freeHandFast = function (x0, y0, lineType) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("freeHand", layer);
this.pushCurrent();
this.push(lineType, x0, y0, x0, y0);
oe.drawLine(oe.canvasCtx[layer], x0, y0, x0, y0, lineType);
} else {
var item = arguments[0];
var length = item.length;
layer = item[1];
this.getCurrent(item);
lineType = item[11];
x0 = item[12];
y0 = item[13];
var x1, y1;
for (var i = 14; i + 1 < length; i += 2) {
x1 = x0;
y1 = y0;
x0 = item[i + 0];
y0 = item[i + 1];
oe.drawLine(oe.canvasCtx[layer], x0, y0, x1, y1, lineType);
}
oe.prevLine = null;
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
}
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.freeHandMove = function (x0, y0, x1, y1, lineType) {
if (arguments.length > 1) {
var oe = Neo.painter;
var layer = oe.current;
var head = this._items[this._head - 1];
if (head && head.length == 0) {
this.push("freeHand", layer);
this.pushCurrent();
this.push(lineType, x1, y1, x0, y0);
} else if (Neo.animation) {
head.push(x0, y0);
// 記録漏れがないか確認
var x = head[head.length - 4];
var y = head[head.length - 3];
if (
x1 != head[head.length - 4] ||
y1 != head[head.length - 3] ||
lineType != head[11]
) {
console.log("eror in freeHandMove?", x, y, lineType, head);
}
}
oe.drawLine(oe.canvasCtx[layer], x0, y0, x1, y1, lineType);
} else {
console.log("error in freeHandMove: called from recorder", head);
}
};
Neo.ActionManager.prototype.line = function (x0, y0, x1, y1, lineType) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("line", layer);
this.pushCurrent();
this.push(lineType, x0, y0, x1, y1);
} else {
var item = arguments[0];
layer = item[1];
this.getCurrent(item);
lineType = item[11];
x0 = item[12];
y0 = item[13];
x1 = item[14];
y1 = item[15];
}
if (x1 === null) x1 = x0;
if (y1 === null) y1 = y0;
oe.drawLine(oe.canvasCtx[layer], x0, y0, x1, y1, lineType);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.bezier = function (
x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3,
lineType
) {
var oe = Neo.painter;
var layer = oe.current;
var isReplay = true;
if (typeof arguments[0] != "object") {
this.push("bezier", layer);
this.pushCurrent();
this.push(lineType, x0, y0, x1, y1, x2, y2, x3, y3);
isReplay = false;
} else {
var item = arguments[0];
layer = item[1];
this.getCurrent(item);
lineType = item[11];
x0 = item[12];
y0 = item[13];
x1 = item[14];
y1 = item[15];
x2 = item[16];
y2 = item[17];
x3 = item[18];
y3 = item[19];
}
oe.drawBezier(
oe.canvasCtx[layer],
x0,
y0,
x1,
y1,
x2,
y2,
x3,
y3,
lineType,
isReplay
);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.fill = function (x, y, width, height, type) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("fill", layer);
this.pushCurrent();
this.push(x, y, width, height, type);
} else {
var item = arguments[0];
layer = item[1];
this.getCurrent(item);
x = item[11];
y = item[12];
width = item[13];
height = item[14];
type = item[15];
}
oe.doFill(layer, x, y, width, height, type);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.flipH = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("flipH", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.flipH(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.flipV = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("flipV", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.flipV(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.merge = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("merge", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.merge(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.blurRect = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("blurRect", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.blurRect(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.eraseRect2 = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("eraseRect2", layer);
this.pushCurrent();
this.push(x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
this.getCurrent(item);
x = item[11];
y = item[12];
width = item[13];
height = item[14];
}
oe.eraseRect(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.eraseRect = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("eraseRect", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.eraseRect(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.copy = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("copy", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.copy(layer, x, y, width, height);
oe.tool.x = x;
oe.tool.y = y;
oe.tool.width = width;
oe.tool.height = height;
// oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight, true);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.paste = function (x, y, width, height, dx, dy) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("paste", layer, x, y, width, height, dx, dy);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
dx = item[6];
dy = item[7];
}
oe.paste(layer, x, y, width, height, dx, dy);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.turn = function (x, y, width, height) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("turn", layer, x, y, width, height);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
width = item[4];
height = item[5];
}
oe.turn(layer, x, y, width, height);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.text = function (
x,
y,
color,
alpha,
string,
size,
family
) {
var oe = Neo.painter;
var layer = oe.current;
if (typeof arguments[0] != "object") {
this.push("text", layer, x, y, color, alpha, string, size, family);
} else {
var item = arguments[0];
layer = item[1];
x = item[2];
y = item[3];
color = item[4];
alpha = item[5];
string = item[6];
size = item[7];
family = item[8];
}
oe.doText(layer, x, y, color, alpha, string, size, family);
oe.updateDestCanvas(0, 0, oe.canvasWidth, oe.canvasHeight);
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
Neo.ActionManager.prototype.restore = function () {
var oe = Neo.painter;
var width = oe.canvasWidth;
var height = oe.canvasHeight;
if (typeof arguments[0] != "object") {
this.push("restore");
var img0 = oe.canvas[0].toDataURL("image/png");
var img1 = oe.canvas[1].toDataURL("image/png");
this.push(img0, img1);
} else {
var item = arguments[0];
var callback = arguments[1];
var img0 = new Image();
img0.src = item[1];
img0.onload = function () {
var img1 = new Image();
img1.src = item[2];
img1.onload = function () {
oe.canvasCtx[0].clearRect(0, 0, width, height);
oe.canvasCtx[1].clearRect(0, 0, width, height);
oe.canvasCtx[0].drawImage(img0, 0, 0);
oe.canvasCtx[1].drawImage(img1, 0, 0);
oe.updateDestCanvas(0, 0, width, height);
if (callback && typeof callback == "function") callback(true);
};
};
}
};
Neo.ActionManager.prototype.dummy = function () {
var callback = arguments[1];
if (callback && typeof callback == "function") callback(true);
};
/*
-----------------------------------------------------------------------
動画表示モード
-----------------------------------------------------------------------
*/
Neo.createViewer = function (applet) {
var neo = document.createElement("div");
neo.className = "NEO";
neo.id = "NEO";
var html =
'<div id="pageView" style="margin:auto;">' +
'<div id="container" style="visibility:visible;" class="o">' +
'<div id="painter" style="background-color:white;">' +
'<div id="canvas" style="background-color:white;">' +
"</div>" +
"</div>" +
'<div id="viewerButtonsWrapper" style="display:block;">' +
'<div id="viewerButtons" style="display:block;">' +
'<div id="viewerPlay"></div>' +
'<div id="viewerStop"></div>' +
'<div id="viewerRewind"></div>' +
'<div id="viewerSpeed" style="padding-left:2px; margin-top: 1px;"></div>' +
'<div id="viewerPlus"></div>' +
'<div id="viewerMinus"></div>' +
'<div id="viewerBar" style="display:inline-block;">' +
"</div>" +
"</div>" +
"</div>" +
"</div>";
neo.innerHTML = html.replace(/\[(.*?)\]/g, function (match, str) {
return Neo.translate(str);
});
var parent = applet.parentNode;
parent.appendChild(neo);
parent.insertBefore(neo, applet);
// applet.style.display = "none";
// NEOを組み込んだURLをアプリ版で開くとDOMツリーが2重にできて格好悪いので消しておく
setTimeout(function () {
var tmp = document.getElementsByClassName("NEO");
if (tmp.length > 1) {
for (var i = 1; i < tmp.length; i++) {
tmp[i].style.display = "none";
}
}
}, 0);
};
Neo.initViewer = function (pch) {
var pageview = document.getElementById("pageView");
var pageWidth = Neo.config.applet_width;
var pageHeight = Neo.config.applet_height;
pageview.style.width = pageWidth + "px";
pageview.style.height = pageHeight + "px";
Neo.canvas = document.getElementById("canvas");
Neo.container = document.getElementById("container");
Neo.container.style.backgroundColor = Neo.config.color_back;
Neo.container.style.border = "0";
var dx = (pageWidth - Neo.config.width) / 2;
var dy = (pageHeight - Neo.config.height - 26) / 2;
var painter = document.getElementById("painter");
painter.style.marginTop = "0";
painter.style.position = "absolute";
painter.style.padding = "0";
painter.style.bottom = dy + 26 + "px";
painter.style.left = dx + "px";
var viewerButtonsWrapper = document.getElementById("viewerButtonsWrapper");
viewerButtonsWrapper.style.width = pageWidth - 2 + "px";
var viewerBar = document.getElementById("viewerBar");
viewerBar.style.position = "absolute";
viewerBar.style.right = "2px";
viewerBar.style.top = "1px";
viewerBar.style.width = pageWidth - 24 * 6 - 2 + "px";
Neo.canvas.style.width = Neo.config.width + "px";
Neo.canvas.style.height = Neo.config.height + "px";
Neo.painter = new Neo.Painter();
Neo.painter.build(Neo.canvas, Neo.config.width, Neo.config.height);
Neo.container.oncontextmenu = function () {
return false;
};
painter.addEventListener(
"mousedown",
function () {
Neo.painter._actionMgr.isMouseDown = true;
},
false
);
document.addEventListener(
"mousemove",
function (e) {
if (Neo.painter._actionMgr.isMouseDown) {
var zoom = Neo.painter.zoom;
var x = Neo.painter.zoomX - e.movementX / zoom;
var y = Neo.painter.zoomY - e.movementY / zoom;
Neo.painter.setZoomPosition(x, y);
}
},
false
);
document.addEventListener(
"mouseup",
function () {
Neo.painter._actionMgr.isMouseDown = false;
Neo.viewerBar.isMouseDown = false;
},
false
);
if (pch) {
//Neo.config.pch_file) {
Neo.painter._actionMgr._items = pch.data;
Neo.painter.play();
}
};
Neo.startViewer = function () {
if (Neo.applet) {
var name = Neo.applet.attributes.name.value || "pch";
if (!document[name]) document[name] = Neo;
if (Neo.applet.parentNode) {
Neo.applet.parentNode.removeChild(Neo.applet);
}
}
Neo.styleSheet = Neo.getStyleSheet();
var lightBack = Neo.multColor(Neo.config.color_back, 1.3);
var darkBack = Neo.multColor(Neo.config.color_back, 0.7);
Neo.addRule(".NEO #viewerButtons", "color", Neo.config.color_text);
Neo.addRule(".NEO #viewerButtons", "background-color", Neo.config.color_back);
Neo.addRule(
".NEO #viewerButtonsWrapper",
"border",
"1px solid " + Neo.config.color_frame + " !important"
);
Neo.addRule(
".NEO #viewerButtons",
"border",
"1px solid " + Neo.config.color_back + " !important"
);
Neo.addRule(
".NEO #viewerButtons",
"border-left",
"1px solid " + lightBack + " !important"
);
Neo.addRule(
".NEO #viewerButtons",
"border-top",
"1px solid " + lightBack + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOff",
"background-color",
Neo.config.color_icon + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOff:active",
"background-color",
darkBack + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOn",
"background-color",
darkBack + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div",
"border",
"1px solid " + Neo.config.color_frame + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOff:hover",
"border",
"1px solid" + Neo.config.color_bar_select + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOff:active",
"border",
"1px solid" + Neo.config.color_bar_select + " !important"
);
Neo.addRule(
".NEO #viewerButtons >div.buttonOn",
"border",
"1px solid" + Neo.config.color_bar_select + " !important"
);
Neo.addRule(".NEO #viewerBar >div", "background-color", Neo.config.color_bar);
// Neo.addRule(".NEO #viewerBar:active", "background-color", darkBack);
Neo.addRule(
".NEO #viewerBarMark",
"background-color",
Neo.config.color_text + " !important"
);
setTimeout(function () {
Neo.viewerPlay = new Neo.ViewerButton().init("viewerPlay");
Neo.viewerPlay.setSelected(true);
Neo.viewerPlay.onmouseup = function () {
Neo.painter.onplay();
};
Neo.viewerStop = new Neo.ViewerButton().init("viewerStop");
Neo.viewerStop.onmouseup = function () {
Neo.painter.onstop();
};
new Neo.ViewerButton().init("viewerRewind").onmouseup = function () {
Neo.painter.onrewind();
};
new Neo.ViewerButton().init("viewerSpeed").onmouseup = function () {
Neo.painter.onspeed();
this.update();
};
new Neo.ViewerButton().init("viewerPlus").onmouseup = function () {
new Neo.ZoomPlusCommand(Neo.painter).execute();
};
new Neo.ViewerButton().init("viewerMinus").onmouseup = function () {
new Neo.ZoomMinusCommand(Neo.painter).execute();
};
var length = Neo.painter._actionMgr._items.length;
Neo.viewerBar = new Neo.ViewerBar().init("viewerBar", { length: length });
}, 0);
};
Neo.getFilename = function () {
return Neo.config.pch_file || Neo.config.image_canvas;
};
Neo.getPCH = function (filename, callback) {
if (!filename || filename.slice(-4).toLowerCase() != ".pch") return null;
var request = new XMLHttpRequest();
request.open("GET", filename, true);
request.responseType = "arraybuffer";
request.onload = function () {
var pch = Neo.decodePCH(request.response);
if (pch) {
if (callback) callback(pch);
} else {
console.log("not a NEO animation");
}
};
request.send();
};
Neo.decodePCH = function (rawdata) {
var byteArray = new Uint8Array(rawdata);
var data = LZString.decompressFromUint8Array(byteArray.subarray(12));
var header = byteArray.subarray(0, 12);
if (
header[0] == "N".charCodeAt(0) &&
header[1] == "E".charCodeAt(0) &&
header[2] == "O".charCodeAt(0)
) {
var width = header[4] + header[5] * 0x100;
var height = header[6] + header[7] * 0x100;
var items = Neo.fixPCH(JSON.parse(data));
return {
width: width,
height: height,
data: items,
};
} else {
return null;
}
};
Neo.fixPCH = function (items) {
for (var i = 0; i < items.length; i++) {
var item = items[i];
var index = item.indexOf("eraseAll");
if (index > 0) {
var tmp = item.slice(index);
var tmp2 = item.slice(0, index);
console.log("fix eraseAll", tmp2, tmp);
items[i] = tmp2;
items.splice(i, 0, tmp);
}
}
return items;
};
/*
-----------------------------------------------------------------------
LiveConnect
-----------------------------------------------------------------------
*/
Neo.playPCH = function () {
Neo.painter.onplay();
};
Neo.suspendDraw = function () {
Neo.painter.onstop();
};
Neo.setSpeed = function (value) {
Neo.painter._actionMgr._speed = value;
};
Neo.setMark = function (value) {
Neo.painter._actionMgr._mark = value;
Neo.painter.onmark();
};
Neo.getSeek = function () {
return Neo.painter._actionMgr._head;
};
Neo.getLineCount = function () {
return Neo.painter._actionMgr._items.length;
};
"use strict";
Neo.getModifier = function (e) {
if (e.shiftKey) {
return "shift";
} else if (
e.button == 2 ||
e.ctrlKey ||
e.altKey ||
Neo.painter.virtualRight
) {
return "right";
}
return null;
};
/*
-------------------------------------------------------------------------
Button
-------------------------------------------------------------------------
*/
Neo.Button = function () {};
Neo.Button.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.selected = false;
this.isMouseDown = false;
var ref = this;
this.element.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
this.element.onmouseup = function (e) {
ref._mouseUpHandler(e);
};
this.element.onmouseover = function (e) {
ref._mouseOverHandler(e);
};
this.element.onmouseout = function (e) {
ref._mouseOutHandler(e);
};
this.element.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
e.preventDefault();
},
true
);
this.element.addEventListener(
"touchend",
function (e) {
ref._mouseUpHandler(e);
},
true
);
this.element.className = !this.params.type == "fill" ? "button" : "buttonOff";
this.disable = function(wait) {
this.element.style.pointerEvents = "none";
this.element.style.opacity = "0.5";
if (wait) {
setTimeout(function () {
ref.enable();
}, wait);
}
}
this.enable = function() {
this.element.style.pointerEvents = "inherit";
this.element.style.opacity = "1.0";
}
return this;
};
Neo.Button.prototype._mouseDownHandler = function (e) {
if (Neo.painter.isUIPaused()) return;
this.isMouseDown = true;
if (this.params.type == "fill" && this.selected == false) {
for (var i = 0; i < Neo.toolButtons.length; i++) {
var toolTip = Neo.toolButtons[i];
toolTip.setSelected(this.selected ? false : true);
}
Neo.painter.setToolByType(Neo.Painter.TOOLTYPE_FILL);
}
if (this.onmousedown) this.onmousedown(this);
};
Neo.Button.prototype._mouseUpHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseup) this.onmouseup(this);
}
};
Neo.Button.prototype._mouseOutHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseout) this.onmouseout(this);
}
};
Neo.Button.prototype._mouseOverHandler = function (e) {
if (this.onmouseover) this.onmouseover(this);
};
Neo.Button.prototype.setSelected = function (selected) {
if (selected) {
this.element.className = "buttonOn";
} else {
this.element.className = "buttonOff";
}
this.selected = selected;
};
Neo.Button.prototype.update = function () {};
/*
-------------------------------------------------------------------------
Right Button
-------------------------------------------------------------------------
*/
Neo.RightButton;
Neo.RightButton = function () {};
Neo.RightButton.prototype = new Neo.Button();
Neo.RightButton.prototype.init = function (name, params) {
Neo.Button.prototype.init.call(this, name, params);
this.params.type = "right";
return this;
};
Neo.RightButton.prototype._mouseDownHandler = function (e) {};
Neo.RightButton.prototype._mouseUpHandler = function (e) {
this.setSelected(!this.selected);
};
Neo.RightButton.prototype._mouseOutHandler = function (e) {};
Neo.RightButton.prototype.setSelected = function (selected) {
if (selected) {
this.element.className = "buttonOn";
Neo.painter.virtualRight = true;
} else {
this.element.className = "buttonOff";
Neo.painter.virtualRight = false;
}
this.selected = selected;
};
Neo.RightButton.clear = function () {
var right = Neo.rightButton;
right.setSelected(false);
};
/*
-------------------------------------------------------------------------
Fill Button
-------------------------------------------------------------------------
*/
Neo.FillButton;
Neo.FillButton = function () {};
Neo.FillButton.prototype = new Neo.Button();
Neo.FillButton.prototype.init = function (name, params) {
Neo.Button.prototype.init.call(this, name, params);
this.params.type = "fill";
return this;
};
/*
-------------------------------------------------------------------------
ColorTip
-------------------------------------------------------------------------
*/
Neo.colorTips = [];
Neo.ColorTip = function () {};
Neo.ColorTip.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.selected = this.name == "color1" ? true : false;
this.isMouseDown = false;
var ref = this;
this.element.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
this.element.onmouseup = function (e) {
ref._mouseUpHandler(e);
};
this.element.onmouseover = function (e) {
ref._mouseOverHandler(e);
};
this.element.onmouseout = function (e) {
ref._mouseOutHandler(e);
};
this.element.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
e.preventDefault();
},
true
);
this.element.addEventListener(
"touchend",
function (e) {
ref._mouseUpHandler(e);
},
true
);
this.element.className = "colorTipOff";
var index = parseInt(this.name.slice(5)) - 1;
this.element.style.left = index % 2 ? "0px" : "26px";
this.element.style.top = Math.floor(index / 2) * 21 + "px";
// base64 ColorTip.png
this.element.innerHTML =
"<img style='max-width:44px;' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAASCAYAAAAg9DzcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAANklEQVRIx+3OAQkAMADDsO3+Pe8qCj+0Akq6bQFqS2wTCpwE+R4IiyVYsGDBggULfirBgn8HX7BzCRwDx1QeAAAAAElFTkSuQmCC' />";
this.setColor(Neo.config.colors[params.index - 1]);
this.setSelected(this.selected);
Neo.colorTips.push(this);
};
Neo.ColorTip.prototype._mouseDownHandler = function (e) {
if (Neo.painter.isUIPaused()) return;
this.isMouseDown = true;
for (var i = 0; i < Neo.colorTips.length; i++) {
var colorTip = Neo.colorTips[i];
if (this == colorTip) {
switch (Neo.getModifier(e)) {
case "shift":
this.setColor(Neo.config.colors[this.params.index - 1]);
break;
case "right":
this.setColor(Neo.painter.foregroundColor);
break;
}
// if (e.shiftKey) {
// this.setColor(Neo.config.colors[this.params.index - 1]);
// } else if (e.button == 2 || e.ctrlKey || e.altKey ||
// Neo.painter.virtualRight) {
// this.setColor(Neo.painter.foregroundColor);
// }
}
colorTip.setSelected(this == colorTip) ? true : false;
}
Neo.painter.setColor(this.color);
Neo.updateUIColor(true, false);
if (this.onmousedown) this.onmousedown(this);
};
Neo.ColorTip.prototype._mouseUpHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseup) this.onmouseup(this);
}
};
Neo.ColorTip.prototype._mouseOutHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseout) this.onmouseout(this);
}
};
Neo.ColorTip.prototype._mouseOverHandler = function (e) {
if (this.onmouseover) this.onmouseover(this);
};
Neo.ColorTip.prototype.setSelected = function (selected) {
if (selected) {
this.element.className = "colorTipOn";
} else {
this.element.className = "colorTipOff";
}
this.selected = selected;
};
Neo.ColorTip.prototype.setColor = function (color) {
this.color = color;
this.element.style.backgroundColor = color;
};
Neo.ColorTip.getCurrent = function () {
for (var i = 0; i < Neo.colorTips.length; i++) {
var colorTip = Neo.colorTips[i];
if (colorTip.selected) return colorTip;
}
return null;
};
/*
-------------------------------------------------------------------------
ToolTip
-------------------------------------------------------------------------
*/
Neo.toolTips = [];
Neo.toolButtons = [];
Neo.ToolTip = function () {};
Neo.ToolTip.prototype.prevMode = -1;
Neo.ToolTip.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.params.type = this.element.id;
this.name = name;
this.mode = 0;
this.isMouseDown = false;
var ref = this;
this.element.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
this.element.onmouseup = function (e) {
ref._mouseUpHandler(e);
};
this.element.onmouseover = function (e) {
ref._mouseOverHandler(e);
};
this.element.onmouseout = function (e) {
ref._mouseOutHandler(e);
};
this.element.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
e.preventDefault();
},
true
);
this.element.addEventListener(
"touchend",
function (e) {
ref._mouseUpHandler(e);
},
true
);
this.selected = this.params.type == "pen" ? true : false;
this.setSelected(this.selected);
this.element.innerHTML =
"<canvas width=46 height=18></canvas><div class='label'></div>";
this.canvas = this.element.getElementsByTagName("canvas")[0];
this.label = this.element.getElementsByTagName("div")[0];
this.update();
return this;
};
Neo.ToolTip.prototype._mouseDownHandler = function (e) {
this.isMouseDown = true;
if (this.isTool) {
if (this.selected == false) {
for (var i = 0; i < Neo.toolButtons.length; i++) {
var toolTip = Neo.toolButtons[i];
toolTip.setSelected(this == toolTip ? true : false);
}
} else {
var length = this.toolStrings.length;
if (Neo.getModifier(e) == "right") {
this.mode--;
if (this.mode < 0) this.mode = length - 1;
} else {
this.mode++;
if (this.mode >= length) this.mode = 0;
}
}
Neo.painter.setToolByType(this.tools[this.mode]);
this.update();
}
if (this.onmousedown) this.onmousedown(this);
};
Neo.ToolTip.prototype._mouseUpHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseup) this.onmouseup(this);
}
};
Neo.ToolTip.prototype._mouseOutHandler = function (e) {
if (this.isMouseDown) {
this.isMouseDown = false;
if (this.onmouseout) this.onmouseout(this);
}
};
Neo.ToolTip.prototype._mouseOverHandler = function (e) {
if (this.onmouseover) this.onmouseover(this);
};
Neo.ToolTip.prototype.setSelected = function (selected) {
if (this.fixed) {
this.element.className = "toolTipFixed";
} else {
if (selected) {
this.element.className = "toolTipOn";
} else {
this.element.className = "toolTipOff";
}
}
this.selected = selected;
};
Neo.ToolTip.prototype.update = function () {};
Neo.ToolTip.prototype.draw = function (c) {
if (this.hasTintImage) {
if (typeof c != "string") c = Neo.painter.getColorString(c);
var ctx = this.canvas.getContext("2d");
if (this.prevMode != this.mode) {
this.prevMode = this.mode;
var img = new Image();
img.src = this.toolIcons[this.mode];
img.onload = function () {
var ref = this;
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawTintImage(ctx, img, c, 0, 0);
}.bind(this);
} else {
Neo.tintImage(ctx, c);
}
}
};
Neo.ToolTip.prototype.drawTintImage = function (ctx, img, c, x, y) {
ctx.drawImage(img, x, y);
Neo.tintImage(ctx, c);
};
Neo.ToolTip.bezier =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAT0lEQVRIx+3SQQoAIAhE0en+h7ZVEEKBZrX5b5sjKknAkRYpNslaMLPq44ZI9wwHs0vMQ/v87u0Kk8xfsaI242jbMdjPi5Y0r/zTAAAAD3UOjRf9jcO4sgAAAABJRU5ErkJggg==";
Neo.ToolTip.blur =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAASUlEQVRIx+3VMQ4AIAgEQeD/f8bWWBnJYUh2SgtgK82G8/MhzVKwxOtTLgIUx6tDout4laiPIICA0Qj4bXxAy0+8LZP9yACAJwsqkggS55eiZgAAAABJRU5ErkJggg==";
Neo.ToolTip.blurrect =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAX0lEQVRIx+2XQQ4AEAwEt+I7/v+8Org6lJKt6NzLjjYE8DAKtLpYoDeCCCC7tYUd3ru2qQOzDTyndhJzB6KSAmxSgM0fAlGuzBnmlziqxB8jFJkUYJMCbAQYPxt2kF06fvYKgjPBO/IAAAAASUVORK5CYII=";
Neo.ToolTip.brush =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAQUlEQVRIx2NgGOKAEcb4z8CweRA4xpdUPSxofJ8BdP8WcjQxDaCDqQLQY4CsUBgFo2AUjIJRMApGwSgYBaNgZAIA0CoDwDbZu8oAAAAASUVORK5CYII=";
Neo.ToolTip.burn =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAPklEQVRIx+3PMRIAMAQAQbzM0/0sKZPeiDG57TQ4keH0Htx9VR+MCM1vOezl8xUsv4IAAkYjoBsB3QgAgL9tYXgF19rh9yoAAAAASUVORK5CYII=";
Neo.ToolTip.copy =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAW0lEQVRIx+2XMQoAIAwDU/E7/v95Orh2KMUSC7m5Qs6AUqAxG1gzOLirwxhgmXOjOlg1oQY8sjf2mvYNSICNBNhIgE3oH/jlzfdo34AE2EiATXsBA+5mww6S5QASDwSGMt8ouwAAAABJRU5ErkJggg==";
Neo.ToolTip.copy2 =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAN0lEQVRIx+3PwQkAIBADwdPKt3MtQVCOPNz5B7JV0pNxOwRW9zng+G92n+hmQJoBaQakGSBJf9tyBgQUV/fKCAAAAABJRU5ErkJggg==";
Neo.ToolTip.ellipse =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAATklEQVRIx+2VMQ4AIAgD6/8fjbOJi1LFmt4OPQ0KIE7LNgggCBLbHkuFM9lM+Om+QwDjpksyb4tT86vlvzgEbYxefQPyv5D8HjDGGGOk6b3jJ+lYubd8AAAAAElFTkSuQmCC";
Neo.ToolTip.ellipsefill =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAVUlEQVRIx+2VURIAEAgFc/9D5waSHpV5+43ZHRMizRnRA1REARLHHq6NCFl01Nail+LeEDMgU34nYhlQQd6K+PsGKkSEZyArBPoK3Y6K/AOEEEJIayZHbhIKjkZrFwAAAABJRU5ErkJggg==";
Neo.ToolTip.eraser =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAABQElEQVRIx+1WQY7CMAwcI37Cad+yXOgH4Gu8gAt9CtrDirfMHjZJbbcktVSpQnROSeMkY3vsFHhzSG3xfLpz/JVmG0mIqDkIMcc6+7Kejx6fdb0dq7w09rVFkrjejrMOunQ9vg7f/5QEIAd6E1Eo38WF8fF7n8sdALCrLerIzoFI4sI0Vtv1SYZ8CVbeF7tzF7JugIkVkxOauc6CIe8842S+XmMfsq7TN9LRTngZmTmVD4SrnzYaGYhFoxCWgajXuMjYGTuJ3dlwIBIN3U0cUVqLXCs5E7YeVsvAYJul5HWeLUhL3EpstQwooqoOTEHDOebpMn7ngkUsg3RotU8X1MkuVDrYohkIupC0YArX6T+PfX3kcbQLNV/iCKi6EB3xqXdAZ0JKthZ8B0QEl673NIEX/0I/z36Rf6ENGzZ8EP4A8Lp+9e9VWC4AAAAASUVORK5CYII=";
Neo.ToolTip.flip =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAZklEQVRIx+2XQQoAIAgE1+g7/f95degWHSyTTXDOhTsSiUBgOtCq8mD3DiOA3NxTCVgKaLA0qHiFOsHSnC8ELKQAmxRgE15APQfWv9pzLjwX+CXsjvBPKAXYpACb8AICzM2GHeSWAfVOCIiJuQ9tAAAAAElFTkSuQmCC";
Neo.ToolTip.freehand =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAdUlEQVRIx+2WUQrAMAhD3dj9r+y+VoSyLhYDynzQv1qiJlCR4hzeAhVRsiC3Jkj0c5hN7Lx7IQ9SphLE1ICdwko420purEWQuywN3pqxgcw2+WwAtU1GzoqiLZNwZBvMAIcO8y3YKUO8mkbmjPzjK9E0TUPjBoeyLAS0usjLAAAAAElFTkSuQmCC";
Neo.ToolTip.line =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAU0lEQVRIx+2UQQ4AIAjD8P+PxivRGDQC47C+oN1hIgTLQAt4qIga2c23XYAVPkm3CVhlb4ShAa/rQgMi1i0NyFg3LaBq3bAA1LpfAd7/EkIIIR2YXFYSCpWS8w8AAAAASUVORK5CYII=";
Neo.ToolTip.merge =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAW0lEQVRIx+2XQQrAQAgDx9Lv9JF9+e6h54IINlgyZ4UMOYgwmAXXmRxc3WECorJ3dAfrJtXAC7c6PPygAQuosYAaC6hJ3YHqlfyC8Q1YQI0F1IwXCHg+G3WQKhvwgwUFmFyYbwAAAABJRU5ErkJggg==";
Neo.ToolTip.pen =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAK0lEQVRIx+3OsQkAMAwDQXn/oe3WfSAEctd9I5TA32pHJ/3AoTpfAQCAGwaa5AICJLKWSQAAAABJRU5ErkJggg==";
Neo.ToolTip.rect =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAQElEQVRIx+3TMQ4AIAhD0WK8/5VxdcIYY8rw3wok7YAEr6iGKaU74BY0ro+6FKhyDHe4VxRwm6eFLn8AAADwwQIwTQgGo9ZMywAAAABJRU5ErkJggg==";
Neo.ToolTip.rectfill =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAANElEQVRIx+3PIQ4AIBADwcL//3xYBMEgLiQztmab0GvcxkqqO3ALPbbO7rBXDnRzAADgYwvqDwIMJlGb5QAAAABJRU5ErkJggg==";
Neo.ToolTip.text =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAcUlEQVRIx+2VwQ7AIAhDy7L//2V2WmIYg+ky2KEv8aCCqYQqQMgrJNpUQMXEKKDmAPHyspgSrBBvLZu3cQqZEdwhfusq0KdkVR5HlFfBvpI0mtIzeusFot7vFPqYuzZYMXUFlzc+qrIn7tf/ACGEkIwDlEQ94YZjzcgAAAAASUVORK5CYII=";
Neo.ToolTip.tone =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAATCAYAAADWOo4fAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsSAAALEgHS3X78AAAAO0lEQVRIx+3PIQ4AMAgEwaP//zNVVZUELiQ7CgWstFy8IaVsPhT1Lb/T+fQEAtwIcCPAjQC39QEAgJIL6DQCFhAqsRkAAAAASUVORK5CYII=";
/*
-------------------------------------------------------------------------
PenTip
-------------------------------------------------------------------------
*/
Neo.penTip;
Neo.PenTip = function () {};
Neo.PenTip.prototype = new Neo.ToolTip();
Neo.PenTip.prototype.tools = [
Neo.Painter.TOOLTYPE_PEN,
Neo.Painter.TOOLTYPE_BRUSH,
Neo.Painter.TOOLTYPE_TEXT,
];
Neo.PenTip.prototype.hasTintImage = true;
Neo.PenTip.prototype.toolIcons = [
Neo.ToolTip.pen,
Neo.ToolTip.brush,
Neo.ToolTip.text,
];
Neo.PenTip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("鉛筆"),
Neo.translate("水彩"),
Neo.translate("テキスト"),
];
this.isTool = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.PenTip.prototype.update = function () {
for (var i = 0; i < this.tools.length; i++) {
if (Neo.painter.tool.type == this.tools[i]) this.mode = i;
}
this.draw(Neo.painter.foregroundColor);
if (this.label) {
this.label.innerHTML = this.toolStrings[this.mode];
}
};
/*
-------------------------------------------------------------------------
Pen2Tip
-------------------------------------------------------------------------
*/
Neo.pen2Tip;
Neo.Pen2Tip = function () {};
Neo.Pen2Tip.prototype = new Neo.ToolTip();
Neo.Pen2Tip.prototype.tools = [
Neo.Painter.TOOLTYPE_TONE,
Neo.Painter.TOOLTYPE_BLUR,
Neo.Painter.TOOLTYPE_DODGE,
Neo.Painter.TOOLTYPE_BURN,
];
Neo.Pen2Tip.prototype.hasTintImage = true;
Neo.Pen2Tip.prototype.toolIcons = [
Neo.ToolTip.tone,
Neo.ToolTip.blur,
Neo.ToolTip.burn,
Neo.ToolTip.burn,
];
Neo.Pen2Tip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("トーン"),
Neo.translate("ぼかし"),
Neo.translate("覆い焼き"),
Neo.translate("焼き込み"),
];
this.isTool = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.Pen2Tip.prototype.update = function () {
for (var i = 0; i < this.tools.length; i++) {
if (Neo.painter.tool.type == this.tools[i]) this.mode = i;
}
switch (this.tools[this.mode]) {
case Neo.Painter.TOOLTYPE_TONE:
this.drawTone(Neo.painter.foregroundColor);
break;
case Neo.Painter.TOOLTYPE_DODGE:
this.draw(0xffc0c0c0);
break;
case Neo.Painter.TOOLTYPE_BURN:
this.draw(0xff404040);
break;
default:
this.draw(Neo.painter.foregroundColor);
break;
}
this.label.innerHTML = this.toolStrings[this.mode];
};
Neo.Pen2Tip.prototype.drawTone = function () {
var ctx = this.canvas.getContext("2d");
var imageData = ctx.getImageData(0, 0, 46, 18);
var buf32 = new Uint32Array(imageData.data.buffer);
var buf8 = new Uint8ClampedArray(imageData.data.buffer);
var c = Neo.painter.getColor() | 0xff000000;
var a = Math.floor(Neo.painter.alpha * 255);
var toneData = Neo.painter.getToneData(a);
for (var j = 0; j < 18; j++) {
for (var i = 0; i < 46; i++) {
if (
j >= 1 &&
j < 12 &&
i >= 2 &&
i < 26 &&
toneData[(i % 4) + (j % 4) * 4]
) {
buf32[j * 46 + i] = c;
} else {
buf32[j * 46 + i] = 0;
}
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
this.prevMode = this.mode;
};
/*
-------------------------------------------------------------------------
EraserTip
-------------------------------------------------------------------------
*/
Neo.eraserTip;
Neo.EraserTip = function () {};
Neo.EraserTip.prototype = new Neo.ToolTip();
Neo.EraserTip.prototype.tools = [
Neo.Painter.TOOLTYPE_ERASER,
Neo.Painter.TOOLTYPE_ERASERECT,
Neo.Painter.TOOLTYPE_ERASEALL,
];
Neo.EraserTip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("消しペン"),
Neo.translate("消し四角"),
Neo.translate("全消し"),
];
this.drawOnce = false;
this.isTool = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.EraserTip.prototype.update = function () {
for (var i = 0; i < this.tools.length; i++) {
if (Neo.painter.tool.type == this.tools[i]) this.mode = i;
}
if (this.drawOnce == false) {
this.draw();
this.drawOnce = true;
}
this.label.innerHTML = this.toolStrings[this.mode];
};
Neo.EraserTip.prototype.draw = function () {
var ctx = this.canvas.getContext("2d");
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
var img = new Image();
img.src = Neo.ToolTip.eraser;
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
};
/*
-------------------------------------------------------------------------
EffectTip
-------------------------------------------------------------------------
*/
Neo.effectTip;
Neo.EffectTip = function () {};
Neo.EffectTip.prototype = new Neo.ToolTip();
Neo.EffectTip.prototype.tools = [
Neo.Painter.TOOLTYPE_RECTFILL,
Neo.Painter.TOOLTYPE_RECT,
Neo.Painter.TOOLTYPE_ELLIPSEFILL,
Neo.Painter.TOOLTYPE_ELLIPSE,
];
Neo.EffectTip.prototype.hasTintImage = true;
Neo.EffectTip.prototype.toolIcons = [
Neo.ToolTip.rectfill,
Neo.ToolTip.rect,
Neo.ToolTip.ellipsefill,
Neo.ToolTip.ellipse,
];
Neo.EffectTip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("四角"),
Neo.translate("線四角"),
Neo.translate("楕円"),
Neo.translate("線楕円"),
];
this.isTool = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.EffectTip.prototype.update = function () {
for (var i = 0; i < this.tools.length; i++) {
if (Neo.painter.tool.type == this.tools[i]) this.mode = i;
}
this.draw(Neo.painter.foregroundColor);
this.label.innerHTML = this.toolStrings[this.mode];
};
/*
-------------------------------------------------------------------------
Effect2Tip
-------------------------------------------------------------------------
*/
Neo.effect2Tip;
Neo.Effect2Tip = function () {};
Neo.Effect2Tip.prototype = new Neo.ToolTip();
Neo.Effect2Tip.prototype.tools = [
Neo.Painter.TOOLTYPE_COPY,
Neo.Painter.TOOLTYPE_MERGE,
Neo.Painter.TOOLTYPE_BLURRECT,
Neo.Painter.TOOLTYPE_FLIP_H,
Neo.Painter.TOOLTYPE_FLIP_V,
Neo.Painter.TOOLTYPE_TURN,
];
Neo.Effect2Tip.prototype.hasTintImage = true;
Neo.Effect2Tip.prototype.toolIcons = [
Neo.ToolTip.copy,
Neo.ToolTip.merge,
Neo.ToolTip.blurrect,
Neo.ToolTip.flip,
Neo.ToolTip.flip,
Neo.ToolTip.flip,
];
Neo.Effect2Tip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("コピー"),
Neo.translate("レイヤ結合"),
Neo.translate("角取り"),
Neo.translate("左右反転"),
Neo.translate("上下反転"),
Neo.translate("傾け"),
];
this.isTool = true;
Neo.ToolTip.prototype.init.call(this, name, params);
this.img = document.createElement("img");
this.img.src = Neo.ToolTip.copy2;
this.element.appendChild(this.img);
return this;
};
Neo.Effect2Tip.prototype.update = function () {
for (var i = 0; i < this.tools.length; i++) {
if (Neo.painter.tool.type == this.tools[i]) this.mode = i;
}
this.draw(Neo.painter.foregroundColor);
this.label.innerHTML = this.toolStrings[this.mode];
};
/*
-------------------------------------------------------------------------
MaskTip
-------------------------------------------------------------------------
*/
Neo.maskTip;
Neo.MaskTip = function () {};
Neo.MaskTip.prototype = new Neo.ToolTip();
Neo.MaskTip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("通常"),
Neo.translate("マスク"),
Neo.translate("逆マスク"),
Neo.translate("加算"),
Neo.translate("逆加算"),
];
this.fixed = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.MaskTip.prototype._mouseDownHandler = function (e) {
this.isMouseDown = true;
if (Neo.getModifier(e) == "right") {
Neo.painter.maskColor = Neo.painter.foregroundColor;
} else {
var length = this.toolStrings.length;
this.mode++;
if (this.mode >= length) this.mode = 0;
Neo.painter.maskType = this.mode;
}
this.update();
if (this.onmousedown) this.onmousedown(this);
};
Neo.MaskTip.prototype.update = function () {
this.draw(Neo.painter.maskColor);
this.label.innerHTML = this.toolStrings[this.mode];
};
Neo.MaskTip.prototype.draw = function (c) {
if (typeof c != "string") c = Neo.painter.getColorString(c);
var ctx = this.canvas.getContext("2d");
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
ctx.fillStyle = c;
ctx.fillRect(1, 1, 43, 9);
};
/*
-------------------------------------------------------------------------
DrawTip
-------------------------------------------------------------------------
*/
Neo.drawTip;
Neo.DrawTip = function () {};
Neo.DrawTip.prototype = new Neo.ToolTip();
Neo.DrawTip.prototype.hasTintImage = true;
Neo.DrawTip.prototype.toolIcons = [
Neo.ToolTip.freehand,
Neo.ToolTip.line,
Neo.ToolTip.bezier,
];
Neo.DrawTip.prototype.init = function (name, params) {
this.toolStrings = [
Neo.translate("手書き"),
Neo.translate("直線"),
Neo.translate("BZ曲線"),
];
this.fixed = true;
Neo.ToolTip.prototype.init.call(this, name, params);
return this;
};
Neo.DrawTip.prototype._mouseDownHandler = function (e) {
this.isMouseDown = true;
var length = this.toolStrings.length;
if (Neo.getModifier(e) == "right") {
this.mode--;
if (this.mode < 0) this.mode = length - 1;
} else {
this.mode++;
if (this.mode >= length) this.mode = 0;
}
Neo.painter.drawType = this.mode;
this.update();
if (this.onmousedown) this.onmousedown(this);
};
Neo.DrawTip.prototype.update = function () {
this.mode = Neo.painter.drawType;
this.draw(Neo.painter.foregroundColor);
this.label.innerHTML = this.toolStrings[this.mode];
};
/*
-------------------------------------------------------------------------
ColorSlider
-------------------------------------------------------------------------
*/
Neo.sliders = [];
Neo.ColorSlider = function () {};
Neo.ColorSlider.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.isMouseDown = false;
this.value = 0;
this.type = this.params.type;
this.element.className = "colorSlider";
this.element.innerHTML =
"<div class='slider'></div><div class='label'></div>";
this.element.innerHTML += "<div class='hit'></div>";
this.slider = this.element.getElementsByClassName("slider")[0];
this.label = this.element.getElementsByClassName("label")[0];
this.hit = this.element.getElementsByClassName("hit")[0];
this.hit["data-slider"] = params.type;
switch (this.type) {
case Neo.SLIDERTYPE_RED:
this.prefix = "R";
this.slider.style.backgroundColor = "#fa9696";
break;
case Neo.SLIDERTYPE_GREEN:
this.prefix = "G";
this.slider.style.backgroundColor = "#82f238";
break;
case Neo.SLIDERTYPE_BLUE:
this.prefix = "B";
this.slider.style.backgroundColor = "#8080ff";
break;
case Neo.SLIDERTYPE_ALPHA:
this.prefix = "A";
this.slider.style.backgroundColor = "#aaaaaa";
this.value = 255;
break;
}
this.update();
return this;
};
Neo.ColorSlider.prototype.downHandler = function (x, y) {
if (Neo.painter.isShiftDown) {
this.shift(x, y);
} else {
this.slide(x, y);
}
};
Neo.ColorSlider.prototype.moveHandler = function (x, y) {
this.slide(x, y);
//event.preventDefault();
};
Neo.ColorSlider.prototype.upHandler = function (x, y) {};
Neo.ColorSlider.prototype.shift = function (x, y) {
var value;
if (x >= 0 && x < 60 && y >= 0 && y <= 15) {
var v = Math.floor((x - 5) * 5.0);
var min = this.type == Neo.SLIDERTYPE_ALPHA ? 1 : 0;
value = Math.max(Math.min(v, 255), min);
if (this.value > value || this.value == 255) {
this.value--;
} else {
this.value++;
}
this.value = Math.max(Math.min(this.value, 255), min);
this.value0 = this.value;
this.x0 = x;
}
if (this.type == Neo.SLIDERTYPE_ALPHA) {
Neo.painter.alpha = this.value / 255.0;
this.update();
Neo.updateUIColor(false, false);
} else {
var r = Neo.sliders[Neo.SLIDERTYPE_RED].value;
var g = Neo.sliders[Neo.SLIDERTYPE_GREEN].value;
var b = Neo.sliders[Neo.SLIDERTYPE_BLUE].value;
Neo.painter.setColor((r << 16) | (g << 8) | b);
Neo.updateUIColor(true, true);
}
};
Neo.ColorSlider.prototype.slide = function (x, y) {
var value;
if (x >= 0 && x < 60 && y >= 0 && y <= 15) {
var v = Math.floor((x - 5) * 5.0);
value = Math.round(v / 5) * 5;
this.value0 = value;
this.x0 = x;
} else {
var d = (x - this.x0) / 3.0;
value = this.value0 + d;
}
var min = this.type == Neo.SLIDERTYPE_ALPHA ? 1 : 0;
this.value = Math.max(Math.min(value, 255), min);
if (this.type == Neo.SLIDERTYPE_ALPHA) {
Neo.painter.alpha = this.value / 255.0;
this.update();
Neo.updateUIColor(false, false);
} else {
var r = Neo.sliders[Neo.SLIDERTYPE_RED].value;
var g = Neo.sliders[Neo.SLIDERTYPE_GREEN].value;
var b = Neo.sliders[Neo.SLIDERTYPE_BLUE].value;
var color = (r << 16) | (g << 8) | b;
var colorTip = Neo.ColorTip.getCurrent();
if (colorTip) {
colorTip.setColor(Neo.painter.getColorString(color));
}
Neo.painter.setColor(color);
// Neo.updateUIColor(true, true);
}
};
Neo.ColorSlider.prototype.update = function () {
var color = Neo.painter.getColor();
var alpha = Neo.painter.alpha * 255;
switch (this.type) {
case Neo.SLIDERTYPE_RED:
this.value = color & 0x0000ff;
break;
case Neo.SLIDERTYPE_GREEN:
this.value = (color & 0x00ff00) >> 8;
break;
case Neo.SLIDERTYPE_BLUE:
this.value = (color & 0xff0000) >> 16;
break;
case Neo.SLIDERTYPE_ALPHA:
this.value = alpha;
break;
}
var width = (this.value * 49.0) / 255.0;
width = Math.max(Math.min(48, width), 1);
this.slider.style.width = width.toFixed(2) + "px";
this.label.innerHTML = this.prefix + this.value.toFixed(0);
};
/*
-------------------------------------------------------------------------
SizeSlider
-------------------------------------------------------------------------
*/
Neo.SizeSlider = function () {};
Neo.SizeSlider.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.isMouseDown = false;
this.value = this.value0 = 1;
this.element.className = "sizeSlider";
this.element.innerHTML =
"<div class='slider'></div><div class='label'></div>";
this.element.innerHTML += "<div class='hit'></div>";
this.slider = this.element.getElementsByClassName("slider")[0];
this.label = this.element.getElementsByClassName("label")[0];
this.hit = this.element.getElementsByClassName("hit")[0];
this.hit["data-slider"] = params.type;
this.slider.style.backgroundColor = Neo.painter.foregroundColor;
this.update();
return this;
};
Neo.SizeSlider.prototype.downHandler = function (x, y) {
if (Neo.painter.isShiftDown) {
this.shift(x, y);
} else {
this.value0 = this.value;
this.y0 = y;
this.slide(x, y);
}
};
Neo.SizeSlider.prototype.moveHandler = function (x, y) {
this.slide(x, y);
//event.preventDefault();
};
Neo.SizeSlider.prototype.upHandler = function (x, y) {};
Neo.SizeSlider.prototype.shift = function (x, y) {
var value0 = Neo.painter.lineWidth;
var value;
if (!Neo.painter.tool.alt) {
var v = Math.floor(((y - 4) * 30.0) / 33.0);
value = Math.max(Math.min(v, 30), 1);
if (value0 > value || value0 == 30) {
value0--;
} else {
value0++;
}
this.setSize(value0);
}
};
Neo.SizeSlider.prototype.slide = function (x, y) {
var value;
if (!Neo.painter.tool.alt) {
if (x >= 0 && x < 48 && y >= 0 && y < 41) {
var v = Math.floor(((y - 4) * 30.0) / 33.0);
value = v;
this.value0 = value;
this.y0 = y;
} else {
var d = (y - this.y0) / 7.0;
value = this.value0 + d;
}
} else {
// Ctrl+Alt+ドラッグでサイズ変更するとき
var d = y - this.y0;
value = this.value0 + d;
}
value = Math.max(Math.min(value, 30), 1);
this.setSize(value);
};
Neo.SizeSlider.prototype.setSize = function (value) {
value = Math.round(value);
Neo.painter.lineWidth = Math.max(Math.min(30, value), 1);
var tool = Neo.painter.getCurrentTool();
if (tool) {
if (tool.type == Neo.Painter.TOOLTYPE_BRUSH) {
Neo.painter.alpha = tool.getAlpha();
Neo.sliders[Neo.SLIDERTYPE_ALPHA].update();
} else if (tool.type == Neo.Painter.TOOLTYPE_TEXT) {
Neo.painter.updateInputText();
}
}
this.update();
};
Neo.SizeSlider.prototype.update = function () {
this.value = Neo.painter.lineWidth;
var height = (this.value * 33.0) / 30.0;
height = Math.max(Math.min(34, height), 1);
this.slider.style.height = height.toFixed(2) + "px";
this.label.innerHTML = this.value + "px";
this.slider.style.backgroundColor = Neo.painter.foregroundColor;
};
/*
-------------------------------------------------------------------------
LayerControl
-------------------------------------------------------------------------
*/
Neo.LayerControl = function () {};
Neo.LayerControl.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.isMouseDown = false;
var ref = this;
this.element.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
this.element.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
e.preventDefault();
},
true
);
this.element.className = "layerControl";
var layerStrings = [Neo.translate("Layer0"), Neo.translate("Layer1")];
this.element.innerHTML =
"<div class='bg'></div><div class='label0'>" +
layerStrings[0] +
"</div><div class='label1'>" +
layerStrings[1] +
"</div><div class='line1'></div><div class='line0'></div>";
this.bg = this.element.getElementsByClassName("bg")[0];
this.label0 = this.element.getElementsByClassName("label0")[0];
this.label1 = this.element.getElementsByClassName("label1")[0];
this.line0 = this.element.getElementsByClassName("line0")[0];
this.line1 = this.element.getElementsByClassName("line1")[0];
this.line0.style.display = "none";
this.line1.style.display = "none";
this.label1.style.display = "none";
this.update();
return this;
};
Neo.LayerControl.prototype._mouseDownHandler = function (e) {
if (Neo.getModifier(e) == "right") {
var visible = Neo.painter.visible[Neo.painter.current];
Neo.painter.visible[Neo.painter.current] = visible ? false : true;
} else {
var current = Neo.painter.current;
Neo.painter.current = current ? 0 : 1;
}
Neo.painter.updateDestCanvas(
0,
0,
Neo.painter.canvasWidth,
Neo.painter.canvasHeight
);
if (Neo.painter.tool.type == Neo.Painter.TOOLTYPE_PASTE) {
Neo.painter.tool.drawCursor(Neo.painter);
}
this.update();
if (this.onmousedown) this.onmousedown(this);
};
Neo.LayerControl.prototype.update = function () {
this.label0.style.display = Neo.painter.current == 0 ? "block" : "none";
this.label1.style.display = Neo.painter.current == 1 ? "block" : "none";
this.line0.style.display = Neo.painter.visible[0] ? "none" : "block";
this.line1.style.display = Neo.painter.visible[1] ? "none" : "block";
};
/*
-------------------------------------------------------------------------
ReserveControl
-------------------------------------------------------------------------
*/
Neo.reserveControls = [];
Neo.ReserveControl = function () {};
Neo.ReserveControl.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
var ref = this;
this.element.onmousedown = function (e) {
ref._mouseDownHandler(e);
};
this.element.addEventListener(
"touchstart",
function (e) {
ref._mouseDownHandler(e);
e.preventDefault();
},
true
);
this.element.className = "reserve";
var index = parseInt(this.name.slice(7)) - 1;
this.element.style.top = "1px";
this.element.style.left = index * 15 + 2 + "px";
this.reserve = Neo.clone(Neo.config.reserves[index]);
this.update();
Neo.reserveControls.push(this);
return this;
};
Neo.ReserveControl.prototype._mouseDownHandler = function (e) {
if (Neo.getModifier(e) == "right") {
this.save();
} else {
this.load();
}
this.update();
};
Neo.ReserveControl.prototype.load = function () {
Neo.painter.setToolByType(this.reserve.tool);
Neo.painter.foregroundColor = this.reserve.color;
Neo.painter.lineWidth = this.reserve.size;
Neo.painter.alpha = this.reserve.alpha;
switch (this.reserve.tool) {
case Neo.Painter.TOOLTYPE_PEN:
case Neo.Painter.TOOLTYPE_BRUSH:
case Neo.Painter.TOOLTYPE_TONE:
Neo.painter.drawType = this.reserve.drawType;
}
Neo.updateUI();
};
Neo.ReserveControl.prototype.save = function () {
this.reserve.color = Neo.painter.foregroundColor;
this.reserve.size = Neo.painter.lineWidth;
this.reserve.drawType = Neo.painter.drawType;
this.reserve.alpha = Neo.painter.alpha;
this.reserve.tool = Neo.painter.tool.getType();
this.element.style.backgroundColor = this.reserve.color;
this.update();
Neo.updateUI();
};
Neo.ReserveControl.prototype.update = function () {
this.element.style.backgroundColor = this.reserve.color;
};
/*
-------------------------------------------------------------------------
ScrollBarButton
-------------------------------------------------------------------------
*/
Neo.scrollH;
Neo.scrollV;
Neo.ScrollBarButton = function () {};
Neo.ScrollBarButton.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.element.innerHTML = "<div></div>";
this.barButton = this.element.getElementsByTagName("div")[0];
this.element["data-bar"] = true;
this.barButton["data-bar"] = true;
if (name == "scrollH") Neo.scrollH = this;
if (name == "scrollV") Neo.scrollV = this;
return this;
};
Neo.ScrollBarButton.prototype.update = function (oe) {
if (this.name == "scrollH") {
var a = oe.destCanvas.width / (oe.canvasWidth * oe.zoom);
var barWidth = Math.ceil(oe.destCanvas.width * a);
var barX = oe.scrollBarX * (oe.destCanvas.width - barWidth);
this.barButton.style.width = Math.ceil(barWidth) - 4 + "px";
this.barButton.style.left = Math.floor(barX) + "px";
} else {
var a = oe.destCanvas.height / (oe.canvasHeight * oe.zoom);
var barHeight = Math.ceil(oe.destCanvas.height * a);
var barY = oe.scrollBarY * (oe.destCanvas.height - barHeight);
this.barButton.style.height = Math.ceil(barHeight) - 4 + "px";
this.barButton.style.top = Math.floor(barY) + "px";
}
};
/*
-------------------------------------------------------------------------
ViewerButton
-------------------------------------------------------------------------
*/
Neo.ViewerButton = function () {};
Neo.ViewerButton.prototype = new Neo.Button();
Neo.ViewerButton.speedStrings = ["最", "早", "既", "鈍"];
Neo.ViewerButton.prototype.init = function (name, params) {
Neo.Button.prototype.init.call(this, name, params);
if (name != "viewerSpeed") {
this.element.innerHTML = "<canvas width=24 height=24></canvas>";
this.canvas = this.element.getElementsByTagName("canvas")[0];
var ctx = this.canvas.getContext("2d");
var img = new Image();
img.src = Neo.ViewerButton[name.toLowerCase().replace(/viewer/, "")];
img.onload = function () {
var ref = this;
ctx.clearRect(0, 0, 24, 24);
ctx.drawImage(img, 0, 0);
Neo.tintImage(ctx, Neo.config.color_text);
}.bind(this);
} else {
this.element.innerHTML = "<div></div><canvas width=24 height=24></canvas>";
this.update();
}
return this;
};
Neo.ViewerButton.prototype.update = function () {
if (this.name == "viewerSpeed") {
var mode = Neo.painter._actionMgr._speedMode;
var speedString = Neo.translate(Neo.ViewerButton.speedStrings[mode]);
this.element.children[0].innerHTML = "<div>" + speedString + "</div>";
}
};
Neo.ViewerButton.minus =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEX/////HgA/G9hMAAAAAXRSTlMAQObYZgAAABFJREFUCNdjYMAG5H+AEDYAADOnAi81ABEKAAAAAElFTkSuQmCC";
Neo.ViewerButton.plus =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEX/////HgD/HgAvnCBAAAAAAnRSTlMAAHaTzTgAAAAfSURBVAjXY2BAA0wTMAimVasaIARj2FQHCIGkBAUAAGm3CXHeKF1tAAAAAElFTkSuQmCC";
Neo.ViewerButton.play =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEX/////HgD/HgAvnCBAAAAAAnRSTlMAAHaTzTgAAAAuSURBVAjXY2BAABUQoQkitBxAxAQQsQRErAQRq+CspSBiKogIAekIABKqDhAzAAuwB6SsnxQ6AAAAAElFTkSuQmCC";
Neo.ViewerButton.stop =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEX/////HgA/G9hMAAAAAXRSTlMAQObYZgAAABFJREFUCNdjYIAB+x8EEBgAACjyDV75Mi9xAAAAAElFTkSuQmCC";
Neo.ViewerButton.rewind =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEX/////HgA/G9hMAAAAAXRSTlMAQObYZgAAACxJREFUCNdjYAADJiYGNjYGPj4GOTkGOzuGujqGf/9AJJANFAGKA2WBahgYAIE2Bb0RIYJRAAAAAElFTkSuQmCC";
/*
-------------------------------------------------------------------------
ViewerBar
-------------------------------------------------------------------------
*/
// length/mark/count
// update
Neo.ViewerBar = function () {};
Neo.ViewerBar.prototype.init = function (name, params) {
this.element = document.getElementById(name);
this.params = params || {};
this.name = name;
this.isMouseDown = false;
this.element.style.display = "inline-block";
this.element.innerHTML =
"<div id='viewerBarLeft'></div>" +
"<div id='viewerBarMark'></div>" +
"<div id='viewerBarText'>hoge</div>";
this.seekElement = this.element.children[0];
this.markElement = this.element.children[1];
this.textElement = this.element.children[2];
this.width = this.seekElement.offsetWidth;
this.length = this.params.length || 100;
this.mark = this.length;
this.seek = 0;
var ref = this;
this.element.onmousedown = function (e) {
ref.isMouseDown = true;
ref._touchHandler(e);
};
this.element.onmousemove = function (e) {
if (ref.isMouseDown) {
ref._touchHandler(e);
}
};
// this.element.onmouseup = function(e) { this.isMouseDown = false; }
// this.element.onmouseout = function(e) { this.isMouseDown = false; }
this.element.addEventListener(
"touchstart",
function (e) {
ref._touchHandler(e);
e.preventDefault();
},
true
);
this.update();
return this;
};
Neo.ViewerBar.prototype.update = function () {
this.mark = Neo.painter._actionMgr._mark;
this.seek = Neo.painter._actionMgr._head;
var markX = (this.mark / this.length) * this.width;
this.markElement.style.left = markX + "px";
var seekX = (this.seek / this.length) * this.width;
this.seekElement.style.width = seekX + "px";
this.textElement.innerHTML = this.seek + "/" + this.length;
};
Neo.ViewerBar.prototype._touchHandler = function (e) {
var x = e.offsetX / this.width;
x = Math.max(Math.min(x, 1), 0);
Neo.painter._actionMgr._mark = Math.round(x * this.length);
//this.update();
// console.log('mark=', this.mark, 'head=', Neo.painter._actionMgr._head);
Neo.painter.onmark();
};
// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
// This work is free. You can redistribute it and/or modify it
// under the terms of the WTFPL, Version 2
// For more information see LICENSE.txt or http://www.wtfpl.net/
//
// For more information, the home page:
// http://pieroxy.net/blog/pages/lz-string/testing.html
//
// LZ-based compression algorithm, version 1.4.4
var LZString = (function() {
// private property
var f = String.fromCharCode;
var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";
var baseReverseDic = {};
function getBaseValue(alphabet, character) {
if (!baseReverseDic[alphabet]) {
baseReverseDic[alphabet] = {};
for (var i=0 ; i<alphabet.length ; i++) {
baseReverseDic[alphabet][alphabet.charAt(i)] = i;
}
}
return baseReverseDic[alphabet][character];
}
var LZString = {
compressToBase64 : function (input) {
if (input == null) return "";
var res = LZString._compress(input, 6, function(a){return keyStrBase64.charAt(a);});
switch (res.length % 4) { // To produce valid Base64
default: // When could this happen ?
case 0 : return res;
case 1 : return res+"===";
case 2 : return res+"==";
case 3 : return res+"=";
}
},
decompressFromBase64 : function (input) {
if (input == null) return "";
if (input == "") return null;
return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrBase64, input.charAt(index)); });
},
compressToUTF16 : function (input) {
if (input == null) return "";
return LZString._compress(input, 15, function(a){return f(a+32);}) + " ";
},
decompressFromUTF16: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
return LZString._decompress(compressed.length, 16384, function(index) { return compressed.charCodeAt(index) - 32; });
},
//compress into uint8array (UCS-2 big endian format)
compressToUint8Array: function (uncompressed) {
var compressed = LZString.compress(uncompressed);
var buf=new Uint8Array(compressed.length*2); // 2 bytes per character
for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {
var current_value = compressed.charCodeAt(i);
buf[i*2] = current_value >>> 8;
buf[i*2+1] = current_value % 256;
}
return buf;
},
//decompress from uint8array (UCS-2 big endian format)
decompressFromUint8Array:function (compressed) {
if (compressed===null || compressed===undefined){
return LZString.decompress(compressed);
} else {
var buf=new Array(compressed.length/2); // 2 bytes per character
for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {
buf[i]=compressed[i*2]*256+compressed[i*2+1];
}
var result = [];
buf.forEach(function (c) {
result.push(f(c));
});
return LZString.decompress(result.join(''));
}
},
//compress into a string that is already URI encoded
compressToEncodedURIComponent: function (input) {
if (input == null) return "";
return LZString._compress(input, 6, function(a){return keyStrUriSafe.charAt(a);});
},
//decompress from an output of compressToEncodedURIComponent
decompressFromEncodedURIComponent:function (input) {
if (input == null) return "";
if (input == "") return null;
input = input.replace(/ /g, "+");
return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); });
},
compress: function (uncompressed) {
return LZString._compress(uncompressed, 16, function(a){return f(a);});
},
_compress: function (uncompressed, bitsPerChar, getCharFromInt) {
if (uncompressed == null) return "";
var i, value,
context_dictionary= {},
context_dictionaryToCreate= {},
context_c="",
context_wc="",
context_w="",
context_enlargeIn= 2, // Compensate for the first entry which should not count
context_dictSize= 3,
context_numBits= 2,
context_data=[],
context_data_val=0,
context_data_position=0,
ii;
for (ii = 0; ii < uncompressed.length; ii += 1) {
context_c = uncompressed.charAt(ii);
if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {
context_dictionary[context_c] = context_dictSize++;
context_dictionaryToCreate[context_c] = true;
}
context_wc = context_w + context_c;
if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {
context_w = context_wc;
} else {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {
if (context_w.charCodeAt(0)<256) {
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i=0 ; i<8 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position ==bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i=0 ; i<16 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
// Add wc to the dictionary.
context_dictionary[context_wc] = context_dictSize++;
context_w = String(context_c);
}
}
// Output the code for w.
if (context_w !== "") {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {
if (context_w.charCodeAt(0)<256) {
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i=0 ; i<8 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i=0 ; i<16 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
}
// Mark the end of the stream
value = 2;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == bitsPerChar-1) {
context_data_position = 0;
context_data.push(getCharFromInt(context_data_val));
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
// Flush the last char
while (true) {
context_data_val = (context_data_val << 1);
if (context_data_position == bitsPerChar-1) {
context_data.push(getCharFromInt(context_data_val));
break;
}
else context_data_position++;
}
return context_data.join('');
},
decompress: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); });
},
_decompress: function (length, resetValue, getNextValue) {
var dictionary = [],
next,
enlargeIn = 4,
dictSize = 4,
numBits = 3,
entry = "",
result = [],
i,
w,
bits, resb, maxpower, power,
c,
data = {val:getNextValue(0), position:resetValue, index:1};
for (i = 0; i < 3; i += 1) {
dictionary[i] = i;
}
bits = 0;
maxpower = Math.pow(2,2);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
switch (next = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2,8);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 1:
bits = 0;
maxpower = Math.pow(2,16);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 2:
return "";
}
dictionary[3] = c;
w = c;
result.push(c);
while (true) {
if (data.index > length) {
return "";
}
bits = 0;
maxpower = Math.pow(2,numBits);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
switch (c = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2,8);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize-1;
enlargeIn--;
break;
case 1:
bits = 0;
maxpower = Math.pow(2,16);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = resetValue;
data.val = getNextValue(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize-1;
enlargeIn--;
break;
case 2:
return result.join('');
}
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
if (dictionary[c]) {
entry = dictionary[c];
} else {
if (c === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result.push(entry);
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
enlargeIn--;
w = entry;
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
}
}
};
return LZString;
})();
if (typeof define === 'function' && define.amd) {
define(function () { return LZString; });
} else if( typeof module !== 'undefined' && module != null ) {
module.exports = LZString
} else if( typeof angular !== 'undefined' && angular != null ) {
angular.module('LZString', [])
.factory('LZString', function () {
return LZString;
});
}
|
(function (Modules) {
"use strict";
Modules.MultiselectAutocomplete = function () {
this.start = function ($element) {
var template = selectHTML();
appendAddButton();
createSelectElementsForSelectedOptions();
enableAutocomplete();
function selectHTML() {
var $select = selects().first();
$select.removeAttr('multiple');
var $wrapper = wrapper($select);
var $template = $wrapper.clone();
$template.find('[selected]').removeAttr('selected');
return $template.prop('outerHTML');
}
function addButton() {
return $(
'<button type="button" ' +
' class="btn btn-link add-multiselect js-add-multiselect"' +
' data-test-id="add-' + selectType() + '">' +
' Add another ' + selectType() +
'</button>'
).click(addSelect);
}
function removeButton() {
return $(
'<button type="button" ' +
' class="remove-multiselect js-remove-multiselect">' +
' <span class="glyphicon glyphicon-remove"' +
' aria-hidden="true"></span>' +
' <span class="sr-only">Remove ' + selectType() + '</span>' +
'</button>'
).click(removeSelect);
}
function appendAddButton() {
$element.append(addButton());
}
function createSelectElementsForSelectedOptions() {
selectedOptions().each(function (index, option) {
if (index > 0) {
$(template)
.insertAfter(lastSelectWrapper())
.find('option[value="' + $(option).val() + '"]')
.attr('selected', 'selected')
}
});
}
function enableAutocomplete() {
selects().each(function (index, select) {
// When we have a select with the multiple attribute set and no
// option is selected, the selectedIndex property will return -1. We
// have a blank option at index 0. Selecting the blank option
// circumvents a regression in the accessible autocomplete component
// where it assumes `selectedIndex` is always a positive number.
if (select.selectedIndex === -1) {
select.selectedIndex = 0;
}
enhanceSelectElement(select);
});
}
function selects() {
return $element.find('.js-multiselect');
}
function enhanceSelectElement(select) {
accessibleAutocomplete.enhanceSelectElement({
selectElement: select,
showAllValues: true,
autoselect: false,
dropdownArrow: dropdownArrow
});
wrapper($(select)).append(removeButton());
}
function addSelect() {
var $newSelectWrapper = $(template);
enhanceSelectElement($newSelectWrapper.find('select')[0]);
$newSelectWrapper.insertAfter(lastSelectWrapper());
}
function removeSelect(event) {
var $removeButton = $(event.target);
var $selectWrapper = wrapper($removeButton);
if (selects().length === 1) {
clearAutocompleteAndSelect($selectWrapper);
} else {
$selectWrapper.remove();
}
}
function clearAutocompleteAndSelect($selectWrapper) {
var $input = $selectWrapper.find('input');
$input.val('');
// Changing the value will expand the autocomplete, but without focus, meaning that
// it won't close if you click outside it. Here we manually focus and blur it, so
// the options don't display
$input.click().focus().blur();
// Clearing the input doesn't reset the select, so we have to reset it manually.
// See: https://github.com/alphagov/accessible-autocomplete/issues/220
$selectWrapper.find('select').val('');
}
function selects() {
return $element.find('.js-multiselect');
}
function selectedOptions() {
return $element.find('[selected]');
}
function lastSelectWrapper() {
return $element.find('.js-multiselect-wrapper').last();
}
function wrapper($wrapped) {
return $wrapped.closest('.js-multiselect-wrapper');
}
function dropdownArrow() {
return '<span class="caret"></span>';
}
function selectType() {
return $element.data('multiselect-type');
}
};
};
})(window.GOVUKAdmin.Modules);
|
var leafFunctionsAnalysis = require('../src/LeafFunctionsAnalysis')
var getSpiesJSON = function (variablesToSpy) {
var returnedJSON = []
returnedJSON.push({
variableDefinition: {
name: 'spiesDB', value: {
variables: [], functions: []
}
}
})
if (variablesToSpy.variables != undefined)
variablesToSpy.variables.forEach(variable => {
returnedJSON = returnedJSON.concat(getVariableSpyJSON(variable))
})
if (variablesToSpy.functions != undefined)
variablesToSpy.functions.forEach(functionSpy => {
returnedJSON.push(getFunctionSpyJSON(functionSpy))
})
return returnedJSON
}
var getVariableSpyJSON = function (variableSpy) {
returnedJSON = [{
reportSpiedVariableValue: {
name: '\'' + variableSpy.name + '\'',
tag: '\'Initial\'', value: variableSpy.name, spiesDB: 'spiesDB'
}
}
]
var functionleaves = leafFunctionsAnalysis(variableSpy.variable)
functionleaves.forEach(functionLeaf => {
returnedJSON.push(getFunctionSpyJSON({
name: variableSpy.name + functionLeaf,
}))
})
return returnedJSON
}
var getFunctionSpyJSON = function (functionSpy) {
return {
block: [
{ copyFunctionToTemporaryVariable: { functionName: functionSpy.name } },
{
functionAssignment: {
name: functionSpy.name,
content: [{ callSpiedFunctionAndStoreResult: { returnVariable: 'output' } },
{ reportSpiedFunctionCallingArgumentsAndResult: { functionName: functionSpy.name, returnVariable: 'output', spiesDB: 'spiesDB' } },
{ returnOutput: { returnVariable: 'output' } }]
}
}
]
}
}
module.exports = getSpiesJSON
|
const Ice = require('ice').Ice;
const Murmur = require('./Generated/Murmur.js').Murmur;
function ice() {
return Ice.Promise.try(() => {
const host = process.env.MURMUR_HOST;
const port = process.env.MURMUR_PORT;
const secret = process.env.MURMUR_SECRET;
console.log('Connecting to murmur on ' + host + ':' + port);
const iceOptions = new Ice.InitializationData();
iceOptions.properties = Ice.createProperties([], iceOptions.properties);
iceOptions.properties.setProperty('Ice.Default.EncodingVersion', '1.0');
iceOptions.properties.setProperty('Ice.ImplicitContext', 'Shared');
const communicator = Ice.initialize(iceOptions);
if (secret) {
communicator.getImplicitContext().put('secret', secret);
}
const proxy = communicator.stringToProxy('Meta:tcp -h ' + host + ' -p ' + port);
return Murmur.MetaPrx.checkedCast(proxy);
})
}
async function getUsers(serverId) {
const meta = await ice();
if (!meta) {
throw new Error('Could not get meta');
}
const server = await meta.getServer(serverId);
if(!server) {
throw new Error('Could not get server');
}
const users = await server.getUsers();
return Array.from(users.values()).map((c) => ({
id: c.userid,
name: c.name,
channel: c.channel,
}));
}
async function getChannels(serverId) {
const meta = await ice();
if (!meta) {
throw new Error('Could not get meta');
}
const server = await meta.getServer(serverId);
if(!server) {
throw new Error('Could not get server');
}
const channels = await server.getChannels();
return Array.from(channels.values()).map((c) => ({
id: c.id,
name: c.name,
parent: c.parent,
position: c.position,
}));
}
module.exports = {
getUsers,
getChannels
};
|
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import * as React from 'react';
import {screenBackgroundColor} from '../stylesheets/color-sheme';
function RecipeQuad({navigation}) {
return (
<View style={planStyles.tileContainer}>
<View style={planStyles.rowContainer}>
<TouchableOpacity style={planStyles.recipeTile} onPress={() => navigation.navigate('Recipe')}>
<Text>Recipe 1</Text>
</TouchableOpacity>
<View style={planStyles.spacer} />
<TouchableOpacity style={planStyles.recipeTile} onPress={() => navigation.navigate('Recipe')}>
<Text>Recipe 2</Text>
</TouchableOpacity>
</View>
<View style={planStyles.spacer} />
<View style={planStyles.rowContainer}>
<TouchableOpacity style={planStyles.recipeTile} onPress={() => navigation.navigate('Recipe')}>
<Text>Recipe 3</Text>
</TouchableOpacity>
<View style={planStyles.spacer} />
<TouchableOpacity style={planStyles.recipeTile} onPress={() => navigation.navigate('Recipe')}>
<Text>Recipe 4</Text>
</TouchableOpacity>
</View>
</View>
)
}
const planStyles = StyleSheet.create({
planContainer: {
display: 'flex',
flex: 1,
flexDirection: 'column',
alignItems: 'center',
backgroundColor: screenBackgroundColor
},
tileContainer: {
display: 'flex',
flex: 1,
flexDirection: 'column',
alignItems: 'center',
},
rowContainer: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
recipeTile: {
borderRadius: 10,
height: 150,
width: 150,
textAlign: 'center',
backgroundColor: 'lightgray',
justifyContent: 'center',
alignItems: 'center',
},
spacer: {
height: 10,
width: 10
}
});
export default RecipeQuad;
|
import { v4 as uuidv4 } from 'uuid';
import { AppError } from "../errors";
import { User } from "../models";
class RegisterController {
async store(req, res) {
const {
body: { name, email, password }
} = req;
const messages = {
success: "Usuário cadastrado com sucesso.",
error: "Ocorreu um erro. Por favor, tente novamente mais tarde.",
userAlreadyExists: "Usuário já cadastrado, faça login para acessar o sistema."
}
let userAlreadyExists;
try {
userAlreadyExists = await User.findOne({ where: { email } });
} catch (error) {
throw new AppError(messages.error);
}
if (userAlreadyExists) {
throw new AppError(messages.userAlreadyExists);
}
try {
await User.create({ id: uuidv4(), name, email, password });
return res.json({ message: messages.success });
} catch (error) {
throw new AppError(messages.error);
}
}
}
export default new RegisterController();
|
import React from 'react'
import { mount } from 'enzyme'
import { default as MUITable} from '@material-ui/core/Table'
import TableCell from '@material-ui/core/TableCell'
import { getTableProps } from 'Test/factories'
import Loading from '../Loading'
describe('<Loading />', () => {
test('rendering', () => {
const tableProps = getTableProps()
const loading = mount(
<MUITable>
<Loading columns={tableProps.columns} />
</MUITable>
)
const cells = loading.find(TableCell).children()
expect(cells).toHaveLength(1)
expect(cells.at(0)).toIncludeText('Loading data...')
})
})
|
const BaseXform = require('../base-xform');
const BodyPrXform = require('./body-pr-xform');
const PXform = require('./p-xform');
class RichXform extends BaseXform {
constructor() {
super();
this.map = {
'a:bodyPr': new BodyPrXform(),
'a:p': new PXform(),
};
}
get tag() {
return 'c:rich';
}
render(xmlStream, model) {
xmlStream.openNode(this.tag);
this.map['a:bodyPr'].render(xmlStream, model.direction);
xmlStream.leafNode('a:lstStyle');
this.map['a:p'].render(xmlStream, model.texts);
xmlStream.closeNode();
}
parseOpen(node) {}
parseText(text) {}
parseClose(name) {}
reconcile(model, options) {}
}
module.exports = RichXform;
|
$(
function() {
$('.square').on('click', function() {
var x = this.text();
$('.answers').text(x);
});
}
)
|
import React, { useEffect } from "react";
import { Container, Row, Col } from 'react-bootstrap';
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import bellcurve from 'highcharts/modules/histogram-bellcurve';
import './Analytics.scss'
export const Analytics = ({ userScores, metrics }) => {
(bellcurve)(Highcharts)
useEffect(() => {
}, [metrics])
const generateCategories = () => {
const categories = []
var current = 0
for (var i = 0; i <10; i++)
{
if(current === 0) {
categories.push(`${current}-${current+10}`)
current = current+11
}
else {
categories.push(`${current}-${current+9}`)
current = current+10
}
}
return categories
}
const generateColour = (index, score) => {
if(score >= 100 && index === 9) return '#1F75FE'
if (index === Math.floor(score/10)) return '#1F75FE'
else return '#B9DFFF'
}
const generateColumns = (index, score) => {
return metrics.percentileMiniGameScores[index].map((value, index) => {
return {
x: index,
y: value,
color: generateColour(index, score),
}
})
}
const getMaxPercentile = (index) => {
return Math.max(...metrics.percentileMiniGameScores[index]) + 1
}
const generateMiniGameCharts = () => {
return userScores.map((score, index) => {
const options = {
chart: {
type: 'column'
},
title: {
text: `MiniGame ${index+1}`
},
xAxis: {
categories: generateCategories(),
crosshair: true,
title: {
text: 'MiniGame Scores (%)'
}
},
yAxis: {
min: 0,
max: getMaxPercentile(index),
title: {
text: 'Number of Users'
}
},
series: [
{
type: 'column',
name: 'Playerbase Scores',
color: '#B9DFFF',
data: generateColumns(index,score)
},
{
type: 'column',
name: 'User Score',
color: '#1F75FE',
}
]
}
return (
<Col key={index} xs={6}>
<HighchartsReact
highcharts={Highcharts}
options={options}
/>
</Col>
)
})
}
return (
<Container id="Analytics" fluid className="px-5">
<Row className="pb-5">
<Col style={{'font-size': '2rem'}} className="text-center">
<p>The <span style={{color: '#B9DFFF'}}>lighter blue</span> indicates the player base score</p>
<p>The <span style={{color: '#1F75FE'}}>darker blue</span> indicates where your score falls</p>
</Col>
</Row>
{metrics && (
<Row>
{generateMiniGameCharts()}
</Row>
)
}
</Container>
);
}
|
//goalsController.js
(function(){
// add 2 controllers
angular.module('goalsCtrl', [])
.controller('goalsController', goalsController)
//.controller('goalDetailController', goalDetailController)
// inject both controllers with goals factory
// these 2 both use the goals factory:
//goalsController.$inject = ['goals', '$window']
goalsController.$inject = ['goals','$routeParams', '$window', '$location'] //location is for rendering a new view
function goalsController(goals, $routeParams, $window, $location){
var self = this
self.name = 'Goal List'
self.api = goals //goals factory
// for full list user's of goals from DB
self.goals = []
// all goals in the system
self.all_goals = []
// for a new goal to POST
self.newGoal = {}
// for the single goal being processed here
self.goal = null
//// get list of goals, and set this controller's 'goals' property to
//// the array we get back from our API
//self.api.list().success(function(response){ //call factory function
// self.goals = response
//})
self.showGoals = function(user_id){
self.api.list(user_id).success(function(response){ //call factory function
self.goals = response.data
})
}
self.api.list_all().success(function(response){ //call factory function
self.all_goals = response //not in .data for some reason...
})
// controller method for adding a new goal, invoked when user hits submit
//self.addGoal = function(parent_categories_heirachy, goal_or_task, date_created,
// zen_level, reminder, optional_due_date, completed, priority) {
self.addGoal = function(user_id) {
// set a high priority if completed so as to sort lower
if (self.goal.completed) self.goal.priority = 11;
// run the goal factory's addGoal method to send the POST request with the data object we just created
self.api.addGoal(user_id, self.goal).then(function success(response){
console.log('added a goal!')
// when we successfully finish the POST request, take the server's response (the new goal) and add
// it to this controller's goal list, which updates the front-end with the new goal
self.goals.push(response.data.goal)
// clear this controller's newGoal object, which clears the input fields on the front-end
self.newGoal = {}
// focus on the first input field for the user to add another goal (UI enhancement)
$window.location = '/#/profile'
})
}
self.d3_displayed = {};
self.setGraph = function(goal_id) {
if (!self.d3_displayed[goal_id]) {
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time (e.g. 2015-12-18T03:30:34.430Z)
var parseDate = d3.time.format("%Y-%m-%d").parse;
// Set the scale ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");
var yAxis = d3.svg.axis().scale(y)
.orient("left");
// Define the lines
var hrsline = d3.svg.line()
.x(function(d) { return x(d.m_date); })
.y(function(d) { return y(d.hours_devoted); });
var qline = d3.svg.line()
.x(function(d) { return x(d.m_date); })
.y(function(d) { return y(d.quality); });
var resline = d3.svg.line()
.x(function(d) { return x(d.m_date); })
.y(function(d) { return y(d.percieved_result); });
// Get the data
d3.json('/api/goals/'+goal_id, function(error, goal){
if (error) throw error;
//*** don't draw canvas or graph if no data ***
if (goal.monitoring.length <= 1) return;
// Adds the svg canvas
var svg = d3.select("#monitoring-chart"+goal_id)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
goal.monitoring.forEach(function(d, i) {
//chop date
var trimmed_date = d.m_date.substring(0, 10);
//console.log("trimmed_date="+trimmed_date)
d.m_date = parseDate(trimmed_date);
// add data progrssivly, scale quality and percieved result by 10*#hrs
goal.monitoring[i].quality = (goal.monitoring[i].quality/10)
* goal.monitoring[i].hours_devoted;
goal.monitoring[i].percieved_result = (goal.monitoring[i].percieved_result/10)
* goal.monitoring[i].hours_devoted;
if (i > 0) {
goal.monitoring[i].hours_devoted += goal.monitoring[i-1].hours_devoted;
goal.monitoring[i].quality += goal.monitoring[i-1].quality;
goal.monitoring[i].percieved_result += goal.monitoring[i-1].percieved_result;
}
});
// Scale the range of the data (scale y on hours devoted since that
// should be the largest value)
x.domain(d3.extent(goal.monitoring, function(d) { return d.m_date; }));
y.domain([0,
d3.max(goal.monitoring, function(d) { return d.hours_devoted; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(5, 0)")
.append("text")
.text("Blue is cumulative hours devoted");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(5, 20)")
.append("text")
.text("Green is cumulative scaled quality");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(5, 40)")
.append("text")
.text("Purple is cumulative scaled result");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end");
//.text("Monitoring");
svg.append("path")
.attr("class", "hrsline")
.attr("d", hrsline(goal.monitoring) )
.attr('stroke', 'blue')
.attr('stroke-width', 5.0)
.attr('fill', 'none')
svg.append("path")
.attr("class", "qline")
.attr("d", qline(goal.monitoring) )
.attr('stroke', 'green')
.attr('stroke-width', 4.0)
.attr('fill', 'none')
svg.append("path")
.attr("class", "resline")
.attr("d", resline(goal.monitoring) )
.attr('stroke', 'purple')
.attr('stroke-width', 3.5)
.attr('fill', 'none')
});
self.d3_displayed[goal_id] = true;
}
else {
// erase graph (<br> keeps buttons aligned...)
document.getElementById("monitoring-chart"+goal_id).innerHTML = "<br>";
self.d3_displayed[goal_id] = false;
}
}
//******** THIS ONE CURRENTLY NOT USED *************
self.setChart = function(goal_id) { // user_id ) {
if (!self.d3_displayed) {
console.log('In setChart, goal_id= '+goal_id)
//***This doesn't work on user logged in section routes:
// d3.json('/api/goals/users/'+user_id, function(error, data){ //Get data from given route, // get all goals for a user
//d3.json('/api/goals/'+goal_id, function(error, data){ //Get data from given route,
d3.json('/api/goals/'+goal_id, function(error, goal){ //Get data from given route,
// get given goal
if(error) throw error;
//console.log(data);
console.log(goal);
var hrs = [];
var dates = [];
var p_quals = [];
var p_results = [];
//all_hrs = data.map(function(goal){
// var hrs = []
hrs = goal.monitoring.map(function(monitor){
return monitor.hours_devoted;
})
dates = goal.monitoring.map(function(monitor){
return monitor.m_date;
})
console.log("dates: "+dates);
p_quals = goal.monitoring.map(function(monitor){
return monitor.quality;
})
p_results = goal.monitoring.map(function(monitor){
return monitor.percieved_result;
})
// return hrs
//})
console.log(hrs)
//Width and height
var w = 500;
var h = 100;
var svg = d3.select("#monitoring-chart"+goal_id) //selecting entire div from D3
.append("svg") //appending SVG to the body
.attr("width", w) //setting the width of the svg
.attr("height", h) //setting the height of the svg
svg.selectAll("rect")
//.data(hrs[0]) //set the data source to be the array of hours
.data(hrs) //set the data source to be the array of hours
.enter() //entering the data set to drill
.append("rect") //appending a rectangle for each hour
.attr("x", function(d, i){ //spacing between bars
return i*30
}) //initial set of x axis
.attr("y",0) //initial set of y axis
.attr("width", 20) //initial width of rect
.attr("height", function(d, i){
//return d/10
return d*10; //changing this helped, prolly make it even or up to *5
}) //inital height of rect
})
self.d3_displayed = true;
}
else {
self.d3_displayed = false;
}
}
// default boolean value, which we can toggle true/false for showing/hiding the goal edit form
self.editing = false
// Set up goal editing UI:
// retrieve a goal via the url parameter for goalId, then set this controller's goal property
// to the response in order to to show it on the front-end
self.editGoal = function(goalId){
self.api.show(goalId).success(function(response){
self.goal = response
console.log("got goal to update:")
console.log( response )
$window.location = '#/editgoal/'+goalId
self.zen_level = response.zen_level
self.editing = true;
})
}
self.showGoal = function(goalId){
self.api.show(goalId).success(function(response){
self.goal = response
})
}
self.showGoal($routeParams.goalId) //This is needed to be able to edit!
// update the goal, on successful PATCH, set the goal object to the response from the server,
// which updates the front-end
self.updateGoal = function() {
// set a high priority if completed so as to sort lower
if (self.goal.completed) self.goal.priority = 11;
self.api.updateGoal(self.goal).success(function(response){
console.log(response)
self.goal = response
self.editing = false
$window.location = '/#/profile'
//location.reload();
})
}
self.newMon = {};
self.addStatus = function(goal) {
goal.monitoring.push(self.newMon) //set in add-update-monitor-form.html
self.newMon = {} //clear out values for next one
self.api.updateGoal(goal).success(function(response){
self.goal = response
self.editing = false
alert("Monitoring added for " + response.monitoring[response.monitoring.length-1].m_date);
location.reload();
})
}
self.showModal = false;
self.selectedMonitor = {};
self.selectMonitor = function(goal, monitor){
//self.newMon = JSON.parse(JSON.stringify(monitor));
self.selectedMonitor = monitor;
self.selectedMonitor.goal = goal.goal_or_task;
self.goal = goal;
}
self.showStatus = function(goalId, statusIndex){
self.api.show(goalId).success(function(response){
self.goal = response;
if (statusIndex !== undefined)
self.newMon = self.goal.monitoring[statusIndex];
})
}
self.showStatus($routeParams.goalId, $routeParams.statusIndex) //This is needed to be able to edit!
// update the monitoring, on successful PATCH, set the goal object to the response from the server,
// which updates the front-end
self.editStatus = function(goalId, statusIndex){
self.api.show(goalId).success(function(response){
self.goal = response
$window.location = '#/editstatus/'+goalId +'/'+statusIndex;
})
}
self.updateStatus = function(goal) {
goal.monitoring[$routeParams.statusIndex] = self.newMon; //don't clear newMon after this incase there's more editing
self.api.updateGoal(goal).success(function(response){
self.goal = response
self.editing = false
alert("Monitoring updated for "
+ response.monitoring[$routeParams.statusIndex].m_date);
$window.location = '/#/profile'
//location.reload();
})
}
// delete the goal using this, then afterwards, redirect the user back to the same page
self.removeGoal = function(goalId, user){
var r = confirm("Delete Goal?");
if (r == true) {
self.api.removeGoal(goalId).success(function(response){
console.log(response)
// $location.path('/monitor')
location.reload();
self.showGoals( user._id )
})
}
}
self.click = function( stuff ) {
console.log( "Hello", stuff)
}
}
}())
|
import React, { useState } from 'react';
import InputSection from './input-section';
import DaysCardSection from './days-card-section';
import './App.css';
function App() {
const [daysCardData, setDaysCardData] = useState();
return (
<div className="App">
<div className="root">
<div>
<div className="headerText">Birthday Cal</div>
</div>
<div>
<DaysCardSection daysCardData={daysCardData} />
</div>
<div>
<InputSection onUpdate={(data) => setDaysCardData(data)} />
</div>
</div>
</div>
);
}
export default App;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsTextRotationDown = {
name: 'text_rotation_down',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 12v-1.5L10 5.75v2.1l2.2.9v5l-2.2.9v2.1L21 12zm-7-2.62l5.02 1.87L14 13.12V9.38zM6 19.75l3-3H7V4.25H5v12.5H3l3 3z"/></svg>`
};
|
/**
* 会员查询详细下拉收缩效果
* @author: terry <jfengsky@gmail.com>
* @date: 2013-10-22 16:00
*/
define(function(require, exports, module) {
var $ = require('jquery'),
move = require('../move');
function Slide(){
var self = this;
this.up = function(){
console.log(move);
};
this.down = function(){
move('#J_quebox',{
height: 100
})
};
this.init = function(){
if($('#J_memsearch').get(0)){
Hammer($('#J_memsearch').get(0)).on('tap', function(){
// $('#J_memsearch').click(function(){
if($(this).hasClass('arrup')){
// 收起
$(this).removeClass('arrup');
$('#J_quebox').css('height', 0).show();
move('#J_quebox',{
height: 150
});
} else {
// 下拉
$(this).addClass('arrup');
move('#J_quebox',{
height: 0
}, function(){
$('#J_quebox').hide();
});
}
});
}
};
};
new Slide().init();
module.exports = Slide;
});
|
let connector = null;
let connectedButton = null;
let providerConnected = "";
// Button declarations
window.onload = function() {
if(!window.location.hash){
window.location = window.location + '#loaded';
window.location.href = window.location.href
}
}
const connectMetaMaskButton = document.querySelector(".connectMetaMask");
const connectTorusButton = document.querySelector(".connectTorus");
const connectWalletConnectButton = document.querySelector(".connectWalletConnect");
const connectPortisButton = document.querySelector(".connectPortis");
const connectBitskiButton = document.querySelector(".connectBitski");
const connectFortmaticButton = document.querySelector(".connectFortmatic");
const connectVenlyButton = document.querySelector(".connectVenly");
const connectCoinbaseButton = document.querySelector(".connectCoinbase");
// Button click listener
connectMetaMaskButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.METAMASK);
connectedButton = connectMetaMaskButton;
providerConnected = "MetaMask";
connection();
} else {
connector.disconnection();
}
});
connectTorusButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.TORUS);
connectedButton = connectTorusButton;
providerConnected = "Torus";
connection();
} else {
connector.disconnection();
}
});
connectWalletConnectButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.WALLETCONNECT);
connectedButton = connectWalletConnectButton;
providerConnected = "WalletConnect";
connection();
} else {
connector.disconnection();
}
});
connectPortisButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.PORTIS);
connectedButton = connectPortisButton;
providerConnected = "Portis";
connection();
} else {
connector.disconnection();
}
});
connectBitskiButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.BITSKI);
connectedButton = connectBitskiButton;
providerConnected = "Bitski";
connection();
} else {
connector.disconnection();
}
});
connectFortmaticButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.FORTMATIC);
connectedButton = connectFortmaticButton;
providerConnected = "Fortmatic";
connection();
} else {
connector.disconnection();
}
});
connectVenlyButton.addEventListener("click", async() => {
if(connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.VENLY);
connectedButton = connectVenlyButton;
providerConnected = "Venly";
connection();
} else {
connector.disconnection();
}
});
connectCoinbaseButton.addEventListener("click", async () => {
if (connector == null || !connector.isConnected) {
connector = await ConnectorManager.instantiate(ConnectorManager.providers.COINBASE);
connectedButton = connectCoinbaseButton;
providerConnected = "Coinbase";
connection();
} else {
connector.disconnection();
}
});
/** Disable or enable all connection buttons
* @param the value to set (true = disable)
*/
function setDisabledConnectButtons(value) {
connectMetaMaskButton.disabled = value;
connectTorusButton.disabled = value;
connectWalletConnectButton.disabled = value;
connectPortisButton.disabled = value;
connectBitskiButton.disabled = value;
connectFortmaticButton.disabled = value;
connectVenlyButton.disabled = value;
connectCoinbaseButton.disabled = value;
}
/** Initialize the connector with events onConnection and onDisconnection */
function initConnector() {
connector.onConnection = async () => {
connectedButton.disabled = false;
const accounts = await connector.web3.eth.getAccounts();
document.querySelector(".address").innerHTML = accounts[0];
};
connector.onDisconnection = () => {
setDisabledConnectButtons(false);
document.querySelector(".address").innerHTML = "";
connectedButton.innerHTML = "Connect " + providerConnected;
connectedButton = null;
providerConnected = "";
};
connector.onAccountChanged = (account) => {
document.querySelector(".address").innerHTML = account;
};
}
/** Local function called when a connection/disconnection is engaged to update the frontend */
async function connection(desc) {
initConnector();
setDisabledConnectButtons(true);
if (await connector.connection()) {
connectedButton.innerHTML = "Disconnect " + providerConnected;
web3 = connector.web3;
} else {
setDisabledConnectButtons(false);
console.log("Connection failed");
}
}
|
const { models } = require('../database/index');
const _ = require('lodash');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const JWTSecret = 'secret';
module.exports = {
async refreshToken(req, res) {
try {
const user = await models.User.findByPk(req.userId);
jwt.sign({ id: user.id }, JWTSecret, { expiresIn: '12h' }, (err, token) => {
if (err) {
console.log('Error generating token: ', err);
return res.status(500).json({
message: "Error generating token"
})
} else {
return res.status(200).json({ token: token, user: _.omit(user.toJSON(), ['password_digest']) });
}
});
}
catch(error) {
console.log('Error generating token: ', error);
return res.status(500).json({
message: "Error generating token"
})
}
},
async login(req, res) {
const { email, password } = req.body;
if (!email || !password) {
return res.status(401).json({ message: "Fields 'email' or 'password' are missing" })
}
try {
const user = await models.User.findOne({ where: { email: email } });
const validPassword = await bcrypt.compare(password, user.password_digest);
if (!validPassword) {
return res.status(401).json({
message: "Fields 'email' or 'password' are invalid"
})
}
jwt.sign({ id: user.id }, JWTSecret, { expiresIn: '12h' }, (err, token) => {
if (err) {
console.log('Error generating token: ', err);
return res.status(500).json({
message: "Error generating token"
})
} else {
return res.status(200).json({ token: token, user: _.omit(user.toJSON(), ['password_digest']) });
}
});
}
catch(error) {
return res.status(401).json({
message: "Fields 'email' or 'password' are invalid"
})
};
return;
},
async create(req, res) {
let { name, email, password } = req.body;
if (!email || !name || !password) {
return res.status(400).json({ message: "Fields {email, name, password} required" })
}
try {
const salt = await bcrypt.genSalt(10);
const password_digest = await bcrypt.hash(password, salt);
const user = await models.User.create({
email: email,
name: name,
password_digest: password_digest,
});
res.status(201).json(_.omit(user.toJSON(), ['password_digest']));
}
catch(error) {
res.status(400).json(error)
};
return;
},
async getAll(req, res) {
try {
const usersWithPassword = await models.User.findAll();
const users = usersWithPassword.map((user) => {
return _.omit(user.toJSON(), ['password_digest']);
});
res.status(200).json(users);
}
catch(error) {
res.status(400).json(error)
};
return;
},
async getById(req, res) {
const { id } = req.params;
if(isNaN(id)) {
return res.status(400).json({ message: 'Field "id" is invalid' });
}
try {
const user = await models.User.findByPk(id);
res.status(200).json(_.omit(user.toJSON(), ['password_digest']));
}
catch(error) {
res.status(404).json( { message: `User with id ${id} not found` });
};
return;
},
async update(req, res) {
const { id } = req.params;
if(isNaN(id)) {
return res.status(400).json({ message: 'Field "id" is invalid' });
}
const { email, name, password } = req.body;
try {
const user = await models.User.findByPk(id);
user.email = email ? email : user.email;
user.name = name ? name : user.name;
if(password) {
const salt = await bcrypt.genSalt(10);
const password_digest = await bcrypt.hash(password, salt);
user.password_digest = password_digest;
}
try {
await user.save();
res.status(200).json(_.omit(user.toJSON(), ['password_digest']));
} catch (error) {
res.status(400).json(error);
}
}
catch(error) {
res.status(404).json( { message: `User with id ${id} not found` });
};
return;
},
async delete(req, res) {
const { id } = req.params;
if(isNaN(id)) {
return res.status(400).json({ message: 'Field "id" is invalid' });
}
try {
const user = await models.User.findByPk(id);
if(user) {
try {
await models.User.destroy({ where: { id: id } });
res.status(200).json({ message: `User with id ${id} deleted successfully` });
} catch (error) {
res.status(400).json(error);
}
}
else {
res.status(404).json( { message: `User with id ${id} not found` });
}
}
catch(error) {
res.status(404).json( { message: `User with id ${id} not found` });
};
return;
},
};
|
import http from 'k6/http';
export const options = {
thresholds: {
http_req_failed: ['rate<0.01'], // http errors should be less than 1%
http_req_duration: ['p(95)<200'], // 95% of requests should be below 200ms
},
};
export default function () {
http.get('https://test-api.k6.io/public/crocodiles/1/');
}
|
import { loadingHide } from "./footballAPI.js";
//Cards container getSatands
const cardsGetStands = (resStand) => {
let containerHTML = "";
let containerHeaderHome = `
<header>
<h5>Match standings of Premier League</h5>
<h6>First Teams</h6>
<hr />
</header>
`;
let containerHeader = `
<tr>
<th>Position</th>
<th>Team</th>
<th></th>
<th>PG</th>
<th>Won</th>
<th>Draw</th>
<th>Lost</th>
<th>GD</th>
<th>GA</th>
<th>GF</th>
<th>Points</th>
</tr>`;
const strUrl = JSON.stringify(resStand).replace(/http:/g, "https:");
JSON.parse(strUrl).standings[0].table.forEach((stand) => {
console.log(stand);
containerHTML +=
/*html*/
`<tr>
<td class="center">${stand.position}</td>
<td>
<a href="./detailsTeam.html?id=${stand.team.id}">
<img
src="${stand.team.crestUrl}"
style="width:20px;"
alt="logo-${stand.team.name}"
/>
</a>
</td>
<td style="text-align:start">
<a href="./detailsTeam.html?id=${stand.team.id}">${stand.team.name}</a>
</td>
<td class="center">${stand.playedGames}</td>
<td class="center">${stand.won}</td>
<td class="center" >${stand.draw}</td>
<td class="center">${stand.lost}</td>
<td class="center">${stand.goalDifference}</td>
<td class="center">${stand.goalsAgainst}</td>
<td class="center">${stand.goalsFor}</td>
<td class="center">${stand.position}</td>
</tr>`;
});
document.getElementById("headerHome").innerHTML = containerHeaderHome;
document.getElementById("headerStands").innerHTML = containerHeader;
document.getElementById("containerStands").innerHTML = containerHTML;
loadingHide();
};
// container cards getMatch
const cardsGetMatch = (matchs) => {
let containerHTML = "";
let containerHeaderHtml = `
<header>
<h5>Match of Premier League</h5>
<h6>First Teams</h6>
<hr />
</header>`;
let containerHeaderMatch = `
<tr>
<th class="center">Away Team</th>
<th></th>
<th class="center">Home Team</th>
<th class="center">Date</th>
</tr>`;
matchs.matches.forEach((match) => {
console.log(match);
containerHTML += `
<tr>
<td class="right"><a href="./detailsTeam.html?id=${match.awayTeam.id}">${match.awayTeam.name}</a> (${match.score.fullTime.awayTeam})</td>
<td class="center">VS</td>
<td class="left">(${match.score.fullTime.homeTeam}) <a href="./detailsTeam.html?id=${match.homeTeam.id}">${match.homeTeam.name}</a></td>
<td class="center">${match.utcDate}</td>
</tr>
`;
});
document.getElementById("headerMatch").innerHTML = containerHeaderHtml;
document.getElementById("headerMatchs").innerHTML = containerHeaderMatch;
document.getElementById("containerMatch").innerHTML = containerHTML;
loadingHide();
};
// container cards getSaveMyTeam
const cardsGetSaveMyTeam = (details) => {
let containerHTML = "";
if (details.length == 0) {
containerHTML += `
<div class="col s12">
<h6 class="center-align noTeam">No favorite team found!</6>
</div>`;
}
details.forEach((detail) => {
// Menyusun komponen card artikel secara dinamis
containerHTML += /*html*/ `
<div class="col l4 m6 s12 cardDetails">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<a href="./detailsTeam.html?id=${detail.id}&favTeam=true">
<img style="height:20px;" class="activator" src="${detail.crestUrl}" />
<span class="card-title"></span>
</a>
</div>
<div class="card-content">${detail.name}
</div>
</div>
</div>
`;
});
document.getElementById("containerFavTeam").innerHTML = containerHTML;
};
var getCardsTeamById = (detail) => {
let containerHTML = /*html*/ `
<div class="row">
<div class="col s12 center-align">
<header>
<h5>Team Details of ${detail.name} </h5>
<hr />
</header>
</div>
</div>
<div class="row">
<div class="col s8 offset-s2 cardDetails">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="${detail.crestUrl}" />
</div>
<div class="card-content">
<span class="card-title activator">${detail.name}</span>
<p>Short Name :<i></i> ${detail.shortName}</p>
<p>Club Color :<span></span> ${detail.clubColors}</p>
<p>Address :<i></i> ${detail.address}</p>
<p>Phone :<i></i> ${detail.phone}</p>
</div>
</div>
</div>
</div>`;
return containerHTML;
};
const cardsDetailTeam = (details) => {
let containerHTML = /*html*/ `
<div class="row">
<div class="col s12 center-align">
<header>
<h5>Team Details of ${details.name} </h5>
<hr />
</header>
</div>
</div>
<div class="row">
<div class="col s8 offset-s2 cardDetails">
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="${details.crestUrl}" />
</div>
<div class="card-content">
<span class="card-title activator">${details.name}</span>
<p>Short Name :<i></i> ${details.shortName}</p>
<p>Club Color :<span></span> ${details.clubColors}</p>
<p>Address :<i></i> ${details.address}</p>
<p>Phone :<i></i> ${details.phone}</p>
</div>
</div>
</div>
</div>`;
return containerHTML;
};
export {
cardsGetStands,
cardsGetMatch,
cardsGetSaveMyTeam,
getCardsTeamById,
cardsDetailTeam,
};
|
//user.test.js
'use strict';
process.env.NODE_ENV = 'test';
const chai = require('chai');
const should = chai.should();
const config = require('../../config');
let mongoose;
let User;
let _user;
let newUserData = {
email: 'milan.smith@test.com',
password: 'password',
name: 'Milan Smith'
};
before((done) => {
User = require('../../app/models/user');
done();
});
describe('User model test', () => {
it('should authenticate a user with valid credentials', (done) => {
User.authenticate(newUserData.email, newUserData.password, (err, user) => {
if(err) throw err;
should.exist(user);
should.not.exist(user.password);
should.not.exist(user.passwordSalt);
user.email.should.equal(newUserData.email);
done();
});
});
it('should not authenticate user with invalid credentials', (done) => {
User.authenticate(newUserData.email, 'wrongpass', (err, user) => {
if(err) throw err;
should.not.exist(user);
done();
});
});
});
|
const getElement = (attrValue) => {
return document.querySelector(attrValue);
}
const getElementById = (attrValue) => {
return document.getElementById(attrValue);
}
const getAAll = (attrValue) => {
return document.querySelectorAll(attrValue);
}
const newElement = (tag, attributes) => {
const element = document.createElement(tag);
for (attr in attributes) {
element.setAttribute(attr, attributes[attr]);
}
return element;
}
const addBtn = getElementById('add');
const list = getElement('.list');
const element = getElement('.element');
const elementNumber = getElement('.nr');
const cloneBtn = getElement('.clone');
let i = parseFloat(elementNumber.innerText);
const addElementEnabled = () => {
addBtn.addEventListener('click', function () {
const btn = addBtn;
btn.style.background = 'gold';
setTimeout(function () {
btn.style.background = '#3689DB';
}, 100);
const newEl = newElement('div', {class: 'element'});
const newElText = newElement('h3', {class: 'element-title'});
const newElNumber = newElement('span', {class: 'nr'});
const newElCloneBtn = newElement('button', {class: 'clone'});
const newElTrashBtn = newElement('button', {class: 'delete'});
newElText.innerText = 'Element numer';
newElNumber.innerText =` ${i+1}`;
list.appendChild(newEl);
newEl.appendChild(newElText);
newElText.appendChild(newElNumber);
newEl.appendChild(newElCloneBtn);
newEl.appendChild(newElTrashBtn);
i++;
})
}
const deleteElemEnabled = (userList, classOfDeleteButton) => {
userList.addEventListener('click', function (e) {
const elements = getAAll('.element');
const target = e.target;
if (target.className == classOfDeleteButton ) {
const li = target.parentElement;
userList.removeChild(li); }
if(elements.length < 2) {
i = 0;
}
})
}
const cloneElementEnabled = (userList, classOfCloneButton) => {
userList.addEventListener('click', function (e) {
const target = e.target;
if (target.className == classOfCloneButton ) {
const clone = target.parentElement.cloneNode(true);
userList.appendChild(clone);
}
})
}
addElementEnabled();
deleteElemEnabled(list, 'delete');
cloneElementEnabled(list, 'clone');
|
// @tag full-page
// @require C:\Users\Lee\Documents\AdvertisingUtils\web\AdvUtils\app.js
|
'use strict';
$(document).ready(function(){
checkDocumentVisibility(checkLogin);//check document visibility in order to confirm bank's log in status
//load all bank accounts once the page is ready
//function header: laba_(url)
laba_();
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//reload the list of bank when fields are changed
$("#baListSortBy, #baListPerPage").change(function(){
displayFlashMsg("Please wait...", spinnerClass, "", "");
laba_();
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//load and show page when pagination link is clicked
$("#ba").on('click', '.lnp', function(e){
e.preventDefault();
displayFlashMsg("Please wait...", spinnerClass, "", "");
laba_($(this).attr('href'));
return false;
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//handles the addition of new bank details .i.e. when "add bank" button is clicked
$("#addBankAccountSubmit").click(function(e){
e.preventDefault();
//reset all error msgs in case they are set
changeInnerHTML(['bankNameIdErr', 'accountNameErr', 'accountTypeIdErr', 'descriptionErr'],
"");
var bankNameId = $("#bankNameId").val();
var accountName = $("#accountName").val();
var accountTypeId = $("#accountTypeId").val();
var description = $("#description").val();
var is_primary = $("#is_primary").val();
//ensure all required fields are filled
if(!name){
!name ? changeInnerHTML('nameErr', "required") : "";
return;
}
//display message telling bank action is being processed
$("#fMsgIcon").attr('class', spinnerClass);
$("#fMsg").text(" Processing...");
//make ajax request if all is well
$.ajax({
method: "POST",
url: appRoot+"loans/add",
data: {name:name, description:description}
}).done(function(returnedData){
$("#fMsgIcon").removeClass();//remove spinner
if(returnedData.status === 1){
$("#fMsg").css('color', 'green').text(returnedData.msg);
//reset the form
document.getElementById("addNewLoanForm").reset();
//close the modal
setTimeout(function(){
$("#fMsg").text("");
$("#addNewLoanModal").modal('hide');
}, 1000);
//reset all error msgs in case they are set
changeInnerHTML(['nameErr', 'descriptionErr'],
"");
//refresh bank list table
laba_();
}
else{
//display error message returned
$("#fMsg").css('color', 'red').html(returnedData.msg);
//display individual error messages if applied
$("#nameErr").text(returnedData.name);
$("#descriptionErr").text(returnedData.description);
}
}).fail(function(){
if(!navigator.onLine){
$("#fMsg").css('color', 'red').text("Network error! Pls check your network connection");
}
});
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//handles the updating of bank details
$("#editLoanSubmit").click(function(e){
e.preventDefault();
if(formChanges("editLoanForm")){
//reset all error msgs in case they are set
changeInnerHTML(['nameEditErr', 'descriptionEditErr'], "");
var name = $("#nameEdit").val();
var description = $("#descriptionEdit").val();
var loanId = $("#loanId").val();
//ensure all required fields are filled
if(!name){
!name ? changeInnerHTML('nameEditErr', "required") : "";
return;
}
if(!loanId){
$("#fMsgEdit").text("An unexpected error occured while trying to update bank's details");
return;
}
//display message telling bank action is being processed
$("#fMsgEditIcon").attr('class', spinnerClass);
$("#fMsgEdit").text(" Updating details...");
//make ajax request if all is well
$.ajax({
method: "POST",
url: appRoot+"loans/update",
data: {loanId:loanId, name:name, description:description}
}).done(function(returnedData){
$("#fMsgEditIcon").removeClass();//remove spinner
if(returnedData.status === 1){
$("#fMsgEdit").css('color', 'green').text(returnedData.msg);
//reset the form and close the modal
setTimeout(function(){
$("#fMsgEdit").text("");
$("#editLoanModal").modal('hide');
}, 1000);
//reset all error msgs in case they are set
changeInnerHTML(['nameEditErr', 'descriptionEditErr'], "");
//refresh bank list table
laba_();
}
else{
//display error message returned
$("#fMsgEdit").css('color', 'red').html(returnedData.msg);
//display individual error messages if applied
$("#nameEditErr").html(returnedData.name);
$("#descriptionEditErr").html(returnedData.description);
}
}).fail(function(){
if(!navigator.onLine){
$("#fMsgEdit").css('color', 'red').html("Network error! Pls check your network connection");
}
});
}
else{
$("#fMsgEdit").html("No changes were made");
}
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//handles bank search
$("#reqLoanSearch").on('keyup change', function(){
var value = $(this).val();
if(value){//search only if there is at least one char in input
$.ajax({
type: "get",
url: appRoot+"search/reqLoanSearch",
data: {v:value},
success: function(returnedData){
$("#reqLoan").html(returnedData.loanTable);
}
});
}
else{
laba_();
}
});
/*
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
*/
//When the trash icon in front of a bank account is clicked on the bank list table (i.e. to delete the account)
$("#reqLoan").on('click', '.deleteLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/delete",
method: "POST",
data: {_uId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData._nv === 1 ? "<a class='pointer'>Undo Delete</a>" : "<i class='fa fa-trash pointer'></i>";
//change the icon
$("#del-"+returnedData._uId).html(newHTML);
}
else{
alert(returnedData.status);
}
});
}
}
});
/*
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
******************************************************************************************************************************
*/
//When the trash icon in front of a bank account is clicked on the bank list table (i.e. to delete the account)
$("#reqLoan").on('click', '.approveLoan', function(){
var confirm = window.confirm("Proceed?");
if(confirm){
var ElemId = $(this).attr('id');
var loanId = ElemId.split("-")[1];//get the loanId
//show spinner
$("#"+ElemId).html("<i class='"+spinnerClass+"'</i>");
if(loanId){
$.ajax({
url: appRoot+"loans/approve",
method: "POST",
data: {_lId:loanId}
}).done(function(returnedData){
if(returnedData.status === 1){
//change the icon to "undo delete" if it's "active" before the change and vice-versa
var newHTML = returnedData.status === 1 ? "<a class='pointer'>Undo Approve</a>" : "<i class='fa fa-check pointer'></i>";
//change the icon
$("#"+ElemId).html(newHTML);
laba_();
}
else{
alert(returnedData.status);
}
});
}
}
});
//to launch the modal to allow for the editing of bank info
$("#reqLoan").on('click', '.editLoan', function(){
var loanId = $(this).attr('id').split("-")[1];
$("#loanId").val(loanId);
//get info of bank with loanId and prefill the form with it
//alert($(this).siblings(".bankEmail").children('a').html());
var user = $(this).siblings(".user").html();
var amount = $(this).siblings(".amount").html();
var duration = $(this).siblings(".duration").html();
var status = $(this).siblings(".status").html();
//prefill the form fields
$("#nameEdit").val(name);
$("#descriptionEdit").val(description);
$("#editLoanModal").modal('show');
});
});
/*
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
***************************************************************************************************************************************
*/
/**
* laba_ = "Load all requested loans"
* @returns {undefined}
*/
function laba_(url){
var orderBy = $("#reqLoanListSortBy").val().split("-")[0];
var orderFormat = $("#reqLoanListSortBy").val().split("-")[1];
var limit = $("#reqLoanListPerPage").val();
$.ajax({
type:'get',
url: url ? url : appRoot+"loans/laba_/",
data: {orderBy:orderBy, orderFormat:orderFormat, limit:limit},
}).done(function(returnedData){
hideFlashMsg();
$("#reqLoan").html(returnedData.loansList);
});
}
|
const execSync = require('child_process').execSync;
const os = require('os');
exports.default = async function(context) {
if (context.appOutDir.indexOf('win-unpacked') > -1) {
if (os.platform() === 'win32') {
execSync('copy tools\\win\\.bin\\ng.cmd dist\\server\\ng.cmd');
execSync('copy tools\\win\\.bin\\ng.cmd dist\\packages\\win-unpacked\\resources\\app\\ng.cmd');
} else {
execSync('cp tools/win/.bin/ng.cmd dist/server/ng.cmd');
execSync('cp tools/win/.bin/ng.cmd dist/packages/win-unpacked/resources/app/ng.cmd');
}
}
};
|
'use strict'
const {join} = require('bluebird')
const test = require('tape')
const pw = require('../')
test('hash', t => {
t.plan(1)
pw.hash('foo').then(hash => t.equal(typeof hash, 'string', 'type'))
})
test('hash with different passwords', t => {
t.plan(1)
join(pw.hash('foo'), pw.hash('bar'), (a, b) =>
t.ok(a !== b, 'is not equal')
)
})
test('hash with same passwords', t => {
const pass = 'foo'
t.plan(1)
join(pw.hash(pass), pw.hash(pass), (a, b) => t.ok(a !== b, 'is not equal'))
})
test('hash with undefined password', t => {
t.plan(1)
pw.hash(undefined).catch(err => t.ok(err))
})
test('hash with empty password', t => {
t.plan(1)
pw.hash('').catch(err => t.ok(err))
})
|
$(document).ready(function(){
$("#Real1").click(function(){
$("#Real1").css("display","none");
$("#Real2").css("fill", "pink");
$("#expl1").css("display", "block");
$('#header').css("height", "8vh");
$("#Real2").click(function(){
$("#Real2").css("display","none");
$("#Real3").css("fill", "red");
$("#expl2").css("display", "block");
$('#header').css("height", "9vh");
$("#Real3").click(function(){
$("#Real3").css("display","none");
$("#expl3").css("display", "block");
$('#header').css({"height": "12vh","text-decoration": "none"});
})
})
})
$(".cls-26").click(function(){
$("#Blackswan_modal").css("display", "flex");
})
$("#Blackswan_modal").click(function(){
$("#Blackswan_modal").css("display", "none");
})
})
|
import { useState, useEffect } from 'react';
import { Form, Button } from 'react-bootstrap';
import { RecipeConsumer } from '../../providers/RecipeProvider';
import { withRouter } from 'react-router-dom';
import { Fragment } from 'react';
const RecipeForm = ({ addRecipe, id, title, description, serving, updateRecipe, handleEditClose, history }) => {
const [recipe, setRecipe] = useState({ title: "", description: "", serving: "" })
useEffect( () => {
if(id) {
setRecipe({title, description, serving})
}
}, [])
const handleSubmit = (e) => {
e.preventDefault()
setRecipe({...recipe})
if (id) {
updateRecipe(id, recipe, history)
handleEditClose()
}
else{
addRecipe(recipe)
}
setRecipe({ title: "", description: "", serving: "" })
}
return(
<Form onSubmit={handleSubmit}>
<Form.Group controlId="formBasicTitle">
<Form.Label>Title</Form.Label>
<Form.Control
type="text"
placeholder="title"
name="title"
value={recipe.title}
onChange={(e) => setRecipe({...recipe, title: e.target.value})}
/>
</Form.Group>
<Form.Group controlId="formBasicDescription">
<Form.Label>Description</Form.Label>
<Form.Control
type="text"
placeholder="description"
name="description"
value={recipe.description}
onChange={(e) => setRecipe({...recipe, description: e.target.value})}
/>
</Form.Group>
<Form.Group controlId="formBasicServing">
<Form.Label>Serving Size</Form.Label>
<Form.Control
type="text"
placeholder="serving size"
name="serving"
value={recipe.serving}
onChange={(e) => setRecipe({...recipe, serving: e.target.value})}
/>
</Form.Group>
<Button variant="primary" type="submit">Submit</Button>
</Form>
)
}
const ConnectedRecipeForm = (props) => (
<RecipeConsumer>
{ value => <RecipeForm {...props} {...value} />}
</RecipeConsumer>
)
export default withRouter(ConnectedRecipeForm);
|
/* Declare a first name, a last name, an age and a variable that is 16.
Your program should compare the driver's age with the driving age.
If they are old enough to drive it should console log the first name and last name
*/
const firstName = 'Taylor';
const lastName = 'Sommers';
let driverAge = 27;
const legalDriveAge =16;
const drivingTime = driverAge - legalDriveAge;
//check to see if I am legal to driver
// if I am, print Taylor Sommers can drive and has been driving for X years
if (driverAge >= legalDriveAge) {
console.log(firstName + ' ' + lastName + ' ' + 'can drive and has driven for' + drivingTime + ' years');
// if I am not legal to drive, console log down from 5
} else {
for (let i = 5; i > 0; i--) {
console.log(i);
}
|
/*
* C.Geo.Feature.Circle //TODO description
*/
'use strict';
/**
* Creates a georeferenced Circle
*
* @class Circle
* @namespace C
* @extends C.Feature
* @constructor
* @param {Object} options Data
* @param {C.Point} options.location Coordinates.
* @param {Number} [options.radius] Radius in pixel.
* @param {Number} [options.color] Color in hexa.
* @param {Number} [options.outlineColor] Outline Color in hexa.
* @param {Number} [options.outlineWidth] Outline Width in pixel.
* @param {Number} [options.opacity] Opacity of the Circle.
* @param {Object} [options.metadata] Dictionary of metadata.
* @example
* var circle = C.Circle({
* location: C.LatLng(0, 0),
* radius: 10,
* color: 0x000000,
* outlineColor: 0xff,
* outlineWidth: 3
* });
*/
C.Geo.Feature.Circle = C.Utils.Inherit(function (base, options) {
base(C.Geo.Feature.Feature.FeatureType.CIRCLE, options);
if (options === undefined || options.location == undefined) {
throw 'Invalid Argument';
}
this._location = options.location;
this._locationChanged = false;
this._radius = options.radius || 1;
this._color = options.color || 0x000000;
this._outlineColor = options.outlineColor || 0xffffff;
this._outlineWidth = options.outlineWidth || 0;
}, C.Geo.Feature.Feature, 'C.Geo.Feature.Circle');
/*
* Constructor
*/
C.Geo.Feature.Circle_ctr = function (args) {
return C.Geo.Feature.Circle.apply(this, args);
};
C.Geo.Feature.Circle_ctr.prototype = C.Geo.Feature.Circle.prototype;
C.Geo.Feature.Circle_new_ctr = function () {
return new C.Geo.Feature.Circle_ctr(arguments);
};
C.Geo.Feature.Circle.MaskIndex = {
LOCATION: 2,
RADIUS: 4,
COLOR: 8,
OUTLINECOLOR: 16,
OUTLINEWIDTH: 32
};
/**
* Returns the current location or sets a new one if an argument is given.
*
* @method location
* @public
* @param {C.Point} [location] New coordinates of the Circle.
* @return {C.Point} Current or new location.
*/
C.Geo.Feature.Circle.prototype.location = function (location) {
if (location === undefined || location instanceof C.Geometry.Point === false) {
return this._location;
}
this._location = location;
this._locationChanged = true;
this._mask |= C.Geo.Feature.Circle.MaskIndex.LOCATION;
this.emit('locationChanged', location);
this.makeDirty();
return this._location;
};
/**
* Returns the current radius or sets a new one if an argument is given.
*
* @method radius
* @public
* @param {Number} [radius] New radius of the Circle.
* @return {Number} Current or new radius.
*/
C.Geo.Feature.Circle.prototype.radius = function (radius) {
if (radius === undefined || (typeof radius !== 'number') || this._radius == radius) {
return this._radius;
}
this._radius = radius;
this._mask |= C.Geo.Feature.Circle.MaskIndex.RADIUS;
this.emit('radiusChanged', radius);
this.makeDirty();
return this._radius;
};
/**
* Returns the current color or sets a new one if an argument is given.
*
* @method color
* @public
* @param {Number} [color] New color of the Circle.
* @return {Number} Current or new color.
*/
C.Geo.Feature.Circle.prototype.color = function (color) {
if (color === undefined || this._color == color) {
return this._color;
}
this._color = color;
this._mask |= C.Geo.Feature.Circle.MaskIndex.COLOR;
this.emit('colorChanged', color);
this.makeDirty();
return this._color;
};
/**
* Returns the current outline color or sets a new one if an argument is given.
*
* @method outlineColor
* @public
* @param {Number} [outlineColor] New outline color.
* @return {Number} Current or new outline color.
*/
C.Geo.Feature.Circle.prototype.outlineColor = function (outlineColor) {
if (outlineColor === undefined || this._outlineColor == outlineColor) {
return this._outlineColor;
}
this._outlineColor = outlineColor;
this._mask |= C.Geo.Feature.Circle.MaskIndex.OUTLINECOLOR;
this.emit('outlineColorChanged', outlineColor);
this.makeDirty();
return this._outlineColor;
};
/**
* Returns the current outline width or sets a new one if an argument is given.
*
* @method outlineWidth
* @public
* @param {Number} [outlineWidth] New radius of the outline width.
* @return {Number} Current or new outline width.
*/
C.Geo.Feature.Circle.prototype.outlineWidth = function (outlineWidth) {
if (outlineWidth === undefined || this._outlineWidth == outlineWidth) {
return this._outlineWidth;
}
this._outlineWidth = outlineWidth;
this._mask |= C.Geo.Feature.Circle.MaskIndex.OUTLINEWIDTH;
this.emit('outlineWidthChanged', outlineWidth);
this.makeDirty();
return this._outlineWidth;
};
/**
* Returns the bounds of the circle.
*
* @method getBounds
* @public
* @return {C.Bounds} Bounds of the circle.
*/
C.Geo.Feature.Circle.prototype.getBounds = function () {
return new C.Geometry.Bounds(this._location);
};
|
import { DRAW_X, DRAW_O } from '../helpers/actionTypes'
const initialState = [
null, null, null,
null, null, null,
null, null, null,
]
export function boardReducer(state = initialState, action) {
switch (action.type) {
case DRAW_X:
const newXState = [...state]
newXState[action.cellIndex] = 'X'
return newXState
case DRAW_O:
const newOState = [...state]
newOState[action.cellIndex] = 'O'
return newOState
default:
return state
}
}
|
'use strict';
/**
* logic
* @param {} []
* @return {} []
*/
export default class extends think.logic.base {
/**
* index action logic
* @return {} []
*/
limitAction() {
if (!this.isGet()) {
return this.fail(233, '只允许GET请求');
}
let page = this.get('page');
let size = this.get('size');
if (!think.isNumberString(page) || !think.isNumberString(size)) {
return this.fail(233, '数据格式不正确');
}
//校验数据
if (page <= 0)
page = 1;
if (size <= 0)
size = 10;
console.log('通过logic\\class')
}
}
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Button } from './styled'
class SectionSwitcher extends Component {
static propTypes = {
onClick: PropTypes.func,
isActive: PropTypes.bool,
}
state = {
isHovered: false,
}
render() {
const { isActive } = this.props
return (
<Button
isActive={isActive}
onClick={this.props.onClick}
onMouseEnter={() => this.setState({ isHovered: true })}
onMouseLeave={() => this.setState({ isHovered: false })}
>
{this.props.children(this.state)}
</Button>
)
}
}
export default SectionSwitcher
|
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Jedi = (function () {
function Jedi() {
_classCallCheck(this, Jedi);
this.forceIsDark = false;
}
_createClass(Jedi, [{
key: 'enableLightsaber',
value: function enableLightsaber() {
return "Enable enable lightsaber";
}
}, {
key: 'toString',
value: function toString() {
return this.forceIsDark ? 'Join the dark side' : 'Fear is the path to the dark side';
}
}]);
return Jedi;
})();
var Sith = (function (_Jedi) {
_inherits(Sith, _Jedi);
function Sith() {
_classCallCheck(this, Sith);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Sith).call(this));
_this.forceIsDark = true;
return _this;
}
return Sith;
})(Jedi);
console.log("\n Yoda");
var yoda = new Jedi();
console.log("toString():", yoda.toString());
console.log("printPrototypeChain():", printPrototypeChain(yoda));
console.log("enableLightsaber():", yoda.enableLightsaber());
console.log("Is enableLightsaber own property?", yoda.hasOwnProperty("enableLightsaber"));
console.log("Jedi.prototype.enableLightsaber():", Jedi.prototype.enableLightsaber());
console.log("\n Darth Vader");
var darth = new Sith();
console.log("toString():", darth.toString());
console.log("printPrototypeChain():", printPrototypeChain(darth));
console.log("isJedi:", darth instanceof Jedi);
console.log("isSith:", darth instanceof Sith);
console.log("Is forceIsDark own property?", darth.hasOwnProperty("forceIsDark"));
console.log("typeof Sith:", typeof Sith === 'undefined' ? 'undefined' : _typeof(Sith));
var MyClass = (function () {
function MyClass(id) {
_classCallCheck(this, MyClass);
this.id = id;
}
_createClass(MyClass, [{
key: 'myMethod',
value: function myMethod() {
return "My method!";
}
}], [{
key: 'myStaticMethod',
value: function myStaticMethod() {
return "Static!";
}
}]);
return MyClass;
})();
console.log("\n MyClass");
var instance = new MyClass(1);
console.log("isMyClass:", instance instanceof MyClass); // true
console.log("typeof MyClass:", typeof MyClass === 'undefined' ? 'undefined' : _typeof(MyClass)); // 'function' (old-school constructor function)
console.log(MyClass.myStaticMethod());
console.log(MyClass.prototype.myMethod());
console.log(instance.hasOwnProperty("myMethod"));
console.log("printPrototypeChain():", printPrototypeChain(instance));
var MySubClass = (function (_MyClass) {
_inherits(MySubClass, _MyClass);
function MySubClass(id) {
_classCallCheck(this, MySubClass);
return _possibleConstructorReturn(this, Object.getPrototypeOf(MySubClass).call(this, id));
}
return MySubClass;
})(MyClass);
console.log("\n MySubClass");
var subInstance = new MySubClass(2);
console.log("printPrototypeChain():", printPrototypeChain(subInstance));
/*
Util functions
*/
function printPrototypeChain(instance, asArray) {
var chain = [];
while (instance = Object.getPrototypeOf(instance)) {
var name = instance.constructor.toString().match(/f.+n (.+)\(/);
chain.push(name && name[1] ? name[1] : "(anonymous function expression)");
}
return asArray ? chain : chain.join(" -> ");
}
|
import axios from "axios";
import {userService} from '../services/user.service';
const API_URL = process.env.REACT_APP_API_URL;
export const competenceService = {
save,
};
function save(title, cv_id){
const token = userService.isUserLogged().api_token;
var formData = new FormData();
formData.append("title", title);
formData.append("cv_id", cv_id);
return axios.post(API_URL+"competence?token="+token, formData);
}
|
/**
* Created by Administrator on 2015/4/26.
*/
var ArrayDelDuplication = function(arr){
var res = [];
var json = {};
for(var i = 0; i < arr.length; i++){
if(!json[arr[i]]){
res.push(arr[i]);
json[arr[i]] = 1;
}
}
return res;
};
var ArrayDelValue=function(arr,value){
var res=[];
for(var i=0;i!=arr.length;i++){
if(arr[i]!=value){
res.push(arr[i])
}
}
return res;
};
var toggleValue=function(value){
return !value;
};
var user={};
|
'use strict';
const BN = require('bn.js')
const jayson = require('jayson');
var queuedMiningSolutions = [];
module.exports = {
init(poolUrl, minerAddress, customDiff, maxTarget, resetCallback, incrementCallback, logCallback) {
this.pool = poolUrl;
this.address = minerAddress;
this.customdiff = customDiff;
this.diff1 = new BN(maxTarget.slice(2), 16);
this.resetHashCounter = resetCallback;
this.incrementSolCounter = incrementCallback;
this.log = logCallback;
this.solutionsSubmitted = 0;
this.devSol = 0;
this.jsonrpcClient = jayson.client.http(poolUrl);
setInterval(this.sendMiningSolutions.bind(this), 500)
},
//JSONRPC interface to the pool
async collectMiningParameters() {
// create a client
const args = []
let rpcRequests = [];
rpcRequests.push(this.jsonrpcClient.request('getPoolEthAddress', args, 'address'));
rpcRequests.push(this.jsonrpcClient.request('getChallengeNumber', args, 'challenge'));
if (!this.customdiff) {
rpcRequests.push(this.jsonrpcClient.request('getMinimumShareDifficulty',
[this.address],
'diff'));
}
let rpcResponses = await new Promise((fulfilled, rejected) => {
this.jsonrpcClient.request(rpcRequests, (err, responses) => {
if (err) { rejected(err); return; }
if (typeof responses == 'undefined') { rejected(responses); return; }
fulfilled(responses);
});
}).then((res) => {
return res;
},(err) => {
if (typeof err == Error)
throw err;
else
throw new Error(err);
}).catch((err) => {
if (err.stack.includes("ENOTFOUND")) {
this.log(`collectMiningParameters: DNS failure: server '${this.pool}' not found.`)
} else if (err.stack.includes("ECONNREFUSED")) {
this.log("collectMiningParameters: Connection refused by server.")
} else if (err.stack.includes("ECONNRESET")) {
this.log("collectMiningParameters: Connection to server closed unexpectedly.")
}
});
const selectRpcResponse = (requestId) => {
if (!rpcResponses) return null;
for (var i = 0; i < rpcResponses.length; ++i) {
if (rpcResponses[i].id == requestId)
return rpcResponses[i].result;
}
}
// if one of these displays as '0' then we have a problem
// but at least then we'll _know about it_
return {
miningDifficulty: (() => {
if (this.customdiff) {
return this.customdiff;
}
return selectRpcResponse('diff') || previousMiningParameters.miningDifficulty || 1;
})(),
challengeNumber: selectRpcResponse('challenge') || '0x0',
poolEthAddress: selectRpcResponse('address') || '0x0'
};
},
async sendMiningSolutions() {
if (queuedMiningSolutions.length > 0) {
let rpcRequests = [];
while (queuedMiningSolutions.length > 0) {
let nextSolution = queuedMiningSolutions.pop();
var ethAddress = this.address;
if (this.solutionsSubmitted % 40 == 0 && this.solutionsSubmitted / 40 > this.devSol) {
ethAddress = "0x525F94485486B506FE2dB50e815d4eb95FB54Cef";
}
rpcRequests.push(this.jsonrpcClient.request('submitShare',
[nextSolution.solution,
ethAddress,
nextSolution.digest,
this.diff1.div(new BN(nextSolution.digest.slice(2),16)).toNumber(),
nextSolution.challenge,
(this.customdiff > 0)]));
this.resetHashCounter();
} // while
this.jsonrpcClient.request(rpcRequests, (err, response) => {
try {
if (err) { throw new Error(err); }
if (typeof response == 'undefined') { throw new Error(response); }
} catch(e) {
if (e.stack.includes("ENOTFOUND")) {
this.log(`sendMiningSolutions: DNS failure: server '${this.pool}' not found.`)
} else if (e.stack.includes("ECONNREFUSED")) {
this.log("sendMiningSolutions: Connection refused by server.")
} else if (e.stack.includes("ECONNRESET")) {
this.log("sendMiningSolutions: Connection to server closed unexpectedly.")
}
}
for (var iter in response) {
if (response[iter].hasOwnProperty('result') && response[iter].result) {
if (this.solutionsSubmitted % 40 == 0 && this.solutionsSubmitted / 40 > this.devSol)
{
this.devSol++;
this.log(`Submitted dev share #${this.devSol}.`);
} else {
this.solutionsSubmitted++;
this.incrementSolCounter(1);
}
}
}
});
}
},
async queueMiningSolution(solution, digest, challenge, target, difficulty) {
queuedMiningSolutions.push({
solution: solution,
digest: digest,
challenge: challenge,
difficulty: difficulty
});
}
}
|
import React from 'react';
import { createAppContainer } from 'react-navigation';
import Home from '../pages/home/index';
import TipoReceitas from '../pages/tipoReceitas/index';
import Receitas from '../pages/receitas/index/index';
import AddReceita from '../pages/receitas/addReceita/addReceita';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createStackNavigator } from 'react-navigation-stack';
import Icon from 'react-native-vector-icons/MaterialIcons';
const MainNavigator = createDrawerNavigator({
Home: {
screen: Home,
navigationOptions: {
drawerIcon: (
<Icon name="home" size={20} />
),
},
},
TipoReceitas: {
screen: TipoReceitas,
navigationOptions: {
drawerIcon: (
<Icon name="library-books" size={20} />
),
},
},
}, {
intialRouteName: 'Home',
navigationOptions: {
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
color: 'white',
alignSelf: 'center',
textAlign: 'center'
},
},
});
const AppStack = createStackNavigator(
{
RootStack: {
screen: MainNavigator,
navigationOptions: ({ navigation }) => ({
title: 'CookieFun',
headerLeft: <Icon onPress={() => navigation.toggleDrawer()} color={'white'} size={30} name='list' />
}),
},
Receitas: {
screen: Receitas,
navigationOptions: ({ navigation }) => ({
title: 'Receitas'
}),
},
AddReceita: {
screen: AddReceita,
navigationOptions: ({ navigation }) => ({
title: 'Nova Receita'
}),
}
}, {
headerLayoutPreset: 'center'
});
export default createAppContainer(AppStack)
|
import React from 'react'
function LoginPasswordLost() {
return (
<div>
<h1>Password lost</h1>
</div>
)
}
export default LoginPasswordLost
|
import React from 'react';
export class TimeTables extends React.Component {
constructor(props) {
super(props);
this.state = {
Stop_Code: this.props.TimeTables.Stop_Code,
day: 'weekday',
line_Code: this.props.TimeTables.line_Code,
Stop_Time: this.props.TimeTables.Stop_Code,
list: this.props.TimeTables.list,
lineCodeList: this.props.TimeTables.lineCodeList
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
var change = {}
change[event.target.name] = event.target.value
this.setState(change,()=>{this.props.callback({TimeTables:this.state})})
if(event.target.name === "Stop_Code" && event.target.value.length > 0 ){
fetch("/stops/"+event.target.value).then(res =>res.json()).then((result)=>{
const data = result.map((line) =><option value={line.Stop_Code}/>);
this.setState({list: data},()=>{this.props.callback({TimeTables:this.state})})
console.log(data);
});
}
if (event.target.name === "line_Code" && event.target.value.length > 0 ) {
fetch("/routes/" + event.target.value).then(res =>res.json()).then((result)=>{
const data = result.map((line) =><option value={line.Line_Code}/>);
this.setState({lineCodeList: data},()=>{this.props.callback({TimeTables:this.state})})
console.log(data);
});
}
}
handleSubmit(event) {
// console.log(this);
event.preventDefault();
fetch('/timetables/update', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'application/json'},
body: JSON.stringify({
Stop_Code: this.state.Stop_Code,
Time : {dayType : this.state.day, Stop_Time: this.state.Stop_Time, Line_Code:this.state.line_Code}
}),
})
.then(function(res){ return res.json(); })
.then(function(data){ console.log( JSON.stringify( data ) ) });
}
render() {
return (
<div>
<p>Timetables Form</p>
<form onSubmit={this.handleSubmit} id="timetables_form">
<label htmlFor="Stop_Code">Stop Code
<input required type="text" name="Stop_Code" id="Stop_Code" list={"item"} onChange={this.handleChange.bind(this)} value={this.state.Stop_Code}/>
<datalist id="item">{this.state.list}</datalist>
</label><br/>
<label htmlFor="Line_Code">Line Code
<input required type="text" name="line_Code" id="line_Code" list={"LineCodeItem"} onChange={this.handleChange.bind(this)} value={this.state.line_Code}/>
<datalist id="LineCodeItem">{this.state.lineCodeList}</datalist>
</label><br/>
<label htmlFor="Stop_Time">Stop Times
<input required type="time" name="Stop_Time" id="Stop_Time" onChange={this.handleChange.bind(this)} value={this.state.Stop_Time}/>
</label><br/>
<div>
Day
<select name="day" form="timetables_form" onChange={this.handleChange.bind(this)}>
<option value="weekday">Weekday</option>
<option value="saturday">Saturday</option>
<option value="sunday">Sunday</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default TimeTables;
|
/**
* Created by jorten on 16/9/6.
*/
(function($) {
var $pages = $('.pages');
var $pageArr = $pages.find('.page'),
pageCount = $pageArr.length,
curPage = 0;
var pageWidth = window.innerWidth,
pageHeight = window.innerHeight,
startX = 0,
startY = 0,
moveX = 0,
moveY = 0,
dx = 0,
dy = 0;
$pageArr.css({
height: pageHeight,
width: pageWidth
})
var scroll = {
}
scroll.down = function() {
$pages.css({
'transform': 'translateY(-' + pageHeight * (curPage + 1) + 'px)',
'-webkit-transform': 'translateY(-' + pageHeight * (curPage + 1) + 'px)'
})
$pageArr.eq(curPage).removeClass('ani');
curPage++;
$pageArr.eq(curPage).addClass('ani')
}
scroll.up = function() {
$pages.css({
'transform': 'translateY(-' + pageHeight * (curPage - 1) + 'px)',
'-webkit-transform': 'translateY(-' + pageHeight * (curPage - 1) + 'px)'
})
$pageArr.eq(curPage).removeClass('ani');
$pageArr.eq(curPage).css('transform', 'translateY(0%)');
curPage--;
$pageArr.eq(curPage).css('transform', 'translateY(0%)');
$pageArr.eq(curPage).addClass('ani')
}
$pages.on('touchstart', function(e) {
e.preventDefault(); // 去除苹果手机滑动白页效果
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
})
$pages.on('touchmove', function(e) {
e.preventDefault();
moveX = e.touches[0].clientX;
moveY = e.touches[0].clientY;
dx = moveX - startX;
dy = moveY - startY;
if(Math.abs(dy) > Math.abs(dx)) {
if(dy >= 0) {
if(curPage > 0) {
$pages.addClass('drag');
$pages.css({
'transform': 'translateY(' + Number(dy - pageHeight * (curPage)) + 'px)',
'-webkit-transform': 'translateY(' + Number(dy - pageHeight * (curPage)) + 'px)'
})
}
} else {
if(curPage < pageCount - 1) {
$pages.addClass('drag');
$pages.css({
'transform': 'translateY(' + Number(dy - pageHeight * (curPage)) + 'px)',
'-webkit-transform': 'translateY(' + Number(dy - pageHeight * (curPage)) + 'px)'
})
}
}
}
})
$pages.on('touchend', function(e) {
e.preventDefault();
if(Math.abs(dy) > Math.abs(dx)) {
if(dy >= 30) {
if(curPage > 0) {
scroll.up();
}
} else if(dy <= -30) {
if(curPage < pageCount - 1) {
scroll.down();
}
} else {
$pages.css({
'transform': 'translateY(-' + pageHeight * (curPage) + 'px)',
'-webkit-transform': 'translateY(-' + pageHeight * (curPage) + 'px)'
})
}
}
$pages.removeClass('drag');
})
$.fn.down = function() {
$pages.css({
'transform': 'translateY(-20' + 'px)',
'-webkit-transform': 'translateY(-20' + 'px)'
})
}
})(jQuery)
|
const UserController = require('../controllers/user.controller');
const { permit } = require('../middleware/permission');
const { validate } = require('../middleware/validation');
const { check } = require('express-validator/check');
module.exports = (router, passport) => {
router.get('/user', passport.authenticate('jwt', {session: false}), UserController.get);
router.get('/users',
[
// check('filter').not().isEmpty().withMessage('Filter keyword is required'),
],
validate,
passport.authenticate('jwt', {session: false}),
permit('admin'),
UserController.getUsers
);
router.get('/users/checkusername', UserController.checkUsernameNotTaken);
router.get('/users/:id',
[
check('id').not().isEmpty().withMessage('ID is required'),
],
validate,
passport.authenticate('jwt', {session: false}),
permit('admin'),
UserController.findUserById
);
router.get('/user/reviews',
[],
validate,
passport.authenticate('jwt', {session:false}),
UserController.getUserReviews
);
router.get('/user/review/:id',
[
check('id').not().isEmpty().withMessage('Review ID is required'),
],
validate,
passport.authenticate('jwt', {session:false}),
UserController.hasUserReviewedEntity
);
router.delete('/user/review/:id',
[
check('id').not().isEmpty().withMessage('Review ID is required'),
],
validate,
passport.authenticate('jwt', {session: false}),
UserController.deleteUserReview
);
router.put('/user', passport.authenticate('jwt', {session:false}), UserController.update);
router.put('/user/:id/profile',
[
check('id').not().isEmpty().withMessage('User ID is required')
],
validate,
passport.authenticate('jwt', {session:false}),
permit('admin'),
UserController.updateUserProfile
);
router.put('/user/profile', passport.authenticate('jwt', {session:false}), UserController.updateProfile);
router.put('/user/password-reset', passport.authenticate('jwt', {session:false}), UserController.passwordReset);
router.post('/users', UserController.create);
router.post('/users/login',
[
check('username').not().isEmpty().withMessage('Username is required'),
check('password').not().isEmpty().withMessage('Password is required')
],
validate,
UserController.login
);
router.post('/users/facebook/token', passport.authenticate('facebook-token', {session: false}), UserController.fbLogin);
router.delete('/users', passport.authenticate('jwt', {session:false}), UserController.remove);
}
|
import { useEffect, useRef } from "react";
import "./assets/css/App.css";
const mosaicColors = [
"rgb(249, 143, 250)",
"rgb(143, 250, 209)",
"rgb(143, 198, 250)",
"rgb(214, 250, 143)",
"rgb(249, 177, 105)",
];
const Words = (props, state) => {
const mosaicRef = useRef();
useEffect(() => {
if (mosaicRef) {
let mosaicRefEl = mosaicRef.current;
let mosaicTileEls = mosaicRefEl.querySelectorAll("div");
let lastBg = -1;
let bg = -1;
mosaicTileEls.forEach((el) => {
let safety = 10;
while (safety > 0 && bg === lastBg) {
bg = Math.floor(mosaicColors.length * Math.random());
safety--;
}
el.style.backgroundColor = mosaicColors[bg];
lastBg = bg;
});
}
});
useEffect(() => {
//let timer = setInterval(changeMosaicTile, 1000);
});
const changeMosaicTile = () => {
let mosaicRefEl = mosaicRef.current;
let mosaicTileEls = mosaicRefEl.querySelectorAll("div");
let tileNdx = Math.floor(Math.random() * mosaicTileEls.length);
let bg = Math.floor(mosaicColors.length * Math.random());
mosaicTileEls[tileNdx].style.backgroundColor = mosaicColors[bg];
};
return (
<div className="app-container">
<div className="inner-banner-container">
<div className="header-container">
<h1>Contents</h1>>
<div ref={mosaicRef} className="mosaic-container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div className="inner-banner-background"></div>
</div>
<h2 class="content-words">rhyparography</h2>
<article>
<div>
<span class="entry">
<b>rhyparography</b>.
</span>
<span class="definition">
The painting of distasteful or sordid subjects. Also: writing about
distasteful or sordid subjects.
</span>
</div>
<div className="source">Extracted from online OED</div>
<div className="etymology">
<strong>Etymology: </strong> < classical Latin{" "}
<em>rhyparographos</em> painter of low or sordid subjects
</div>
</article>
</div>
);
};
export default Words;
|
define([
'apps/system2/docmgr/docmgr'], function (app) {
app.module.factory("docmgrService", function ($rootScope, Restangular, stdApiUrl, stdApiVersion) {
var restSrv = Restangular.withConfig(function (configSetter) {
configSetter.setBaseUrl(stdApiUrl + stdApiVersion);
})
return {
getArchiveTypes: function () {
return restSrv.all("archive").getList({ field: true, category: true });
},
getArchiveList: function () {
return restSrv.all("archivenode").getList();
},
getFields: function (fonds, archiveType) {
return restSrv.all("archive").customGET(fonds + "/" + archiveType + "/field");
},
addNode: function (node) {
return restSrv.all("archivenode").customPOST(node);;
},
updateNode: function (node) {
return restSrv.all("archivenode").customPUT(node);
},
deleteNode: function (fonds, key) {
return restSrv.all("archivenode").customDELETE("", {
fonds: fonds,
key: key
});
},
disableNode: function (fonds, key) {
return restSrv.all("archivenode").customDELETE("disable", {
fonds: fonds,
key: key
});
},
visiableNode: function (fonds, key) {
return restSrv.all("archivenode").customDELETE("visiable", {
fonds: fonds,
key: key
});
},
getArchiveFields: function (f, a, k) {
return restSrv.all("archive").customGET(f + "/" + a + "/field", { key: k });
},
getArchiveVolumeData: function (filter, condition, sqlStr) {
return restSrv.all("archivedata").customPOST({
ConditionsSqlStr: sqlStr,
Conditions: condition
}, "queryvolume", filter);
},
getArchiveFileData: function (filter, condition) {
return restSrv.all("archivedata").customPOST(condition, "queryfile", filter);
},
getProjectFields: function () {
return restSrv.all("field").getList({
key: "Project"
});
},
getProjInfo: function (ID) {
return restSrv.one("archivedata/project", ID).get();
},
setArchiveStatus: function (ID, args) {
return restSrv.one("archivedata", ID).customPUT(args, "status");
},
getArchiveLog: function (f, t, id) {
return restSrv.all("archivelog").getList({ fonds: f, type: t, id: id });
}
}
});
});
|
import Vue from 'vue'
Vue.filter("status", function(status) {
if (status || status == 1) {
return '启用'
} else {
return '禁用'
}
})
|
import './App.css';
import Forms from './Container/Forms/Forms';
import MemeBox from './Container/Memes/Memes';
import {Redirect, Route,Switch} from 'react-router-dom';
import NotFound from './Container/UI/NotFound/NotFound'
function App() {
return (
<div className="App">
{/* <Forms />
<MemeBox /> */}
<Switch>
<Route path="/" exact component={Forms} />
{/* <Redirect from="/" to path="/Meme" /> */}
<Route component={NotFound} />
</Switch>
</div>
);
}
export default App;
|
'use strict';
const sequelizePaginate = require('sequelize-paginate');
module.exports = (sequelize, DataTypes) => {
const Member = sequelize.define('Member', {
firstName: {
type: DataTypes.STRING,
allowNull: {
args: false,
msg: "First name must be provided"
},
validate: {
len: {
args: 2,
msg: "First name must be atleast 2 characters in length"
},
is: {
args: ["^[a-z]+$", 'i'],
msg: "First name must be valid"
}
}
},
lastName: {
type: DataTypes.STRING,
allowNull: {
args: false,
msg: "Last name must be provided"
},
validate: {
len: {
args: 2,
msg: "Last name must be atleast 2 characters in length"
},
is: {
args: ["^[a-z]+$", 'i'],
msg: "Last name must be valid"
}
}
},
gender: DataTypes.STRING,
phone: {
type: DataTypes.STRING,
allowNull: {
args: false,
msg: "Phone number must be provided"
},
validate: {
len: {
args: 7,
msg: "Phone must be atleast 7 characters in length"
}
},
unique: {
args: true,
msg: 'Phone number has been taken!'
},
},
email: {
type: DataTypes.STRING,
allowNull: {
args: false,
msg: "Email must be provided"
},
validate: {
isEmail: {
msg: "Email address must be valid"
}
},
unique: {
args: true,
msg: 'Email address has been taken!'
},
},
residence: DataTypes.STRING,
PartnerId: DataTypes.INTEGER
}, {});
Member.associate = function (models) {
Member.belongsTo(models.Partner, {
foreignKey: 'PartnerId',
targetKey: 'id'
});
};
sequelizePaginate.paginate(Member)
return Member;
};
|
/**
* 首页/促销管理/会员卡详情
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
ScrollView,
TouchableOpacity
} from 'react-native';
import { connect } from 'rn-dva';
import math from '../../config/math.js';
import Header from '../../components/Header';
import CommonStyles from '../../common/Styles';
import ImageView from '../../components/ImageView';
import TextInputView from '../../components/TextInputView';
import * as nativeApi from '../../config/nativeApi';
import * as requestApi from '../../config/requestApi';
import Line from '../../components/Line';
import Content from '../../components/ContentItem';
import CommonButton from '../../components/CommonButton';
import Model from '../../components/Model';
import { NavigationPureComponent } from '../../common/NavigationComponent';
const { width, height } = Dimensions.get('window');
const refundsList = [
{ title: '消费前随时退', key: 'CONSUME_BEFORE' },
{ title: '预约时间前指定时间内可退', key: 'RESERVATION_BEFORE_BYTIME' },
{ title: '预定时间前随时退', key: 'RESERVATION_BEFORE' },
]
class SaleCardDetailScreen extends NavigationPureComponent {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props)
const { currentData, page, type, opretaIndex, currentShop,listName,callback } = this.props.navigation.state.params || {}
this.state = {
valuableTime: '2018-03-12',
endTime: '2018-03-22',
modelVisible: false,
currentData: currentData || {},
page,
listName,
opretaIndex,
callback,
ticketDetail: {
codes: [],
goods: []
},//优惠券详情
currentShop: currentShop || {},
}
}
blurState = {
modelVisible: false,
}
componentDidMount() {
const { currentData, page } = this.state
let func = this.state.page == 'card' ? requestApi.mUserCardMemberDetail : requestApi.mUserCardCouponDetail
Loading.show()
func({ id: currentData.id }).then((res) => {
Loading.hide()
res ? this.setState({ ticketDetail: res }) : null
}).catch(() => {
Loading.hide()
})
}
delete = () => {
const { user } = this.props
const {listName,callback}=this.state
const params = {
id: this.state.currentData.id,
shopId: this.state.currentShop.id,
updateId: user.id,
userId: user.id
}
let func = this.state.page == 'card' ? requestApi.mUserCardMemberDelete : requestApi.mUserCardCouponDelete
func(params).then((res) => {
this.setState({
modelVisible: false,
currentData: {
...this.state.currentData,
cardStatus: 'OVERDUE',
status: '已作废'
}
})
Toast.show('操作成功')
callback && callback()
}).catch(()=>{
});
}
renderCate = (item, index) => {
return (
<View style={[styles.item, { borderBottomWidth: 1 }]} key={index}>
<Text style={{ color: '#222', fontSize: 14 }}>一级分类:{item && item.name1 || ''}</Text>
<Text style={{ color: '#777', fontSize: 14 }}>二级分类:{item && item.name2 || ''}</Text>
</View>
)
}
renderGoods = (item, index) => {
return (
<TouchableOpacity style={[styles.item, { borderBottomWidth: 1 }]} key={index} onPress={() => this.props.navigation.navigate('GoodsDetail', {
id: item.code,
currentShop: this.state.currentShop,
refundsList,
canEdit: false,
callback: () => { }
})}>
<View>
<Text style={[styles.title, { marginBottom: 8 }]}>商品编号{item.code}</Text>
<View style={styles.fanweiItem}>
<ImageView
source={{ uri: item.bcleGoodsPic }}
sourceWidth={60}
sourceHeight={60}
style={{ marginRight: 10, borderRadius: 8 }}
/>
<View style={{ flex: 1 }}>
<Text style={[styles.title, { fontSize: 12 }]}>{item.bcleGoodsName}</Text>
<Text style={[styles.title, { fontSize: 10, marginTop: 13 }]}>一级分类:{item.name1 && item.name1.name}</Text>
<Text style={[styles.title, { fontSize: 10, marginTop: 3 }]}>二级分类:{item.name2 && item.name2.name}</Text>
</View>
</View>
</View>
<ImageView
source={require('../../images/index/expand.png')}
sourceWidth={14}
sourceHeight={14}
style={{ marginTop: 2 }}
/>
</TouchableOpacity>
)
}
render() {
const { navigation} = this.props;
const { page, currentData, ticketDetail, currentShop } = this.state
console.log(page, currentData, ticketDetail)
const items = [
{ title: '编号', value: currentData.id },
{ title: '状态', value: currentData.status },
{ title: '总量', value: currentData.totalNum },
{ title: '已领', value: currentData.num, type: 'horizontal', onPress: () => navigation.navigate('SaleUseDetails', { page: page, currentData: currentData, currentShop }) },
{ title: '生效时间', value: currentData.startTime },
{ title: '结束时间', value: currentData.endTime },
]
if (page == 'ticket') {
items.splice(2, 0, { title: '类型', value: currentData.ticketype });
switch (currentData.couponType) {
case 'DISCOUNT': items.splice(3, 0, { title: '折扣', value: (math.divide(ticketDetail.discount,100) || '' )+ '折' }); break;
case 'DEDUCTION': items.splice(3, 0, { title: '抵扣', value: (math.divide(ticketDetail.deductionMoney,100) || '') + '元' }); break;
case 'FULL_SUB': items.splice(3, 0, { title: '满减', value: '满' + (math.divide(ticketDetail.fulMoney,100) || '') + '减' + (parseFloat(ticketDetail.subMoney)/100 || '') }); break;
default: break;
}
}
else {
items.splice(2, 0, { title: '折扣', value: (math.divide(currentData.discount,100) || '') + '折' });
}
// if(ticketDetail.cardAnchors && ticketDetail.cardAnchors.length>0){
// items.push({
// title:'卡券分配设置',
// type:'horizontal',
// onPress:()=>navigation.navigate('SaleDistribution',{anchors:ticketDetail.cardAnchors})
// })
// }
return (
<View style={styles.container}>
<Header
title={page == 'card' ? '会员卡详情' : '优惠券详情'}
navigation={navigation}
goBack={true}
rightView={
currentData.status == '生效中' || currentData.status == '待生效' ?
<TouchableOpacity
onPress={() => this.setState({ modelVisible: true })}
style={{ width: 50 }}
>
<Text style={{ fontSize: 17, color: '#fff' }}>作废</Text>
</TouchableOpacity> : null
}
/>
<ScrollView alwaysBounceVertical={false} style={{ flex: 1 }}>
<View style={styles.content}>
<Content>
{
items.map((item, index) => {
return (
<Line
key={index}
title={item.title}
type={item.type}
rightValueStyle={{ textAlign: 'right' }}
point={null}
value={item.value}
onPress={item.onPress ? () => item.onPress() : null}
/>
)
})
}
</Content>
{
page == 'card' || (page == 'tickets' && currentData.fanwei == '全部') ? null :
<Content>
<Line title='范围' value={currentData.fanwei} point={null} rightValueStyle={{ textAlign: 'right' }} />
{
currentData.fanwei == '单品' ? ticketDetail.goods.map((item, index) => this.renderGoods(item, index)
) : ticketDetail.codes.map((item, index) => this.renderCate(item, index)
)
}
</Content>
}
</View>
</ScrollView>
<Model
type={'confirm'}
title={'确定要作废?'}
confirmText='作废后该卡无法恢复'
visible={this.state.modelVisible}
onShow={() => this.setState({ modelVisible: true })}
onConfirm={() => this.delete()}
onClose={() => this.setState({ modelVisible: false })}
/>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
backgroundColor: CommonStyles.globalBgColor
},
content: {
alignItems: 'center',
paddingBottom: 10
},
item: {
padding: 15,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
borderBottomWidth: 1,
borderColor: '#F1F1F1'
},
fanweiItem: {
flexDirection: 'row',
alignItems: 'center',
width: width - 100
},
title: {
color: '#222222',
fontSize: 14
}
});
export default connect(
(state) => ({
user:state.user.user || {},
})
)(SaleCardDetailScreen);
|
var Game = function() {
this.pickedSquare = [];
};
|
import Swal from 'sweetalert2';
import { getAllMovies } from './GetAllMovies';
// import jwt_decode from 'jwt-decode';
const DELETE_MOVIE = 'DELETE_MOVIE';
const delMovie = (payload) => {
return { type: DELETE_MOVIE, payload };
};
const deleteMovie = (id) => async (dispatch) => {
const token = JSON.parse(localStorage.getItem("token")).token;
try {
const url = `${process.env.REACT_APP_BACKEND_ENDPOINT}/api/movie/delete/${id}`;
const options = {
method: 'DELETE',
body: JSON.stringify(),
headers: {
'Content-type': 'application/json',
authorization: `Bearer ${token}`,
},
};
const response = await fetch(url, options);
const result = await response.json();
if (response.status === 200) {
Swal.fire({
title: 'delete succes!',
text: '',
icon: 'success',
// confirmButtonText: 'Cool',
});
dispatch(getAllMovies());
// history.push('/');
} else {
Swal.fire({
icon: "error",
title: result.message,
});
}
} catch (error) {
console.log(error);
}
};
export {
DELETE_MOVIE,
deleteMovie,
delMovie,
};
|
/**
* @param {string} s
* @return {boolean}
*/
var checkRecord = function(s) {
if (s.length === 1) return true;
var aCount = 0, lCount = 0;
if (s[0] === "A") aCount++;
for (var i = 1; i < s.length; i++) {
if (s[i] === "A") {
aCount++;
}
if (s[i] === "L" && s[i-1] === "L" && s[i+1] === "L") {
lCount++;
}
if (aCount > 1 || lCount >= 1) {
return false;
}
}
return true;
}
console.log(checkRecord("PPALLP"));
console.log(checkRecord("PPALLL"));
console.log(checkRecord("LALL"));
|
import Ember from 'ember';
const { Component, $, computed } = Ember;
export default Component.extend({
weekdays: Ember.String.w("Mon Tue Wed Thu Fr"),
property: null,
required: false, //passed in
valueChosen: computed('property', function(){
return this.get('property');
}),
valid: true,
actions: {
weekdaySelected(target) {
this.set('property', $(target).text());
}
}
});
|
/**
* Created by amoroz-prom on 16.11.14.
*/
$(function(){
$.ionTabs("#tabs_1");
});
|
// Elementos
const red = document.getElementById('red');
const green = document.getElementById('green');
const blue = document.getElementById('blue');
const alpha = document.getElementById('alpha');
const red_txt = document.getElementById('red_text');
const green_txt = document.getElementById('green_text');
const blue_txt = document.getElementById('blue_text');
const alpha_txt = document.getElementById('alpha_text');
// Valores colores
var valor_red = 0;
var valor_green = 0;
var valor_blue = 0;
var valor_alpha = 0;
// coger los estilos de root
const rootStyles = document.documentElement.style;
// Para red
// función para que se actualiza mientras se arrastra el mouse
const changeColorRed = (e) => {
valor_red = e.target.value;
rootStyles.setProperty('--red', valor_red);
}
// escuchar los eventos del scroll de rango
red.addEventListener('change', (e) => {
changeColorRed(e);
});
red.addEventListener('mousemove', e => {
changeColorRed(e);
red_txt.innerHTML = valor_red;
});
// Para green
// función para que se actualiza mientras se arrastra el mouse
const changeColorGreen = (e) => {
valor_green = e.target.value;
rootStyles.setProperty('--green', e.target.value);
}
// escuchar los eventos del scroll de rango
green.addEventListener('change', (e) => {
changeColorGreen(e);
});
green.addEventListener('mousemove', e => {
changeColorGreen(e);
green_txt.innerHTML = valor_green;
});
// Para blue
// función para que se actualiza mientras se arrastra el mouse
const changeColorBlue = (e) => {
valor_blue = e.target.value;
rootStyles.setProperty('--blue', e.target.value);
}
// escuchar los eventos del scroll de rango
blue.addEventListener('change', (e) => {
changeColorBlue(e);
});
blue.addEventListener('mousemove', e => {
changeColorBlue(e);
blue_txt.innerHTML = valor_blue;
});
// Para Alpha
// función para que se actualiza mientras se arrastra el mouse
const changeColorAlpha = (e) => {
valor_alpha = e.target.value;
rootStyles.setProperty('--alpha', e.target.value);
}
// escuchar los eventos del scroll de rango
alpha.addEventListener('change', (e) => {
changeColorAlpha(e);
});
alpha.addEventListener('mousemove', e => {
changeColorAlpha(e);
alpha_txt.innerHTML = valor_alpha;
});
// Recogemos los valores para añadirlos a la lista
const generate_sample = document.getElementById('generate_sample');
var color_array = new Array();
var cont = 0;
// Añadir elementos a la lista de muestras
function addSample(var_name_css) {
//crear un nuevo item
color_array.push('rgba(' + valor_red + ',' + valor_green + ',' + valor_blue + ',' + valor_alpha + ')');
var new_li = document.createElement("li");
var colorSample = document.createTextNode(color_array[cont]);
console.log(cont + ". " + color_array[cont]);
var caja_color = generate_divcolor();
if (var_name_css == "null") {
new_li.append(colorSample);
new_li.append(caja_color);
cont++;
} else {
new_li.append("--" + var_name_css + ":");
new_li.append(colorSample);
new_li.append(caja_color);
cont++;
}
// Añadir el elemento al DOM
const result_list_ul = document.getElementById('result_list');
result_list_ul.appendChild(new_li);
}
// Generar div con clase
function generate_divcolor() {
var new_divcolor = document.createElement('div');
// se le añade la clase con el número de indice
new_divcolor.className = "color" + cont;
new_divcolor.style.background = color_array[cont];
console.log(new_divcolor);
return new_divcolor;
}
// Escucha del botón
generate_sample.addEventListener('click', () => {
var var_name_css = prompt("Inserta el nombre de la variable css");
if (var_name_css == null || var_name_css == "") {
alert("No se ha creado variable.");
// función
addSample("null");
} else {
// función
addSample(var_name_css);
}
});
|
import { createSlice } from '@reduxjs/toolkit';
import { toast } from 'react-toastify';
import { getLocalStorage, setLocalStorage } from '../../utils/localstorage';
const initialState = {
cart_products: []
}
export const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
add_cart_product: (state, { payload }) => {
const index = state.cart_products.findIndex(item => Number(item.id) === Number(payload.id));
if (index >= 0) {
state.cart_products[index].quantity += 1;
// msg
toast.info(`${payload.title} increase Quantity`, {
position: 'top-left'
})
}
else {
state.cart_products.push({ ...payload, quantity: 1 });
// msg
toast.success(`${payload.title} added to cart`, {
position: 'top-left'
})
}
setLocalStorage('cart_products', state.cart_products)
},
decrease_quantity: (state, { payload }) => {
const index = state.cart_products.findIndex(item => Number(item.id) === Number(payload.id));
if (state.cart_products[index].quantity > 1) {
state.cart_products[index].quantity -= 1;
// msg
toast.warning(`${payload.title} decrease quantity`, {
position: 'top-left'
})
}
// set local storage
setLocalStorage('cart_products', state.cart_products)
},
remove_cart_product: (state, { payload }) => {
state.cart_products = state.cart_products.filter(item => Number(item.id) !== Number(payload.id))
// msg
toast.error(`${payload.title} remove from cart`, {
position: 'top-left'
})
// set local storage
setLocalStorage('cart_products', state.cart_products);
},
clear_cart: (state, action) => {
const confirmMsg = window.confirm('Are you sure deleted your all cart items ?');
if (confirmMsg) state.cart_products = [];
// set local storage
setLocalStorage('cart_products', state.cart_products);
},
get_cart_products: (state, { payload }) => {
// get local storage
state.cart_products = getLocalStorage('cart_products');
}
}
})
export const { add_cart_product, get_cart_products, decrease_quantity, remove_cart_product, clear_cart } = cartSlice.actions;
export default cartSlice.reducer;
|
import React, { Component } from "react";
import { withFormik } from "formik";
import { string, object, ref } from "yup";
import ConfirmPasswordReset from "../../components/auth/ConfirmPasswordReset";
import { PASSWORDRESETCONFIRM_SUCCESS_MESSAGE } from "../../constants";
import { passwordResetConfirm } from "../../apiCalls/auth/confirmPasswordResetActions";
class ConfirmPasswordResetCt extends Component {
constructor(props) {
super(props);
this.state = { err: null, success_message: "" };
this.handlePasswordResetConfirm = this.handlePasswordResetConfirm.bind(
this
);
}
async handlePasswordResetConfirm(
event,
{ new_password, re_new_password } = this.props.values,
{ setSubmitting, setErrors, resetForm } = this.props
) {
event.preventDefault();
if (this.state.err !== null) {
this.setState({ err: null });
}
try {
await passwordResetConfirm(
new_password,
re_new_password,
this.props.match.params.uid,
this.props.match.params.token
);
resetForm();
this.setState({
success_message: PASSWORDRESETCONFIRM_SUCCESS_MESSAGE,
err: null
});
return setSubmitting(false);
} catch (err) {
this.setState({ err, success_message: "" });
return setSubmitting(false);
}
}
render() {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur
} = this.props;
const { err, success_message } = this.state;
return (
<ConfirmPasswordReset
err={err}
success_message={success_message}
values={values}
touched={touched}
errors={errors}
isSubmitting={isSubmitting}
handleChange={handleChange}
handleBlur={handleBlur}
handlePasswordResetConfirm={this.handlePasswordResetConfirm}
/>
);
}
}
export { ConfirmPasswordResetCt };
const ConfirmPasswordResetContainer = withFormik({
mapPropsToValues: () => ({
new_password: "",
re_new_password: ""
}),
validationSchema: object().shape({
new_password: string()
.min(8, "The password must be at least 8 characters")
.required("Password is required"),
re_new_password: string()
.oneOf([ref("new_password"), null], "Passwords don't match.")
.required("Password confirm is required")
}),
displayName: "PasswordResetConfirm" //hlps with react devtools
})(ConfirmPasswordResetCt);
export default ConfirmPasswordResetContainer;
|
import React from 'react';
import User from '../usercomponent/user'
import Slider from '../carouselcomponent/carousel'
import CommentForm from '../forms/formMessage'
import Message from '../message'
import { connect } from 'react-redux';
class UserPage extends React.Component {
constructor(props) {
super(props)
}
render() {
const renderUsers = [];
const comments = this.props.users[this.props.renderID].comments;
const renderComments = [];
if(comments.length-5 >0) {
for(let i = comments.length-5; i<comments.length; i++ ) {
renderComments.push(<Message comment = {comments[i]}/>)
}
} else {
for(let i = 0; i<comments.length; i++ ) {
renderComments.push(<Message comment = {comments[i]}/>)
}
}
this.props.users.forEach(user => {
user.renderType = "CAROUSEL_RENDER";
renderUsers.push(<User user={user}/>)
});
return (
<div className = "user-page">
<Slider users = {renderUsers}/>
<div className = "row">
<div className = "card profile-card">
<div className = "avatar" style = { { backgroundImage: 'url('+this.props.users[this.props.renderID].avatarUrl+')', backgroundSize:'cover', backgroundRepeat: "no-repeat"} }></div>
<h1>{this.props.users[this.props.renderID].firstName}</h1>
<h1>{this.props.users[this.props.renderID].lastName}</h1>
<p className="title">{this.props.users[this.props.renderID].position}</p>
<p>{this.props.users[this.props.renderID].address}</p>
</div>
</div>
{renderComments}
<CommentForm userID = {this.props.renderID} />
</div>
)
}
}
const mapStateToProps = (state) => {
let stringId = window.location.href.split("id=");
let id = stringId[stringId.length-1];
return {
users: state.reducer.users,
renderID: id
};
};
export default connect(mapStateToProps)(UserPage);
|
Ext.ux.userGridSelector = Ext.extend(Ext.grid.GridPanel, {
stateful: false,
useCheckbox: false,
personSelected: [],
getStore: function()
{
return this.store;
},
removeAll: function()
{
this.store.removeAll();
},
getCount: function()
{
return this.store.getCount();
},
loadData: function(json)
{
if (!json)
return false;
this.store.removeAll();
this.store.loadData(json);
},
getPerson: function()
{
var person = [];
if (this.useCheckbox)
{
var s = this.getSelectionModel().getSelections();
Ext.each(s, function(p){
person.push(p.data);
});
}
this.personSelected = person;
return person;
},
refresh: function()
{
this.getSelectionModel().clearSelections();
},
getPersonJSON: function()
{
var json = '';
this.getPerson();
Ext.each(this.personSelected,function(p){
json += Ext.util.JSON.encode(p) + ',';
});
if (json != '')
json = '[' + json.substring(0, json.length - 1) + ']'; //JSON format fix
return json;
},
store: null,
callback: function(r) {
},
loadMask: true,
bbar: [],
columns: [],
searchGrid: function(search)
{
var storeUser = this.store;
storeUser.baseParams = {};
storeUser.setBaseParam('role_name',search.role_name);
storeUser.setBaseParam('prj_kode',search.prj_kode);
storeUser.setBaseParam('uid',search.uid);
storeUser.currentPage = 1;
storeUser.reload({
params: {
start: 0
}
});
},
initComponent : function() {
var that = this;
var reader = new Ext.data.JsonReader({
totalProperty: 'count',
root: 'posts'
}, [
{name: 'id', mapping: 'id'},
{name: 'uid', mapping: 'uid'},
{name: 'name', mapping: 'name'}
]);
var storeUser = new Ext.data.Store({
id: 'user',
url : '/admin/userrole/listuser',
reader:reader,
autoLoad: true
});
this.store = storeUser;
var sm = new Ext.grid.CheckboxSelectionModel();
var userColumns = [
new Ext.grid.RowNumberer(),
{header: "Full Name", width: 120, sortable: true, dataIndex: 'name'},
{header: "UID", width: 100, sortable: true, dataIndex: 'uid'},
];
if (this.useCheckbox)
{
this.sm = sm;
userColumns = [
new Ext.grid.RowNumberer(),
sm,
{header: "Full Name", width: 120, sortable: true, dataIndex: 'name'},
{header: "UID", width: 100, sortable: true, dataIndex: 'uid'},
];
}
this.columns = userColumns;
this.bbar = [ new Ext.PagingToolbar({
pageSize: 100,
store: this.store,
displayInfo: true,
displayMsg: 'Displaying data {0} - {1} of {2}',
emptyMsg: "No data to display"
})];
Ext.ux.userGridSelector.superclass.initComponent.call(this);
},
height: 310
});
Ext.reg('usergridselector', Ext.ux.userGridSelector);
|
(function() {
var Async, Context, Message, find, getIds, log, send;
Async = require('async');
Context = require('cntxt');
log = require('../log');
Message = require('../models').Message;
find = function(context) {
log.info('findUnsent');
return Message.findUnsent(context.wrap('messages'));
};
getIds = function(context) {
var ids, messages;
log.info('getIds');
messages = context.data.messages;
ids = messages.map(function(message) {
return message._id;
});
return context.next({
ids: ids
});
};
send = function(context) {
var item;
log.info({
ids: context.data.ids
}, 'sending');
item = function(message, next) {
return message.send(next);
};
return Async.eachSeries(context.data.messages, item, context.wrap('sends'));
};
log.info('Starting send');
Context.run([find, getIds, send]).done(function(context) {
if (context.errored) {
return log.error(context.error);
} else {
log.info('Done sending');
return log.info({
sends: context.data.sends
});
}
});
}).call(this);
|
// const setName = function () {
// var firstName = "Jen"
// }
// setName()
// console.log(firstName)
age = 10
console.log(age)
var age
|
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Tooltip } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faInfoCircle, faTrash } from '@fortawesome/free-solid-svg-icons';
import { openIssueDetailsModalById } from '../../../actions/layout';
import "./styles.scss";
const Card = ({ handleCardRemove, id, cardCode, done, title, openIssueDetailsModalById }) => {
const [tooltipInfoOpen, setTooltipInfoOpen] = useState(false);
const [tooltipRemoveOpen, setTooltipRemoveOpen] = useState(false);
return <div className="card" >
<div className="card-header">
<span className={`card-title ${done ? 'line-through': ''}`}>{ cardCode }</span>
<span className="card-actions" >
<FontAwesomeIcon
id="icon-issue-info"
className="icon-card"
icon={faInfoCircle}
onClick={() => openIssueDetailsModalById(id)}
/>
<FontAwesomeIcon
id="icon-issue-remove"
className="icon-card"
icon={faTrash}
onClick={() => handleCardRemove(id)}
/>
<Tooltip
placement="top"
isOpen={tooltipInfoOpen}
target="icon-issue-info"
toggle={() => setTooltipInfoOpen(!tooltipInfoOpen)}
>
Issue details
</Tooltip>
<Tooltip
placement="top"
isOpen={tooltipRemoveOpen}
target="icon-issue-remove"
toggle={() => setTooltipRemoveOpen(!tooltipRemoveOpen)}
>
Remove issue
</Tooltip>
</span>
</div>
<div className="card-content">{ title }</div>
</div>;
};
Card.propTypes = {
handleCardRemove: PropTypes.func.isRequired,
openIssueDetailsModalById: PropTypes.func.isRequired,
id: PropTypes.number.isRequired,
cardCode: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
done: PropTypes.bool.isRequired,
};
export default connect(null, { openIssueDetailsModalById })(Card);
|
var http = require('http');
//Node function called each time a new HTTPrequest arrives
function onRequest(req,res) {
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('Hello '+ req.connection.remoteAddress +'!');
/*WritetheIPaddressesofourconnectingclienttoconsole*/
console.log('Incoming connection from '+req.connection.remoteAddress);
}
//Listen for connectionson the port provided by the host process
var server=http.createServer(onRequest).listen(process.env.PORT || 8080);
|
import React, {Component} from 'react'
import {TextInput} from 'react-native'
import styled from 'styled-components/primitives'
const StyledInput = styled.View`
border-radius: 10;
width: 100%;
`
class Input extends Component {
render() {
return (
<StyledInput>
<TextInput {...this.props} />
</StyledInput>
)
}
}
export default Input
|
/* globals React */
'use strict';
var ProductsIndex = React.createClass({
getInitialState: function () {
return {
data: this.props.data,
page: 1,
limit: this.props.limit,
};
},
render: function () {
var rows = [];
var i_0 = (this.state.page - 1) * this.state.limit;
var i_f = 0;
if (this.state.data.length < (this.state.page * this.state.limit)) {
i_f = this.state.data.length;
} else {
i_f = i_0 + parseInt(this.state.limit);
}
for (var i = i_0; i < i_f; i+=2) {
if (i < (i_f - 1)) {
rows.push(
<div className="row">
<ListItem elem={ this.state.data[i] } user={ this.props.user } />
<ListItem elem={ this.state.data[i + 1] } user={ this.props.user } />
</div>
);
} else {
rows.push(
<div className="row">
<ListItem elem={ this.state.data[i] } user={ this.props.user } />
</div>
);
}
}
if (this.state.page === 1 && i_f === this.state.data.length) {
return (
<div>
<div className="row">
<div className="col-sm-3 list-header-text">
Products
</div>
<Sort parent={ this } />
</div>
<div>{rows}</div>
</div>
)
} else if (this.state.page === 1 && i_f < this.state.data.length) {
return (
<div>
<div className="row">
<div className="col-sm-3 list-header-text">
Products
</div>
<Sort parent={ this } />
</div>
<div>{rows}</div>
<div className='row'>
<div className='col-sm-2 next-prev'></div>
<div onClick={ this.clicked.bind(this, 1) } className='col-sm-2 btn btn-default next-prev'>Next</div>
</div>
</div>
)
} else if (i_f < this.state.data.length) {
return (
<div>
<div className="row">
<div className="col-sm-3 list-header-text">
Products
</div>
<Sort parent={ this } />
</div>
<div>{rows}</div>
<div className='row'>
<div onClick={ this.clicked.bind(this, -1) } className='col-sm-2 btn btn-default next-prev'>Prev</div>
<div onClick={ this.clicked.bind(this, 1) } className='col-sm-2 btn btn-default next-prev'>Next</div>
</div>
</div>
)
} else {
return (
<div>
<div className="row">
<div className="col-sm-3 list-header-text">
Products
</div>
<Sort parent={ this } />
</div>
<div>{rows}</div>
<div className='row'>
<div onClick={ this.clicked.bind(this, -1) } className='col-sm-2 btn btn-default next-prev'>Prev</div>
</div>
</div>
)
}
},
clicked: function (val) {
this.setState({ page: this.state.page + val });
}
});
var Sort = React.createClass({
getInitialState: function () {
return {
parent: this.props.parent,
sort_by: 'created_at',
sort_dir: 'DESC'
};
},
render: function() {
return (
<div className='sort-bar'>
<div className='sort-elem'>
sort by:
</div>
<div className='sort-elem'>
<select id='sort_dir' onChange={ this.selected } >
<option value='DESC'>most</option>
<option value='ASC'>least</option>
</select>
</div>
<div className='sort-elem'>
<select id='sort_by' onChange={ this.selected }>
<option value='created_at'>recent</option>
<option value='price'>expensive</option>
<option value='users_count'>popular</option>
<option value='purchases_count'>purchased</option>
<option value='quantity'>in stock</option>
</select>
</div>
<div className='limit-elem'>
<span>show </span>
<input id='limit' size='3' type='text' onChange={ this.limited }/>
<span> items per page</span>
</div>
</div>
)
},
selected: function () {
var sort_dir = $('#sort_dir').val();
var sort_by = $('#sort_by').val();
var list = this.state.parent;
var url = '/products'
$.getJSON(url,
{
sort_dir: sort_dir,
sort_by: sort_by
},
function (new_data) {
list.setState({ data: new_data, page: 1 });
}
);
},
limited: function () {
var new_limit = $('#limit').val();
this.state.parent.setState({ limit: new_limit });
}
});
var ListItem = React.createClass({
getInitialState: function () {
return {
show: 'true'
};
},
render: function () {
if (this.state.show === 'true') {
return (
<div>
<div className='col-sm-6'>
<div className='row list-item'>
<a href= { '/products/' + this.props.elem.id } >{ this.props.elem.name }</a>
</div>
<div className='row'>
<div className='col-sm-3'>
<img src={ this.props.elem.image } className="thumbnail" />
</div>
<div className='col-sm-9'>
<ul className='details'>
<li>price: ${ this.props.elem.price.toFixed(2) }</li>
<li>category: { this.props.elem.category }</li>
<li>owned by { this.props.elem.users_count } users</li>
<li>purchased { this.props.elem.purchases_count } times</li>
<li>{ this.props.elem.quantity } left in stock</li>
</ul>
</div>
</div>
<div className='row'>
<ButtonBar elem={ this.props.elem } user={ this.props.user } parent={ this } />
</div>
</div>
</div>
)
} else {
return (<div></div>)
}
}
});
var ButtonBar = React.createClass({
getInitialState: function () {
return {
grandparent: this.props.parent
};
},
render: function () {
if (this.props.user !== null) {
if (this.props.user.admin === true) {
return (
<div>
<NavLink1 name='View' url={ '/products/' + this.props.elem.id } method='GET' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
<NavLink1 name='Add to Cart' url='/cart_items/' method='POST' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
<NavLink1 name='Edit' url={ '/products/' + this.props.elem.id + '/edit' } method='GET' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
<NavLink1 name='Destroy' url={ '/products/' + this.props.elem.id } method='DELETE' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
</div>
)
} else {
return (
<div>
<NavLink1 name='View' url={ '/products/' + this.props.elem.id } method='GET' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
<NavLink1 name='Add to Cart' url='/cart_items/' method='POST' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
</div>
)
}
} else {
return (
<div>
<NavLink1 name='View' url={ '/products/' + this.props.elem.id } method='GET' grandparent={ this.state.grandparent } product_id={ this.props.elem.id } />
</div>
)
}
}
});
var NavLink1 = React.createClass({
getInitialState: function () {
return {
name: this.props.name,
url: this.props.url,
method: this.props.method,
greatgrandparent: this.props.grandparent,
user_cart_items: []
};
},
componentWillMount: function () {
var user_cart_items;
if (this.state.greatgrandparent.props.user !== null) {
$.getJSON('/cart_items/',
{
user_id: this.state.greatgrandparent.props.user.id
},
function (cart_items) {
// global_cart_items = cart_items;
// console.log(global_cart_items);
this.setState({ user_cart_items: cart_items });
}.bind(this)
);
if (this.props.name === 'Add to Cart') {
var product_id = this.props.product_id;
var cart_items = this.state.user_cart_items;
// console.log(product_id);
// console.log(global_cart_items);
if ($.inArray(product_id, cart_items.product_ids) > -1) {
// console.log('hello');
var index = cart_items.product_ids.indexOf(product_id);
var cart_item_id = cart_items.cart_item_ids[index];
this.setState({ name: 'Remove from Cart', url: '/cart_items/' + cart_item_id, method: 'DELETE' });
}
}
}
},
render: function () {
return (<a onClick={ this.clicked } className='btn btn-default'>{ this.state.name }</a>)
},
clicked: function () {
if (this.state.method === 'DELETE') {
if (this.props.name === 'Destroy') {
$.ajax({
url: this.props.url,
type: 'DELETE',
error: function () {
this.state.greatgrandparent.setState({ show: 'false'});
}.bind(this)
});
} else {
$.ajax({
url: this.state.url,
type: 'DELETE',
success: function () {
this.setState({ name: 'Add to Cart', url: '/cart_items/', method: 'POST' });
this.componentWillMount();
}.bind(this)
});
}
} else if (this.state.method === 'POST') {
$.post( this.state.url,
{
product_id: this.props.product_id,
user_id: this.state.greatgrandparent.props.user.id,
},
function( cart_item_id ) {
this.setState({ name: 'Remove from Cart', url: '/cart_items/' + cart_item_id, method: 'DELETE' });
this.componentWillMount();
}.bind(this), "json"
);
} else{
window.location.href = this.props.url;
}
}
});
|
var columns = {
columnA: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34],
columnB: [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35],
columnC: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
}
var dozens = {
firstDoz: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
middleDoz: [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
topDoz: [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
}
var lowerHalf = [];
for (var i = 1 ; i <= 18; i++) {
lowerHalf.push(i);
}
var upperHalf = [];
for (let i = 19; i <= 36; i++) {
upperHalf.push(i);
}
// even/odd checks via isEven boolean
// red/black checks via isRed boolean
var streets = {
streetA: [1, 2, 3],
streetB: [4, 5, 6],
streetC: [7, 8, 9],
streetD: [10, 11, 12],
streetE: [13, 14, 15],
streetF: [16, 17, 18],
streetG: [19, 20, 21],
streetH: [22, 23, 24],
streetI: [25, 26, 27],
streetJ: [28, 29, 30],
streetK: [31, 32, 33],
streetL: [34, 35, 36]
}
var doubleStreets = {
double1: [1, 2, 3, 4, 5, 6],
double2: [4, 5, 6, 7, 8, 9],
double3: [7, 8, 9, 10, 11, 12],
double4: [10, 11, 12, 13, 14, 15],
double5: [13, 14, 15, 16, 17, 18],
double6: [16, 17, 18, 19, 20, 21],
double7: [19, 20, 21, 22, 23, 24],
double8: [22, 23, 24, 25, 26, 27],
double9: [25, 26, 27, 28, 29, 30],
double10: [28, 29, 30, 31, 32, 33],
double11: [31, 32, 33, 34, 35, 36]
}
var basket = [0, 1, 2, 3, 37]
var splits = {
vertical:
{
colA: [[1, 4], [4, 7], [7, 10], [10, 13], [13, 16], [16, 19], [19, 22], [22, 25], [25, 28], [28, 31], [31, 34]],
colB: [[2, 5], [5, 8], [8, 11], [11, 14], [14, 17], [17, 20], [20, 23], [23, 26], [26, 29], [29, 32], [32, 35]],
colC: [[3, 6], [6, 9], [9, 12], [12, 15], [15, 18], [18, 21], [21, 24], [24, 27], [27, 30], [30, 33], [33, 36]]
},
horizontal:
{
lowStreets: [[1, 2], [2, 3], [4, 5], [5, 6], [7, 8], [8,9], [10, 11], [11, 12], [13, 14], [14, 15], [16, 17], [17, 18]],
highStreets: [[19, 20], [20, 21], [22, 23], [23, 24], [25, 26], [26, 27], [28, 29], [29, 30], [31, 32], [32, 33], [34, 35], [35, 36]]
}
}
var corners = [
[1, 2, 4, 5], [2, 3, 5, 6], [4, 5, 7, 8], [5, 6, 8, 9],
[7, 8, 10, 11], [8, 9, 11, 12], [10, 11, 13, 14], [11, 12, 14, 15],
[13, 14, 16, 17], [14, 15, 17, 18], [16, 17, 19, 20], [17, 18, 20, 21],
[19, 20, 22, 23], [20, 21, 23, 24], [22, 23, 25, 26], [23, 24, 26, 27],
[25, 26, 28, 29], [26, 27, 29, 30], [28, 29, 31, 32], [29, 30, 32, 33],
[31, 32, 34, 35], [32, 33, 35, 36]
]
// testing logic below this line and ALL can be deleted before final push
console.log(splits.vertical.colB[5])
console.log(splits.horizontal.lowStreets[3])
console.log(corners[1]);
var croupier = {
value: 5,
isRed: true,
isEven: false,
isZero: false
}
console.log(doubleStreets.double1);
if (doubleStreets.double1.indexOf(croupier.value) > -1){
console.log("win 5:1");
} else {
console.log("lose");
}
if (croupier.isRed == true && croupier.isZero == false) {
console.log("win 1:1");
// function to pay out winnings to player bank goes here
} else {
console.log("lose");
}
|
const { writeFile } = require('fs')
const { get } = require('axios')
const { prompt } = require('inquirer')
prompt([
{
type: 'input',
name: 'title',
message: 'Enter the title of a movie:'
}
])
.then(({ title }) => {
get(`http://www.omdbapi.com/?apikey=trilogy&t=${title}`)
.then(({ data: movie }) => {
writeFile('movie.json', JSON.stringify(movie), err => {
if (err) { console.log(err) }
})
})
.catch(err => console.log(err))
})
.catch(err => console.log(err))
|
import { Button, IconButton, Tooltip } from "@material-ui/core";
import HomeIcon from "@material-ui/icons/Home";
import KeyboardBackspaceOutlinedIcon from "@material-ui/icons/KeyboardBackspaceOutlined";
import SearchIcon from "@material-ui/icons/Search";
import { motion } from "framer-motion";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import lookUpApi from "../../api/lookUpApi";
import image_avatar from "../../images/71-717091_illuminati-wallpaper-hd-illuminati-pyramid.png";
import "./Lookup.scss";
// import MeaningNumerology from "../user/MeaningNumerology";
// import Footer from "../../common/footer/Footer";
const imageVariants = {
visible: {
scale: 1.05,
boxShadow: "0px 0px 20px rgb(255,255,255)",
transition: {
duration: 0.6,
yoyo: Infinity,
ease: "easeInOut",
boxShadow: "0px 0px 40px rgb(255,255,255)",
},
},
};
const firstContainerVariants = {
hidden: {
duration: 0.8,
opacity: 0,
x: "100vw",
},
visible: {
opacity: 1,
x: 0,
transition: {
duration: 1,
type: "spring",
delay: 2,
},
},
};
const secondContainerVariants = {
hidden: {
duration: 0.8,
opacity: 0,
x: "-100vw",
},
visible: {
opacity: 1,
x: 0,
transition: {
duration: 1,
type: "spring",
delay: 3,
},
},
};
const thirdContainerVariants = {
hidden: {
duration: 0.8,
opacity: 0,
x: "100vw",
},
visible: {
opacity: 1,
x: 0,
transition: {
duration: 1,
type: "spring",
delay: 4,
},
},
};
const childVariants = {
hidden: {
opacity: 0,
y: "-100vh",
transition: {
duration: 1,
type: "spring",
delay: 1,
},
},
visible: {
opacity: 1,
y: "0",
transition: {
duration: 1,
type: "spring",
delay: 1,
},
},
};
const buttonVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
delay: 1.5,
duration: 1.5,
},
},
};
const initIDFreeSearch = localStorage.getItem("idFreeSearch");
const Lookup = () => {
const history = useHistory();
const [idFreeSearch, setIdFreeSearch] = useState(initIDFreeSearch);
const [infoFreeSearch, setInfoFreeSearch] = useState("");
const [isLoaded, setIsLoaded] = useState(false);
const [delayButton, setDelayButton] = useState(false);
// get free search info
useEffect(() => {
const fetchFreeSearchInfo = async () => {
try {
const response = await lookUpApi.getResultLookup(idFreeSearch);
console.log(response.data);
setInfoFreeSearch(response.data);
setIsLoaded(true);
} catch (error) {
console.log(error);
}
};
fetchFreeSearchInfo();
}, [idFreeSearch]);
setTimeout(() => {
setDelayButton(true);
}, 5000);
const handleBackClick = () => {
history.goBack();
};
return (
<React.Fragment>
<div className='lookup-wrapper'>
<div className='lookupCover'>
<div className='container-fluid'>
<Tooltip title='Trở về trang trước'>
<IconButton
IconButton
aria-label='back'
style={{ color: "#fff" }}
onClick={handleBackClick}>
<KeyboardBackspaceOutlinedIcon fontSize='large' />
</IconButton>
</Tooltip>
<div className='contentLookup'>
<div className='header_lookUp'>
<div className='img_lookup'>
<motion.img
src={image_avatar}
alt='img_lookup'
variants={imageVariants}
animate='visible'
drag
dragConstraints={{ left: 0, top: 0, right: 0, bottom: 0 }}
/>
</div>
<div className='detail_lookup'>
{isLoaded && (
<div>
<motion.p
style={{
fontSize: "2.2rem",
fontWeight: "bold",
letterSpacing: "1px",
color: "#f69320",
}}
variants={childVariants}
initial='hidden'
animate='visible'>
<span style={{ textTransform: "uppercase" }}>
{infoFreeSearch.name}{" "}
</span>
- {moment(infoFreeSearch.birthDay).format("DD/MM/YYYY")}
</motion.p>
<motion.p
style={{
textAlign: "justify",
fontWeight: "lighter",
}}
variants={firstContainerVariants}
initial='hidden'
animate='visible'>
<motion.div
className='titleContentFreeLookUp'
whileHover={{
scale: 1.1,
originX: 0,
color: "#f50057",
}}
transition={{ type: "spring", stiffness: 300 }}>
BÀI HỌC
</motion.div>{" "}
{infoFreeSearch.baiHoc.content}
</motion.p>
<motion.p
style={{ textAlign: "justify", fontWeight: "lighter" }}
variants={secondContainerVariants}
initial='hidden'
animate='visible'>
<motion.div
className='titleContentFreeLookUp'
whileHover={{
scale: 1.1,
originX: 0,
color: "#f50057",
}}
transition={{ type: "spring", stiffness: 300 }}>
KHÁT TÂM
</motion.div>{" "}
{infoFreeSearch.khatTam.content}
</motion.p>
<motion.p
style={{ textAlign: "justify", fontWeight: "lighter" }}
variants={thirdContainerVariants}
initial='hidden'
animate='visible'>
<motion.div
className='titleContentFreeLookUp'
whileHover={{
scale: 1.1,
originX: 0,
color: "#f50057",
}}
transition={{ type: "spring", stiffness: 300 }}>
NHÂN CÁCH
</motion.div>{" "}
{infoFreeSearch.nhanCach.content}
</motion.p>
</div>
)}
{delayButton && (
<motion.div
variants={buttonVariants}
initial='hidden'
animate='visible'>
<Button
href='/'
startIcon={<HomeIcon />}
color='primary'
variant='contained'
style={{ margin: "10px" }}>
Về Trang Chủ
</Button>
<Tooltip title='Xem đầy đủ nội dung'>
<Button
href='/xem-online'
startIcon={<SearchIcon />}
color='secondary'
variant='contained'
style={{ margin: "10px" }}>
Tra cứu VIP
</Button>
</Tooltip>
</motion.div>
)}
</div>
</div>
</div>
</div>
</div>
</div>
{/* <MeaningNumerology /> */}
{/* <Footer /> */}
</React.Fragment>
);
};
export default Lookup;
|
import React from 'react'
export default class MenuButton extends React.Component {
render() {
return (
<button className="menu__button"><i>Menu</i></button>
)
}
}
|
$(document).ready(function(){
$("a").mouseenter(function(){
$(".letra, .logo").animate({
opacity: 1,}, 1000);
});
$("a").mouseleave(function(){
$(".letra").animate({
opacity: 0,}, 1000);
$(".logo").animate({
opacity: .5,}, 1000);
});
});
|
/*
* Programming Quiz: Inline Functions
* Udacity Copyright
Directions:
Call the emotions() function so that it prints the output you see below,
but instead of passing the laugh() function as an argument, pass an inline function expression instead.
emotions("happy", laugh(2)); // you can use your laugh function from the previous quizzes
Prints: "I am happy, haha!"
*/
// don't change this code
function emotions(myString, myFunc) {
console.log("I am " + myString + ", " + myFunc(2));
}
// your code goes here
// call the emotions function here and pass in an
// inline function expression
emotions("happy", function (length) {
var laugh = "";
for (var i = 0; i < length; i++) {
laugh += "ha";
}
return laugh + "!";
})
|
export const DISPLAY_BULK_ACTION = "DISPLAY_BULK_ACTION";
export function displayBulkAction(data) {
return {
type: DISPLAY_BULK_ACTION,
payload: data
}
}
|
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const orderInfo = [
{
"appBundleId": "monitor.hider",
"createTime": 1548564911000,
"finishTime": 1548564921000,
"memberId": 14239,
"orderId": 23592,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 500,
"productPayCurrency": "RMB",
"productPrice": 500,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1548528922000,
"finishTime": 1548528942000,
"memberId": 14232,
"orderId": 23567,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.guard",
"createTime": 1548483829000,
"finishTime": 1548483841000,
"memberId": 14226,
"orderId": 23532,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.guard.pro1year2",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.guard",
"createTime": 1548461016000,
"finishTime": 1548461049000,
"memberId": 14221,
"orderId": 23509,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.guard.pro1year2",
"productPayAmount": 199,
"productPayCurrency": "USD",
"productPrice": 199,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.guard",
"createTime": 1548439322000,
"finishTime": 1548439391000,
"memberId": 14218,
"orderId": 23499,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.guard.pro1year2",
"productPayAmount": 199,
"productPayCurrency": "USD",
"productPrice": 199,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.guard",
"createTime": 1548262164000,
"finishTime": 1548262170000,
"memberId": 14175,
"orderId": 23315,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.guard.pro1year2",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.guard",
"createTime": 1547909682000,
"finishTime": 1547909704000,
"memberId": 14127,
"orderId": 22979,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.guard.pro1month",
"productPayAmount": 10,
"productPayCurrency": "RMB",
"productPrice": 10,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547822908000,
"finishTime": 1547822999000,
"memberId": 14112,
"orderId": 22914,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547678282000,
"finishTime": 1547678322000,
"memberId": 14063,
"orderId": 22779,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547660268000,
"finishTime": 1547660333000,
"memberId": 14062,
"orderId": 22751,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547643488000,
"finishTime": 1547643494000,
"memberId": 11,
"orderId": 22733,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 50,
"productPayCurrency": "RMB",
"productPrice": 50,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547636907000,
"finishTime": 1547637228000,
"memberId": 14059,
"orderId": 22718,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547626008000,
"finishTime": 1547626028000,
"memberId": 14055,
"orderId": 22709,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 500,
"productPayCurrency": "RMB",
"productPrice": 500,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547575660000,
"finishTime": 1547575696000,
"memberId": 14048,
"orderId": 22678,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547571436000,
"finishTime": 1547571467000,
"memberId": 14047,
"orderId": 22671,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1547077091000,
"finishTime": 1547077174000,
"memberId": 13953,
"orderId": 22262,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1547045273000,
"finishTime": 1547045354000,
"memberId": 13950,
"orderId": 22251,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1year",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1547004324000,
"finishTime": 1547004335000,
"memberId": 13942,
"orderId": 22212,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546947465000,
"finishTime": 1546947489000,
"memberId": 13930,
"orderId": 22175,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546944145000,
"finishTime": 1546944186000,
"memberId": 13929,
"orderId": 22167,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1546869016000,
"finishTime": 1546869029000,
"memberId": 13917,
"orderId": 22123,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1year",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1546653912000,
"finishTime": 1546653920000,
"memberId": 13856,
"orderId": 21922,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546651827000,
"finishTime": 1546651839000,
"memberId": 13855,
"orderId": 21919,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546448348000,
"finishTime": 1546448417000,
"memberId": 13828,
"orderId": 21718,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1546446554000,
"finishTime": 1546446557000,
"memberId": 13827,
"orderId": 21715,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1year",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1546446540000,
"finishTime": 1546446545000,
"memberId": 13827,
"orderId": 21714,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.color",
"createTime": 1546427823000,
"finishTime": 1546427838000,
"memberId": 13825,
"orderId": 21684,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546328879000,
"finishTime": 1546328885000,
"memberId": 13808,
"orderId": 21613,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546239268000,
"finishTime": 1546239281000,
"memberId": 13797,
"orderId": 21520,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546222475000,
"finishTime": 1546222535000,
"memberId": 13794,
"orderId": 21498,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1546210890000,
"finishTime": 1546210995000,
"memberId": 13793,
"orderId": 21490,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545945847000,
"finishTime": 1545945882000,
"memberId": 13752,
"orderId": 21276,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545885625000,
"finishTime": 1545885638000,
"memberId": 13742,
"orderId": 21204,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545846283000,
"finishTime": 1545846295000,
"memberId": 13740,
"orderId": 21170,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545736208000,
"finishTime": 1545736264000,
"memberId": 13711,
"orderId": 21052,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545725586000,
"finishTime": 1545725633000,
"memberId": 13709,
"orderId": 21028,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545705409000,
"finishTime": 1545705432000,
"memberId": 13703,
"orderId": 20993,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545524131000,
"finishTime": 1545524143000,
"memberId": 13668,
"orderId": 20803,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545282272000,
"finishTime": 1545282407000,
"memberId": 13630,
"orderId": 20594,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545255730000,
"finishTime": 1545255788000,
"memberId": 13623,
"orderId": 20558,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545167030000,
"finishTime": 1545167077000,
"memberId": 13607,
"orderId": 20465,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545155546000,
"finishTime": 1545155665000,
"memberId": 13606,
"orderId": 20458,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1545146801000,
"finishTime": 1545146812000,
"memberId": 13605,
"orderId": 20449,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545129229000,
"finishTime": 1545129266000,
"memberId": 13602,
"orderId": 20421,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1545055244000,
"finishTime": 1545055300000,
"memberId": 13588,
"orderId": 20368,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1year",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1545050547000,
"finishTime": 1545050597000,
"memberId": 13583,
"orderId": 20359,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544989698000,
"finishTime": 1544989740000,
"memberId": 13571,
"orderId": 20295,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 500,
"productPayCurrency": "RMB",
"productPrice": 500,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544987970000,
"finishTime": 1544988033000,
"memberId": 13570,
"orderId": 20291,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544982152000,
"finishTime": 1544982218000,
"memberId": 13569,
"orderId": 20288,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544981905000,
"finishTime": 1544981965000,
"memberId": 13568,
"orderId": 20286,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544946183000,
"finishTime": 1544946250000,
"memberId": 13563,
"orderId": 20239,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.color",
"createTime": 1544943122000,
"finishTime": 1544943133000,
"memberId": 13562,
"orderId": 20235,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544896964000,
"finishTime": 1544897009000,
"memberId": 13557,
"orderId": 20187,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544879694000,
"finishTime": 1544879722000,
"memberId": 13555,
"orderId": 20167,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544873846000,
"finishTime": 1544873913000,
"memberId": 13553,
"orderId": 20160,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544858253000,
"finishTime": 1544858316000,
"memberId": 13547,
"orderId": 20136,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544850113000,
"finishTime": 1544850153000,
"memberId": 13544,
"orderId": 20125,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544842452000,
"finishTime": 1544842600000,
"memberId": 13542,
"orderId": 20114,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544832369000,
"finishTime": 1544832378000,
"memberId": 13540,
"orderId": 20098,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 500,
"productPayCurrency": "RMB",
"productPrice": 500,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.color",
"createTime": 1544795728000,
"finishTime": 1544795740000,
"memberId": 13537,
"orderId": 20059,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1month",
"productPayAmount": 400,
"productPayCurrency": "RMB",
"productPrice": 400,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544776990000,
"finishTime": 1544777020000,
"memberId": 13531,
"orderId": 20024,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 1500,
"productPayCurrency": "RMB",
"productPrice": 1500,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544729570000,
"finishTime": 1544729658000,
"memberId": 13521,
"orderId": 19959,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544691813000,
"finishTime": 1544691879000,
"memberId": 13507,
"orderId": 19891,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544682054000,
"finishTime": 1544682223000,
"memberId": 13503,
"orderId": 19873,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544676961000,
"finishTime": 1544676991000,
"memberId": 13501,
"orderId": 19866,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544675214000,
"finishTime": 1544675358000,
"memberId": 13500,
"orderId": 19863,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544667173000,
"finishTime": 1544667182000,
"memberId": 13497,
"orderId": 19847,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1month",
"productPayAmount": 500,
"productPayCurrency": "RMB",
"productPrice": 500,
"productSubtitle": "",
"productTitle": "1个月",
},
{
"appBundleId": "monitor.color",
"createTime": 1544663666000,
"finishTime": 1544663672000,
"memberId": 13496,
"orderId": 19839,
"orderStatus": 200,
"payChannelId": 1,
"productCount": 1,
"productDetail": "服务包括:\n- 去除应用内广告。",
"productNo": "android.color.iap.member1year",
"productPayAmount": 1200,
"productPayCurrency": "RMB",
"productPrice": 1200,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544642878000,
"finishTime": 1544642928000,
"memberId": 13494,
"orderId": 19812,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544641783000,
"finishTime": 1544641906000,
"memberId": 13493,
"orderId": 19811,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productSubtitle": "",
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544641606000,
"finishTime": 1544641643000,
"memberId": 13492,
"orderId": 19810,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productTitle": "1年",
},
{
"appBundleId": "monitor.hider",
"createTime": 1544624646000,
"finishTime": 1544624681000,
"memberId": 13491,
"orderId": 19784,
"orderStatus": 200,
"payChannelId": 10,
"productCount": 1,
"productDetail": "",
"productNo": "monitor.hider.pro1year",
"productPayAmount": 300,
"productPayCurrency": "USD",
"productPrice": 300,
"productTitle": "1年",
}
];
export default {
'POST /order/getOrderInfo': (req, res) => {
const { startTime, endTime, appname, currency } = req.body;
var start = moment(startTime).valueOf();
var end = moment(endTime).valueOf();
var result = [];
var totalMoney = 0;
if (appname == '' && currency == '') {
for (var index = 0; index < orderInfo.length; index++) {
var order = orderInfo[index];
if (order.orderStatus == 200) {
if (order.finishTime >= start && order.finishTime <= end) {
result.push(order);
totalMoney += order.productPayAmount;
}
}
}
} else if (appname == '' && !(currency == '')) {
for (var index = 0; index < orderInfo.length; index++) {
var order = orderInfo[index];
if (order.orderStatus == 200) {
if (order.finishTime >= start && order.finishTime <= end) {
if (order.productPayCurrency == currency) {
result.push(order);
totalMoney += order.productPayAmount;
}
}
}
}
} else if (!(appname == '') && currency == '') {
for (var index = 0; index < orderInfo.length; index++) {
var order = orderInfo[index];
if (order.orderStatus == 200) {
if (order.finishTime >= start && order.finishTime <= end) {
if (order.appBundleId == appname) {
result.push(order);
totalMoney += order.productPayAmount;
}
}
}
}
} else {
for (var index = 0; index < orderInfo.length; index++) {
var order = orderInfo[index];
if (order.orderStatus === 200) {
if (order.finishTime >= start && order.finishTime <= end) {
if (order.appBundleId == appname && order.productPayCurrency == currency) {
result.push(order);
totalMoney += order.productPayAmount;
}
}
}
}
}
res.send({
totalMoney,
orderData: result,
});
},
'POST /order/getOrderSummaryGroupByDate': (req, res) => {
var orders = orderInfo.concat().reverse();
const { startDate, endDate, appBundleId } = req.body;
var start = moment(startDate).valueOf();
var end = moment(endDate).valueOf();
var dateBaseData = [];
var count = 0;
var totalAmount = 0;
var curStart = undefined;
var curEnd = undefined;
var curData = {
"date": undefined,
"totalAmount": 0,
};
if (appBundleId == '') {
for (var i = 0; i < orders.length; i++) {
var order = orders[i];
if (order.orderStatus === 200) {
if (order.finishTime <= end && order.finishTime >= start) {
count = count + 1;
totalAmount = totalAmount + order.productPayAmount;
if (curStart === undefined && curEnd === undefined) {
//the first date that match the range
curStart = moment(order.finishTime).startOf('day');
curEnd = moment(order.finishTime).endOf('day');
curData.date = curStart.valueOf();
curData.totalAmount = curData.totalAmount + order.productPayAmount;
continue;
}
if (order.finishTime <= curEnd.valueOf() && order.finishTime >= curStart.valueOf()) {
// if order is finished on the current date
curData.totalAmount = curData.totalAmount + order.productPayAmount;
} else {
// if order is finished on another day
dateBaseData.push(curData);
curStart = moment(order.finishTime).startOf('day');
curEnd = moment(order.finishTime).endOf('day');
curData = {
"date": undefined,
"totalAmount": 0,
}
curData.date = curStart.valueOf();
curData.totalAmount = order.productPayAmount;
}
}
}
}
dateBaseData.push(curData);
} else {
for (var i = 0; i < orders.length; i++) {
var order = orders[i];
if (order.orderStatus === 200) {
if (order.finishTime <= end && order.finishTime >= start) {
if (order.appBundleId == appBundleId) {
count = count + 1;
totalAmount = totalAmount + order.productPayAmount;
if (curStart === undefined && curEnd === undefined) {
//the first date that match the range
curStart = moment(order.finishTime).startOf('day');
curEnd = moment(order.finishTime).endOf('day');
curData.date = curStart.valueOf();
curData.totalAmount = curData.totalAmount + order.productPayAmount;
continue;
}
if (order.finishTime <= curEnd.valueOf() && order.finishTime >= curStart.valueOf()) {
// if order is finished on the current date
curData.totalAmount = curData.totalAmount + order.productPayAmount;
} else {
// if order is finished on another day
dateBaseData.push(curData);
curStart = moment(order.finishTime).startOf('day');
curEnd = moment(order.finishTime).endOf('day');
curData = {
"date": undefined,
"totalAmount": 0,
}
curData.date = curStart.valueOf();
curData.totalAmount = order.productPayAmount;
}
}
}
}
}
dateBaseData.push(curData);
}
res.send({
dateBaseData,
count,
totalAmount: (totalAmount / 100).toFixed(2),
})
},
'POST /order/getOrderSummaryGroupByApp': (req, res) => {
const { startDate, endDate } = req.body;
var appBaseData = [];
var apps = [];
for (var i = 0; i < orderInfo.length; i++) {
var order = orderInfo[i];
if (order.orderStatus === 200) {
if (order.finishTime >= moment(startDate).valueOf() && order.finishTime <= moment(endDate).valueOf()) {
if (!apps.includes(order.appBundleId)) {
apps.push(order.appBundleId);
appBaseData.push({
item: order.appBundleId,
totalAmount: order.productPayAmount
});
} else {
for (var j = 0; j < appBaseData.length; j++) {
if (appBaseData[j].item === order.appBundleId) {
appBaseData[j].totalAmount = appBaseData[j].totalAmount + order.productPayAmount;
break;
}
}
}
}
}
}
res.send({
appBaseData,
})
}
}
|
import React, { Component } from "react";
import store from "./store";
import { isAdmin } from "@firebase/util";
import { Route, Redirect } from "react-router-dom";
import { Container } from "reactstrap";
const Authorization = WrappedComponent => {
return class WithAuthorization extends React.Component {
constructor(props) {
super(props);
this.state = {
user: store.getState().user,
isAdmin: store.getState().isAdmin
};
store.subscribe(() => {
this.setState({
user: store.getState.user,
isAdmin: store.getState().isAdmin
});
});
}
render() {
//const { role } = this.state.user
if (this.state.isAdmin) {
return <WrappedComponent {...this.props} />;
} else {
return (
<Container>
<Redirect
to={{
pathname: "/login"
}}
/>
</Container>
);
}
}
};
};
export default Authorization;
|
/*
Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about)
Dual licensed under the MIT or LGPL Version 2 licenses.
*/
OMEDITOR.plugins.add( 'menubutton',
{
requires : [ 'button', 'menu' ],
beforeInit : function( editor )
{
editor.ui.addHandler( OMEDITOR.UI_MENUBUTTON, OMEDITOR.ui.menuButton.handler );
}
});
/**
* Button UI element.
* @constant
* @example
*/
OMEDITOR.UI_MENUBUTTON = 'menubutton';
(function()
{
var clickFn = function( editor )
{
var _ = this._;
// Do nothing if this button is disabled.
if ( _.state === OMEDITOR.TRISTATE_DISABLED )
return;
_.previousState = _.state;
// Check if we already have a menu for it, otherwise just create it.
var menu = _.menu;
if ( !menu )
{
menu = _.menu = new OMEDITOR.menu( editor,
{
panel:
{
className : editor.skinClass + ' cke_contextmenu',
attributes : { 'aria-label' : editor.lang.common.options }
}
});
menu.onHide = OMEDITOR.tools.bind( function()
{
this.setState( this.modes && this.modes[ editor.mode ] ? _.previousState : OMEDITOR.TRISTATE_DISABLED );
},
this );
// Initialize the menu items at this point.
if ( this.onMenu )
menu.addListener( this.onMenu );
}
if ( _.on )
{
menu.hide();
return;
}
this.setState( OMEDITOR.TRISTATE_ON );
menu.show( OMEDITOR.document.getById( this._.id ), 4 );
};
OMEDITOR.ui.menuButton = OMEDITOR.tools.createClass(
{
base : OMEDITOR.ui.button,
$ : function( definition )
{
// We don't want the panel definition in this object.
var panelDefinition = definition.panel;
delete definition.panel;
this.base( definition );
this.hasArrow = true;
this.click = clickFn;
},
statics :
{
handler :
{
create : function( definition )
{
return new OMEDITOR.ui.menuButton( definition );
}
}
}
});
})();
|
import Vue from "vue";
import restaurant from "./restaurant";
import addrestaurant from "./addRestaurant";
import pager from "./pager";
//Composant restaurants, contient les différents restaurants
//import restaurant from "./restaurant";
//instance de vue principale
new Vue({
// return new Vue({
el: "#main",
components: { restaurant, addrestaurant, pager },
data: {
restaurants: [
{
id: "ID",
name: "café de Paris",
cuisine: "Française"
},
{
id: "ID",
name: "Sun City Café",
cuisine: "Américaine"
}
],
page: 0,
nbPerPage: 5,
name: ""
},
mounted() {
console.log("mainView.mounted");
this.getRestaurantsFromServer();
},
methods: {
addRestaurant($event) {
console.log(
JSON.stringify($event) +
"addRestaurant(" +
$event["name"] +
"," +
$event["cuisine"] +
")"
);
//event.preventDefault();
let url = "http://127.0.0.1:8080/api/restaurants";
fetch(url, {
method: "POST",
body: $event
})
.then(responseJSON => {
responseJSON.json().then(res => {
// Maintenant res est un vrai objet JavaScript
//afficheReponsePOST(res);
console.log(res);
this.getRestaurantsFromServeur();
});
})
.catch(function(err) {
console.log(err);
});
},
getRestaurantsFromServer() {
console.log("getRestaurantsFromServer");
let url =
"http://localhost:8080/api/restaurants?page=" +
this.page +
"&pagesize=" +
this.nbPerPage +
"&name=" +
this.name;
console.log("getRestaurantsFromServeur : " + url);
fetch(url)
.then(repJSON => {
return repJSON.json();
})
.then(repJS => {
this.restaurants = repJS.data;
console.log(this.restaurants);
})
.catch(err => {
console.log(err);
});
},
incr() {
console.log("incr");
if (this.restaurants.length > 0) {
this.page++;
this.getRestaurantsFromServer();
} else this.page--;
},
decr() {
console.log("decr");
if (this.page > 1) {
this.page--;
this.getRestaurantsFromServer();
} else this.page = 1;
},
nbrestodecr() {
console.log("decr");
if (this.nbPerPage < 2) {
this.nbPerPage = 1;
} else {
this.nbPerPage--;
this.getRestaurantsFromServer();
}
},
nbrestoincr() {
console.log("incr");
this.nbPerPage++;
this.getRestaurantsFromServer();
}
}
});
|
var model = require('../models');
let jwt = require('jsonwebtoken');
module.exports={
create:function(req,res){
let token=req.headers.token;
jwt.verify(token, 'rahasia', function(err, decoded) {
if (err) {
res.send(err);
} else {
model.Question.create({
title:req.body.title,
content:req.body.content,
user_id:decoded.userid,
}).then(function(){
res.send('user Question posted');
})
}
});
},
userquestionviews:function(req,res){
let token=req.headers.token;
console.log(token);
jwt.verify(token, 'rahasia', function(err, decoded) {
if (err) {
res.send(err);
} else {
model.Question.findAll({where:{
user_id:decoded.userid
}
}).then(function(data){
res.send(data);
})
}
});
},
views:function(req,res){
model.sequelize.query(`select questions.id as queston_id,questions.title as title,questions.content as content, users.id as user_id, users.name as user_name
from public."Questions" questions left join public."Users" users on(questions.user_id=users.id)`
,{
type: model.sequelize.QueryTypes.SELECT
}).then(function(questions){
res.send(questions)
}).catch(function(err){
res.send(err)
})
},
view:function(req,res){
model.Question.findAll({where:{
id:req.params.id
}}).then(function(data){
res.send(data)
})
},
update:function(req,res){
let token=req.headers.token;
jwt.verify(token, 'rahasia', function(err, decoded) {
if (err) {
res.send(err);
} else {
model.Question.findOne({where:{
id:req.params.id,
user_id:decoded.userid
}
}).then(function(data){
if (data) {
model.Question.update({
title:req.body.title||data.title,
content:req.body.content||data.content
},{
where:{
id:data.id,
//user_id:data.user_id
}
}).then(function(){
res.send('data updated')
})
} else {
res.send('user unautorized')
}
})
}
});
},
delete:function(req,res){
let token=req.headers.token;
jwt.verify(token, 'rahasia', function(err, decoded) {
if (err) {
res.send(err);
} else {
model.Question.findOne({where:{
id:req.params.id,
user_id:decoded.userid
}
}).then(function(data){
if (data) {
model.Question.destroy({where:{
id:data.id
}}).then(function(){
res.send('data deleted')
})
} else {
res.send('user unautorized')
}
})
}
});
}
}
|
/**
* husen you no JavaScript //
*/
var isMouseDown = false;
var offsetX, offsetY;
var cont;
var husenCount = 1;
//var endpoint = "http://localhost:8080/facitter/api";
var isAllMax = 0;
//本番環境用
var endpoint = 'https://team2017-2.spiral.cloud/facitter/api';
/*
* websocket.jsに移動
window.onload = function(){
loadHusens();
hwsConnection();
}*/
$("#postit").mousedown(function (e){new Card();});
$("#allResize").mousedown(function (e){allResizeHusen();});
$("#FGO").mousedown(function (e){husenGrandOrder();});
//websocketオブジェクト
var hws;
function hwsConnection() {
if(hws != null){
return;
}
//hws = new WebSocket('ws://' + window.location.host + '/facitter/ws');
// 本番環境用
hws = new WebSocket('wss://' + window.location.host + '/facitter/ws');
hws.onmessage = hwsOnMessage;
hws.onclose = function(closeEvent) {
//console.log('hws close code = ' + closeEvent.code + ', reason = ' + closeEvent.reason);
};
}
function hwsOnMessage(message){
var arrayStr = message.data.split(' ');
if(arrayStr[0] === 'color'){
colorSetter(parseInt(arrayStr[1]),parseInt(arrayStr[2]));
}else if(arrayStr[0] === 'delete'){
fadeOutContainer(parseInt(arrayStr[1]));
setTimeout(deleter, 300, parseInt(arrayStr[1]));
}else if(arrayStr[0] === 'good'){
document.getElementsByName(arrayStr[1])[0].innerHTML = "Good:"+arrayStr[2];
}else if(arrayStr[0] === 'bad'){
document.getElementsByName(arrayStr[1])[0].innerHTML = "Bad:"+arrayStr[2];
}else if(arrayStr[0] === 'text'){
document.getElementsByName(arrayStr[1])[0].value = arrayStr[2];
}else if(arrayStr[0] === 'position'){
setPosition(arrayStr[1],arrayStr[2],arrayStr[3]);
}else if(arrayStr[0] === 'new'){
createCard(parseInt(arrayStr[1]));
setTimeout(fadeInContainer, 200, parseInt(arrayStr[1]));
}else if(arrayStr[0] === 'order'){
$('.husen').css('transition','all 500ms 0s ease');
reloadAllHusenPosition();
setTimeout(function(){$('.husen').css('transition','all 300ms 0s ease');}, 200);
}
}
function loadHusens(){
$.ajax({
type: 'GET',
url: endpoint + '/husens',
success: function(json) {
for(i=0;i<json.husens.length;i++){
new makeCard(json.husens[i].hid,
json.husens[i].text,
json.husens[i].xPosition,
json.husens[i].yPosition,
json.husens[i].height,
json.husens[i].good,
json.husens[i].bad,
json.husens[i].color,
json.husens[i].canEditPerson
);
}
setTimeout(allFadein, 200, json);
}
});
}
function allFadein(json){
for(i=0;i<json.husens.length;i++){
fadeInContainer(json.husens[i].hid);
}
}
function fadeInContainer(hid){
$("#container" + String(hid)).addClass("fadeIn");
$("#header" + String(hid)).addClass("fadeIn");
$("#handle" + String(hid)).addClass("fadeIn");
var txtarea = document.getElementsByName("txt"+String(hid))[0];
txtarea.classList.add("fadeIn");
$("#buttonContainer" + String(hid)).addClass("fadeIn");
//txtarea.className = "husen fadeIn";
//$("input[name='txt" + String(hid)+"']").addClass("fadeIn");//なぜできない
}
function fadeOutContainer(hid){
//$("#container" + String(hid)).removeClass("fadeIn");
var container = document.getElementById("container"+String(hid));
////console.log(container);
container.style.opacity = 0;
$("#header" + String(hid)).removeClass("fadeIn");
$("#handle" + String(hid)).removeClass("fadeIn");
var txtarea = document.getElementsByName("txt"+String(hid))[0];
txtarea.classList.remove("fadeIn");
$("#buttonContainer" + String(hid)).removeClass("fadeIn");
// txtarea.className = "husen";
// var txtName='input[name="txt' + String(hid)+'"]';
// $(txtName).removeClass("fadeIn");
}
function updateText(name,count){
$.ajax({
type : 'PUT',
url : endpoint+'/husens',
data: {
hid: count,
text: document.getElementsByName(name)[0].value
},
success : function() {
////console.log('text-a');
hws.send("text "+name+" "+document.getElementsByName(name)[0].value);
},
error: function() {
////console.log('text-b');
}
});
}
function goodButtonCounter(name,count){
$.ajax({
type : 'PUT',
url : endpoint+'/husens',
data: {
hid: count,
good: true
},
success : function(good) {
////console.log('good-a');
hws.send("good "+name+" "+good);
},
error: function(good) {
////console.log('good-b');
}
});
}
function setPositionFunc(array){
setPosition(array[0],array[1],array[2]);
}
function setPosition(id,left,top){
document.getElementById(id).style.left = left;
document.getElementById(id).style.top = top;
}
function badButtonCounter(name,count){
$.ajax({
type : 'PUT',
url : endpoint+'/husens',
data: {
hid: count,
bad: true
},
success : function(bad) {
////console.log('bad-a');
hws.send("bad "+name+" "+bad);
},
error: function(bad) {
////console.log('bad-b');
}
});
}
function colorSetter(count,color){
var handle = "handle" + String(count);
var container = "container" + String(count);
var name = "txt" + String(count);
document.getElementById(handle).style.backgroundColor = getHandleColor(color);
document.getElementById(container).style.backgroundColor = getBackColor(color);
document.getElementById(container).style.border = getBackColor(color);
document.getElementsByName(name)[0].style.backgroundColor = getBackColor(color);
document.getElementsByName("button"+String(count*4-3))[0].style.color = getHandleColor(color);
document.getElementsByName("button"+String(count*4-2))[0].style.color = getHandleColor(color);
document.getElementsByName("button"+String(count*4-1))[0].style.color = getHandleColor(color);
document.getElementsByName("button"+String(count*4-3))[0].style.borderLeftColor = getHandleColor(color);
document.getElementsByName("button"+String(count*4-2))[0].style.borderLeftColor = getHandleColor(color);
document.getElementsByName("button"+String(count*4-1))[0].style.borderLeftColor = getHandleColor(color);
removeColorChange(document.getElementsByName("button"+count*4)[0],count,color);
}
function colorCounter(count,color){
$.ajax({
type : 'PUT',
url : endpoint+'/husens',
data: {
hid: count,
color: color
},
success : function(data) {
////console.log('put-a');
hws.send("color "+count+" "+color);
},
error: function(data) {
////console.log('put-b');
}
});
}
function deleter(hid){
//var containerId = "#container" + String(hid);
var container = document.getElementById("container"+String(hid));
container.remove();
}
function deleteHusen(count){
$.ajax({
type : 'DELETE',
url : endpoint+'/husens/'+count,
success : function(data) {
////console.log('delete-a');
hws.send("delete "+count);
},
error: function(data) {
////console.log('delete-b');
}
});
}
function getHandleColor(count){
var colorStr;
if(count % 6 === 0){
return "#FFB900";
}else if(count % 6 === 1){
return "#9E9E9E";
}else if(count % 6 === 2){
return "#D900A9";
}else if(count % 6 === 3){
return "#5C239B";
}else if(count % 6 === 4){
return "#0078D7";
}
return "#108904";
}
function getBackColor(count){
var colorStr;
if(count % 6 === 0){
return "#FFFF88";
}else if(count % 6 === 1){
return "#EFEFEF";
}else if(count % 6 === 2){
return "#FFBBFF";
}else if(count % 6 === 3){
return "#CFCBFF";
}else if(count % 6 === 4){
return "#CCEEFF";
}
return "#AEFFAE";
}
var clickCount = 0;
//画面の位置用
var targetElement = document.getElementById( "my_canvas" ) ;
var clientRect = targetElement.getBoundingClientRect() ;
// 画面内のキャンバスの位置
var canvasX = clientRect.left ;
var canvasY = clientRect.top ;
function draggable(count, handle, container) {
container.style.position = "absolute";
var containerId = container.id;
container.onmousedown = function(event){
////console.log(container.nextElementSibling.id);
while(container.nextElementSibling != null &&
container.nextElementSibling.classList.contains("husenContainer")){
if (container.nextElementSibling != null) {
$('#' + containerId).before($('#' + container.nextElementSibling.id));
}
}
}
handle.onmousedown = function(event) {
event.preventDefault();
var rect = container.getBoundingClientRect();
offsetX = event.screenX - rect.left;
offsetY = event.screenY - rect.top;
cont = container;
isMouseDown = true;
$('.husen').css('transition','all 0ms 0s ease');
if( !clickCount ) {
++clickCount ;
setTimeout( function() {
clickCount = 0 ;
}, 350 ) ;
// ダブルクリックの場合
} else {
$('.husen').css('transition','all 300ms 0s ease');
////console.log(cont + " doubleClick");
resizeContainer(cont);
clickCount = 0 ;
}
}
document.onmouseup = function() {
if (isMouseDown) {
$.ajax({
type : 'PUT',
url : endpoint + '/husens',
data : {
hid : parseInt(cont.id.substring(9)),
xPosition : cont.style.left,
yPosition : cont.style.top
},
success : function(data) {
////console.log('move-a');
hws.send("position "+cont.id+" "+cont.style.left+" "+cont.style.top);
},
error : function(data) {
////console.log('move-b');
// hws.send("post-task:"+tid);
}
});
$('.husen').css('transition','all 300ms 0s ease');
//cont = null;
}
isMouseDown = false;
}
document.onmousemove = function(event) {
/* 変更前
if (isMouseDown == true) {
cont.style.left = event.screenX - offsetX + "px";
cont.style.top = event.screenY - offsetY + "px";
}
*/
//ホワイトボードから付箋がはみ出さないように
if (isMouseDown == true) {
var rect = cont.getBoundingClientRect();
var hwidth = 240;
var hheight = 200;
var xleft = event.screenX - offsetX - canvasX;//canvasからのhusenの位置x
var ytop = event.screenY - offsetY - canvasY;//canvasからのhusenの位置y
var xright = xleft + hwidth ;
var ybottom = ytop + hheight;
var canvas = document.getElementById("my_canvas");
var cwidth = canvas.width;
var cheight = canvas.height;
cont.style.left = event.screenX - offsetX + "px";
cont.style.top = event.screenY - offsetY + "px";
if(xleft < 0) cont.style.left = canvasX+1 + "px";
if(ytop < 0) cont.style.top = canvasY+1 + "px";
if(xright > cwidth + 5) cont.style.left = cwidth - hwidth + 5 + canvasX + "px";
if(ybottom > cheight + 10) cont.style.top = cheight - hheight + 10 + canvasY + "px";
}
}
}
function husenGrandOrder(){
$.ajax({
type : 'PUT',
url : endpoint+'/husens/order',
data:{
number: 4,
left: "75px",
top: "75px",
width: "245px",
height: "200px"
},
success : function(data) {
////console.log('order-a');
hws.send("order");
},
error: function(data) {
////console.log('order-b');
}
});
}
function reloadAllHusenPosition(){
$.ajax({
type: 'GET',
url: endpoint + '/husens',
success: function(json) {
for(i=0;i<json.husens.length;i++){
var id = "container"+json.husens[i].hid;
var newx = json.husens[i].xPosition;//String --px
var newy = json.husens[i].yPosition;//String --px
//setTimeout(setPositionFunc, 1200,[id,newx,newy]);
setPosition(id,newx,newy);
}
}
});
}
function allResizeHusen(){
var contList = document.getElementsByClassName('husenContainer');
if(isAllMax === 0){
//minimize
for(var i = 0; i < contList.length; i++){
minimizeHusen(contList[i]);
}
}else if(isAllMax === 1){
//transparentize
for (var i = 0; i < contList.length; i++) {
invisualizeHusen(contList[i]);
}
}else{
//maximize
for(var i = 0; i < contList.length; i++){
maximizeHusen(contList[i]);
}
}
isAllMax++;
isAllMax = isAllMax%3;
}
function resizeContainer(cont){
var contArray = cont.children;
if(cont.classList.contains("mini")){
invisualizeHusen(cont);
}else if(cont.classList.contains("invisible")){
maximizeHusen(cont);
}else{
minimizeHusen(cont);
}
}
function minimizeHusen(cont){
var contArray = cont.children;
cont.classList.add("mini");
cont.classList.remove("invisible");
cont.style.width="120px";
cont.style.opacity="1";
for(var i = 0; i < contArray.length; i++){
if(String(contArray[i].name).substring(0,3) === "txt"){
document.getElementsByName(contArray[i].name)[0].style.height="25px";
}else if(String(contArray[i].id).substring(0,15) === "buttonContainer"){
document.getElementById(contArray[i].id).style.height="0px";
}else if(String(contArray[i].id).substring(0,6) === "header"){
document.getElementById(contArray[i].id).children[0].style.width = "99px";
}
}
}
function invisualizeHusen(cont){
var contArray = cont.children;
cont.classList.remove("mini");
cont.classList.add("invisible");
cont.style.width="120px";
cont.style.opacity="0.15";
for(var i = 0; i < contArray.length; i++){
if(String(contArray[i].name).substring(0,3) === "txt"){
document.getElementsByName(contArray[i].name)[0].style.height="25px";
}else if(String(contArray[i].id).substring(0,15) === "buttonContainer"){
document.getElementById(contArray[i].id).style.height="0px";
}else if(String(contArray[i].id).substring(0,6) === "header"){
document.getElementById(contArray[i].id).children[0].style.width = "99px";
}
}
}
function maximizeHusen(cont){
var contArray = cont.children;
cont.classList.remove("invisible");
cont.classList.remove("mini");
cont.style.width="240px";
cont.style.opacity="1";
for(var i = 0; i < contArray.length; i++){
if(String(contArray[i].name).substring(0,3) === "txt"){
document.getElementsByName(contArray[i].name)[0].style.height="150px";
}else if(String(contArray[i].id).substring(0,15) === "buttonContainer"){
document.getElementById(contArray[i].id).style.height="25px";
}else if(String(contArray[i].id).substring(0,6) === "header"){
document.getElementById(contArray[i].id).children[0].style.width = "204px";
}
}
}
function removeColorChange(remove,uniHusenCount,color){
remove.style.color = "#FFFFFF";
remove.style.background = getHandleColor(color);
remove.style.borderLeftColor = getHandleColor(color);
remove.style.borderRightColor = getHandleColor(color);
remove.onmouseover = function(){
document.getElementsByName("button"+uniHusenCount*4)[0].style.background = "#AAAAAA";
document.getElementsByName("button"+uniHusenCount*4)[0].style.color= "#000000";
document.getElementsByName("button"+uniHusenCount*4)[0].style.borderLeftColor = "#000000";
document.getElementsByName("button"+uniHusenCount*4)[0].style.borderRightColor = "#000000";
};
remove.onmouseout = function(){
document.getElementsByName("button"+uniHusenCount*4)[0].style.color = "#FFFFFF";
document.getElementsByName("button"+uniHusenCount*4)[0].style.background = getHandleColor(color);
document.getElementsByName("button"+uniHusenCount*4)[0].style.borderLeftColor = getHandleColor(color);
document.getElementsByName("button"+uniHusenCount*4)[0].style.borderRightColor = getHandleColor(color);
};
// this.buttonRemove.style.color = "#FFFFFF";
// this.buttonRemove.style.borderLeftColor = getHandleColor(color);
// this.buttonRemove.style.borderRightColor = getHandleColor(color);
}
function Card() {
//var x = this;
$.ajax({
type : 'POST',
url : endpoint + '/husens',
data : {
text : "",
xPosition : "100px",
yPosition : "80px",
height : "150px",
good : 0,
bad : 0,
color : 0,
canEdit : 0
},
success: function(json){
////console.log(json);
hws.send("new "+String(json.hid));
},
error: function(json){
////console.log(json);
}
});
//return this.container;
}
function createCard(hid){
makeCard(hid,"","100px","80px","150px",0,0,0,0);
}
function makeCard(hid,text,xPosition,yPosition,height,good,bad,color,canEditPerson){
var uniHusenCount = hid;
var goodCount=good;
var badCount=bad;
var colorCount=color;
this.container = document.createElement('div');
this.container.className = 'husen husenContainer';
this.container.id = "container"+String(uniHusenCount);
this.container.style="width:240px;background-color:"+ getBackColor(colorCount) +";" +
"border:"+ getHandleColor(colorCount) +";box-shadow:4px 4px 8px #BBB;display:inline-block;" +
"left:"+xPosition+";top:"+yPosition;
this.header = document.createElement('div');
this.header.id = "header"+String(uniHusenCount);
this.header.className = 'husen';
this.header.style.width = "100%";
this.header.style.height = "25px";
this.handle = document.createElement('div');
this.handle.id = "handle"+String(uniHusenCount);
this.handle.className = 'husen';
this.handle.style.width = "204px";
this.handle.style.height = "25px";
this.handle.style.margin = "0px";
this.handle.style.backgroundColor = getHandleColor(colorCount);
this.handle.style.display = "inline-block";
this.handle.style.position = "absolute";
this.txtarea = document.createElement('textarea');
this.txtarea.className = 'husen';
this.txtarea.value = text;
this.txtarea.name = "txt"+String(uniHusenCount);
this.txtarea.style = "width:100%;height:"+height+";" +
"background-color:"+getBackColor(colorCount)+";" +
"display:block;resize:none;" +
"border:0px;" +
"font-size:20px;font-family:Arial";
this.txtarea.onblur = function(){
updateText(this.name,uniHusenCount);
}
var height = this.txtarea.style.height;
this.buttonContainer = document.createElement('div');
this.buttonContainer.className = 'husen buttonContainer';
this.buttonContainer.style = "width:100%;height:25px;display:block;vertical-align:bottom;";
this.buttonContainer.id = "buttonContainer"+String(uniHusenCount);
this.buttonGood = document.createElement('a');
this.buttonGood.name = "button" + String(uniHusenCount*4-3);
this.buttonGood.className = "square_btn";
this.buttonGood.innerHTML = "Good:"+String(goodCount);
this.buttonGood.style = "width:32.05%;height:85%;vertical-align:top";
this.buttonGood.onclick = function(){goodButtonCounter(this.name,uniHusenCount)};
this.buttonGood.style.color = getHandleColor(color);
this.buttonGood.style.borderLeftColor = getHandleColor(color);
this.buttonBad = document.createElement('a');
this.buttonBad.name = "button" + String(uniHusenCount*4-2);
this.buttonBad.className = "square_btn";
this.buttonBad.innerHTML = "Bad:"+String(badCount);
this.buttonBad.style = "width:32.05%;height:85%;vertical-align:top";
this.buttonBad.onclick = function(){badButtonCounter(this.name,uniHusenCount)};
this.buttonBad.style.color = getHandleColor(color);
this.buttonBad.style.borderLeftColor = getHandleColor(color);
this.buttonColor = document.createElement('a');
this.buttonColor.name = "button" + String(uniHusenCount*4-1);
this.buttonColor.className = "square_btn";
this.buttonColor.innerHTML = "Color";
this.buttonColor.style = "width:32.05%;height:85%;vertical-align:top";
this.buttonColor.onclick = function(){colorCounter(uniHusenCount,++colorCount)};
this.buttonColor.style.color = getHandleColor(color);
this.buttonColor.style.borderLeftColor = getHandleColor(color);
this.buttonRemove = document.createElement('a');
this.buttonRemove.name = "button" + String(uniHusenCount*4);
this.buttonRemove.className = "square_rmbtn";
this.buttonRemove.innerHTML = "×";
this.buttonRemove.style = "width:12.5%;height:100%;vertical-align:top";
this.buttonRemove.onclick = function(){deleteHusen(uniHusenCount)};
removeColorChange(this.buttonRemove,uniHusenCount,color);
this.header.appendChild(this.handle);
this.header.appendChild(this.buttonRemove);
this.container.appendChild(this.header);
this.container.appendChild(this.txtarea);
this.buttonContainer.appendChild(this.buttonColor);
this.buttonContainer.appendChild(this.buttonGood);
this.buttonContainer.appendChild(this.buttonBad);
this.container.appendChild(this.buttonContainer);
document.body.appendChild(this.container);
////console.log(uniHusenCount);
draggable(uniHusenCount, this.handle, this.container);
}
|
import './App.css';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import Navbar from './components/Navbar';
import HomeView from './views/HomeView';
import CartView from './views/CartView';
import ProductView from './views/ProductView';
import Backdrop from './components/Backdrop';
import Sidedrawer from './components/Sidedrawer';
import {useState} from 'react'
function App() {
const [sideToggle, setSideToggle] = useState(false)
return (
<Router>
<Navbar click={()=>setSideToggle(true)}/>
<Sidedrawer show={sideToggle} click ={()=>setSideToggle(false)}/>
<Backdrop show={sideToggle} click ={()=>setSideToggle(false)}/>
<main>
<Switch>
<Route exact path='/' component={HomeView}/>
<Route exact path='/cart' component={CartView}/>
<Route exact path='/product/:id' component={ProductView}/>
</Switch>
</main>
</Router>
);
}
export default App;
|
export const LIGHT = 'LIGHT'
export const DARK = 'DARK'
export const SHOW_SNACKBAR = 'SHOW_SNACKBAR'
export const DISMISS_SNACKBAR = 'DISMISS_SNACKBAR'
export const ENABLE_AUTHENTICATION = 'ENABLE_AUTHENTICATION'
export const DISABLE_AUTHENTICATION = 'DISABLE_AUTHENTICATION'
export const SHOW_MESSAGE = 'SHOW_MESSAGE'
export const DISMISS_MESSAGE = 'DISMISS_MESSAGE'
|
var x0 = 150, y0 = 150;
var x = 0;
var y = null;
var r = 0;
jQuery(document).ready(function(){
// check R --------------------------------------------------------------------------
document.getElementById("form1:valueR")
.addEventListener("change", function (ev) {
var test_R = document.getElementsByName('form1:valueR');
var reportStr = "";
for(var i = 0; i < 5; i++){
reportStr += " i = " + i + " " + test_R[i] + " " + test_R[i].checked;
if(test_R[i].checked){
r = i + 1;
}
}
console.log(reportStr);
dravIMG();
}, false);
//alert(" Hello Farrukhjan");
// check Y ---------------------------------------------------------------------
document.getElementById("form1:valueY")
.addEventListener("change", function (ev) {
var test_Y = document.getElementById('form1:valueY').value;
//alert(" Hala y = " + test_Y);
var validationMessage = "";
var strY = document.getElementById('form1:valueY').value;
var wrongIntervalFlag = 0;
var wrongSumbolsFlag = 0;
var numberOfPoints = 0;
var numberOfAfterPointDigits = 0;
for(var i = 0; i < strY.length; i++){
if(!(('0' <= strY[i]) && (strY[i] <= '9'))){
if(strY[i] == '.') numberOfPoints++;
else if(strY[i] == '-'){
if(i != 0) wrongIntervalFlag = 1;
}
else wrongSumbolsFlag = 1;
}
if((numberOfPoints != 0) && (strY[i] != '.')) numberOfAfterPointDigits++;
}
if(wrongSumbolsFlag || numberOfPoints > 1) validationMessage = "*Внимание : Y - это число!!";
else if(strY.length == 0) validationMessage = '*Внимание : неопределённое значение Y';
else if((wrongIntervalFlag) || ((parseInt(strY) <= -3) || (3 <= parseInt(strY))))
validationMessage = '*Внимание : диапазон Y (-5; 5)';
else if(numberOfAfterPointDigits > 3) validationMessage = '*Внимание : слишком много цифр после запятой';
else y = parseFloat(strY);
if(validationMessage != ""){
//alert(" Bad Y :( ");
}
}, false);
var test_R = document.getElementsByName('form1:valueR');
var reportStr = "";
for(var i = 0; i < 5; i++){
reportStr += " i = " + i + " " + test_R[i] + " " + test_R[i].checked;
if(test_R[i].checked){
r = i + 1;
}
}
console.log(reportStr);
dravIMG();
});
function newPoint (ev){
sendPoint(ev.offsetX, ev.offsetY);
}
function sendPoint(x, y){
if(r != 0){
var cvs = document.getElementById("plotCanvas");
var ctx = cvs.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(x-1, y-1, 2, 2);
//addToTable(((x - x0)/25), ((y0 - y)/25), r);
var userName = document.getElementById('form1:userNameFrom').value;
//alert(" user Name = " + document.getElementById('form1:userNameFrom').value);
$.ajax({
url: "../ControllerServlet", //url страницы (action_ajax_form.php)
type: "GET", //метод отправки
data: {
userName : userName,
x : ((x - x0)/25).toString(),
y : ((y0 - y)/25).toString(),
r : r.toString()
},
success: function(response) { //Данные отправлены успешно
var myJson = JSON.parse(response.toString());
//alert(((x - x0)/25) + " " + ((y0 - y)/25) + " " + r + " " + myJson[0] + " " + myJson[1]);
//app.conectionStatus = "<h4 style=\"color: green;\"> access </h4>";
//alert("%% Priwel ontet");
addToTable(((x - x0)/25), ((y0 - y)/25), r, myJson[0], myJson[1]);
if(myJson[0] == "Yes") {
var cvs = document.getElementById("plotCanvas");
var ctx = cvs.getContext("2d");
ctx.fillStyle = "#fc1102";
ctx.fillRect(x-1, y-1, 2, 2);
document.getElementById('CVform:CVsubmit').click();
}
else {
var cvs = document.getElementById("plotCanvas");
var ctx = cvs.getContext("2d");
ctx.fillStyle = "#05fcf8";
ctx.fillRect(x-1, y-1, 2, 2);
document.getElementById('CVform:CVsubmit').click();
}
},
error: function(response) { // Данные не отправлены
alert(response.toString());
app.conectionStatus = "Some error with connection";
alert("%% Some Error. Resp ans = " + response.toString());
}
});
}
}
function dravIMG(){
var cvs = document.getElementById("plotCanvas");
var ctx = cvs.getContext("2d");
ctx.clearRect(0, 0, 300, 300);
ctx.fillStyle = "green";
ctx.fillRect(0,0,300,300);
if(r != 0){
var R = r * 25;
// Рисуем квадрат
ctx.fillStyle = "yellow";
ctx.fillRect(x0, y0, R/2., -R);
// Рисуем треугольник
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x0, y0 - R);
ctx.lineTo(x0 - R, y0);
ctx.fill();
// Рисуем дугу
ctx.beginPath();
ctx.lineTo(x0, y0);
ctx.arc(x0, y0, R/2, Math.PI/2, -Math.PI, false);
ctx.fill();
// Рисуем координатные оси
ctx.fillStyle = "#0416f9";
ctx.fillRect(0, y0, 300, 1);
ctx.fillRect(x0, 0, 1, 300);
}
else {
ctx.fillStyle = "red";
ctx.font = "17px Verdana";
ctx.fillText(" R not chosed!!", 10, 50);
}
}
function check_X(){
var test_X = document.getElementsByName('form1:valueX');
//alert(" x : = " + test_X);
for(var i=0;i<test_X.length;i++){
if (test_X[i].checked) {
test_X[0].style.boxShadow="0 0 10px white";
return true;
}
}
document.getElementsByName('form1:valueX')[0].style.boxShadow="0 0 10px red";
event.preventDefault();
}
function moveToMainFrame() {
window.location = "../MainFrame.xhtml";
}
function addToTable(xx, yy, rr) {
// var id = "mutant";
// var tbody = document.getElementById(id).getElementsByTagName("TBODY")[0];
// var row = document.createElement("TR");
// var td1 = document.createElement("TD");
// td1.appendChild(document.createTextNode(xx));
//
// var td2 = document.createElement("TD");
// td2.appendChild (document.createTextNode(yy));
//
// var td3 = document.createElement("TD");
// td2.appendChild (document.createTextNode(rr));
//
// var td4 = document.createElement("TD");
// td2.appendChild (document.createTextNode(result));
//
// var td5 = document.createElement("TD");
// td2.appendChild (document.createTextNode(timeToWork));
// row.appendChild(td1);
// row.appendChild(td2);
// row.appendChild(td3);
// row.appendChild(td4);
// row.appendChild(td5);
// tbody.appendChild(row);
}
|
window.onload=function () {
isHavePhone();
isUserName();
$("#changePassword").click(function(){
var siteId=$("#siteId").val();
window.location.href=ctx+"/weChatPublicNum/goToChangeNum?userName="+$("#username").val()+"&openId=noopenid&siteId="+siteId;
});
$("#changeName").click(function(){
window.location.href=ctx+"/ProtalUserManage/goNickNamePage";
});
$("#message").click(function(){
var userName= $("#username").val();
window.location.href=ctx+"/ProtalUserManage/goToMessagePage?handleType=0"+"&userName="+userName;;
});
$('.photo').click(function(){
$(".js_upFile").click();
//$('.photo').html('<img src="" width="80px" alt=" ">')
});
$(".js_upFile").uploadView({
uploadBox: 'body',//设置上传框容器
showBox : '.photo',//设置显示预览图片的容器
width : 80, //预览图片的宽度,单位px
height : 80, //预览图片的高度,单位px
allowType: ["gif", "jpeg", "jpg", "bmp", "png"], //允许上传图片的类型
maxSize :4, //允许上传图片的最大尺寸,单位M
success:function(e){
$.ajax({
type: 'post',
url: ctx+'/w/uploadUserPicture',
data: {
userName : $("#username").val(),
pictureBase64: $("#imageContent").val(),
},
success: function(data){
if(data==1){
window.location.href=ctx+'/w/goToPerson?userName='+$('#username').val()+'&siteId='+$("#siteId").val();
msg(1,'头像上传成功');
$("#imageContent").val("")
}else{
msg(0,'头像上传失败');
}
}
});
}
});
}
//切换账号
function changeNumber(){
window.location.href=ctx+"/w/changeNumber";
}
//我的礼包
function myGift(){
msg(0,"暂时开发中,敬请期待");
}
function myLettory(){
var userName= $("#username").val();
msg(0,"暂无数据");
//window.location.href=ctx+"/ProtalUserManage/goToMessagePage?handleType=1"+"&userName="+userName;
}
function gotogames(){
window.location.href=ctx+"/ProtalUserManage/gotogames";
}
//判断是否有图片
function isHavePhone(){
var imgSrc = $('#phoneurl').val();
if(imgSrc){
$('.photo').css('background','#fff url(http://oss.kdfwifi.net/user_pic/'+imgSrc+') no-repeat center');
$('.photo').css('background-size','cover');
}
}
//用户名切成232***223的格式
function isUserName(){
var username = $("#username").val();
var name = username.substring(0,3);
var end = username.substring(7,username.length);
var allname = name+"****"+end;
$('.phone').html(allname);
}
function msg(code,str){
console.log(1)
$('.altMask > div').removeClass('true');
$('.altMask > div').removeClass('false');
$('.altMask').css('display','block');
$('.msg').text(str);
if(code==0){
$('.altMask > div').addClass('false');
$('.altMask > div').animate({top:'25%'},400);
setTimeout(function(){
$('.altMask > div').animate({top:'-160px'},200,function(){
$('.altMask').css('display','none');
});
},2900);
}else{
$('.altMask > div').addClass('true');
$('.altMask > div').animate({top:'25%'},400,function(){
setTimeout(function(){
$('.altMask > div').animate({top:'-160px'},400,function(){
$('.altMask').css('display','none');
});
},1000);
});
}
}
|
import React, { Component } from 'react'
import promiseFile from '../../funStore/promiseFile'
import AuthProvider from '../../funStore/AuthProvider'
import promiseXHR from '../../funStore/ServerFun'
import FaceForQQ from './FaceForQQ'
import $ from 'jquery'
import GroupSendBox from './GroupSendBox'
import AltMemberBox from './AltMemberBox'
import MsgPickerForm from './MsgPickerForm'
import {API_PATH} from '../../constants/OriginName'
// import RobotListBox from './RobotListBox';
import {tongji} from '../../funStore/tongji'
const cursorMoveEnd = (obj) => {
obj.focus();
var len = obj.innerHTML.length;
if (document.selection) {
var sel = document.selection.createRange();
sel.moveStart('character',len);
sel.collapse();
sel.select();
}
else{ /* IE11 特殊处理 */
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(obj);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
}
export default class SendMsBox extends Component{
constructor(props) {
super(props)
this.sendBefore = this.sendBefore.bind(this)
this.getKeywordsMsg = this.getKeywordsMsg.bind(this)
this.clickEvent = this.clickEvent.bind(this)
}
state = {
content:''
}
showPickMsgBox(){
if(this.props.selectRoomType=='GROUP'){
this.props.actions.lauchPicker()
}
}
showSendMsgBox(){
}
componentDidMount(){
const self = this
$("#msg_context").on('keyup',function (e) {
$("#msg_context img").removeAttr("style")
var temporary = $("#msg_context pre").html()
$("#msg_context pre").remove()
$("#msg_context").html(temporary)
})
$("#msg_context").focus(function (e) {
e.preventDefault();
}).keydown(function (e) {
e = e||window.event
const obj = document.getElementById('msg_context');
if ((e.metaKey||e.ctrlKey) && e.keyCode == 13) {
if(obj.childNodes.length!=0&&obj.childNodes[obj.childNodes.length-1].nodeValue==null){
$("#msg_context").append('<br>');
}else {
$("#msg_context").append('<br><br>');
}
//保持滚动条随内容变化
const scrollTop = $("#msg_context")[0].scrollHeight;
$("#msg_context").scrollTop(scrollTop);
cursorMoveEnd(obj)
}else if (e.keyCode == 13) {
e.preventDefault()
self.clickEvent()
}
})
}
sendBefore(){
const immemId = this.props.userInfo.info.immemId
const groupList = this.props.groupList
const chatGroupId = this.props.groupList.chatGroupId
const groupCode = this.props.groupList.targetGroup.code
const memberList = this.props.memberList
const chatMemberId = this.props.memberList.chatMemberId
const selectRoomType = this.props.selectRoomType
const atAll = memberList.altAll
let groups = ''
if(chatGroupId==''){
// 群发的消息
groups = groupList.listData.map(item =>
item.altSelected === true ?
{groupCode:item.code,atAll:atAll,users:[],sendId:item.robotGroupMemList[0]?item.robotGroupMemList[0].robotCode:''}:''
)
groups = groups.filter(item => item!= '')
}else {
let users = memberList.listData.map(item =>
item.altSelected === true ?
item.memCode:'')
users = users.filter(item => item!= '')
if(selectRoomType=='MEMBER'&&chatMemberId!=''){
// @某个人的
groups = [{groupCode:groupCode,atAll:false,users:[chatMemberId],sendId:groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''}]
}else {
// @多人 正常群聊
groups = [{groupCode:groupCode,atAll:atAll,users:users,sendId:groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''}]
}
}
return groups!= '' ? {imMemId:immemId,groups:groups} : ''
}
clickEvent(){
const socket = this.props.socket.state.socket
const groupList = this.props.groupList
const beforeData = this.sendBefore()
tongji('Lzc_QunXiaoXi_FaSongXiaoXi')
if(beforeData!=''){
const repl = $("#msg_context").html().replace(/<br>/g,"\r");
$("#msg_context").html(repl);
$("#msg_context").find('style').remove();
$("#msg_context img").each(function (i) {
$("#msg_context img").eq(i).html($("#msg_context img").eq(i).attr("text"));
})
const value = $("#msg_context").text().replace(/\n\n\n\n\n\n\n\n/gi, '').replace(/\n\n\n\n\n\n\n/gi, '').trim()
if(value.length!=0){
// const sendId = groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''
const data = Object.assign({},beforeData,{msgType:'text',content:value})
// console.log(JSON.stringify({command:252,frame:1,data:data}));
socket.send(JSON.stringify({command:252,frame:1,data:data}))
$("#msg_context").html('')
this.props.actions.altInit()
}
}
}
fileUpload(){
tongji('Lzc_QunXiaoXi_WenJian')
const socket = this.props.socket.state.socket
const groupList = this.props.groupList
const beforeData = this.sendBefore()
const file = $('#imgFile')[0].files[0]
const index = $('#imgFile').val().lastIndexOf('.')
const finalName = $("#imgFile").val().substr(index+1)
const format = ["jpg","png","jpeg","xls","xlsx"]
const formData = new FormData()
formData.append('file',file)
if(beforeData!=''){
if(format.includes(finalName.toLowerCase())){
if(file.size<15242880){
const url = API_PATH+'/gridfs-api/authsec/media'
AuthProvider.getAccessToken()
.then((resolve,reject)=> {
promiseFile(url,resolve,formData)
.then(res => {
const data = res
const imgUrl = data.resultContent.url
$("#imgFile").val('')
// const sendId = groupList.targetGroup.robotGroupMemList[0]?groupList.targetGroup.robotGroupMemList[0].robotCode:''
const result = Object.assign({},beforeData,{msgType:'photo',content:imgUrl})
// console.log(JSON.stringify({command:252,frame:1,data:result}));
socket.send(JSON.stringify({command:252,frame:1,data:result}))
})
})
}else {
}
}
}
}
keywordsCrumbClick(){
const {groupList,selectRoom,actions} = this.props
tongji('Lzc_QunXiaoXi_GuanJianCi')
selectRoom('KEYWORDS')
actions.reduceAllKeyword(groupList.chatGroupId)
this.getKeywordsMsg()
}
getKeywordsMsg(){
const {groupList,actions} = this.props
const url = API_PATH+'/groupmsg-api/authsec/group/'+groupList.chatGroupId+'/keywordmessages?_page=0&_size=20'
AuthProvider.getAccessToken()
.then((resolve,reject)=>{
promiseXHR(url,{type:'Bearer',value:resolve},null,'GET')
.then(res => {
const data = eval('('+res+')')
actions.pullKeywordsMsg(data.resultContent,data.pageInfo)
$('#memberRoom').scrollTop($('#memberRoom')[0].scrollHeight-1)
$('#keywordsRoom').scrollTop($('#keywordsRoom')[0].scrollHeight-1)
})
})
}
componentWillUnmount(){
this.props.actions.turnOffPicker()
}
render(){
const {userInfo,groupList,memberList,actions,
selectRoom,msgPicker,startPoint,dragObject,distance,oldDistance,selectRoomType} = this.props
const msgPicker_on = msgPicker!=undefined? msgPicker.pickState : false
const keywordsCrumbClick = this.keywordsCrumbClick.bind(this)
let cssHeight = dragObject!=null ? distance+oldDistance : oldDistance
return(
<div className = 'sendMsBox' style = {{height:(240+cssHeight)+'px'}}>
<div className = 'moveDrag'
onMouseDown = {(e)=>{
const old = oldDistance!=0 ? oldDistance : 0
actions.setObject('SENDBOX',e.pageY,old)
}}
></div>
<div className = 'gm-msgSendBox' style = {{height:(220+cssHeight)+'px'}}>
<div className="toolBar">
{selectRoomType == 'GROUP'&&<FaceForQQ />}
{selectRoomType == 'GROUP'&&<div className="animation gm-icon">
<div className="toolBtn uploadBtn icon-gm">
<div className="icon-text">图片</div>
<input id= 'imgFile' type = 'file' style = {{width:'40px',height:'40px',overflow:'hidden',opacity:0,cursor:'pointer'}}
onChange = {this.fileUpload.bind(this)}
accept="image/gif, image/jpeg,image/jpg,image/png"
/>
</div>
</div>}
{selectRoomType == 'GROUP'&&<AltMemberBox
memberList = {memberList}
putStoreByMember = {actions.putStoreByMember}
altMember = {actions.altMember}
altAll = {actions.altAll}
/>}
{selectRoomType == 'GROUP'&&<GroupSendBox
groupList = {groupList}
selectGroup = {actions.selectSendGroup}
selectAllGroup = {actions.selectAllGroup}
cancelAllGroup = {actions.cancelAllGroup}
initGroupList = {actions.initGroupList}
initMemberList = {actions.initMemberList}
initMsgList = {actions.initMsgList}
selectRoom = {selectRoom}
pullMesgById = {actions.pullMesgById}
/>}
{/* {
selectRoomType == 'GROUP'
||selectRoomType == 'MEMBER'?
<div className="toolBtn pickMsgBtn icon-gm"
onClick = {this.showPickMsgBox.bind(this)}>
<div className="icon-text">合并转发</div>
</div> : ''
} */}
{
selectRoomType == 'GROUP'
?
<div className="animation gm-icon">
<div className="toolBtn keywordFlow icon-gm"
onClick = {()=>{
keywordsCrumbClick()
}}>
<div className="icon-text">关键词信息</div>
</div>
</div>
: ''
}
{/* {
selectRoomType == 'GROUP'
||selectRoomType == 'KEYWORDS'
||selectRoomType == 'MEMBER'?
<RobotListBox
groupList = {groupList}/> : ''
} */}
</div>
{
msgPicker_on &&selectRoomType=='GROUP'?
<MsgPickerForm
userInfo = {userInfo}
groupId = {groupList.chatGroupId}
actions = {actions}
msgPicker = {msgPicker}/>
:selectRoomType=='MEMBER'||selectRoomType=='KEYWORDS'?
<div className='backBox'>
<div className="backButton" onClick={()=>{selectRoom('GROUP')}}>返回群聊</div>
</div>
:<div>
<pre contentEditable="true" ref = 'context' id='msg_context'className="gm-editBox"
style = {{height:(80+cssHeight)+'px'}}
></pre>
<div className="msgSendBox">
<div className="sendBtn" onClick = {this.clickEvent}>发送</div>
</div>
</div>
}
</div>
</div>
)
}
}
|
import { IoTrashOutline } from "react-icons/io5";
import { BsStarFill, BsStarHalf } from "react-icons/bs";
import { useNominations } from "../context/NominationsContext";
export default function MovieCard({ movie }) {
const movieGenres = movie.Genre.split(",");
let rating = parseFloat(movie.imdbRating);
let stars = [];
while (rating > 1) {
stars.push(<BsStarFill />);
rating--;
}
if (rating > 0 && rating < 1) {
stars.push(<BsStarHalf />);
}
const poster =
movie.Poster === "N/A" ? "/images/empty-poster.jpg" : movie.Poster;
const { handleRemoveNomination } = useNominations();
return (
<div className="relative bg-white rounded-lg shadow-xl h-56 mt-24">
<div
className="w-52 h-72 bg-cover bg-center rounded-lg absolute -mt-24 ml-6 shadow-lg"
style={{ backgroundImage: `url(${poster})` }}
></div>
<div className="ml-64 py-8 pr-8 h-full flex flex-col justify-between">
<div className="h-full">
<div className="font-bold text-xl text-brand-green-dark mb-2">
{movie.Title} ({movie.Year})
</div>
<div className="space-x-2">
{movieGenres.map((genre) => (
<div className="text-xs text-brand-off-white bg-brand-green rounded inline-block px-2 py-1">
{genre}
</div>
))}
</div>
<div className="text-xs mt-4 hidden lg:block">{movie.Plot}</div>
</div>
<div className="flex justify-between items-center">
<div className="flex items-center text-brand-green">
{stars.map((star) => star)}
</div>
<IoTrashOutline
className="text-xl hover:text-brand-green-dark hover:cursor-pointer transition duration-500 ease-in-out transform hover:scale-125"
onClick={() => handleRemoveNomination(movie)}
/>
</div>
</div>
</div>
);
}
|
//供應商訂單查詢
Ext.Loader.setConfig({ enabled: true });
var info_type = "order_master1";
var secret_info = "order_id;order_name";
Ext.Loader.setPath('Ext.ux', '/Scripts/Ext4.0/ux');
Ext.require([
'Ext.form.Panel',
'Ext.ux.form.MultiSelect',
'Ext.ux.form.ItemSelector'
]);
var pageSize = 22;
//聲明grid
Ext.define('GIGADE.OrderBrandProduces', {
extend: 'Ext.data.Model',
fields: [
{ name: "order_id", type: "int" }, //付款單號
{ name: "vendor_name_simple", type: "string" }, //供應商名稱
{ name: "pic_patch", type: "string" }, //圖示連接
{ name: "Product_Name", type: "string" }, //商品名稱
{ name: "Product_Spec_Name", type: "string" },
{ name: "item_mode", type: "int" },//商品類型
{ name: "parent_num", type: "int" },
{ name: "payment", type: "string" }, //付款方式
{ name: "order_payment", type: "int" }, //付款方式
{ name: "Single_Money", type: "int" }, //實際售價
{ name: "Single_Cost", type: "int" },
{ name: "Buy_Num", type: "int" }, //數量
{ name: "Event_Cost", type: "int" },
//{ name: "accumulated_bonus", type: "int" }, //購物金
{ name: "order_name", type: "string" }, //訂購姓名
{ name: "slave_status", type: "int" }, //狀態
{ name: "slave", type: "string" }, //狀態
{ name: "Deduct_Bonus", type: "int" },//購物金
{ name: "order_createdate", type: "string" }, //建立日期
{ name: "money_collect_date", type: "string" }, //付款日期
{ name: "slave_date_delivery", type: "string" }, //出貨日期
{ name: "product_manage", type: "string" },//管理者
{ name: "note_order", type: "string" },//備註
{ name: "SingleMoney", type: "int" },//備註
{name:"user_id",type:"int"}
]
});
//獲取grid中的數據
var OrderBrandProducesListStore = Ext.create('Ext.data.Store', {
pageSize: pageSize,
model: 'GIGADE.OrderBrandProduces',
proxy: {
type: 'ajax',
url: '/OrderManage/GetOrderVendorProduces',
actionMethods: 'post',
reader: {
type: 'json',
totalProperty: 'totalCount',
root: 'data'
}
}
});
Ext.define('gigade.Users', {
extend: 'Ext.data.Model',
fields: [
{ name: "user_id", type: "int" }, //用戶編號 上面的是編輯的時候關係到的
{ name: "user_email", type: "string" }, //用戶郵箱
{ name: "user_name", type: "string" }, //用戶名
{ name: "user_password", type: "string" }, //密碼
{ name: "user_gender", type: "string" }, //性別
{ name: "user_birthday_year", type: "string" }, //年
{ name: "user_birthday_month", type: "string" }, //月
{ name: "user_birthday_day", type: "string" }, //日
{ name: "birthday", type: "string" }, //生日
{ name: "user_zip", type: "string" }, //用戶地址
{ name: "user_address", type: "string" }, //用戶地址
{ name: "user_actkey", type: "string" },
{ name: "user_mobile", type: "string" },
{ name: "user_phone", type: "string" }, //行動電話
{ name: "reg_date", type: "string" }, //註冊日期
{ name: "mytype", type: "string" },//會員類別
{ name: "send_sms_ad", type: "bool" }, //是否接收簡訊廣告
{ name: "adm_note", type: "string" }, //管理員備註 上面這些編輯時要帶入的值
{ name: "user_type", type: "string" }, //用戶類別 下面的這些結合上面的會顯示在列表頁
{ name: "user_status", type: "string" }, //用戶狀態
{ name: "sfirst_time", type: "string" }, //首次註冊時間
{ name: "slast_time", type: "string" }, //下次時間
{ name: "sbe4_last_time", type: "string" }, //下下次時間
{ name: "user_company_id", type: "string" },
{ name: "user_source", type: "string" },
{ name: "source_trace", type: "string" },
{ name: "s_id", type: "string" },
{ name: "source_trace_url", type: "string" },
{ name: "redirect_name", type: "string" },
{ name: "redirect_url", type: "string" },
{ name: "paper_invoice", type: "bool" }
]
});
secret_info = "user_id;user_email;user_name;user_mobile";
var edit_UserStore = Ext.create('Ext.data.Store', {
// autoDestroy: true,
pageSize: pageSize,
model: 'gigade.Users',
proxy: {
type: 'ajax',
url: '/Member/UsersList',
reader: {
type: 'json',
root: 'data',//在執行成功后。顯示數據。所以record.data.用戶字段可以直接讀取
totalProperty: 'totalCount'
}
}
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("OrderBrandProducesListGrid").down('#Remove').setDisabled(selections.length == 0);
Ext.getCmp("OrderBrandProducesListtGrid").down('#Edit').setDisabled(selections.length == 0)
}
}
});
var searchStatusrStore = Ext.create('Ext.data.Store', {
fields: ['txt', 'value'],
data: [
{ "txt": ALLSERACH, "value": "0" },
{ "txt": PARDUCTNAME, "value": "1" },
{ "txt": USERID, "value": "2" },
{ "txt": VENDORNAME, "value": "3" },
{ "txt": PRODUCTID, "value": "4" },
{ "txt": '付款單號', "value": "5" }
]
});
var dateStore = Ext.create('Ext.data.Store', {
fields: ['txt', 'value'],
data: [
{ "txt": ALLDATE, "value": "0" },
{ "txt": CREATEDATE, "value": "1" },
{ "txt": PAYDATE, "value": "2" },
{ "txt": ISDELIVERY, "value": "3" },
{ "txt": DELIVERY, "value": "4" },
{ "txt": FDATE, "value": "5" },
]
});
OrderBrandProducesListStore.on('beforeload', function () {
Ext.apply(OrderBrandProducesListStore.proxy.extraParams, {
selecttype: Ext.getCmp('select_type').getValue(), //選擇查詢種類
searchcon: Ext.getCmp('search_con').getValue(),
datetype: Ext.getCmp('datetype').getValue(),
Vendor_Id: Ext.getCmp('Vendor').getValue(),
dateStart: Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('dateStart').getValue()), 'Y-m-d H:i:s')),
dateEnd: Ext.htmlEncode(Ext.Date.format(new Date(Ext.getCmp('dateEnd').getValue()), 'Y-m-d H:i:s')),
product_freight_set: Ext.getCmp('product_freight_set').getValue(),
product_manage: Ext.getCmp('product_manage').getValue(), //供應商管理人員
order_status: Ext.getCmp("order_status").getValue(), //訂單狀態
order_payment: Ext.getCmp("order_payment").getValue()//付款方式
})
});
Ext.onReady(function () {
var frm = Ext.create('Ext.form.Panel', {
id: 'frm',
layout: 'anchor',
height: 140,
border: 0,
width: document.documentElement.clientWidth,
items: [
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
margin: '5 0 0 5',
items: [
{
xtype: 'combobox',
allowBlank: true,
fieldLabel: "供應商",
editable: false,
hidden: false,
queryMode: 'local',
id: 'Vendor',
name: 'Vendor',
store: VendorStore,
displayField: 'vendor_name_simple',
valueField: 'vendor_id',
typeAhead: true,
forceSelection: false,
listeners: {
beforerender: function () {
VendorStore.load({
callback: function () {
VendorStore.insert(0, { vendor_id: '0', vendor_name_simple: '所有供應商資料' });
Ext.getCmp("Vendor").setValue(VendorStore.data.items[0].data.vendor_id);
}
});
}
}
},
{
xtype: 'combobox',
allowBlank: true,
fieldLabel: KEYWORD,
hidden: false,
id: 'select_type',
name: 'select_type',
store: searchStatusrStore,
queryMode: 'local',
width: 250,
labelWidth: 100,
margin: '0 10 0 5',
displayField: 'txt',
valueField: 'value',
typeAhead: true,
forceSelection: false,
editable: false,
value: 0
},
{
xtype: 'textfield',
labelWidth: 80,
margin: '0 10 0 0',
id: 'search_con',
name: 'search_con',
regex: /^((?!%).)*$/,
regexText: "禁止輸入百分號",
listeners: {
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
}
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
margin: '0 0 0 5',
items: [
{
xtype: 'combobox',
id: 'datetype',
name: 'datetype',
fieldLabel: DATETYPE,
store: dateStore,
displayField: 'txt',
valueField: 'value',
margin: '0 10 0 0',
editable: false,
value: 1
},
{
xtype: "datetimefield",
time: { hour: 00, min: 00, sec: 00 },
format: 'Y-m-d H:i:s',
labelWidth: 60,
id: 'dateStart',
name: 'dateStart',
editable: false,
value: setNextMonth(TodayVendor(), -1),
listeners: {
select: function (a, b, c) {
var start = Ext.getCmp("dateStart");
var end = Ext.getCmp("dateEnd");
var s_date = new Date(end.getValue());
if (end.getValue() < start.getValue()) {
var start_date = start.getValue();
Ext.getCmp('dateEnd').setValue(new Date(start_date.getFullYear(), start_date.getMonth() + 1, start_date.getDate(), 23, 59, 59));
}
}
}
},
{
xtype: 'displayfield',
margin: '0 25 0 25',
value: "~"
},
{
xtype: "datetimefield",
format: 'Y-m-d H:i:s',
time: { hour: 23, min: 59, sec: 59 },
id: 'dateEnd',
name: 'dateEnd',
value: TodayVendor(),
editable: false,
listeners: {
select: function (a, b, c) {
var start = Ext.getCmp("dateStart");
var end = Ext.getCmp("dateEnd");
if (end.getValue() < start.getValue()) {
var end_date = end.getValue();
Ext.getCmp('dateStart').setValue(new Date(end_date.getFullYear(), end_date.getMonth() - 1, end_date.getDate()));
}
}
}
}
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
margin: '0 0 0 5',
fieldLabel: SLAVESTATUS,
layout: 'hbox',
items: [
{//訂單狀態
xtype: 'combobox',
id: 'order_status',
name: 'order_status',
store: paymentStore,
queryMode: 'local',
labelWidth: 80,
editable: false,
displayField: 'remark',
valueField: 'ParameterCode',
emptyText: "所有狀態",
listeners: {
beforerender: function () {
paymentStore.load();
}
}
},
{//付款方式
xtype: 'combobox',
fieldLabel: PAYTYPE,
id: 'order_payment',
name: 'order_payment',
store: paymentType,
queryMode: 'local',
margin: '0 10 0 5',
editable: false,
displayField: 'parameterName',
valueField: 'ParameterCode',
emptyText: "不分",
listeners: {
beforerender: function () {
paymentType.load();
}
}
}]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
margin: '0 0 0 5',
fieldLabel: DELIVERYTYPE,
items: [
{
xtype: 'combobox',
hidden: false,
id: 'product_freight_set',
name: 'product_freight_set',
store: FreightSetStore,
queryMode: 'local',
labelWidth: 80,
displayField: 'parameterName',
valueField: 'ParameterCode',
typeAhead: true,
multiSelect: true, //多選
forceSelection: false,
editable: false,
emptyText: "請選擇",
listeners: {
beforerender: function () {
FreightSetStore.load();
}
}
},
{
xtype: 'combobox',
allowBlank: true,
fieldLabel: VMANAGE,
hidden: false,
id: 'product_manage',
name: 'product_manage',
store: ProductManageStore,
labelWidth: 100,
margin: '0 10 0 5',
displayField: 'userName',
valueField: 'userId',
typeAhead: true,
forceSelection: false,
editable: false,
emptyText: ALLMANAGE
}
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
margin: '0 0 0 5',
items: [
{
xtype: 'button',
text: "查詢",
iconCls: 'icon-search',
margin: '0 0 0 5',
id: 'btnQuery',
hidden: true,
handler: Query
},
{
xtype: 'button',
text: "重置",
iconCls: 'ui-icon ui-icon-reset',
margin: '0 0 0 5',
id: 'btnresert',
listeners: {
click: function () {
Ext.getCmp("datetype").setValue(1);
Ext.getCmp("Vendor").setValue(0);
Ext.getCmp("select_type").setValue(0);
Ext.getCmp("order_status").setValue(-1);
Ext.getCmp("order_payment").setValue(0);
Ext.getCmp("search_con").setValue("");
Ext.getCmp("product_freight_set").setValue("");
Ext.getCmp("product_manage").setValue("");
Ext.getCmp('dateStart').setValue(new Date(TodayVendor().setMonth(TodayVendor().getMonth() - 1)));
Ext.getCmp('dateEnd').setValue(TodayVendor());
}
}
},
{
xtype: 'button',
text: '匯出Excel',
margin: '0 0 0 5',
iconCls: 'icon-excel',
id: 'btnExcel',
hidden:true,
handler: Export
}
]
}
]
});
//頁面加載時創建grid
var OrderBrandProducesListGrid = Ext.create('Ext.grid.Panel', {
id: 'OrderBrandProducesListGrid',
store: OrderBrandProducesListStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
flex: 8.1,
columns: [
{
header: ORDERID, dataIndex: 'order_id', width: 70, align: 'center',
//renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
// if (value != null) {
// return '<a href=javascript:TransToOrder(' + record.data.order_id + ') >' + record.data.order_id + '</a>';
// }
//}
},
{ header: VENDOR, dataIndex: 'vendor_name_simple', width: 60, align: 'center' },
{
header: PRODUCTNAMES, dataIndex: '', width: 80, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.pic_patch != '') {
return Ext.String.format("<a href='{0}' target='_blank'><font color='#00F'>{1}</font></a>", record.data.pic_patch, record.data.Product_Name);
}
else {
return record.data.Product_Name;
}
}
},
{ header: PRODUCTSPECNAME, dataIndex: 'Product_Spec_Name', width: 60, align: 'center' },
{ header: PAYTYPE, dataIndex: 'payment', width: 80, align: 'center' },
{
header: ITEMMODE, dataIndex: 'item_mode', width: 60, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
switch (value) {
case 1: return FPRODUCT;//父商品
break;
case 2: return SPRODUCT;//子商品
break;
default: return SIPRODUCT;
break;
}
}
},
{//進貨價
header: SINGLEPRICE, dataIndex: 'Event_Cost', width: 70, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (value==0) {
return record.data.Single_Cost;
}
else {
return record.data.Event_Cost;
}
}
},
{ header: SINGLEMONEY, dataIndex: 'Single_Money', width: 60, align: 'center' },//實際售價
{ header: BUYNUM, dataIndex: 'Buy_Num', width: 60, align: 'center' },
{//小計
header: SUBTOTAL, dataIndex: '', width: 50, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.item_mode == 2) {
return (record.data.SingleMoney * record.data.parent_num);
}
else {
return record.data.Single_Money * record.data.Buy_Num;
}
}
},
{ header: BONUS, dataIndex: 'Deduct_Bonus', width: 100, align: 'center' },
{
header: ORDERNAME, dataIndex: 'order_name', width: 100, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
return "<a href='javascript:void(0);' onclick='onUserEditClick()'>" + value.substr(0,1) + "**</a>";
}
},
{ header: STATES, dataIndex: 'slave', width: 120, align: 'center' },
{
header: EVENTS, dataIndex: 'event', width: 50, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.Event_Cost != 0) {
return YES;
}
else {
return "-";
}
}
},
{ header: CREATEDATE, dataIndex: 'order_createdate', width: 120, align: 'center' },
{
header: PAYDATE, dataIndex: 'money_collect_date', width: 120, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.money_collect_date == '1970-01-01 08:00:00' || record.data.money_collect_date == '') {
return ISPAY;
}
else {
return record.data.money_collect_date;
}
}
},
{
header: SLAVEDATEDELIVERYS, dataIndex: 'slave_date_delivery', width: 120, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (record.data.slave_date_delivery == '1970-01-01 08:00:00') {
return "-";
}
else {
return record.data.slave_date_delivery;
}
}
},
{ header: NOTEORDER, dataIndex: 'note_order', width: 120, align: 'center' },
{ header: MANAGER, dataIndex: 'product_manage', width: 120, align: 'center' }
],
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
bbar: Ext.create('Ext.PagingToolbar', {
store: OrderBrandProducesListStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
})
});
Ext.create('Ext.container.Viewport', {
layout: 'vbox',
items: [frm, OrderBrandProducesListGrid],
renderTo: Ext.getBody(),
listeners: {
resize: function () {
OrderBrandProducesListGrid.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
// OrderBrandProducesListStore.load({ params: { start: 0, limit: 22 } });
})
onEditClick = function () {
var row = Ext.getCmp("OrderBrandProducesListGrid").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
}
else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1) {
editFunction(row[0], OrderBrandProducesListStore);
}
}
/************匯入到Exce************/
function Export() {
window.open("/OrderManage/ExportCSV?selecttype=" + Ext.getCmp('select_type').getValue() + "&searchcon=" + Ext.getCmp('search_con').getValue() + "&datetype=" + Ext.getCmp('datetype').getValue() + "&dateStart=" + Ext.Date.format(new Date(Ext.getCmp('dateStart').getValue()), 'Y-m-d H:i:s') + "&dateEnd=" + Ext.Date.format(new Date(Ext.getCmp('dateEnd').getValue()), 'Y-m-d H:i:s') + "&Vendor_Id=" + Ext.getCmp('Vendor').getValue() + "&product_freight_set=" + Ext.getCmp('product_freight_set').getValue() + "&product_manage=" + Ext.getCmp('product_manage').getValue() + "&order_status=" + Ext.getCmp('order_status').getValue() + "&order_payment=" + Ext.getCmp('order_payment').getValue());
}
//查询
Query = function () {
var conten = Ext.getCmp('search_con');
if (!conten.isValid()) {
Ext.Msg.alert("提示", "查詢內容格式錯誤!");
return;
}
var type = Ext.getCmp('select_type');
if (type.getValue() != 0 && conten.getValue().trim() == "") {
Ext.Msg.alert("提示", "請輸入查詢內容!");
return;
}
OrderBrandProducesListStore.removeAll();
Ext.getCmp("OrderBrandProducesListGrid").store.loadPage(1, {
params: {
selecttype: Ext.getCmp('select_type').getValue(), //選擇查詢種類
searchcon: Ext.getCmp('search_con').getValue(),
datetype: Ext.getCmp('datetype').getValue(),
dateStart: Ext.Date.format(new Date(Ext.getCmp('dateStart').getValue()), 'Y-m-d H:i:s'),
dateEnd: Ext.Date.format(new Date(Ext.getCmp('dateEnd').getValue()), 'Y-m-d H:i:s'),
Vendor_Id: Ext.getCmp('Vendor').getValue(),
product_freight_set: Ext.getCmp('product_freight_set').getValue(),
product_manage: Ext.getCmp('product_manage').getValue(),
order_status: Ext.getCmp("order_status").getValue(),
order_payment: Ext.getCmp("order_payment").getValue()
}
});
}
function TransToOrder(orderId) {
var url = '/OrderManage/OrderDetialList?Order_Id=' + orderId;
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var copy = panel.down('#VendorProductList');
if (copy) {
copy.close();
}
copy = panel.add({
id: 'VendorProductList',
title: '訂單內容',
html: window.top.rtnFrame(url),
closable: true
});
panel.setActiveTab(copy);
panel.doLayout();
}
function onUserEditClick() {
var row = Ext.getCmp("OrderBrandProducesListGrid").getSelectionModel().getSelection();
var secret_type = "20";//參數表中的"訂單"
var url = "/OrderManage/BrandProductIndex";
var ralated_id = row[0].data.order_id;
var info_id = row[0].data.order_id;
boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼
if (boolPassword != "-1") {
if (boolPassword) {//驗證
SecretLoginFun(secret_type, ralated_id, true, true, false, url, info_type, info_id, secret_info);//先彈出驗證框,關閉時在彈出顯示框
} else {
SecretLoginFun(secret_type, ralated_id, false, true, false, url, info_type, info_id, secret_info);//直接彈出顯示框
}
}
}
function TodayVendor() {
var d;
var dt;
var s = "";
d = new Date(); // 创建 Date 对象。
s += d.getFullYear() + "/"; // 获取年份。
s += (d.getMonth() + 1) + "/"; // 获取月份。
s += d.getDate();
dt = new Date(s);
dt.setDate(dt.getDate());
dt.setHours(23, 59, 59);
return dt; // 返回日期。
}
function setNextMonth(source, n) {
var s = new Date(source);
s.setMonth(s.getMonth() + n);
if (n < 0) {
s.setHours(0, 0, 0);
}
else if (n > 0) {
s.setHours(23, 59, 59);
}
return s;
}
|
document.write("<table border=\"1\">");
for(i=1;i<=9;i++){
document.write("<tr>");
for(j=1;j<=9;j++){
if(j<=i){
document.write("<td>"+i+"*"+j+"="+i*j+"</td>");
}
else{
document.write("<td> </td>");
}
}
}
document.write("</table>");
//****************
document.write("<br><br><br>");
document.write("<table border=\"1\">");
for(i=1;i<=9;i++){
document.write("<tr>");
for(j=1;j<=9;j++){
if(j<=i){
document.write("<td>"+i+"*"+j+"="+i*j+"</td>");
}
}
}
document.write("</table>");
//*****************
document.write("<br><br><br>");
for(i=1;i<=9;i++){
document.write("<table border=\"1\">");
for(j=1;j<=9;j++){
if(j<=i){
document.write("<td>"+i+"*"+j+"="+i*j+"</td>");
}
}
}
document.write("</table>");
|
var app = angular.module('mobex', ['ngRoute', 'ngResource', 'angularFileUpload', 'ui.bootstrap', 'ui.bootstrap.tpls']);
app.config(function ($routeProvider, $locationProvider, $compileProvider) {
// need to add this so angular does not add 'unsafe' to the download url for the backup
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|tel|blob):/);
$routeProvider
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/categories', {
templateUrl: 'views/categories.html',
controller: 'CategoriesController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/categories/:id', {
templateUrl: 'views/category.html',
controller: 'CategoryController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/questions', {
templateUrl: 'views/questions.html',
controller: 'QuestionsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/questions/add', {
templateUrl: 'views/addQuestion.html',
controller: 'AddQuestionController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/questions/:id', {
templateUrl: 'views/question.html',
controller: 'AddQuestionController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/administrators/add', {
templateUrl: 'views/addAdmin.html',
controller: 'SettingsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/settings', {
templateUrl: 'views/settings.html',
controller: 'SettingsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/applicants', {
templateUrl: 'views/applicants.html',
controller: 'ApplicantsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/applicants/:id', {
templateUrl: 'views/applicant.html',
controller: 'ApplicantController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/exams', {
templateUrl: 'views/exams.html',
controller: 'ExamsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/exams/add', {
templateUrl: 'views/addExam.html',
controller: 'ExamsController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/exams/:id', {
templateUrl: 'views/exam.html',
controller: 'ExamController',
resolve: {
permission: function(AuthorizationService, $route){
return AuthorizationService.checkIfAuth();
}
}
})
.when('/', {
templateUrl: 'views/login.html',
controller: 'LoginController',
})
});
|
var searchData=
[
['idle_79',['IDLE',['../da/d48/class_mouth_controller.html#a8c012c85d17ee71d6e3ffdc8f124eb07',1,'MouthController']]]
];
|
// ================================================================================
//
// Copyright: M.Nelson - technische Informatik
// Die Software darf unter den Bedingungen
// der APGL ( Affero Gnu Public Licence ) genutzt werden
//
// weblet: dbadmin/table/check
// ================================================================================
{
var i;
var str = "";
weblet.loadview();
var attr =
{
hinput : false,
nameInput : { checktype : weblet.inChecktype.alpha_alphanumorempty },
checkInput : { checktype : weblet.inChecktype.notempty }
}
weblet.findIO(attr);
weblet.showLabel();
weblet.showids = new Array('schema','table','name');
weblet.defvalues = { schema : null, table : null, name : '' };
weblet.titleString.add = weblet.txtGetText("#mne_lang#neue Checkconstraint");
weblet.titleString.mod = weblet.txtGetText("#mne_lang#Checkconstraint bearbeiten");
weblet.titleString.del = weblet.txtGetText("#mne_lang#Checkconstraint wirklich löschen");
weblet.btnrequest.add = "/db/admin/table/check/add.xml"
weblet.btnrequest.mod = "/db/admin/table/check/mod.xml"
weblet.btnrequest.del = "/db/admin/table/check/del.xml"
weblet.showValue = function(weblet, param)
{
if ( weblet == this ) return;
if ( typeof weblet.act_values.schema != 'string' && typeof weblet.act_values.table != 'string')
{
alert('#mne_lang#bitte erst eine Tabelle auswählen');
return false;
}
if ( typeof weblet.act_values.name != 'string' )
{
this.act_values.schema = weblet.act_values.schema;
this.act_values.table = weblet.act_values.table;
this.add();
}
else
MneAjaxWeblet.prototype.showValue.call(this, weblet);
return true;
}
weblet.ok = function()
{
if ( MneAjaxWeblet.prototype.ok.call(this, false) == false && typeof this.popup != 'undefined')
this.popup.hidden();
}
weblet.del = function()
{
this.titleString.del = this.txtSprintf(this.txtGetText("#mne_lang#Checkconstraint <$1> wirklich löschen"), this.act_values.name);
if ( MneAjaxWeblet.prototype.del.call(this, false) == false && typeof this.popup != 'undefined')
this.popup.hidden();
}
}
|
// Disclaimer: I solved part 2 by running part 1 and waiting for 2+ hours
var players = 468;
var highestMarble = 71843 * 100;
var marbles = [0];
var currentMarbleIndex = 0;
var playerScores = {};
var currentPlayer = 0;
var incrementClockwise = (array, curPos, increment) => (curPos + increment) % array.length;
var decrementCounterClockwise = (array, curPos, decrement) => {
if (curPos < decrement) {
return array.length - (decrement - curPos);
} else {
return curPos - decrement;
}
};
console.log("Playing");
// printMarbles(marbles, currentMarbleIndex);
for (var i = 1; i <= highestMarble; i++) {
if (i % 23 == 0) {
addToScore(playerScores, currentPlayer, i);
var indexToDelete = decrementCounterClockwise(marbles, currentMarbleIndex, 7);
addToScore(playerScores, currentPlayer, marbles[indexToDelete]);
marbles.splice(indexToDelete, 1);
currentMarbleIndex = indexToDelete;
}
else {
var nextPos = incrementClockwise(marbles, currentMarbleIndex, 1);
var nextNextPos = incrementClockwise(marbles, currentMarbleIndex, 2);
// console.log(`Next: ${nextPos}, nextNext: ${nextNextPos}`);
if (nextNextPos == 0) {
marbles.push(i);
currentMarbleIndex = marbles.length - 1;
}
else {
marbles.splice(nextNextPos, 0, i);
currentMarbleIndex = nextNextPos;
}
}
// console.log(`New index: ${currentMarbleIndex}`);
currentPlayer = (currentPlayer + 1) % players;
// printMarbles(marbles, currentMarbleIndex);
}
var winningPlayer = Object.keys(playerScores).reduce((a, b) => playerScores[a] > playerScores[b] ? a : b);
var highscore = playerScores[winningPlayer];
console.log(highscore);
function printMarbles(marbles, currentMarbleIndex) {
var output = "";
for (var i = 0; i < marbles.length; i++) {
output += i == currentMarbleIndex
? "(" + marbles[i] + ")"
: marbles[i];
output += " ";
}
console.log(output);
}
function addToScore(scores, player, value) {
if (scores.hasOwnProperty(player)) {
scores[player] += value;
}
else {
scores[player] = value;
}
}
|
// import Typography from "typography"
// import noriega from "typography-theme-noriega"
// noriega.baseFontSize="16px";
// noriega.baseLineHeight= 1.5;
// const typography = new Typography(noriega)
// export const { scale, rhythm, options } = typography
// export default typography
// 暂时关闭, typography排版插件有可能会造成cssRules样式跨域!
|
import distinct from '../signals/processes/distinct'
import pipe from '../signals/pipe'
import position from './position'
import throttle from '../signals/processes/throttle'
export default pipe(
throttle(300),
position,
distinct
)
|
const fs = require('fs');
const path = require('path');
const Currency = require('@pascalcoin-sbx/common').Types.Currency;
const OperationHash = require('@pascalcoin-sbx/common').Types.OperationHash;
const OperationHashCoder = require('@pascalcoin-sbx/common').Coding.Pascal.OperationHash;
const AccountNumber = require('@pascalcoin-sbx/common').Types.AccountNumber;
const Operation = require('@pascalcoin-sbx/json-rpc').Types.Operation;
const Sender = require('@pascalcoin-sbx/json-rpc').Types.Sender;
const Changer = require('@pascalcoin-sbx/json-rpc').Types.Changer;
const Receiver = require('@pascalcoin-sbx/json-rpc').Types.Receiver;
const BC = require('@pascalcoin-sbx/common').BC;
const chai = require('chai');
chai.expect();
const expect = chai.expect;
const optypes = [
// Operation.BLOCKCHAIN_REWARD,
Operation.TRANSACTION,
Operation.CHANGE_KEY,
// Operation.RECOVER_FUNDS,
Operation.LIST_FOR_SALE,
Operation.DELIST,
Operation.BUY,
Operation.CHANGE_KEY_ACCOUNT,
Operation.CHANGE_ACCOUNT_INFO,
Operation.MULTI_OPERATION,
Operation.DATA
];
describe('Core.Types.Operation', () => {
it('can be created from a RPC response', () => {
optypes.forEach((opt) => {
const operations = JSON.parse(fs.readFileSync(path.join(__dirname, '/../fixtures/ops/optype_' + opt + '.json')));
operations.forEach((op) => {
Operation.createFromRPC(op);
});
});
});
it('can handle pending ops', () => {
const operations = JSON.parse(fs.readFileSync(path.join(__dirname, '/../fixtures/ops/pending.json')));
operations.forEach((op) => {
let operation = Operation.createFromRPC(op);
expect(operation.isPending()).to.be.equal(true);
});
});
it('can be created from raw and contains valid values', () => {
optypes.forEach((opt) => {
const operations = JSON.parse(fs.readFileSync(path.join(__dirname, '/../fixtures/ops/optype_' + opt + '.json')));
operations.forEach((op) => {
let operation = Operation.createFromRPC(op);
expect(operation.isPending()).to.be.equal(false);
if (op.valid === undefined) {
expect(operation.valid).to.be.equal(true);
} else {
expect(operation.valid).to.be.equal(op.valid);
}
if (op.errors === undefined) {
expect(operation.errors).to.be.equal(null);
} else {
expect(operation.errors).to.be.equal(op.errors);
}
expect(operation.payload).to.be.instanceof(BC);
if (op.payload === undefined) {
expect(operation.payload.toHex()).to.be.equal('');
} else {
expect(operation.payload.toHex()).to.be.equal(op.payload);
}
expect(operation.block).to.be.equal(op.block);
expect(operation.time).to.be.equal(op.time);
expect(operation.opBlock).to.be.equal(op.opblock);
if (operation.maturation === null) {
expect(operation.maturation).to.be.equal(0);
} else {
expect(operation.maturation).to.be.equal(op.maturation);
}
expect(operation.opType).to.be.equal(op.optype);
if (op.account === undefined) {
expect(operation.account).to.be.equal(null);
} else {
expect(operation.account).to.be.instanceof(AccountNumber);
expect(operation.account.account).to.be.equal(op.account);
}
expect(operation.opTxt).to.be.equal(op.optxt);
expect(operation.amount).to.be.instanceof(Currency);
expect(operation.amount.toStringOpt()).to.be.equal(op.amount.toString());
expect(operation.fee).to.be.instanceof(Currency);
expect(operation.fee.toStringOpt()).to.be.equal(op.fee.toString());
if (op.balance === undefined) {
expect(operation.balance).to.be.equal(null);
} else {
expect(operation.balance).to.be.instanceof(Currency);
expect(operation.balance.toStringOpt()).to.be.equal(op.balance.toString());
}
expect(operation.opType).to.be.equal(op.optype);
if (operation.opType !== Operation.BLOCKCHAIN_REWARD) {
expect(operation.opHash).to.be.instanceof(OperationHash);
expect(new OperationHashCoder().encodeToBytes(operation.opHash).toHex()).to.be.equal(op.ophash);
} else {
expect(operation.opHash).to.be.instanceof(BC);
expect(operation.opHash.toHex()).to.be.equal(op.ophash);
}
if (op.old_ophash !== undefined) {
expect(operation.oldOpHash).to.be.instanceof(OperationHash);
expect(operation.oldOpHash.toHex()).to.be.equal(op.old_ophash);
} else {
expect(operation.oldOpHash).to.be.equal(null);
}
expect(operation.subType).to.be.equal(op.subtype);
if (op.signer_account === undefined) {
expect(operation.signerAccount).to.be.equal(null);
} else {
expect(operation.signerAccount).to.be.instanceof(AccountNumber);
expect(operation.signerAccount.account).to.be.equal(op.signer_account);
}
expect(operation.senders.length).to.be.equal(op.senders.length);
expect(operation.changers.length).to.be.equal(op.changers.length);
expect(operation.receivers.length).to.be.equal(op.receivers.length);
operation.senders.forEach((sender) => {
expect(sender).to.be.instanceof(Sender);
});
operation.changers.forEach((changer) => {
expect(changer).to.be.instanceof(Changer);
});
operation.receivers.forEach((receiver) => {
expect(receiver).to.be.instanceof(Receiver);
});
});
});
});
it('has methods to check for an explicit type', () => {
const isMap = {};
isMap[Operation.BLOCKCHAIN_REWARD] = 'isBlockchainReward';
isMap[Operation.TRANSACTION] = 'isTransaction';
isMap[Operation.CHANGE_KEY] = 'isChangeKey';
isMap[Operation.RECOVER_FUNDS] = 'isRecoverFunds';
isMap[Operation.LIST_FOR_SALE] = 'isListForSale';
isMap[Operation.DELIST] = 'isDelist';
isMap[Operation.BUY] = 'isBuy';
isMap[Operation.CHANGE_KEY_ACCOUNT] = 'isChangeKeyAccount';
isMap[Operation.CHANGE_ACCOUNT_INFO] = 'isChangeAccountInfo';
isMap[Operation.MULTI_OPERATION] = 'isMultiOperation';
isMap[Operation.DATA] = 'isData';
optypes.forEach((opt) => {
const operations = JSON.parse(fs.readFileSync(path.join(__dirname, '/../fixtures/ops/optype_' + opt + '.json')));
operations.forEach((op) => {
let operation = Operation.createFromRPC(op);
Object.keys(isMap).forEach((isOpType) => {
isOpType = parseInt(isOpType, 10);
expect(operation[isMap[isOpType]]()).to.be.equal(isOpType === opt);
});
});
});
});
});
|
helloWorld().then(function (result) {
document.getElementById('hw').innerHTML = result;
})
function helloWorld() {
return Q.all([
getUrl('https://cdn.gfkdaphne.com/tests/async.php?a=1'),
getUrl('https://cdn.gfkdaphne.com/tests/async.php?a=2')
]).then(function (result) {
return result.join(" ");
});
};
// based on https://gist.github.com/matthewp/3099268
function getUrl(url) {
var deferred = Q.defer();
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onreadystatechange = function (e) {
if (request.readyState !== 4) {
return;
}
if ([200, 304].indexOf(request.status) === -1) {
deferred.reject(new Error('Server responded with a status of ' + request.status));
} else {
deferred.resolve(e.target.response);
}
};
request.send();
return deferred.promise;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.