text
stringlengths
7
3.69M
var albumPicasso = { title: 'The Colors', artist: 'Pablo Picasso', label: 'Cubism', year: '1881', albumArtUrl: 'assets/images/album_covers/01.png', songs: [ {title: 'Blue', duration: '161.71', audioUrl: 'assets/music/blue'}, {title: 'Green', duration: '103.96', audioUrl: 'assets/music/green'}, {title: 'Red', duration: '268.45', audioUrl: 'assets/music/red'}, {title: 'Pink', duration: '153.14', audioUrl: 'assets/music/pink'}, {title: 'Magenta', duration: '374.22', audioUrl: 'assets/music/magenta'} ] }; var albumMarconi = { title: 'The Telephone', artist: 'Guglielmo Marconi', label: 'EM', year: '1909', albumArtUrl: 'assets/images/album_covers/20.png', songs: [ { title: 'Hello, Operator?', duration: '1:01' }, { title: 'Ring, Ring, Ring', duration: '5:01' }, { title: 'Fits in Your Pocket', duration: '3:21' }, { title: 'Can You Hear Me Now?', duration: '3:14' }, { title: 'Wrong Phone Number', duration: '2:15' } ] }; var albumAdams = { title: 'National Parks', artist: 'Ansel Adams', label: 'Department of the Interior', year: '1941', albumArtUrl: 'assets/images/album_covers/09.png', songs: [ { title: 'The Face of Half Dome', duration: '3:02' }, { title: 'Rose and Driftwood', duration: '2:26' }, { title: 'Canyon de Chelly', duration: '3:45' }, { title: 'Mooonrise', duration: '4:10' }, { title: 'El Capitan', duration: '3:31' } ] };
import React, { Component } from 'react'; import {View, Text, Platform, Image} from 'react-native'; class InfoScreen extends Component { static navigationOptions = ({ navigation }) => { return { tabBarVisible : false, headerTintColor: "#fff", headerStyle : { marginTop : Platform.OS === 'android' ? 24 : 0, backgroundColor : "#267689" }, } }; render(){ return( <Image source={require('../img/form.png')} style={styles.backgroundImage}> <View style={styles.container}> <Text style={{fontSize: 32, color:'#000', fontWeight:'700', textAlign:'center', justifyContent:'center', backgroundColor:'rgba(0,0,0,0)',paddingBottom:40}}>Ana sponsor </Text> <Image source={require('../img/guclu.png')} style={{width:150, height:150,marginBottom:10}}/> <View style={{borderBottomWidth:1, borderColor:'#D4E1F3', width:270 }}></View> <Image source={require('../img/logo2.png')} style={{width:150, height:150, marginTop : 10}}/> <Text style={{backgroundColor:'rgba(0,0,0,0)', textAlign:'center',fontSize:19, marginTop: 20,alignSelf:'center',fontWeight:'600'}}>İletişim : otoyolsuresi@gmail.com </Text> </View> </Image> ); } } const styles = { container: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingTop:10, }, backgroundImage: { flex: 1, width: null, height: null, resizeMode: 'cover' }, textStyle :{ backgroundColor: "rgba(0,0,0,0)", color : '#fff', fontSize: 26 } } export default InfoScreen;
import React, { PropTypes } from 'react' import API from 'API' import { Button } from 'forms/material/Material' import LoginStore from 'LoginStore' import Notification from 'NotificationActions' import WebStorage from 'WebStorage' import { Card, CardContent, CardTitle, CardFooter } from 'Card' import { Map, Marker, LayerGroup, Popup, TileLayer } from 'react-leaflet' import MyLocationMarker from 'MyLocationMarker' var EditGroupLocation = React.createClass({ propTypes: { group: PropTypes.object.isRequired, onChange: PropTypes.func }, getInitialState() { let loginState = LoginStore.getState() let group_location = { latitude: this.props.group.lat, longitude: this.props.group.lng } return { myLocation: loginState.user.location, markerCoords: group_location || loginState.user.location, groupAddress: '' } }, componentDidMount() { LoginStore.listen(this._onChange) }, componentWillUnmount() { LoginStore.unlisten(this._onChange) }, _onChange(state) { this.setState(state) }, getDefaultProps() { return { onChange: () => {} } }, edit(event) { event.preventDefault() let { markerCoords } = this.state let { latitude, longitude } = markerCoords API.post(`groups/${this.props.group.id}/location`, { longitude, latitude }, () => { this.props.onChange({ lat: latitude, lng: longitude }) Notification.success('Groep locatie is gewijzigd!') }) }, moveMarker(event) { let { markerCoords } = this.state markerCoords.latitude = event.latlng.lat markerCoords.longitude = event.latlng.lng this.setState({ markerCoords }) }, myLocation(event) { event.preventDefault() this.setState({ markerCoords: this.userLocation() }) }, userLocation() { return WebStorage.fromStore('user', { location: { latitude: null, longitude: null } }).location }, render() { let { group } = this.props let markerCoords = this.state.markerCoords let hasGroupLocation = markerCoords.latitude != null && markerCoords.latitude != "" if ( ! hasGroupLocation) { markerCoords = this.userLocation() } return ( <div> <form onSubmit={this.edit}> <Card> <CardContent> <CardTitle>Locatie Wijzigen</CardTitle> <p> Klik op de kaart om een juiste locatie te kiezen voor deze groep. </p> <Map ref="map" center={[markerCoords.latitude, markerCoords.longitude]} zoom={17} style={{height: 300}} onClick={this.moveMarker} > <TileLayer url='http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png' attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> <MyLocationMarker map={this.refs.map}/> <Marker position={[markerCoords.latitude, markerCoords.longitude]}> <Popup> <span>{group.name}</span> </Popup> </Marker> </Map> { ! hasGroupLocation && ( <p>Vermits deze groep nog geen locatie heeft, hebben we een schatting van je huidige locatie gemaakt.</p> )} </CardContent> <CardFooter> <Button onClick={this.myLocation}>Ga naar mijn Locatie</Button> <Button right>Wijzig groep locatie</Button> </CardFooter> </Card> </form> </div> ) } }) export default EditGroupLocation
module.exports = { up: (queryInterface, Sequelize) => { return Promise.all([ queryInterface.createTable('VerificationToken', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, UserId: { type: Sequelize.INTEGER, onUpdate: 'cascade', onDelete: 'cascade', references: { model: 'User', key: 'id' } }, token: { allowNull: false, type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }) ]).then(() => { return queryInterface.sequelize.query(` CREATE OR REPLACE FUNCTION delete_old_tokens() RETURNS event_trigger LANGUAGE plpgsql AS $$ BEGIN DELETE FROM "VerificationToken" WHERE "createdAt" >= NOW() - INTERVAL '24 HOURS'; END; $$; CREATE EVENT TRIGGER expireToken ON ddl_command_start EXECUTE PROCEDURE delete_old_tokens(); `); }); }, down: (queryInterface, Sequelize) => { return queryInterface .dropTable('VerificationToken') .then(() => { return queryInterface.sequelize.query( `DROP EVENT TRIGGER IF EXISTS expireToken; DROP FUNCTION IF EXISTS "delete_old_tokens"; ` ); }) .then(() => { console.log('expireToken event dropped'); }); } };
import express from 'express'; import session from 'express-session'; import morgan from 'morgan'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import http from 'http'; import socketIo from 'socket.io'; import socketioJwt from 'socketio-jwt'; import api from './routes/api'; import { initDb } from './initDb'; import socket from './sockets/socketIo'; import moment from 'moment'; const app = express(); initDb(); const server = http.createServer(app); const io = socketIo.listen(server); const users = []; moment().locale('fr'); io.use(socketioJwt.authorize({ secret: 'mybadasssecretkey', handshake: true })); io.on('connection', socket(users)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(morgan('dev')); app.use('/api', api); app.use(function(err, req, res, next) { res.status(422).send({error: err.message}); }); app.set('port', (process.env.PORT || '5000')); server.listen(app.get('port'), () => { console.log('Server started on port '+ app.get('port')) }); module.exports = app;
import { handleActions } from 'redux-actions'; import { GET_TAGS, BUILD_CLOUD, } from './actions'; const initialState = { tags: [], cloudElements: [], }; const tagsReducer = handleActions( { [GET_TAGS]: (state, action) => ({ ...state, tags: action.payload, }), [BUILD_CLOUD]: (state, action) => ({ ...state, cloudElements: action.payload, }), }, initialState, ); export default tagsReducer;
const axios = require('axios') const Redis = require('ioredis') const redis = new Redis() const movieURL = 'http://localhost:5001/movies' const seriesURL = 'http://localhost:5002/series' class EntertainController { static async getAllCategories(req, res) { try { const cache = await redis.get('cache') if(cache) { res.status(200).json(JSON.parse(cache)) } else { const moviesData = await axios.get(movieURL) const seriesData = await axios.get(seriesURL) const data = { movies: moviesData.data, series: seriesData.data } const setCache = await redis.set('cache', JSON.stringify(data)) res.status(200).json(data) } } catch (err) { res.status(500).json(err) } } } module.exports = EntertainController
import React from "react"; import { Link } from "react-router-dom"; import "./css/footer.css" export default class Footer extends React.Component { render() { return ( <footer> <br /> <div className="container"> <div className="row"> <div id="firstFooterColumn" className="col-8"> <h2> Know of an open gym? <Link to="/Form"> Contact Us!</Link> </h2> <br/> <p> If you facilitate and/or know of an open gym that you would like to suggest, send us an email! Please ensure to include information including location, name of the gym, cost to play, and competition level. </p> <br/> <p className="align-center"> &copy; 2020 Sport Spots. All rights reserved. </p> </div> <div className="col-4 secondFooterColumn"> <h2>Sports</h2> <Link to="/Volleyball" title="Go to Volleyball page">Volleyball</Link> <Link to="/Basketball" title="Go to Basketball page">Basketball</Link> <Link to="/Tennis" title="Go to Tennis page">Tennis</Link> <Link to="/Soccer" title="Go to Soccer page">Soccer</Link> <Link to="/MMA" title="Go to MMA page">MMA</Link> <Link to="/Swimming" title="Go to Swimming page">Swimming</Link> </div> </div> </div> </footer> ); } }
import React from 'react'; import ReactDOM from 'react-dom'; import * as style from './style.less'; class Modal extends React.Component { constructor() { super(); this.state = { div: null, }; if (typeof window === 'object') { this.state.div = document.createElement('div'); } } componentDidMount() { if (typeof window === 'object') { document.body.appendChild(this.state.div); } } componentWillUnmount() { if (typeof window === 'object') { document.body.removeChild(this.state.div); } } render() { const { div } = this.state; if (!div) return null; const { onCancel } = this.props; return ( ReactDOM.createPortal( <div className={style.maskBox}> <div className={style.mask} onClick={onCancel} /> {this.props.children} </div>, div ) ); } } export default Modal;
let http = require("http"); let url = require("url"); let fs = require("fs") let port = 9090; let addTask = ` <h1 style = "text-align : center">Task Planner<h1/> <h3 style = "text-decoration: underline">Add Task<h3/> <form action="/store" method="get"> <label>Emp Id: </label> <input type="text" name="empId"/><br/> <label>Task Id: </label> <input type="text" name="taskId"/><br/> <label>Task: </label> <input type="text" name="task"/><br/> <label>Deadline: </label> <input type="date" name="deadline" placeholder="mm-dd-yyyy" value="" min="2021-01-01" max="2030-12-31"/><br/> <input type="submit" value="Add Task" /> </form> <h3 style = "text-decoration: underline">Delete Task</h3> <form action="/delete" method="get"> <label>Task Id</label> <input type="text" name="taskId"/><br/> <input type="submit" value="Delete Task"/> </form> <h3 style = "text-decoration: underline">List Tasks</h3> <form action="/display" method="get"> <input type="submit" value="List all tasks" /> </form> ` let taskResultTitles = ` <table style="border-spacing: 10px;"> <thead> <th>Emp ID: </th> <th>Task ID: </th> <th>Task: </th> <th>Deadline: </th> </thead> </table> ` let server = http.createServer((req,res)=> { console.log(req.url) res.setHeader("content-type","text/html"); res.write(addTask); if(req.url != "/favicon.ico"){ var getPath = url.parse(req.url,true).pathname; if(getPath=="/store"){ console.log("here") let info = url.parse(req.url,true).query; let checkAdd = true; let tasks = getTasks(); for (var i in tasks){ if (tasks[i].taskId == info.taskId){ checkAdd = false; } } if (checkAdd){ console.log(checkAdd) let task = makeJSON(info.empId,info.taskId,info.task,info.deadline); tasks.push(task) var tasksString = JSON.stringify(tasks, null,2); fs.writeFileSync("task.json",tasksString); } }else if(getPath=="/delete"){ let info = url.parse(req.url,true).query; let tasks = getTasks(); for (var i in tasks){ if (tasks[i].taskId == info.taskId){ tasks.splice(i,1); } } console.log(tasks) var tasksString = JSON.stringify(tasks, null, 2); fs.writeFileSync("task.json",tasksString); }else if(getPath=="/display"){ let tasks = getTasks() let taskData = `` console.log(tasks) for (var i in tasks){ taskData += ` <table style="border-spacing: 25px;"> <tr> <td>${tasks[i].empId}</td> <td>${tasks[i].taskId}</td> <td>${tasks[i].task}</td> <td>${tasks[i].deadline}</td> </tr> </table> ` } res.write(taskResultTitles) res.write(taskData) res.write(`</table>`) } res.end(); } }); server.listen(port,()=>console.log(`Server running on port number ${port}`)); function makeJSON(empId,taskId,task,deadline) { return {"empId":empId, "taskId":taskId,"task":task, "deadline":deadline}; } function getTasks(){ let tasks = new Array(); try { let taskData = fs.readFileSync("task.json"); let jsonString = taskData.toString(); let json = JSON.parse(jsonString); tasks = []; for (var i in json){ tasks.push(json[i]); } return tasks; } catch (error) { return tasks; } }
import React from 'react'; import PropTypes from 'prop-types'; import Cell from './Cell'; const rowStyle = { display: "flex", flexDirection: "row", justifyContent: "center", alignItems: "center", } const columnStyle = { display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", } const Table = ({ hor, ver, func }) => ( <div style={columnStyle}> { ver.map( y => <div key={y} style={rowStyle} >{ hor.map( x => <Cell key={x*y} num={x*y} func={func(x, y)}/>) }</div> ) } </div> ); export default Table;
import _ from 'underscore'; import restify from 'restify'; import { Router } from 'restify-router'; const router = new Router();; // Get all statistics of users router.get('/:group/users', (req, res, next) => { next(); }); // Get all statistics of users router.get('/plugins', (req, res, next) => { next(); }); module.exports = router;
//***pedir datos por teclado */ var nombre = prompt("Ingrese su nombre"); console.log("Este es mi nombre",nombre); alert(nombre); var edad = prompt("Ingrese su edad"); console.log("Esta es mi edad",edad); alert(edad); //** variables numericas */ var num = 5; console.log("num",num) //** variables de texto */ var palabras = "palabras"; console.log("palabras",palabras); //** variables booleanas */ var activo = true; console.log("activo",activo); //** variables tipo arreglo */ var colores = ["red","cyan",activo,num]; console.log("colores",colores); //** variables tipo objeto u object */ var vehiculo = { tipo:"automovil", modelo:2018, usado:true }; console.log("vehiculo",vehiculo); console.log("tipo de vehiculo",vehiculo.tipo); var nombre = "carlos"; console.log("nombre",nombre); nombre=true; console.log("nombre",nombre); nombre=20; console.log("nombre",nombre); //** diferencias entre var y let */ var apellido="lola"; console.log("apellido",apellido); nombre=14; console.log("apellido numerico",apellido); if (true){ apellido="pinches"; console.log("apellido dentro del if",apellido); }
function solve(args) { args = args.map(Number); let sumOfNumbers = 0; let sumOfInversedValueOfNumbers = 0; let concatedNumbers = ''; function calculateSum(args) { let sum = 0; for (let num of args) { sum += num; } return sum; } function sumOfTheInversedValues(numbers) { let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += 1 / numbers[i]; } return sum; } function concatElements(numbers) { let numbersAsString = ''; for (let num of numbers) { numbersAsString += num; } return numbersAsString; } sumOfNumbers = calculateSum(args); sumOfInversedValueOfNumbers = sumOfTheInversedValues(args); concatedNumbers = concatElements(args); console.log(sumOfNumbers); console.log(sumOfInversedValueOfNumbers); console.log(concatedNumbers); } solve(['1', '2', '3']); solve(['2', '4', '8', '16']);
$(document).ready(function(){ var $texto; var $tabla = $('tbody'); $('button').click(function(){ $texto = $('input[name="texto"]').val(); $tabla.append('<tr><td>'+$texto+'</td><td><button>borrar</button></td></tr>'); }); $tabla.on('click', 'button', function(){ $(this).closest('tr').remove(); }); });
'use strict'; module.exports = function(app) { var product = require('../controllers/productController'); // todoList Routes app.route('/rest/v1/products') .get(product.list_all_products) .post(product.create_a_product); app.route('/rest/v1/product/:productId') .get(product.read_a_product) .put(product.update_a_product) .delete(product.delete_a_product); };
/** * Created by gaspardchavardes on 13/01/2017. */ class ProjectPage { constructor () { this.state = { page: 0 } } init () { this.pageCount = this.items.length } increment () { this.state.page === 3 ? this.state.page = 0 : this.state.page++ this.next() } decrement () { this.state.page === 0 ? this.state.page = 3 : this.state.page-- this.next() } // // next and previous next () { this.state.nextOne === 3 ? this.state.nextOne = 1 : this.state.nextOne++ this.state.previousOne === 1 ? this.state.previousOne = 3 : this.state.previousOne-- } } export default new ProjectPage()
import { StyleSheet } from 'react-native' const style = StyleSheet.create({ farmDetails: { flexDirection: 'row', paddingVertical: 12, }, farmLogo: { height: 32, width: 32, marginRight: 12, }, h1: { fontFamily: 'MontserratBold', fontSize: 24, lineHeight: 42, }, h2: { fontFamily: 'MontserratBold', fontSize: 16, lineHeight: 24, color: '#464646', }, p: { color: '#A3A3A3', fontSize: 16, fontFamily: 'MontserratRegular', fontWeight: 'normal', }, lead: { color: '#2A9F85', fontFamily: 'MontserratBold', fontSize: 28, marginTop: 8, marginBottom: 20, }, }) export default style
/** * 图片的Utils类 * Created by yuansc on 2017/3/13. */ "use strict"; const config = require('config'); const path = require('path'); let ImageUtils = module.exports = {}; /** * 根据文件path 生成对外的url * @param {String} filePath 文件绝对路径 * @returns {String} url 对外地址 */ ImageUtils.genUrlByPath = function (filePath) { return config.get('domain') + filePath.replace(path.join(__dirname, '../public'), ''); }; /** * 根据url获取文件的绝对路径 * 用于删除图片时使用 * @param {String} url 图片Url * @returns {String} path 文件相对路径 */ ImageUtils.getPathByUrl = function (url) { return path.join(__dirname, '../public', url.replace(config.get('domain'), '')); };
const express = require('express'); const next = require('next'); const path = require('path'); const url = require('url'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const cors = require('cors'); const mongoose = require('mongoose'); const dev = process.env.NODE_ENV !== 'production'; const server = express(); const app = next({ dev }); const handle = app.getRequestHandler(); app .prepare() .then(() => { // api route files const indexRouter = require('./server/routes/index'); const usersRouter = require('./server/routes/users'); // database connection mongoose.connect( 'mongodb+srv://rinXer7:640509-040147manGanas@fullstack-deneme-obnlb.mongodb.net/test?retryWrites=true&w=majority', {useNewUrlParser: true, useCreateIndex: true} ) .then(() => { console.log('We\'re connected to database! :)'); }) .catch(err => { console.log('Unable to connect with the database', err); }); // api routes server.use('/api', indexRouter); server.use('/api/users', usersRouter); // custom routes server.get('/user/:username', (req, res) => { const mergedQuery = Object.assign({}, req.query, req.params); return app.render(req, res, '/user', mergedQuery); }); server.get('*', (req, res) => { const parsedUrl = url.parse(req.url, true); const { pathname } = parsedUrl; if (pathname === '/service-worker.js') { const filePath = join(__dirname, '.next', pathname); app.serveStatic(req, res, filePath); } else { handle(req, res, parsedUrl); } }); server.use(cors()); server.use(logger('dev')); server.use(express.json()); server.use(express.urlencoded({ extended: false })); server.use(cookieParser()); const port = process.env.PORT || 3000; server.listen(port, err => { if (err) throw err; console.log(`> Ready on port ${port}...`); }); }); //module.exports = server;
import React from 'react' function Navbar() { return ( <div > <nav className='nav'> <img className='logo' src='assets/logo.png' alt='Logo' /> <ul className='list'> <li className='list_item'> About</li> <li className='list_item'> Sign In</li> <li className='list_item'> Creators</li> <li className='list_item'> FAQ </li> </ul> </nav> </div> ) } export default Navbar;
import React, { Component } from 'react' import * as api from "../../api" export default class Voter extends Component { state = { thumbed: 0 } render() { const { thumbed } = this.state let { votes, article_id, comment_id } = this.props votes += thumbed; return ( <div className="articleCardVoter"> <button className="thumbsUp" onClick={() => { this.handleThumbs(1, article_id, comment_id) }} disabled={thumbed === 1}> <span role="img" aria-label="Thumbs Up"> 👍 </span> </button> <p> Votes: {votes} </p> <button className="thumbsDown" onClick={() => { this.handleThumbs(-1, article_id, comment_id) }} disabled={thumbed === -1}> <span role="img" aria-label="Thumbs Down"> 👎 </span> </button> </div> ) } handleThumbs = (num, article_id, comment_id) => { if (article_id) { this.setState(currentState => { return { thumbed: currentState.thumbed + num } }) api.handleVote(article_id, "article", num) } else if (comment_id) { this.setState(currentState => { return { thumbed: currentState.thumbed + num } }) api.handleVote(comment_id, "comment", num) } } }
module.exports = function () { return async function (event) { event.mappings = event.mappings.map(x => { const launches = x.roles.length > 0 ? x.roles.map(roleId => { return { stateMachineName: 'auth0_removeMappingForm_1_0', title: `Remove ${roleId} mapping`, input: { auth0: x.auth0, roleId } } }) : [] return { ...x, launches } }) return event } }
import { FETCHING_ASSESSMENT, FETCHING_ASSESSMENT_SUCCESS, FETCHING_ASSESSMENT_FAILURE, REMOVE_FETCHING_ASSESSMENT, UPDATE_RESPONSE, SUBMIT_RESPONSE, PROCESSING_RESPONSE_ERROR, CHECK_RESPONSE, UPDATE_PERSONAL_INFO, RETURN_PREVIOUS_QUESTION, } from '../actions/types'; const initialState = { isFetching: true, error: '', type: '', assessment: '', assessmentLength: '', history: [], responses: '', currentQuestion: '', currentResponse: '', progress: '', personalInfo: { firstName: '', secondName: '', middleName: '', gender: '', birthdate: '', }, } export default function(state = initialState, action) { switch (action.type) { case FETCHING_ASSESSMENT: return { ...state, isFetching: true, }; case FETCHING_ASSESSMENT_SUCCESS: return { ...state, isFetching: false, assessment: action.assessment, assessmentLength: action.assessmentLength, history: [action.firstQuestionId], currentQuestion: action.firstQuestionId, progress: [action.firstQuestionId] / action.assessmentLength, }; case FETCHING_ASSESSMENT_FAILURE: return { ...state, isFetching: false, error: action.error, }; case REMOVE_FETCHING_ASSESSMENT: return { ...state, isFetching: false, }; case UPDATE_RESPONSE: return { ...state, currentResponse: action.response, }; case UPDATE_PERSONAL_INFO: return { ...state, personalInfo: { ...state.personalInfo, [action.fieldName]: action.response } }; case SUBMIT_RESPONSE: if (action.responseId) { return { ...state, //toggle response.check flags assessment: { ...state.assessment, [action.questionId]: { ...state.assessment[action.questionId], responses: state.assessment[action.questionId].responses.map((response) => { if (response.id === action.responseId) { response.checked = !response.checked; } return response; }), }, }, history: [action.nextQuestion, ...state.history], currentQuestion: action.nextQuestion, progress: ([action.questionId, ...state.history].length) / state.assessmentLength, }; } else { return { ...state, history: [action.nextQuestion, ...state.history], currentQuestion: action.nextQuestion, progress: ([action.questionId, ...state.history].length) / state.assessmentLength, }; } case CHECK_RESPONSE: return { ...state, //toggle response.check flags assessment: { ...state.assessment, [action.questionId]: { ...state.assessment[action.questionId], responses: state.assessment[action.questionId].responses.map((response) => { if (response.id === action.responseId) { response.checked = !response.checked; } return response; }), }, }, }; case RETURN_PREVIOUS_QUESTION: state.history.shift(); return { ...state, //Reset all response.check flags to false: assessment: { ...state.assessment, [state.history[0]]: { ...state.assessment[state.history[0]], responses: state.assessment[state.history[0]].responses.map((response) => { response.checked = false; return response; }), }, }, currentQuestion: state.history[0], progress: (state.history.length) / state.assessmentLength, }; case PROCESSING_RESPONSE_ERROR: return { ...state, error: action.error, }; default: return state; } }
import AbstractComponent from './abstract-component.js'; const FIRST_LETTER_INDEX = 4; const LAST_LETTER_INDEX = 11; const getMonthAndDate = (day) => { return day.slice(FIRST_LETTER_INDEX, LAST_LETTER_INDEX); }; export default class MainTrip extends AbstractComponent { constructor(cities, days) { super(); this._cities = cities; this._days = days; } getTemplate() { return `<div class="trip-info__main"> <h1 class="trip-info__title">${this._cities[0].name} &mdash; ... &mdash; ${this._cities[this._cities.length - 1].name}</h1> <p class="trip-info__dates">${getMonthAndDate(this._days[0])}&nbsp;&mdash;&nbsp;${getMonthAndDate(this._days[this._days.length - 1])}</p> </div>`.trim(); } }
const state ={ cart : localStorage.getItem('cart')?JSON.parse(localStorage.getItem('cart')) :{} } export default state
const connection = require('../db/config'); const User = {}; const cleanUser = (user) => ({ ...user, passwordHash: 'hidden' }) User.create = (userInfo, callback) => { connection.query( `INSERT INTO user (username, passwordHash) VALUES ( ?, SHA(?) ) `, [userInfo.username, userInfo.password], (err, results, fields) => callback(err, results, fields) ) } User.findByUsernameAndPassword = (username, password, callback) => { connection.query( `SELECT * FROM user WHERE username = ? AND passwordHash = SHA(?)`, [username, password], (err, results, fields) => callback(err, cleanUser(results[0]), fields) ) } User.findById = (id, callback) => { connection.query( `SELECT * FROM user WHERE id = ?`, [id], (err, results, fields) => callback(err, cleanUser(results[0]), fields) ) } module.exports = User;
const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const projectsSchema = new mongoose.Schema({ title: { type:String, unique:true }, client:{ type:String }, budget:{ type:Number }, targets:{ type:Array // Array of targets / objectives for proposed for project success. }, targetsMet:{ type:Array // Array of how many of the above targets were met }, targetsPercentage:{ type:Number // Percentage of targets met over total targets }, description:{ type:String, max:255, min:6 } }, {timestamps: true}); projectsSchema.plugin(uniqueValidator, {message: 'Project Exists.'}); module.exports = mongoose.model('Project', projectsSchema);
var PagerComponent = function() { var offset; var limit; this.createdCallback = function() { var _this = this; this.querySelector("z-pager-tooltip[data-type='for']") .addEventListener("click", function(e) { if (this.classList.contains("disabled")) { return; } _this.pageEvent(offset + limit); }, false); this.querySelector("z-pager-tooltip[data-type='back']") .addEventListener("click", function(e) { if (this.classList.contains("disabled")) { return; } _this.pageEvent(offset - limit); }, false); }; this.render = function(num_items, new_offset, new_limit) { if (typeof num_items !== "number" || typeof new_offset !== "number" || typeof new_limit !== "number") { console.log("z-pager ERROR: argument error"); return; } offset = new_offset; limit = new_limit; this.querySelector("z-pager-title").innerHTML = (offset + 1) + " &mdash; " + (offset + num_items); var tooltip_for = this.querySelector("z-pager-tooltip[data-type='for']"); // last page if (num_items < limit) { tooltip_for.classList.add("disabled"); } else { tooltip_for.classList.remove("disabled"); } var tooltip_back = this.querySelector("z-pager-tooltip[data-type='back']"); // first page if (offset < limit) { tooltip_back.classList.add("disabled"); } else { tooltip_back.classList.remove("disabled"); } } this.pageEvent = function(new_offset) { var page_event = new CustomEvent( "z-pager-turn", {detail: {offset: new_offset}}); this.dispatchEvent(page_event); }; //this.forElement = function(elem) { // var callback = elem.paginationEvent; // this.init(); // this.renderTitle(); // this.observeTooltips(callback, elem); //}; //this.disable = function(tooltip) { // var _this = this; // tooltip.forEach(function(t) { // _this.querySelector(".tooltip." + t).classList.add("disabled"); // }); //}; //this.enable = function(tooltip) { // var _this = this; // tooltip.forEach(function(t) { // _this.querySelector(".tooltip." + t).classList.remove("disabled"); // }); //}; //this.init = function() { // this.initCurrentPage(); // this.initLastItem(); // this.initNumPerPage(); // this.initNumPages(); //}; //this.initCurrentPage = function() { // var curr_page = parseInt(this.getAttribute('data-current-page'), 10); // if (isNaN(curr_page)) { // curr_page = 0; // } // this.current_page = curr_page; //}; //this.initLastItem = function() { // var end = parseInt(this.getAttribute('data-last-item'), 10); // if (isNaN(end)) { // end = 0; // } // this.end = end; //}; //this.initNumPerPage = function() { // var per_page = parseInt(this.getAttribute('data-per-page'), 10); // if (isNaN(per_page)) { // per_page = 1; // } // this.per_page = per_page; //}; //this.initNumPages = function() { // this.pages = Math.ceil((this.end - 1) / this.per_page); //}; //this.renderTitle = function() { // var current_page = this.current_page; // var per_page = this.per_page; // var end = this.end; // var title = this.querySelector(".title"); // var start = (current_page) * per_page + 1; // var current_end = start + per_page - 1; // if (current_end > end) { // current_end = end; // } // title.innerHTML = // "<b>" + start + "</b> - <b>" + current_end; // if (this.getAttribute('data-title') == 'semi') { // return; // } // title.innerHTML += "</b> of <b>" + end + "</b>"; //}; //this.observeTooltips = function(cb, caller) { // var backward_tooltip = this.querySelector(".backward"); // var forward_tooltip = this.querySelector(".forward"); // var base = this; // backward_tooltip.onclick = function() { // if (this.classList.contains('disabled')) { // return; // } // var pages = base.pages; // var current_page = base.current_page; // if (current_page > 0 || base.hasAttribute('data-circling')) { // var new_page = (current_page + pages - 1) % pages; // cb(new_page, caller); // base.current_page = new_page; // base.renderTitle(); // } // }; // forward_tooltip.onclick = function() { // if (this.classList.contains('disabled')) { // return; // } // var pages = base.pages; // var current_page = base.current_page; // if (current_page < pages - 1) { // base.current_page = current_page + 1; // base.renderTitle(); // cb(current_page + 1, caller); // } else { // if (base.hasAttribute('data-circling')) { // base.current_page = 0; // base.renderTitle(); // cb(0, caller); // } // } // }; //}; }; var proto = Object.create(HTMLElement.prototype); PagerComponent.apply(proto); document.registerElement("z-pager", { prototype: proto });
// !include ../stores/DeviceStore.js var DeviceListView = React.createClass({ deviceListUpdateCallbackId: null, getInitialState: function() { return { 'deviceList': [], 'activeIndex': null }; }, componentDidMount: function() { this.deviceListUpdateCallbackId = deviceStore.registerDeviceListChange( this.handleDeviceListUpdate.bind(this)); dispatcher.dispatch(Actions.createGetDeviceListAction()); }, componentWillUnmount: function() { deviceStore.unregisterDeviceListChange(this.deviceListUpdateCallbackId); }, handleDeviceListUpdate: function() { var deviceList = deviceStore.getDeviceList(); this.setState({ 'deviceList': deviceList, 'activeIndex': null }); }, handleDeviceClicked: function(device, index) { // @device is a element in this.state['deviceList'] // TODO var action = Actions.createSelectDeviceAction(device['id']); dispatcher.dispatch(action); var action = Actions.createGetDeviceDetailAction(device['id']); dispatcher.dispatch(action); this.setState({ 'activeIndex': index }); }, render: function() { var deviceList = this.state['deviceList']; var ListElmsUi = _.map(deviceList, function(device, index) { var activeIndex = this.state['activeIndex']; if (activeIndex == index) { return ( <li className='active'> <a href='javascript:void(0)'> {device['name']} </a> </li> ); } else { return ( <li> <a href='javascript:void(0)' onClick={this.handleDeviceClicked.bind(this, device, index)}> {device['name']} </a> </li> ); } }, this); var ListUi = ( <ul className='nav nav-pills nav-stacked'> {ListElmsUi} </ul> ); return ( <div className='col-md-12'> <h2> Device List </h2> <div className='col-md-12'> {ListUi} </div> </div> ); } }); var testDeviceListView = function(deviceStore, htmlContainerId) { var ui = (<DeviceListView />); ReactDOM.render( ui, document.getElementById(htmlContainerId) ); } // var ui = (<DeviceListView />); // ReactDOM.render( // ui, // document.getElementById('main') // );
import React, { Component } from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItemLink from 'component/MenuItemLink'; import AppBar from 'material-ui/AppBar'; class NavDrawer extends Component { render() { const { open, closeNav } = this.props; return ( <Drawer open={open} docked={false} onRequestChange={closeNav}> <AppBar title="Cosmere" showMenuIconButton={false} /> <MenuItemLink to="/" exact={true}>Home</MenuItemLink> <MenuItemLink to="/series" exact={true}>Series</MenuItemLink> <MenuItemLink to="/books">Books</MenuItemLink> </Drawer> ); } } export default NavDrawer;
const rules = [ { find: /M.+/ }, { find: /;.+/ }, { find: /G92.+/ }, { find: /G90.+/ }, { find: /M104.+/ }, { find: /E.+/ }, { find: /G92.+/ }, { find: /G90.+/ }, { find: /M109.+/ }, { find: /E.+/ } ] export { rules }
import Axios from 'axios'; import {showMessage, storeData} from '../../utils'; import {setLoading} from './global'; const API_HOST = { url: 'https://test-api-campus.herokuapp.com/api/v1', }; export const signUpAction = (dataRegister, navigation) => (dispatch) => { // post through api Axios.post(`${API_HOST.url}/signup`, dataRegister) .then((res) => { const token = `${res.data.toke_type} ${res.data.token}`; const profile = res.data; // save token storeData('token', { value: token, }); // save user data storeData('userProfile', profile); navigation.reset({index: 0, routes: [{name: 'Home'}]}); // show loading loader dispatch(setLoading(false)); }) .catch((err) => { // show loading loader dispatch(setLoading(false)); // show alert showMessage('Registration fail, please try again !'); }); }; export const signInAction = (form, navigation) => (dispatch) => { dispatch(setLoading(true)); Axios.post(`${API_HOST.url}/login`, form) .then((res) => { const token = `${res.data.toke_type} ${res.data.token}`; const profile = res.data; dispatch(setLoading(false)); // store to async storeData('token', {value: token}); storeData('userProfile', profile); navigation.reset({index: 0, routes: [{name: 'Home'}]}); }) .catch((err) => { dispatch(setLoading(false)); showMessage('Login fail, please try again !'); }); };
import Taro, { Component } from "@tarojs/taro"; import { View, Text, Button } from "@doctorwork/components"; import HybridBridage from "../../utils/GTAHybridBridge"; import "./listDetailItem.styl"; export default class ListDetailItem extends Component { componentWillMount() {} componentDidMount() {} componentWillUnmount() {} componentDidShow() {} componentDidHide() {} buttonClick(msg) { this.props.onButtonClick(msg); } render() { const env = process.env.TARO_ENV; const subs = this.props.subs.map((sub, index) => { let hybridUrl = HybridBridage.getHybridUrl({ method: sub.function }); return ( <View key={index}> <Text className='listDetailItem-detail'>{sub.desc}</Text> <Button className='listDetailItem-button' onClick={this.buttonClick.bind(this, sub)} > <Text className='listDetailItem-button'>{sub.function}</Text> </Button> {env == "h5" ? ( <a className='listDetailItem-a' href={hybridUrl}> {sub.function} </a> ) : ( <View /> )} </View> ); }); return ( <View className='listDetailItem'> <Text id={this.props.key} name={this.props.key} className='listDetailItem-title' > {this.props.title} </Text> {subs} </View> ); } }
import * as moment from 'moment' const PostIntro = (props) => { return ( <> <p className="time">{moment(props.post.created_on).format("Do MMMM YYYY")}</p> <div style={{width: "100%", maxHeight: "300px", overflow: "hidden", borderRadius: "5px"}}> <picture> {/* WebP */} <source media="(min-width: 900px)" srcSet={require(`../public/${props.post.cover_image}?resize&size=650&webp`)} type="image/webp"/> <source media="(max-width: 500px)" srcSet={require(`../public/${props.post.cover_image}?resize&size=500&webp`)} type="image/webp"/> {/* just resized */} <source media="(min-width: 900px)" srcSet={require(`../public/${props.post.cover_image}?resize&size=650`)}/> <source media="(max-width: 500px)" srcSet={require(`../public/${props.post.cover_image}?resize&size=500`)}/> {/* fallback & parameters */} <img style={{maxWidth: "100%", height: "auto"}} src={require(`../public/${props.post.cover_image}?resize&size=650`)} alt={props.post.cover_image_author} /> </picture> </div> <h1>{props.post.title}</h1> <p className="description">{props.post.description}</p> <style jsx>{` .time { font-size: 0.8em; color: #BBB; margin-top: 0px; } .description { color: #BBB; } `}</style> </> )} export default PostIntro
export const SIGN_IN = 'signIn'; export const SIGN_OUT = 'signOut'; export const ROLE_MENU_LIST = 'getRoleMenu'; export const GET_ONLINE_USER_INFO = 'getOnlineUserInfo'; export const IS_ONLINE = 'isOnline'; export const USER_MANAGE_LIST = 'getUserManageList'; export const ADD_USER = 'addUser'; export const EDIT_USER = 'editUser'; export const DELETE_USER = 'deleteUser'; export const RESET_PASSWORD = 'resetPassword'; export const CHANGE_USER_PWD = 'changeUserPwd'; export const FREEZE_USER = 'freezeUser'; export const UNFREEZE_USER = 'unfreezeUser'; export const DEPT_TREE = 'getDeptTree'; export const ADD_DEPT = 'addDept'; export const UPDATE_DEPT = 'updateDept'; export const DEL_DEPT = 'delDept'; export const GET_ROLE_LIST = 'getRoleList'; export const ADD_ROLE = 'addRole'; export const EDIT_ROLE = 'editRole'; export const DEL_ROLE = 'delRole'; export const SET_ROLE_AUTHORITY = 'setRoleAuthority'; export const GET_DICT_LIST = 'getDictList'; export const ADD_DICT = 'addDict'; export const EDIT_DICT = 'editDict'; export const DEL_DICT = 'delDict'; export const GET_MENU_LIST = 'getMenuList'; export const ADD_MENU = 'addMenu'; export const EDIT_MENU = 'editMenu'; export const DEL_MENU = 'delMenu'; export const MENU_TREE_LIST_BY_ROLE_ID = 'menuTreeListByRoleId'; export const GET_LOGIN_LOG_LIST = 'getLoginLogList'; export const EMPTY_LOGIN_LOG = 'emptyLoginLog'; export const GET_OPERATION_LOG_LIST = 'getOperationLogList'; export const EMPTY_OPERATION_LOG = 'emptyOperationLog'; export const OPERATION_LOG_DETAIL = 'operationLogDetail'; export const NOTICE_LIST = 'noticeList'; export const ADD_NOTICE = 'addNotice'; export const DEL_NOTICE = 'delNotice'; export const EDIT_NOTICE = 'editNotice'; export const DATA_PERMISSION_LIST = 'dataPermissionList'; export const ADD_DATA_PERMISSION = 'addDataPermission'; export const UPDATE_DATA_PERMISSION = 'updateDataPermission'; export const DEL_DATA_PERMISSION = 'delDataPermission'; export const DATA_PERMISSION_RULE_LIST = 'dataPermissionRuleList'; export const ADD_DATA_PERMISSION_RULE = 'addDataPermissionRule'; export const DEL_DATA_PERMISSION_RULE = 'delDataPermissionRule'; export const CHOOSE_DATA_PERMISSION_RULE = 'chooseDataPermissionRule'; export const DATA_PERMISSION_GROUP_TYPE = 'dataPermissionGroupType'; export const DATA_PERMISSION_GROUP_NAME_LIST = 'dataPermissionGroupNameList'; export const DATA_PERMISSION_BINDING_GROUP = 'dataPermissionBindingGroup'; export const JOB_LIST = 'jobList'; export const ADD_JOB = 'addJob'; export const EDIT_JOB = 'editJob'; export const DELETE_JOB = 'deleteJob'; export const PAUSE_JOB = 'pauseJob'; export const RESUME_JOB = 'resumeJob'; export const EXPORT_FILE_LIST = 'exportFilePageList'; export const DELETE_EXPORT_FILE_BY_CODES = 'deleteExportFileByCodes'; export const VALIDATE_EXPORT_FILE = 'validateExportFile'; export const MD_LOGISTICS_COMPANY_LIST = 'mdLogisticsCompanyList'; export const ADD_MD_LOGISTICS_COMPANY = 'addMdLogisticsCompany'; export const EDIT_MD_LOGISTICS_COMPANY = 'editMdLogisticsCompany'; export const DEL_MD_LOGISTICS_COMPANY = 'delMdLogisticsCompany'; export const SHOP_LIST = 'shopList'; export const INIT_SHOP = 'initShop'; export const ADD_SHOP = 'addShop'; export const UPDATE_SHOP = 'updateShop'; export const GET_SHOP_BY_ID = 'getShopById'; export const WAREHOUSE_LIST = 'warehouseList'; export const ADD_WAREHOUSE = 'addWarehouse'; export const UPDATE_WAREHOUSE = 'updateWarehouse'; export const FREEZE_WAREHOUSE = 'freezeWarehouse'; export const UNFREEZE_WAREHOUSE = 'unfreezeWarehouse'; export const DELETE_WAREHOUSE = 'deleteWarehouse'; export const GET_AREAS = 'getAreas'; export const GET_AREA_BY_PID = 'getAreaByPid'; export const FIND_WAREHOUSE_BY_ID = 'findWarehouseById'; export const SALES_ACCOUNT_LIST = 'salesAccountList'; export const SALES_ACCOUNT_INIT = 'salesAccountInit'; export const SALES_ACCOUNT_DOWNLOAD_EXPORT = 'salesAccountDownloadExport'; export const TAX_BALANCE_LIST = 'taxBalanceList'; export const TAX_BALANCE_INIT = 'taxBalanceInit'; export const TAX_BALANCE_DOWNLOAD_EXPORT = 'taxBalanceDownloadExport'; export const TAX_STATEMENT_LIST = 'taxStatementList'; export const TAX_STATEMENT_INIT = 'taxStatementInit'; export const TAX_STATEMENT_DOWNLOAD_EXPORT = 'taxStatementDownloadExport'; export const WAREHOUSE_STOCK_LIST = 'warehouseStockList'; export const ADD_WAREHOUSE_STOCK = 'addWarehouseStock'; export const UPDATE_WAREHOUSE_STOCK = 'updateWarehouseStock'; export const GET_WAREHOUSE_STOCK_DETAIL = 'getWarehouseStockDetail'; export const BRAND_LIST = 'brandList'; export const ADD_BRAND = 'addBrand'; export const UPDATE_BRAND = 'updateBrand'; export const DELETE_BRAND = 'deleteBrand'; export const MERCHANT_LIST = 'merchantList'; export const ADD_MERCHANT = 'addMerchant'; export const UPDATE_MERCHANT = 'updateMerchant'; export const DELETE_MERCHANT = 'deleteMerchant'; export const PRODUCT_LIST = 'productList'; export const PRODUCT_EDIT_INIT = 'productEditInit'; export const ADD_PRODUCT = 'addProduct'; export const UPDATE_PRODUCT = 'updateProduct'; export const DELETE_PRODUCT = 'deleteProduct'; export const PRODUCT_DETAIL = 'productDetail'; export const TEMP_SO_LIST = 'tempSoList'; export const TEMP_SO_EXPORT = 'tempSoExport'; export const TEMP_SO_INIT = 'tempSoInit'; export const TEMP_SO_GENERATE = 'tempSoGenerate'; export const TEMP_SO_PULLING_ORDER = 'tempSoPullingOrder'; export const SO_ORDER_LIST = 'soOrderList'; export const SO_ORDER_INIT = 'soOrderInit'; export const SO_ORDER_EXPORT_VIRTUAL_ORDER = 'soOrderExportVirtualOrder'; export const SO_ORDER_EXPORT_TRUE_OUT = 'soOrderExportTrueOut'; export const SO_ORDER_PASS_STATUS = 'soOrderPassStatus'; export const SO_ORDER_CANCEL_ORDER = 'soOrderCancelOrder'; export const SO_ORDER_REMARK = 'soOrderRemark'; export const SO_ORDER_USER_UPDATE_INIT = 'soOrderUserUpdateInit'; export const SO_ORDER_USER_UPDATE = 'soOrderUserUpdate'; export const SO_OPERATE_LOG_LIST = 'soOperateLogList'; export const TEMP_SO_OPERATE_LOG = 'tempSoOperateLog'; export const TEMP_SO_DETAIL = 'tempSoDetail'; export const TEMP_SO_ITEM_LIST = 'tempSoItemList'; export const SO_ORDER_DETAIL = 'soOrderDetail'; export const SO_ORDER_ITEM_LIST = 'soOrderItemList'; export const SO_ORDER_CARRY_REMARK = 'soOrderCarryRemark'; export const SO_ORDER_UPDATE_CARRY = 'soOrderUpdateCarry'; export const GRF_HEADER_INIT = 'grfHeaderInit'; export const GRF_HEADER_LIST = 'grfHeaderList'; export const GRF_HEADER_DETAIL = 'grfHeaderDetail'; export const REFUND_ORDER_INIT = 'refundOrderInit'; export const REFUND_ORDER_LIST = 'refundOrderList'; export const TEMP_SO_TO_ABNORMAL = 'tempSOToAbnormal'; export const TEMP_SO_TO_HANDLE_ABNORMAL_GOODS = 'tempSOToHandleAbnormalGoods'; export const MD_COMBO_PRODUCT_LIST = 'mdComboProductList'; export const ADD_MD_COMBO_PRODUCT = 'addMdComboProduct'; export const MD_COMBO_PRODUCT_DETAIL = 'mdComboProductDetail'; export const UPDATE_MD_COMBO_PRODUCT = 'updateMdComboProduct'; export const DELETE_MD_COMBO_PRODUCT = 'deleteMdComboProduct';
// /////////////////////////////// // Set up firebase // /////////////////////////////// // Import firebase elements we need import * as firebase from 'firebase/app' import 'firebase/auth' import 'firebase/database' import config from './helpers/firebase-config' // /////////////////////////////// // Import functions // /////////////////////////////// import * as user from './functions/firebase-userman' import * as contacts from './functions/firebase-contactman' import * as meetings from './functions/firebase-meetingman' import { listen } from './helpers/firebase-db' // /////////////////////////////// // App wrapper // /////////////////////////////// class App { constructor( config ) { // Init firebase & link auth and db this.fb = firebase this.fb.initializeApp( config ) this.auth = this.fb.auth() this.db = this.fb.database() } // USER MANAGEMENT login( email, password ) { return user.login( this, email, password ) } logout( ) { return user.logout( this ) } register( email, password ) { return user.register( this, email, password ) } currentUser( ) { return user.get( this ) } deleteUser( ) { return user.destroy( this ) } // CONTACT MANAGEMENT addContact( name, bio, frequency ) { return contacts.create ( this, name, bio, frequency ) } getContacts( ) { return contacts.get( this ) } updateContact( id, data ) { return contacts.update( this, id, data ) } destroyContact( id ) { return contacts.destroy( this, id ) } // MEETING MANAGEMENT addMeeting( contactid, date, location, meetingnotes ) { return meetings.create( this, contactid, date, location, meetingnotes ) } getMeetingsWith( contactid ) { return meetings.get( this, contactid ) } updateMeeting( contactid, meetingid, newdata ) { return meetings.update( this, contactid, meetingid, newdata ) } destroyMeeting( contactid, meetingid ) { return meetings.destroy( this, contactid, meetingid ) } // HELPERS listen( path ) { return listen( this, path ) } } export default new App( config )
fetch = require("node-fetch"); const [CreateComment, CreateReply] = require("./comment_classes.js") class Scraping { // main_list will contain all of the comment instances // video_id is the youtube-id in the video url // limit_max_comment represents the limit the user entered in the url constructor(video_id, max_comments) { this.main_list = [] this.video_id = video_id this.limit_max_comments = max_comments } set_total_comments(total_comments) { this.total_comments = total_comments } countReplies() { let replies = 0 for (let i=0; i<this.main_list.length; i++) { replies += this.main_list[i].getReply() } return replies } get_headers() { return { "referrer": "https://youtubecommentviewer.com/", "referrerPolicy": "strict-origin-when-cross-origin", "body": null, "method": "GET", "mode": "cors" } } // creating the api call // differentiates between the api call for the first 100 comments // which is different from an api call for comments beyond 100, where the 'NEXT_PAGE_TOKEN' should be at the end // which is also different from api calls for replies fetch_url(reply, id, next_page_token=false) { let comment_filler = "commentThreads" let which_id = "videoId" if (reply) { comment_filler = "comments" which_id = "parentId" } let url = `https://www.googleapis.com/youtube/v3/${comment_filler}?key=AIzaSyBUt7dFDp63KcOMflf7ksZOYWcbiwxH1og&textFormat=plainText&part=snippet&${which_id}=${id}&maxResults=100&pageToken=` if (next_page_token) { url = url.concat(next_page_token) } return url } // fetching the total amount of comments from the api async fetch_total_comments(video_id) { const url = `https://www.googleapis.com/youtube/v3/videos?key=AIzaSyBUt7dFDp63KcOMflf7ksZOYWcbiwxH1og&part=snippet,statistics&id=${video_id}` const fetched_data = await fetch(url, this.get_headers()) const data = await fetched_data.json() return data["items"][0]["statistics"]["commentCount"] } // fetching up to 100 comments with a single api call // and storing them within the main_list variable // each comment is represented as a class instance // if the comment contains replies, it sends another api call // and stores it in, but does not await the promise async scrape(next_page_token=false) { if (!next_page_token){ const total_comment_num = await this.fetch_total_comments(this.video_id) this.set_total_comments(total_comment_num) } const url_text = this.fetch_url(false, this.video_id, next_page_token) const fetched_data = await fetch(url_text, this.get_headers()) const data = await fetched_data.json() next_page_token = data["nextPageToken"] const comment_num = data["pageInfo"]["totalResults"] const json_comments = data["items"] let reply_num = 0 for (let i=0; i<json_comments.length; i++) { const comment = json_comments[i]["snippet"]["topLevelComment"]["snippet"] const comment_instance = new CreateComment(comment["textOriginal"], comment["authorDisplayName"], json_comments[i]["id"], json_comments[i]["snippet"]["totalReplyCount"], comment["authorChannelUrl"]) if (comment_instance.getReply()) { reply_num += comment_instance.getReply() const url = this.fetch_url(true, comment_instance.getId()) comment_instance.setReplyList(fetch(url, this.get_headers())) } this.main_list.push(comment_instance) } return [comment_num, next_page_token, reply_num] } // handles the meta data of the video, and decides // how many times to call the scrape func, depending // on user parameters and video total comments // here we wait for the replies promises async starter() { let total_replies, comment_total total_replies = comment_total = 0 let token = false let total, next_token, current_replies; while (true) { // calling the scraping func for every 100 comments [total, next_token, current_replies] = await this.scrape(token) token = next_token total_replies += current_replies comment_total += total // checking the url filled parameter for max comments if (comment_total >= this.limit_max_comments) { this.main_list = this.main_list.slice(0,this.limit_max_comments) total_replies = this.countReplies() break } // checking for total comments minus replies if (comment_total >= this.total_comments - total_replies) { break } } // now we will await the replies promises for (let i=0; i<this.main_list.length; i++) { //checking if there are replies if (this.main_list[i].getReply() > 0) { const promisee = await this.main_list[i].getReplyList() const reply_data = await promisee.json() const reply_list = [] // creating reply instance for every reply fetched for a single comment for (let j=0; j<reply_data["items"].length; j++) { const reply = new CreateReply(reply_data["items"][j]["snippet"]["textOriginal"], reply_data["items"][j]["snippet"]["authorDisplayName"]) reply_list.push(reply) } this.main_list[i].setFinalReplyList(reply_list) } } return [this.main_list, total_replies] } } module.exports = Scraping
$('#menu_consultar').on('click',function(){ $('#menu_consultar').addClass("active"); $('#menu_cadastrar').removeClass("active"); $('#menu_deletar').removeClass("active"); $('#menu_alterar').removeClass("active"); $('#consultar').css('display',''); $('#cadastrar').css('display','none'); $('#deletar').css('display','none'); $('#alterar').css('display','none'); }); $('#menu_cadastrar').on('click',function(){ $('#menu_cadastrar').addClass("active"); $('#menu_consultar').removeClass("active"); $('#menu_deletar').removeClass("active"); $('#menu_alterar').removeClass("active"); $('#consultar').css('display','none'); $('#cadastrar').css('display',''); $('#deletar').css('display','none'); $('#alterar').css('display','none'); }); $('#menu_alterar').on('click',function(){ $('#menu_cadastrar').removeClass("active"); $('#menu_consultar').removeClass("active"); $('#menu_deletar').removeClass("active"); $('#menu_alterar').addClass("active"); $('#consultar').css('display','none'); $('#cadastrar').css('display','none'); $('#deletar').css('display','none'); $('#alterar').css('display',''); }); $('#menu_deletar').on('click',function(){ $('#menu_cadastrar').removeClass("active"); $('#menu_consultar').removeClass("active"); $('#menu_deletar').addClass("active"); $('#menu_alterar').removeClass("active"); $('#consultar').css('display','none'); $('#cadastrar').css('display','none'); $('#deletar').css('display',''); $('#alterar').css('display','none'); }); // $('#formulario').on('submit',function(){ // if (($('#rg').val() == '') || // ($('#primeiro_nome').val() == '') || // ($('#ultimo_nome').val() == '')|| // ($('#telefone').val() == '')|| // ($('#email').val() == '')|| // ($('comentarios').val() == '')){ // alert('Preencha todos os campos!!!'); // return false // }else{ // return true // } // });
require("dotenv").config(); const firebase = require("firebase"); const admin = require("firebase-admin"); firebase.initializeApp({ apiKey: process.env.FB_KEY, authDomain: process.env.FB_AUTH_DOMAIN, databaseURL: process.env.FB_DB_URL, projectId: process.env.FB_PROJECT_ID, storageBucket: process.env.FB_STORAGE_BUCKET, messagingSenderId: process.env.FB_MESSAGING_SENDER_ID, appId: process.env.FB_APP_ID, measurementId: process.env.FB_MEASUREMENT_ID }); admin.initializeApp({ databaseURL: "https://schematic-capture.firebaseio.com", credential: admin.credential.cert({ type: process.env.SERVICE_ACCOUNT_TYPE, project_id: process.env.SERVICE_ACCOUNT_PROJECT_ID, private_key_id: process.env.SERVICE_ACCOUNT_PRIVATE_KEY_ID, private_key: process.env.SERVICE_ACCOUNT_PRIVATE_KEY, client_email: process.env.SERVICE_ACCOUNT_CLIENT_EMAIL, client_id: process.env.SERVICE_ACCOUNT_CLIENT_ID, auth_uri: process.env.SERVICE_ACCOUNT_AUTH_URI, token_uri: process.env.SERVICE_ACCOUNT_TOKEN_URI, auth_provider_x509_cert_url: process.env.SERVICE_ACCOUNT_AUTH_PROVIDER_X509_CERT_URL, client_x509_cert_url: process.env.SERVICE_ACCOUNT_CLIENT_X509_CERT_URL }) }); module.exports = { firebase, admin };
import React from 'react' import { Router } from 'react-router' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import routes from './routes' import theme from './base/materialUiTheme' // We can't use pure function here because in that case hot reloading won't work // eslint-disable-next-line react/prefer-stateless-function class App extends React.Component { render() { return ( <MuiThemeProvider muiTheme={theme}> <Router routes={routes} /> </MuiThemeProvider> ) } } export default App
import React from 'react' import List from '../List' import { getRect, calculateDimensions, activateDropdown } from './helpers.js' export const initialState = { active: false, dropdownStyle: { top: 'auto', bottom: 'auto', left: 'auto', right: 'auto', maxHeight: 'auto', width: 'auto' } } export function getVerticalPosition (triggerRect, windowDimensions) { const fromTriggerToTop = triggerRect.top const fromTriggerToBottom = windowDimensions.height - triggerRect.bottom return fromTriggerToTop < fromTriggerToBottom ? { top: '100%', maxHeight: fromTriggerToBottom - this.margin + 'px' } : { bottom: '100%', maxHeight: fromTriggerToTop - this.margin - 5 + 'px' } } export function getHorizontalPosition (triggerRect, windowDimensions) { const fromTriggerToLeft = triggerRect.left const fromTriggerToRight = windowDimensions.width - triggerRect.right return fromTriggerToLeft < fromTriggerToRight ? { left: 0, width: Math.min(windowDimensions.width - fromTriggerToLeft, this.maxWidth) - this.margin + 'px' } : { right: 0, width: Math.min(windowDimensions.width - fromTriggerToRight, this.maxWidth) - this.margin + 'px' } } export function toggle () { if (!this.state.active) { this.enable() } else { this.disable() } } export function enable () { const triggerRect = getRect(this.triggerRef) const windowDimensions = calculateDimensions() const verticalPosition = this.getVerticalPosition(triggerRect, windowDimensions) const horizontalPosition = this.getHorizontalPosition(triggerRect, windowDimensions) this.setState(activateDropdown(this.state, verticalPosition, horizontalPosition)) } export function disable () { this.triggerRef.current.focus() this.setState(initialState) } export function handleEsc (e) { if (this.state.active && e.key === 'Escape') { this.disable() } } const checkIfPositionInsideRect = (position, rect) => (position.x > rect.left) && (position.x < rect.right) && (position.y > rect.top) && (position.y < rect.bottom) export function handleClickOutside (e) { const active = this.state.active const rootRect = this.rootRef.current.getBoundingClientRect() const dropdownRect = this.dropdownRef.current.getBoundingClientRect() const clickPos = { x: e.clientX, y: e.clientY } const clickIsOutside = !checkIfPositionInsideRect(clickPos, rootRect) && !checkIfPositionInsideRect(clickPos, dropdownRect) if (active && clickIsOutside) { this.disable() } } export function enhanceChildren (children) { if (children && children.type === List) { const originalProps = children.props return ( <List { ...originalProps } onChange={ e => { setTimeout(this.disable, 100) originalProps.onChange(e) }} /> ) } else { return children || "" } }
// 跑 Test 時,隱藏 console.error global.console.error = () => {};
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Link } from 'react-router'; import ReactMarkdown from 'react-markdown'; import { get, put } from '../shared/http'; import Loading from '../components/Loading'; class Editor extends Component { constructor(props){ super(props); this.state = { loading: true, data: {} }; } componentDidMount() { const self = this; const type = self.props.params.type; const id = this.props.params.id; get(`api/${type}/${id}`) .then(data => data.json()) .then((data) =>{ self.setState({ loading: false, data: data }); }); } updateMarkDown(e) { this.setState({ data: { ...this.state.data, markdown: e.target.value } }); } updateAttr(key, e){ this.setState({ data: { ...this.state.data, attr: { ...this.state.data.attr, [key]: e.target.value } } }); } saveContent() { const self = this; const type = self.props.params.type; const id = this.props.params.id; this.setState({ loading: true }); const data = this.state.data; const dataStr = JSON.stringify(data); put(`api/${type}/${id}`, dataStr) .then((resp) => { console.log(resp); this.setState({ loading: false }); }); } render() { const id = this.props.params.id; const state = this.state; const data = state.data; if (state.loading) { return <Loading /> } return ( <div className="container-wrapper"> <div className="types-list container"> <fieldset> <div className="float-right"> <button onClick={() => { this.saveContent(); }} className="button">Save</button> </div> <h1>{data.slug}</h1> {Object.keys(data.attr).map((key) => { const val = data.attr[key]; return (<div key={key}> <label>{key}</label> <input type="text" value={val} onChange={(e) => { this.updateAttr(key, e); }} /> </div>); })} <div className="row editor-w-preview"> <div className="column column-50"> <textarea value={state.data.markdown} onChange={(e) => { this.updateMarkDown(e) }} /> </div> <div className="column column-50"> <ReactMarkdown source={state.data.markdown} /> </div> </div> </fieldset> </div> </div> ); } }; export default Editor;
//Linked to a spreadsheet on Andrew's account. Don't change //Handles the saving of data through a Map like structure //Saves everything into a spreadsheet //Stored as key value pairs. var prev = 0; function DataMap(live){ url='https://docs.google.com/spreadsheets/d/176z44O-mgCBX20skzYfsT7Kx1yibE4jguVcvXEHpn3M/edit' this.spreadsheet = SpreadsheetApp.openByUrl(url); if (live == 0) { this.sheet = this.spreadsheet.getSheets()[1]; } else { this.sheet = this.spreadsheet.getSheets()[0]; } this.range = this.sheet.getRange(1, 1, this.sheet.getMaxRows(), 2); this.values = this.range.getValues(); this.url = url; } //get url DataMap.prototype.getURL = function(){ return this.url; } //sets the url DataMap.prototype.setURL = function(url){ this.url = url; } //gets a value from its key DataMap.prototype.get = function(key) { for (var row in this.values) { if((this.values[row][0] == key)){ return this.values[row][1]; } } } //gets the size of this map DataMap.prototype.getSize = function () { for(i = 1; i < this.sheet.getMaxRows(); i++){ if(this.sheet.getRange(i, 1).getValue() == "" && this.sheet.getRange(i, 2).getValue() == "") { return i - 1; } } } //set a value with its key, value DataMap.prototype.set = function(key, value) { for(j = 1; j < this.sheet.getMaxRows(); j++){ if(this.sheet.getRange(j, 1).getValue() == key) { this.sheet.getRange(j, 2).setValue(value); return; } } //the key is not existent so add to a new row for(i = 1; i < this.sheet.getMaxRows(); i++){ if(this.sheet.getRange(i, 1).getValue() == "" && this.sheet.getRange(i, 2).getValue() == "") { this.sheet.getRange(i, 1).setValue(key); this.sheet.getRange(i, 2).setValue(value); return; } } } //set a value with its key, value. Start parsing based on count DataMap.prototype.setNew = function(key, value, v) { //the key is not existent so add to a new row for(i = v; i < this.sheet.getMaxRows(); i++){ if(this.sheet.getRange(i, 2).getValue() == "") { this.sheet.getRange(i, 1).setValue(key); this.sheet.getRange(i, 2).setValue(value); return; } } } //used for overriding previous entries, writes based on count DataMap.prototype.setReplace = function(key, value, score) { //the key is not existent so add to a new row for(var i = key + 1; i < this.sheet.getMaxRows(); i++){ this.sheet.getRange(i, 1).setValue(key); this.sheet.getRange(i, 2).setValue(value); this.sheet.getRange(i, 3).setValue(score); return; } } //reloads spreedsheet and values DataMap.prototype.reload = function(){ this.spreadsheet = SpreadsheetApp.openByUrl(this.url); this.sheet = this.spreadsheet.getSheets()[0]; this.range = this.sheet.getRange(1, 1, this.sheet.getMaxRows(), 2); this.values = this.range.getValues(); }
class Dustbin{ constructor(x,y){ this.x=x; this.y=y; this.dustbinWidth=200; this.dustbinHeight=100; this.wallThick=10; this.angle=0; this.image=loadImage("dustbingreen.png"); this.bottomBody=Bodies.rectangle(this.x,this.y,this.dustbinWidth,this.wallThick,{isStatic:true}); this.leftBody=Bodies.rectangle(this.x-this.dustbinWidth/2,this.y-this.dustbinHeight/2,this.wallThick, this.dustbinHeight,{isStatic:true}); Matter.Body.setAngle(this.leftBody,this.angle); this.rightBody=Bodies.rectangle(this.x+this.dustbinWidth/2,this.y-this.dustbinHeight/2,this.wallThick, this.dustbinHeight,{isStatic:true}); Matter.Body.setAngle(this.rightBody,-1*this.angle); World.add(world,this.bottomBody); World.add(world,this.rightBody); World.add(world,this.leftBody); } display(){ var bottomPos=this.bottomBody.position; var leftPos=this.leftBody.position; var rightPos=this.rightBody.position; push() translate(leftPos.x, leftPos.y); rectMode(CENTER) angleMode(RADIANS) fill(255); stroke(255); rotate(this.angle) rect(0,0,this.wallThick, this.dustbinHeight); pop() push() translate(rightPos.x, rightPos.y); rectMode(CENTER) stroke(255); angleMode(RADIANS) fill(255); rotate(-1*this.angle) rect(0,0,this.wallThick, this.dustbinHeight); pop() push() translate(bottomPos.x,bottomPos.y); rectMode(CENTER) stroke(255); angleMode(RADIANS) fill(255); rect(0,0,this.dustbinWidth, this.wallThick); imageMode(CENTER); image(this.image,0,-this.dustbinHeight/2,this.dustbinWidth,this.dustbinHeight); pop() } };
var config = require('config.json') var configJSON = JSON.parse(config)
import React from 'react'; import {Link} from 'react-router-dom'; import './style.css'; import {deleteTopic, getAllTopics} from '../../../services/ref-data/topic'; import {TopicManagerTableHeaderRow,TopicManagerTableBodyRow} from './topic-manager-table-row'; export default class TopicManagerComponent extends React.Component{ state={ message:'', isError:false, topics:[], } componentDidMount=()=>{ getAllTopics() .then(data => { this.setState({topics:data.topics}); }); } onDoubleClick = (id)=>{ this.props.history.push(`${this.props.match.url}/edit-topic/`+id); } onDelete = (id) =>{ deleteTopic(id).then((data)=>{ this.setState({message:data.message}); }) .catch(error =>{ this.setState({isError:true, message:error.message}); }); } render(){ window.scrollTo(0,0); return (<div className="container-fluid topic-manager-container"> <div className="row"> <div > <Link className="btn btn-primary" to={`${this.props.match.url}/add-topic`}>Add New</Link> </div> <div className="flex-grow-1 text-center"> Topic Manager </div> </div> <div className="row justify-content-center"> <div className="text-center"> {this.state.message? <div className={"alert "+ (this.state.isError?' alert-danger':'alert-success') }> {this.state.message} </div>:''} </div> </div> <div className="row topic-manager-table"> <table className="table table-hover"> <thead> <TopicManagerTableHeaderRow /> </thead> <tbody> {Array.isArray(this.state.topics)?this.state.topics.map((topic,index)=>{ return <TopicManagerTableBodyRow key={index} onDelete={this.onDelete} onDoubleClick={this.onDoubleClick} topic={topic}/> ; }):<tr><td>Topics not found!</td></tr>} </tbody> </table> </div> </div>); }; }
import React, {useEffect, useState} from 'react'; import {useSelector, useDispatch} from 'react-redux'; import {View, TextInput, Button} from 'react-native'; import styles from './TodoScreen.style'; import {addDataTodo, RemoveMuchData} from '../../redux/actions'; import CardText from '../../components/CardText'; const TodoScreen = ({navigation}) => { const listTodo = useSelector((state) => state.todo.listtodos); useEffect(() => { console.log(listTodo, 'listTodo'); }, []); const [value, onChangeText] = useState('Add an task'); const dispatch = useDispatch(); return ( <View style={styles.scrollView}> <View style={styles.topHead}> <TextInput style={styles.textInput} onChangeText={(text) => onChangeText(text)} value={value} /> <Button onPress={() => { dispatch( addDataTodo({ id: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15), name: value, }), ); onChangeText(''); }} title="Add Task" color="#841584" accessibilityLabel="Learn more about this purple button" /> </View> <Button title="Remove Selected" onPress={() => { dispatch(RemoveMuchData()); }} color="#841584" /> <View style={{marginTop: 10}}> {listTodo?.map((item) => ( <CardText key={item.id} item={item} /> ))} </View> </View> ); }; export default TodoScreen;
var array = [1,3,5,7,9,11,,11,12]; var binary =binarySearch(array,11); if(binary > 0){ console.log("result found at position",binary); } else{ console.log("result not found"); } function binarySearch(array,x){ var low =0 , high =array.length-1 , mid; while(low<=high) { mid = Math.floor(low+high)/2; if(array[mid]==x) return mid; else if(array[mid]<x) low = mid +1; else high = mid -1; } return -1; } // function binarySearch(array,x) // { // var startIndex ,endIndex,length; // startIndex = 0; // endIndex = array.length-1; // let midIndex = Math.floor(startIndex+endIndex)/2; // // console.log(array[midIndex]); // while(startIndex <= endIndex && array[midIndex]!=x){ // if(x<array[midIndex]) // endIndex = midIndex-1; // else // startIndex =midIndex+1; // midIndex = Math.floor(startIndex+endIndex)/2; // } // if(array[midIndex]==x){ // length = midIndex; // } // else // length = -1; // } // // if(array[midIndex]==x){ // // return console.log("TARGET FOUND"); // // } // // if(array[midIndex] < x){ // // console.log("Searching in left side"); // // endIndex = midIndex - 1; // // } // // else // // console.log("Not found in first loop");
const initialState = { nodes: [], edgesAndCost: [], }; function searchForArray(haystack, needle) { var i, j, current; for (i = 0; i < haystack.length; ++i) { if (needle.length === haystack[i].length) { current = haystack[i]; for (j = 0; j < needle.length-1 && needle[j] === current[j]; ++j); if (j === needle.length-1) return i; } } return -1; } export default function (state = initialState, action) { switch (action.type) { case "ADD_NODE": let newNodes = [...state.nodes]; if (!newNodes.includes(action.node1)) { newNodes.push(action.node1); } if (!newNodes.includes(action.node2)) { newNodes.push(action.node2); } return { ...state, nodes: newNodes, }; case "ADD_EDGES_AND_COST": let newEdgesAndCost = [...state.edgesAndCost]; if (searchForArray(newEdgesAndCost, action.edge) === -1) { newEdgesAndCost.push(action.edge); return { ...state, edgesAndCost: newEdgesAndCost, }; } else { return { ...state, edgesAndCost: newEdgesAndCost, }; } default: return state; } }
/** * 城市切换公用函数 * @returns {undefined} */ $(function () { $('#pro').change(function () { $.ajax({ type: "post", url: $(this).data('url'), data: 'pro_id=' + $('#pro').val(), dataType: "json", success: function (data) { $('#city').html(data); } }); }); $('#city').change(function () { $.ajax({ type: "post", url: $(this).data('url'), data: 'pro_id=' + $('#city').val(), dataType: "json", success: function (data) { $('#area').html(data); } }); }); $('#pro').change(); });
import axios from 'axios'; export default class APIManager { static instance; constructor() { if (APIManager.instance) { return APIManager.instance } this._url = "" this._params = {} this._data = {} this._header = {} APIManager.instance = this } //get 함수 get url() { return this._url; } get params() { return this._params; } get data() { return this._data; } get header() { return this._header } //set 함수 set url(url) { this._url = url; } set params(params) { this._params = params; } set data(data) { this._data = data; } set header(header) { this._header = header } get = (callback) => { axios.get(this._url, { params: this._params }) .then((response) => { if (callback) { callback(response.data) } this.init() }) .catch(function (error) { console.log("axios get error : " + error); }); } post = (callback = null) => { var config = { method: 'post', url: this._url, data: this._data, header: this._header } axios(config) .then(response => { if (callback) { console.log(response.data) callback(response.data) } this.init() }) .catch(function (error) { console.log("axios post error : " + error); }); } init = () => { this._url = "" this._params = {} this._data = {} this._header = {} } }
module.exports = { 'secret': 'SWFGSewrsdXVCQEWRdsftdgewtw', 'ConnectionString' : { user: 'sqldb', password:'MilgaDbsql12!', database:'milga_test', server:'milgadbsrv.database.windows.net' , port: 1433, options: { encrypt: true } } };
import React from 'react'; import ReactDOM from "react-dom"; import App from "./App"; // функция выводи сообщения function MessagesUsers(props) { let arr = props.msg, content = arr.map((elem) => <div className="row mt-2"> <span className="col-6">{elem.name}</span> <span className="col-6">{elem.msg}</span> </div> ); return ( content ); } // фукнция проверки данного пользователя, выводим под него все элементы function CheckRoleUser(props) { switch (props.role) { case 'user': return ( <div className="col-6"></div> ); case 'moderator': if (props.user_role === 'user') { return ( <div className="col-12"> <button data-name={props.user_name} onClick={ClickSelect}>Бан</button> <select> <option value="noTime">Разбанить </option> <option value="one">2 Минуты</option> <option value="hour">На час</option> <option value="forever">Навcегда</option> </select> </div> ); } else { return ( <div className="col-6"></div> ); } case 'admin': if (props.user_role === 'user') { return ( <div className="col-12 row"> <button data-name={props.user_name} onClick={ClickSelect}>Бан</button> <select> <option value="noTime">Разбанить</option> <option value="one">2 Минуты</option> <option value="hour">На час</option> <option value="forever">Навcегда</option> </select> <div className="col-6"> <button data-name={props.user_name} className="btn btn-secondary" onClick={ClickAddModer} type="button"> Сделать модератором </button> </div> </div> ); } else { return ( <div className="col-6"></div> ); } } } // функция вывода элементов function RegisteredUsers(props) { let arr = props.users, content = arr.map((elem) => <div className="row border mt-2"> <span className="col-6">{elem.nickname}</span> <span className="col-6">{elem.role}</span> <CheckRoleUser user_name={elem.nickname} user_role={elem.role} role={props.role}/> </div> ); return ( content ); } // При нажатии кнопку "Создать нового модератора" function ClickAddModer(e) { let th = e.target, message = { "nickname": th.dataset.name, "addModer": 'true', }; console.log(JSON.stringify(message)); soket_web.soket.send(JSON.stringify(message)); } // При нажатии кнопку "Бан" function ClickSelect(e) { let th = e.target, message = { "nickname": th.dataset.name, "ban_time": th.nextSibling.value, }; console.log(JSON.stringify(message)); soket_web.soket.send(JSON.stringify(message)); } var soket_web; // класс обрабатывающий полностью содениение websocket class Websoket extends React.Component { constructor(props) { super(props); this.name = ''; } // Приконективаемся к backend websocket connection(nickname) { this.soket = new WebSocket("ws://192.168.100.3:8000/?user=" + nickname); this.localsocket = new Websoket(); soket_web = this; this.name = nickname; // подключен или нет this.soket.onopen = function (e) { console.log('Подключено'); }; //Отсоиденен this.soket.onclose = function (e) { // проверка на закрытие if (e.wasClean) { console.log('Отключено'); } console.log("Код " + e.code + " причина " + e.reason); }; // когда приходят сообщения и другая информация обработок this.soket.onmessage = function (e) { let answer = JSON.parse(e.data); // if (проверка на бан ) {если да то выкидываем его} else {то выводим сообщения и всех юзеров которые были хотя быраз в чате} if (answer['ban']) { if(answer['date'] === 'f'){ document.getElementById("ban").innerText = 'Вы забанены до бесконечности, через 5 секунд redirect'; } else { document.getElementById("ban").innerText = 'Вы забанены до '+answer['date']+' через 5 секунд redirect'; } setTimeout(()=>{ window.location.href = '/'; }, 5000); } else { if (answer['arr_msg']) { for (let i = 0; i < answer['arr_msg'].length; i++) { if (answer['arr_msg'][i].name === nickname) { answer['arr_msg'][i].name = nickname + "(Я)"; } } ReactDOM.render( <MessagesUsers msg={answer['arr_msg']}/> , document.getElementById('msg')); } let role_user; for (let i = 0; i < answer['arr_users'].length; i++) { if (answer['arr_users'][i].nickname === nickname) { role_user = answer['arr_users'][i].role; } } ReactDOM.render( <RegisteredUsers users={answer['arr_users']} role={role_user}/>, document.getElementById("users") ); } }; this.soket.onerror = function (e) { console.log('Ошибка'); console.log(e.data); }; } // Нажатие на кнопку отправить сообщение addMsg(message) { message.name = this.name; this.soket.send(JSON.stringify(message)); } } export default Websoket;
var assert = require('assert') var proxyquire = require('proxyquire') var _ = require('lodash') var fixtures = require('./blkqt.fixtures') require('terst') /* global describe, it EQ */ /* eslint-disable no-spaced-func */ var atomStub = { '@noCallThru': true // for proxyquire } var ipcStub = { '@noCallThru': true } describe('blkqt', function () { describe('+ getUnspents()', function () { fixtures.getUnspents.valid.forEach(function (f) { it('should get the unspents and return the data', function (done) { var ipc = _.assign({ sendIpc: function (data, callback) { callback(null, _.cloneDeep(f.input)) } }, ipcStub) var stubs = { './ipc': ipc, '../atom': atomStub } var blkqt = proxyquire('../blkqt', stubs) // null => all addresses blkqt.getUnspents(null, function (err, unspents) { assert.ifError(err) assert.equal(f.input.length, unspents.length) for (var i = 0; i < f.input.length; ++i) { var inp = f.input[i] var utxo = unspents[i] var exp = f.expected[i] EQ(utxo.txId, inp.txid) EQ(utxo.txId, exp.txId) EQ(utxo.amountRat, exp.amountRat) EQ(utxo.amountRat, utxo.value) } done() }) }) }) }) })
'use strict'; import LivingThing from './LivingThing'; import Eukaryota from './Eukaryota'; class Animal extends Eukaryota { } export default Animal;
/** * Copyright (c) Kipras Melnikovas 2018 * The main server file */ /** load .env environment variables to process.env */ if (process.env.HEROKU != "true") { require("./utils/loadDotenv")("../.env"); // FOR HEROKU ONLY } const express = require("express"); const mongoose = require("mongoose"); const path = require("path"); const helmet = require("helmet"); /** Load models here: */ const app = express(); const port = process.env.PORT || 5000; app.use(helmet()); // https://helmetjs.github.io/ app.use(express.urlencoded({ extended: false })); app.use(express.json()); /** Connect to MongoDB: */ require("./utils/connectToMongoDB")(); /** Use routes: */ app.use("/api/poll", require("./routes/poll")); app.use("/api/vote", require("./routes/vote")); // if in production: if (process.env.NODE_ENV === "production") { // serve static assets app.use(express.static("../client/build/")); // the '/' is needed! https://stackoverflow.com/a/48666785 // capture everything that's outside our API routes and send the built react application (index.html file): app.get("*", (req, res) => { // both are the same: // res.sendFile(path.join(__dirname, "../client", "build", "index.html")) res.sendFile(path.resolve(__dirname, "../", "client", "build", "index.html")); }); } app.listen(port, () => console.log(`~Server started on port ${port} with NODE_ENV ${process.env.NODE_ENV}`));
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /*global module*/ /* jshint node: true */ /* jshint strict: global */ /* jshint camelcase: false */ 'use strict'; var debug = require('debug')('arpublish:content.upload'); var archiver = require('archiver'); var Busboy = require('busboy'); var crypto = require('crypto'); var fs = require('fs-extra'); var path = require('path'); var Q = require('q'); var uuid = require('uuid'); var vxspublish = require('./vxspublish'); var helper = require('./../helper'); var unzip = require('./../unzip'); var optimizer = require('./callOptimizer'); var freemiumLimits = require('./freemiumLimits'); var EXP_DATA_FILENAME = 'experience.json'; var META_DATA_FILENAME = 'WEB-INF/metadata.json'; var META_DATA_VERSION = '1'; var DEFAULT_TARGET_TYPE = 'SPATIAL'; var VALID_TARGET_TYPES = ['SPATIAL', 'THINGMARK']; module.exports.doUpload = function(req, res, next) { debug('Inside doUpload...'); var toDelete = new Array(); var username = req.user; var thingmark; var uniquename; var archiveNameForVxs; var startTime = process.hrtime(); var uniquename; var displayname; var experienceTemplate; var experienceCustomParams; var thingmark; var publicAccess = false; processFormData(req) .then(function () { helper.recordTime('fileTransferZipTime', startTime, debug, req); debug('Resource File: %j', req.file); debug('Form data : %j', req.body); debug('Zip : ', req.zipPath); toDelete.push(req.zipPath); startTime = process.hrtime(); uniquename = req.body.uniquename; displayname = req.body.displayname ? req.body.displayname : uniquename; experienceTemplate = req.body.experience; experienceCustomParams = req.body.experienceparams; thingmark = req.body.thingmark; //TODO: Do we need to use encodeURIComponent or some other checks to handle unsupported characters? archiveNameForVxs = uniquename; // If publishing to freemium then it should publish to personal thingmark only. // So ignore the input thingmark and use the user's personal thingmark instead. if (req._freemiumServer !== undefined && req._freemiumServer === true) { if ('none' !== thingmark) thingmark = req._thingmarkCode; archiveNameForVxs = crypto.createHash('sha1').update(username).digest('hex') + encodeURIComponent('/') + uniquename; debug('generated unique content name: ', archiveNameForVxs); } const regex = /[\\\/]/; if (regex.test(uniquename)) { console.error("Invalid unique name for Experience, contains / or \\ :" + uniquename); throw new Error("Invalid unique name for Experience, contains / or \\ :" + uniquename); } return freemiumLimits(req, username, thingmark, archiveNameForVxs); }) .then(function(){ return doOptimization(req); }) .then(function (optimizedZip) { helper.recordTime('optimizeTime', startTime, debug, req); if (optimizedZip !== undefined && !helper.isEmpty(optimizedZip)) { debug('switching to zip with optimized file: ' + optimizedZip); req.zipPath = optimizedZip; toDelete.push(optimizedZip); } // upload to experience server return vxspublish(req, thingmark, archiveNameForVxs, req.zipPath, displayname, experienceTemplate, publicAccess, experienceCustomParams) }) .then(function (publishedLocation) { debug('successful completion'); res.status(201).json({ 'es_resource_location': publishedLocation }).end(); }) .catch(function (err) { debug('Inside fail...'); console.error(err); next(err); }) .finally(function () { // cleanup of temp files debug('Inside finally .. No. of files to delete : ' + toDelete.length); if (toDelete.length > 0) { removeContentFiles(toDelete); delete toDelete[0]; } }); } function removeContentFiles( toDelete) { for (var i=0; i<toDelete.length; i++) { var file = toDelete[i]; debug('deleting file : ' + file ); fs.remove(file, function(err) { if (err) { console.error('Unable to delete file. ', err.message || err); } }); } } function processFormData(req) { return Q.promise(function(resolve, reject) { var destDirPath = helper.getUploadDir(req); var tmpName = uuid.v1(); var zipPath = path.join(destDirPath, tmpName +'.zip'); var errDone = false; function onError (err) { debug('Inside onError ...'); if (errDone) return; errDone = true; debug('Zip to delete : '+zipPath); if (fs.existsSync(zipPath)) { //Explicitly closing output stream on error. output.close(); // Delete the zip file debug('Deleting zip on error condition'); fs.remove(zipPath, function(fErr) { if (fErr) { console.error( 'Unable to delete file.', fErr.message || fErr ); //debug('Unable to delete file.', fErr); } else { debug('Delete of zip successful on error conditions'); } }); } if (busboy) { req.unpipe(busboy); busboy.removeAllListeners(); } reject(err); } // Initialize busboy debug('fileSizeLimit : '+req.app.settings.fileSizeLimit + ' kb'); debug('fieldSizeLimit: '+req.app.settings.fieldSizeLimit + ' kb'); var limits = {files : 1}; if (req.app.settings.fieldSizeLimit) { limits.fieldSize = req.app.settings.fieldSizeLimit*1024; } if (req.app.settings.fileSizeLimit) { limits.fileSize = req.app.settings.fileSizeLimit*1024; } var busboy = new Busboy({ headers: req.headers, limits: limits }); // Initialize archive debug('Initializing zip ' + zipPath); fs.mkdirsSync(destDirPath); var archive = archiver('zip'); var output = fs.createWriteStream(zipPath); archive.on('error', function(err) { console.error('Archive operation failed. Archive error: ', err.message || err); onError(err); }); output.on('close', function() { debug('errDone status on output.close : '+errDone); if(!errDone) { debug('archiver has been finalized and the output file descriptor has closed.', archive.pointer() + ' total bytes'); req.zipPath = zipPath; resolve(); } }); output.on('error', function(err) { console.error( 'Archive operation failed. Output stream error: ', err.message || err); onError(err); }); archive.pipe(output); // End of archive initialization // setup busboy event listeners busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { debug('Fieldname [' + fieldname + ']: filename: ' + filename + ', mimeType: '+mimetype); // Checking the file size. file.on('limit', function () { var err = createError('File too large'); onError(err); }); if (fieldname === 'resource'){ req.file = { filename: filename, fieldname: fieldname }; archive.append(file, {name: filename}); } else { file.resume(); } }); busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { debug('Field [' + fieldname + ']: value: ' + val); if(valTruncated === true) { var err = createError('Field value too large'); onError(err); } req.body[fieldname] = val; }); busboy.on('filesLimit', function () { var err = createError('More than one file sent in request.'); onError(err); }); busboy.on('error', function (err) { console.error('Busboy error: ', err.message || err); onError(err); }); busboy.on('finish', function() { debug('Inside busboy finish...'); onBusboyFinish(req, archive, onError); }); // pipe req.pipe(busboy); }); } function onBusboyFinish(req, archive, errCb) { try { validateRequiredFields(req); archive.append(getJSONData(req), {name: EXP_DATA_FILENAME}); archive.append(getMetadata(req), {name: META_DATA_FILENAME}); archive.finalize(); } catch (err) { errCb(err); } } function getJSONData (req) { var emptyInput = {}; var data = req.body.data; var jsonObject = data ? JSON.parse(data) : emptyInput; // Add other fields jsonObject.resource = req.file.filename; jsonObject.targettype = req.body.targettype ? req.body.targettype.toUpperCase() : DEFAULT_TARGET_TYPE; return JSON.stringify(jsonObject,null,2); } function getMetadata (req) { var markerwidth; if (req.body.markerwidth !== undefined) markerwidth = validateMarkerWidth(req.body.markerwidth); var targettype; if (req.body.targettype !== undefined) targettype = req.body.targettype.toUpperCase(); var metadata = { version: META_DATA_VERSION, title: { en: req.body.displayname ? req.body.displayname : req.body.uniquename }, custom: { uniqueName: req.body.uniquename, experience: req.body.experience, resource: req.file.filename, targetType: targettype || DEFAULT_TARGET_TYPE, markerWidth: markerwidth } } if(req.headers.clientinfo !== undefined){ metadata["clientinfo"] = JSON.parse(req.headers.clientinfo); } return JSON.stringify(metadata,null,2); } function validateRequiredFields(req) { if(req.body.uniquename === undefined || helper.isEmpty(req.body.uniquename)) { debug('Input uniquename missing'); var err = createError('Input uniquename missing'); throw err; } if (req.file === undefined || helper.isEmpty(req.file.filename)) { // If no resource file found in request. debug('No resource file in request'); var err = createError('No resource file in request'); throw err; } else { if (!req.app.settings.allowedFileExt.includes(path.extname(req.file.filename))) { debug('Resource file extention "' + path.extname(req.file.filename) + '" unsupported'); var err = createError('Unsupported file type'); throw err; } } if (req.body.targettype !== undefined) { // Check if the targettype is valid value if (VALID_TARGET_TYPES.includes(req.body.targettype.toUpperCase()) === false) { debug('Unsupported target type "' + req.body.targettype); var err = createError('Unsupported target type ' + req.body.targettype); throw err; } } } function createError(msg) { var err = new Error(msg); err.status = 400; return err; } function doOptimization(req) { if (req.body.fidelity !== undefined && !helper.isEmpty(req.body.fidelity)) { // Do optimization debug('Optimization requested to fidelity: ' + req.body.fidelity); var toDelete = new Array(); var extractDir = path.join(helper.getUploadDir(req), uuid.v1()); toDelete.push(extractDir); var origFile = path.join(extractDir, req.file.filename); var extname = path.extname(req.file.filename); var optimizedFile = path.join(extractDir, 'optimized'+extname); var newzip = extractDir + '.zip'; return unzip.extractZipPromise(req.zipPath, extractDir) .then(function() { return optimizer(req, origFile, optimizedFile, req.body.fidelity); }) .then(function() { // delete original file fs.removeSync(origFile); // rename optimized file to original filename fs.renameSync(optimizedFile, origFile); // recreate the zip from files in extractDir return zipDir(newzip, extractDir); }) .then(function() { return Q.resolve(newzip); }) .finally(function() { // cleanup of temp files debug('Inside finally of doOptimization...'); debug('No. of files to delete : '+toDelete.length); if( toDelete.length > 0 ) { removeContentFiles(toDelete); delete toDelete[0]; } }); } else { return Q.resolve(); } } function zipDir(zipPath, sourceDir) { return Q.promise(function(resolve, reject) { debug('Zip directory ' + sourceDir + ' to ' + zipPath); var archive = archiver('zip'); var output = fs.createWriteStream(zipPath); var errDone = false; archive.on('error', function(err) { console.error('Archive operation failed. Archive error: ', err.message || err); errDone = true; reject(err); }); output.on('close', function() { debug('errDone status on output.close : '+errDone); if(!errDone) { debug('archiver has been finalized and the output file descriptor has closed.', archive.pointer() + ' total bytes'); resolve(); } }); output.on('error', function(err) { console.error( 'Archive operation failed. Output stream error: ', err.message || err); errDone = true; reject(err); }); archive.pipe(output); archive.directory(sourceDir, false); archive.finalize(); }); } function validateMarkerWidth(markerWidth) { var retMarkerWidth = markerWidth; if (typeof retMarkerWidth === "string") { if (/^-?\d+\.?\d*$/.test(retMarkerWidth)) { retMarkerWidth = parseFloat(retMarkerWidth); } } if (isNaN(retMarkerWidth) || typeof retMarkerWidth !== 'number') { var err = createError("Invalid markerwidth: " + JSON.stringify(markerWidth)); throw err; } return retMarkerWidth; };
import styles from './Monitor.less'; import React from 'react'; import {Row,Col ,Tabs} from 'antd'; import SimpleColumnChart from '../../component/SimpleChart/SimpleColumnChart'; import CurveChart from '../../component/SimpleChart/CurveChart'; import MeterShart from '../../component/SimpleChart/MeterChart'; const cities=["淮北", "徐州", "宿迁", "连云港", "枣庄", "济宁", "商丘", "宿州"]; //直方图分析页面 class Monitor extends React.Component{ constructor(props){ super(props); } state={ aqi:0, citydata:[], } getData=(city)=>{ fetch('http://api.help.bj.cn/apis/aqi/?id='+city) .then(res=>res.json()) .then(data=>{ data.data.map((value)=>{ value.aqi= parseInt(value.aqi); value.pm25=parseInt(value.pm25); value.lv=parseInt(value.lv); return value; }) this.setState({ citydata:data.data, aqi:data.aqi}); }) } callback=(key)=>{ this.getData(cities[key]) } componentDidMount(){ this.getData('徐州'); } render(){ return ( <div className={styles.pageContent}> <Tabs className={styles.tabList} onChange={this.callback}> { cities.map((data,i)=>{ return ( <Tabs.TabPane tab={data} key={i}> <Row> <Col span={8} > <MeterShart aqi={this.state.aqi}/> </Col> <Col span={16} > <h2>{data}市AQI指数直方图分析</h2> <SimpleColumnChart citydata={this.state.citydata}/> </Col> </Row> <h3>AQI与PM2.5分析图</h3> <CurveChart dataSource={this.state.citydata}/> </Tabs.TabPane> ) }) } </Tabs> </div> ) } } export default Monitor;
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.ui.toolbar.item.SaveToServiceItem'); goog.require('audioCat.action.ActionType'); goog.require('audioCat.service.EventType'); goog.require('audioCat.ui.toolbar.item.Item'); goog.require('audioCat.ui.toolbar.item.Item.createIcon'); goog.require('goog.events'); /** * A toolbar item for saving to a service that we integrate with. * @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions. * @param {!audioCat.service.Service} service Integrates with some other * service. * @param {!audioCat.state.editMode.EditModeManager} editModeManager Manages the * current edit mode. * @param {!audioCat.action.ActionManager} actionManager Manages actions. * @param {!audioCat.ui.tooltip.ToolTip} toolTip Displays tips sometimes after * user hovers over something. * @constructor * @extends {audioCat.ui.toolbar.item.Item} */ audioCat.ui.toolbar.item.SaveToServiceItem = function( domHelper, service, editModeManager, actionManager, toolTip) { /** * The service to save to. * @private {!audioCat.service.Service} */ this.service_ = service; var label = 'Save project to ' + service.getServiceName() + '.'; audioCat.ui.toolbar.item.SaveToServiceItem.base( this, 'constructor', domHelper, editModeManager, actionManager, toolTip, label, undefined, undefined, label); this.activateOrDeactivate_(); /** * A list of keys of events to possibly clean up later. * @private {!Array.<goog.events.Key>} */ this.listenKeys_ = [ goog.events.listen(service, audioCat.service.EventType.SHOULD_SAVE_STATE_CHANGED, this.activateOrDeactivate_, false, this) ]; }; goog.inherits( audioCat.ui.toolbar.item.SaveToServiceItem, audioCat.ui.toolbar.item.Item); /** * Activates the button. * @private */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.activate_ = function() { this.domHelper.listenForUpPress( this.getDom(), this.handleUpPress_, false, this); this.setVisualizeEnabledState(true); }; /** * De-activates the item. * @private */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.deActivate_ = function() { this.domHelper.unlistenForUpPress( this.getDom(), this.handleUpPress_, false, this); this.setVisualizeEnabledState(false); }; /** * Handles what happens when the command history changes. * @private */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.activateOrDeactivate_ = function() { if (this.service_.getSaveNeeded()) { this.activate_(); } else { this.deActivate_(); } }; /** * Executes an undo. * @private */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.handleUpPress_ = function() { var action = /** @type {!audioCat.action.service.SaveToServiceAction} */ ( this.actionManager.retrieveAction( audioCat.action.ActionType.SAVE_TO_SERVICE)); // Save the current project to the service. action.doAction(); }; /** @override */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.getInternalDom = function() { return audioCat.ui.toolbar.item.Item.createIcon( this.domHelper, 'images/' + this.service_.getSaveIconImage()); }; /** @override */ audioCat.ui.toolbar.item.SaveToServiceItem.prototype.cleanUp = function() { goog.base(this, 'cleanUp'); for (var i = 0; i < this.listenKeys_.length; ++i) { goog.events.unlistenByKey(this.listenKeys_[i]); } };
const FRONTEND_PORT = 8080 const BACKEND_PORT = 8081 const webpack = require('webpack') const WebpackDevServer = require('webpack-dev-server') const express = require('express') const compression = require('compression') const config = require('./webpack.config') const moment = require('moment') new WebpackDevServer(webpack(config), config.devServer) .listen(FRONTEND_PORT, 'localhost', (err, result) => { if (err) { return console.log(err) } console.log('Listening at http://localhost:8080/') }) const getRandom = arr => { const index = Math.round(Math.random() * (arr.length - 1)) return arr[index] } const getDate = () => { let date = moment('2016-01-01') //Add a rand num of days to the start date const r = Math.round(Math.random() * 362) //open 363 days per year date.add(r, 'days') return date } const manufacturers = ['Levi\'s', 'Diesel', 'Wrangler', 'Pepe Jeans', 'Armani Jeans', 'G-Star Raw','Jean Machine'] const deliveryCountries = ['Russia', 'Germany', 'Turkey', 'France', 'United Kingdom', 'Italy', 'Spain',] const genders = ['Male', 'Female'] const sizes = ['28/28','28/30','30/30','30/32','32/32','32/34','34/34','34/36','36/36'] const colors = ['Black', 'Grey', 'Dark Blue','Light Blue'] const styles = ['Normal', 'Relaxed', 'Straight','Slim','Skinny','Boot Cut'] let sales = [] const TOTAL = 100000 console.log(`generating ${TOTAL} rows of random json`) for (let i = 0; i < TOTAL; i++) { const date = getDate() const manufacturer = getRandom(manufacturers) const deliveryCountry = getRandom(deliveryCountries) const gender = getRandom(genders) const size = getRandom(sizes) const color = getRandom(colors) const style = getRandom(styles) const randSale = { date, manufacturer, deliveryCountry, gender, size, color, style, } sales.push(randSale) } sales.sort((a, b) => a.date.unix() - b.date.unix()) console.log('done') createBackendServer = PORT => { const app = express() app.use(compression()) const seasonMap = {'Winter': 3, 'Spring': 6, 'Summer': 9, 'Autumn': 12} app.get('/api/sales', (req, res) => { const season = req.param('season') const end = seasonMap[season] const start = end - 3 const data = sales.filter(({date}) => { let month = date.month() return date >= start && month < end }) res.send(data) }); app.listen(PORT, () => { console.log(`Backend server listening to port ${PORT}`) }) } // const createAssetsServer = require('./servers/assets.js') createBackendServer(BACKEND_PORT) // createAssetsServer(8080)
let words = [ { "word": "home", "translate1": "дом", "translate2": "домик", "translate3": "хата", "translate4": "хатка" }, { "word": "door", "translate1": "дверь", "translate2": "дверька" }, { "word": "deal", "translate1": "сделка", "translate2": "дело", "translate3": "сотрудничество", "translate4": "договор" }, { "word": "son", "translate1": "сын", "translate2": "сыночек", "translate3": "сынишка", "translate4": "сынуля" }, { "word": "voyage", "translate1": "путешествие", "translate2": "рейс", "translate3": "перелет", "translate4": "полет" }, { "word": "pillar", "translate1": "столб", "translate2": "колонна", "translate3": "опора", "translate4": "стержень" } ] import {getRandomInt} from './common'; export class TaskWords { constructor() { this.index = getRandomInt(0, words.length); this.getWord = function () { return words[this.index].word; } } checkWord(str) { for (let key in words[this.index]) { if (words[this.index][key] === str) { return true; } } return false; } }
$(function () { var count = 0; var images = ["./images/mainvisual.jpg", "./images/1.jpg", "./images/2.jpg", "./images/3.jpg"]; function imgChange() { $('#imgArea').css('background-image', 'url(' + images[count] + ')'); if (count == 3) { count = 0; } else { count = count + 1; } } setInterval(imgChange, 3000); });
import React from 'react'; import { View, Text, ActivityIndicator, ScrollView, } from 'react-native'; import Cart from '../../common/Cart.js'; import Operation from '../../common/Operation.js'; import NavBar from '../../common/NavBar'; export default function () { return ( <View class="all"> <NavBar title="ReduxDetail" /> <View style={{ flex: 1 }}> <ScrollView class="main"> { this.state.loading ? <ActivityIndicator class="loading" /> : <View class="detail"> <Text class="title">{this.state.detailData.name}</Text> <Text>{this.state.detailData.des}</Text> <View class="operation"> <Operation class="test" index={this.props.param.id} count={this.props.listDataOrigin[this.props.param.id].count} /> </View> </View> } </ScrollView> <Cart /> </View> </View> ); }
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {StyledIconButton} from "./IconButton.style"; const IconButton = function ({icon, ...props}) { return ( <StyledIconButton className="iconButton" {...props}> <FontAwesomeIcon icon={icon} /> </StyledIconButton> ); }; export default IconButton;
import React from 'react' import { CSSTransition } from "react-transition-group" function wrapAnimation(WrapedComponent){ return class extends React.Component{ render(){ let dir = this.props.location.state?this.props.location.state.dir:"left" return( <CSSTransition in={!!this.props.match} classNames = {{ enter:'animated', enterActive:dir==="right"?'fadeInRight':'fadeInLeft', exit:'animated', exitActive: dir === "left" ? 'fadeOutRight' : 'fadeOutLeft', }} timeout = { 300} mountOnEnter={true} unmountOnExit={true} > <WrapedComponent {...this.props}/> </CSSTransition> ) } } } export default wrapAnimation
module.exports = { secret: process.env.NODE_ENV === 'production' ? process.env.SECRET : 'secret', admin: process.env.NODE_ENV === 'production' ? process.env.ADMIN : 'testtest' }
import setAuthorizationToken from "../utils/setAuthorizationToken"; import {isEmpty} from "lodash"; import {setCurrentUser} from "../Actions/Creators/currentUser"; import jwt from 'jsonwebtoken'; import { store } from '../index' export default function checkAuthrizationToken() { let jwtToken = localStorage.jwtToken; if (jwtToken) { setAuthorizationToken(jwtToken); //TODO Liran: what if the user edited the token? ( null value... ) store.dispatch(setCurrentUser(jwt.decode(jwtToken))) } } export function handleAuthorizationToken(token,dispatch = {}) { localStorage.setItem('jwtToken',token); setAuthorizationToken(token); console.log(jwt.decode(token)); if(isEmpty(dispatch)) { store.dispatch(setCurrentUser(jwt.decode(token))); } else { dispatch(setCurrentUser(jwt.decode(token))); } }
const qsort = (list) => { if(list.length <= 1) { return list; } else { const pivot = list.shift(); return list.filter((x) => x < pivot).push(pivot).push(list.filter((x) => x >= pivot)); } }; let test = [5,4,3,2,1]; console.log(qsort(test));
import connectHistoryApiFallback from 'connect-history-api-fallback' const history = connectHistoryApiFallback({ rewrites: [ { from: /^\/articles\/static.*$/, to(context) { const staticPathWithHistory = context.parsedUrl.pathname.replace('/articles', '') return `/${staticPathWithHistory}` }, }, ], }) module.exports = history
const imgArray = ['images/img1.jpg', 'images/img2.jpg', 'images/img3.jpg', 'images/img4.jpg', 'images/img5.jpg', 'images/img6.jpg', 'images/img1.jpg', 'images/img2.jpg', 'images/img3.jpg', 'images/img4.jpg', 'images/img5.jpg', 'images/img6.jpg']; const shuffArr = shuffleImages(imgArray); const cards = document.querySelectorAll(".back"); const newGameBtn = document.querySelector(".new-game"); const currentScore = document.querySelector("#current-score"); let bestScore = document.querySelector("#best-score"); const lowestScore = document.querySelector("#lowest-score"); const totalClicks = document.querySelector("#clicks"); const closeBtn = document.querySelector(".close"); let cardPlayedNum = 0; let clicks = 0; let cardFlippedNum = 0; let currentCards = []; let pointsWon = 0; let lowestPoints = 0; let highestPoints = 0; let localB = ""; let localL = ""; let abt = document.querySelector(".about"); let play = document.querySelector(".play"); const abtInfo = document.querySelector(".about-info"); let gameboard = document.querySelector(".game-board"); let restartDiv = document.querySelector(".restart-div"); // assign new card randomly document.addEventListener("DOMContentLoaded", function () { imgAssignment(shuffArr); localB = JSON.parse(localStorage.getItem("b")); localL = JSON.parse(localStorage.getItem("l")); if (localB !== null) { bestScore.innerHTML = localB; } if (localL !== null) { lowestScore.innerHTML = JSON.parse(localStorage.getItem("l")); } else { lowestScore.innerHTML = 0; } }); //New game button listener newGameBtn.addEventListener("click", function () { startNewGame(); }); // listener for the close button on the modal after at the end of a game closeBtn.addEventListener("click", function () { location.reload(); }); for (let c of cards) { c.addEventListener("click", function (e) { if (cardPlayedNum < 2) { flip(c); cardPlayedNum += 1; const divFlipped = e.target.parentElement.previousElementSibling; const currentImg = divFlipped.querySelector("img"); currentCards.push(currentImg); clicks += 1; totalClicks.innerText = clicks; } if (cardPlayedNum == 2) { if (currentCards[0].src !== currentCards[1].src) { const timer = setTimeout(function () { for (let i of currentCards) { i.parentElement.nextElementSibling.classList.remove("flipped"); cardPlayedNum = 0; currentCards = []; currentScore.innerText = removePoints(); } }, 1000); } else { cardPlayedNum = 0; currentCards = []; currentScore.innerText = addPoints() cardFlippedNum += 2; } //end of else statement }// end of second if statement gameOver(); lowestPoints = parseInt(lowestScore.innerHTML); highestPoints = parseInt(bestScore.innerHTML); localStorage.setItem('b', highestPoints); localStorage.setItem('l', lowestPoints); }); } function flip(el) { el.classList.add("flipped"); } function getBestScore(sc1, sc2) { if (sc1 > sc2) { sc2 = sc1; } return sc2; } function getLowScore(sc1, sc3) { if (sc1 < sc3) { sc3 = sc1; } else if (sc3 == 0) { sc3 = sc1; } return sc3; } function addPoints() { pointsWon += 100; return pointsWon; } // function removePoints() { if (pointsWon < 30) { pointsWon = 0; } else { pointsWon -= 30; } return pointsWon; } //This function reorder the strings in a given array function shuffleImages(arr) { let temp = ""; for (let i = 0; i < arr.length; i++) { randomIndex = Math.floor(Math.random() * arr.length); temp = arr[i]; arr[i] = arr[randomIndex]; arr[randomIndex] = temp; } return arr; } function imgAssignment(arr) { const front = document.querySelectorAll('.frontImage'); let index = 0; for (let i of front) { i.src = arr[index]; index++; } } //This function is called when on load of the game page //or when the restart game nutton is clicked function startNewGame() { clicks = 0; pointsWon = 0; totalClicks.innerHTML = clicks; currentScore.innerHTML = pointsWon; currentCards = []; imgAssignment(shuffleImages(imgArray)); localB = JSON.parse(localStorage.getItem("b")); localL = JSON.parse(localStorage.getItem("l")); if (localB !== null) { bestScore.innerHTML = localB; } if (localL !== null) { lowestScore.innerHTML = JSON.parse(localStorage.getItem("l")); } const cards = document.querySelectorAll(".back"); for (let c of cards) { flip(c); } const timer = setTimeout(function () { for (let c of cards) { c.classList.remove("flipped"); } pointsWon = 0; }, 700); } function gameOver() { if (cardFlippedNum == 12) { bestScore.innerText = getBestScore(pointsWon, highestPoints); lowestScore.innerText = getLowScore(pointsWon, lowestPoints); const timer = setTimeout(function () { for (let c of cards) { c.classList.remove("flipped"); } }, 1000); $('#final-clicks').text(clicks); $('#final-score').text(pointsWon); $('#gameover').modal('show'); } } abt.addEventListener("click", function (e) { abtInfo.removeAttribute("hidden"); gameboard.setAttribute("hidden", true); restartDiv.setAttribute("hidden", true); }); play.addEventListener("click", function (e) { abtInfo.setAttribute("hidden", true); gameboard.removeAttribute("hidden"); restartDiv.removeAttribute("hidden"); });
import { default as update_190802 } from './190802.js'; import { default as update_191115 } from './191115.js'; export const updates = { 190802: update_190802, 191115: update_191115, };
// actionsTypes export const actionsTypes = { ADD_TO_FAVORITES_LIST: 'ADD_TO_FAVORITES_LIST', REMOVE_FROM_FAVORITES_LIST: 'REMOVE_FROM_FAVORITES_LIST', ADD_TO_ORDERS_LIST: 'ADD_TO_ORDERS_LIST', REMOVE_FROM_ORDERS_LIST: 'REMOVE_FROM_ORDERS_LIST', UPDATE_ORDERS_LIST: 'UPDATE_ORDERS_LIST', }; // actions export const addToFavoritesList = (data) => ({ type: actionsTypes.ADD_TO_FAVORITES_LIST, data: data }); export const removeFromFavoritesList = (data) => ({ type: actionsTypes.REMOVE_FROM_FAVORITES_LIST, data: data }); export const addToOrdersList = (data) => ({ type: actionsTypes.ADD_TO_ORDERS_LIST, data: data }); export const removeFromOrdersList = (data) => ({ type: actionsTypes.REMOVE_FROM_ORDERS_LIST, data: data }); export const updateOrdersList = (data) => ({ type: actionsTypes.UPDATE_ORDERS_LIST, data: data });
import { combineReducers } from "redux"; import hebcal from "./hebcal"; export default combineReducers({ hebcal });
/* eslint-disable prettier/prettier */ import React,{useEffect,useState} from 'react' import { IconButtonPropType } from '../propTypes/ComponentPropTypes' import './style.css' export const IconButton = ( { children, size="medium", variant='simple', onClick, color='', disableRipple= false }) => { const [coords, setCoords] = useState({ x: -1, y: -1 }) const [isRippling, setIsRippling] = useState(false) useEffect(() => { if (coords.x !== -1 && coords.y !== -1) { setIsRippling(true) setTimeout(() => setIsRippling(false), 300) } else setIsRippling(false) }, [coords]) useEffect(() => { if (!isRippling) setCoords({ x: -1, y: -1 }) }, [isRippling]) return <i onClick={(e) => { const rect = e.target.getBoundingClientRect() !disableRipple && setCoords({ x: e.clientX - rect.left, y: e.clientY - rect.top }) onClick && onClick(e) }} className={`icon-button ${color&&`${color}Text`} ${size}Icon material-icons`}> {isRippling ? ( <span className={`ripple ${color&&`${color}Ripple`}`} style={{ left: coords.x, top: coords.y }} /> ) : ( '' )} <span className="content">{children}</span> </i> } IconButton.propTypes = IconButtonPropType;
import React from "react"; import Head from 'next/head' import Image from 'next/image' import Link from "next/link" import styles from "../styles/Home.module.css" import NavLink from './../components/NavLink' import styled from 'styled-components' const NavStyle = styled.nav` a { &[aria-current] { color: #cccccc; } }`; export default function Contact() { return ( <> <NavStyle className="lang"> <NavLink href="/about"><a className="lang_tr">TR</a></NavLink> | <NavLink href="/about-en"><a className="lang_en">EN</a></NavLink> </NavStyle> <div className="container"> <Head> <title>About</title> <meta name="description" content="Generated by create next app" /> <link rel = "icon" href = "https://image.flaticon.com/icons/png/512/2639/2639672.png" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossOrigin="anonymous" referrerpolicy="no-referrer" /> </Head> <div className={styles.about_container}> <h2>About Me</h2> <p> My name is Batuhan. I live in in Istanbul. I am a senior at the Gebze Technical University, and soon to be electronic engineer. As a summary of my university life, I have encountered software in the first year and continued to progress every day by putting on the fundamental knowledge that I learned in school. <p> During this time, I worked on the python language and improved myself in various areas such as image processing, machine learning and signal processing with Python. In addition I made a robot arm and various projects with Arduino. </p> <p> C/C++, Matlab and Python are programming languages that I am good at. Also I am familiar with HTML, CSS and a bit of Flutter. </p> <p> I love the internet, technology, and building beautiful things. Some of my favorite things to do are read, coding and learning new things. </p> <p> My career aspirations are to have a professional career in software development as well as to improve myself in machine learning and deep learning. </p> </p> <h2>Schools</h2> <ul> <li>Okyanus College (2017)</li> <li>Gebze Technical University (2017-2022)</li> </ul> <h2>Experiences</h2> <ul> <li>ASELSAN <span>&#8203;</span> (15.08.2020 - 11.09.2020)</li> <li>Ardıctech (05.07.2021 - )</li> </ul> </div> </div> </> ) }
function aaa(){ console.log('aaa func'); } var a = 0; module.exports.aaa = aaa; module.exports.a = a;
var searchData= [ ['t_5fcola',['t_cola',['../structt__cola.html',1,'']]] ];
var planets = ["images/mercury.jpg","images/venus.jpg","images/earth.jpg","images/mars.jpg","images/jupiter.jpg","images/saturn.jpg","images/uranus.jpg","images/neptune.jpg","images/pluto.jpg"]; var img = document.getElementById("planet"); var num = 0; var names = ['Mercury','Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']; var heading = document.getElementById("heading"); function prev(){ num--; if(num <= 0){ num = planets.length - 1; } img.src = planets[num]; heading.innerHTML = names[num]; } function next(){ num++; if(num >= planets.length - 1){ num = 0; } img.src = planets[num]; heading.innerHTML = names[num]; }
import test from "ava"; import http from "http"; import createApp from "../server/app.js"; import createLogger from "../server/logger.js"; import { getResponse, getDocument, createRealWeb, createFakeGames, } from "./_setup.js"; async function assertResponse(t, server, path, status = 200) { const res = await getResponse(server, path); t.is(res.statusCode, status); return res; } function testHeader(t, document, text) {} function testLayout(t, document) { t.truthy(document.querySelector("a[href='/']")); t.truthy(document.querySelector("a[href='/games/']")); } function testMessageDialog(t, document) { const parent = document.getElementById("message"); t.truthy(parent); // The thing is a dialog box. t.true(parent.classList.contains("dialog")); // The dialog is hidden by default. t.true(parent.classList.contains("hide")); // There is a text area. const text = document.getElementById("message-text"); t.truthy(text); t.true(parent.contains(text)); // There is an actions area. const actions = document.getElementById("message-actions"); t.truthy(actions); t.true(parent.contains(actions)); // There is an okay button. const okay = document.getElementById("message-okay"); t.truthy(okay); t.true(parent.contains(okay)); } function testLoadingDialog(t, document) { const parent = document.getElementById("loading"); t.truthy(parent); // The thing is a dialog box. t.true(parent.classList.contains("dialog")); // The dialog is hidden by default. t.true(parent.classList.contains("hide")); // There is a text area. const text = document.getElementById("loading-text"); t.truthy(text); t.true(parent.contains(text)); // There is a busy spinner. const spinner = document.getElementById("loading-spinner"); t.truthy(spinner); t.true(parent.contains(spinner)); } test.before(async (t) => { t.context.web = await createRealWeb(t); }); test("404", async (t) => { const { server, app } = t.context.web; const res = await assertResponse(t, server, "bogus", 404); const document = getDocument(res); testLayout(t, document); testHeader(t, document, app.locals.title); }); test("500", async (t) => { const logger = createLogger(); const games = createFakeGames(); const app = createApp({ games, logger }); // Create a condition that will result in an uncaught exception. app.locals.games = null; const server = http.createServer(app); await new Promise((resolve) => { server.listen(0, async () => { const res = await assertResponse(t, server, "games/", 500); const document = getDocument(res); testLayout(t, document); testHeader(t, document, app.locals.title); server.close(); t.pass(); resolve(); }); }); }); test("/", async (t) => { const { server, app } = t.context.web; const res = await assertResponse(t, server, ""); const document = getDocument(res); testLayout(t, document); testHeader(t, document, app.locals.title); }); test("/games/", async (t) => { const { server, app, games } = t.context.web; const res = await assertResponse(t, server, "games/"); const document = getDocument(res); testLayout(t, document); testHeader(t, document, app.locals.title); // there is a link for each game for (const id of games.keys()) { t.truthy(document.querySelector(`a[href='/games/${id}/']`)); } }); test("/games/:id/", async (t) => { const { server, games } = t.context.web; for (const game of games.values()) { const url = `games/${game.id}/`; const res = await assertResponse(t, server, url); const document = getDocument(res); testLayout(t, document); testHeader(t, document, game.name); testMessageDialog(t, document); testLoadingDialog(t, document); t.truthy(document.querySelector(`a[href='/${url}']`)); // there is a container for the canvases t.truthy(document.getElementById("container")); } });
enyo.depends( "source/Mhd.js", "source/Main.js", "source/Help.js", "source/Mhd.css" );
const express = require('express') const session = require('express-session') require('dotenv').config() const {SESSION_SECRET, SERVER_PORT} = process.env const checkForSession = require('./middlewares/checkForSession') const ctrlSwag = require('./controllers/swag_controller') const ctrlAuth = require('./controllers/auth_controller') const ctrlCart = require('./controllers/cart_controller') const ctrlSearch = require('./controllers/search_controller') let app = express() app.use(express.json()) app.use(session({ secret: SESSION_SECRET, resave: false, saveUninitialized: false })) app.use(checkForSession) app.use(express.static(`${__dirname}/../build`)) app.get('/api/swag' , ctrlSwag.read ) app.post('/api/login', ctrlAuth.login) app.post('/api/register', ctrlAuth.register) app.post('/api/signout', ctrlAuth.signout) app.get('/api/user', ctrlAuth.getUser) app.post('/api/cart', ctrlCart.add) app.post('/api/cart/checkout', ctrlCart.checkout) app.delete('/api/cart', ctrlCart.delete) app.get('/api/search' , ctrlSearch.search) app.listen(SERVER_PORT, () => console.log('Server Listening on ', SERVER_PORT))
import React from 'react'; import { Container, Row, Col } from 'reactstrap'; import './header.css'; import { IoIosHelpCircle, IoMdListBox } from "react-icons/io"; const Logotipo = require("./Logo-Bloop.png"); export default class HeaderLayuot extends React.Component{ render (){ return ( <Container fluid className="Header"> <Row> <Col md="2" className="header"> <img src={Logotipo} className="Logotipo" /> </Col> <Col md="8"> </Col> <Col md="2" className="header2" > <ul> <li className="pt-3"><IoIosHelpCircle /></li> <li><IoMdListBox/></li> </ul> </Col> </Row> </Container> ) } }
import React from 'react' import GlobalStyles from './GlobalStyles' export function Card({ code, origin, destination, name, children }) { return( <div> <GlobalStyles/> <style jsx> { ` h2 { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; font-weight: 700; font-size: 28px; text-align: initial; margin-top: 12px; } div { display: flex; flex-direction: column; justify-content: space-between; align-items: center; box-shadow: 0 0 4px rgba(0,0,0,0.4); border-radius: 20px; width: 320px; height: 440px; } img { width: 97%; height: auto; margin: 3% 0; } span { font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif; font-weight: normal; font-size: 22px; text-align: initial; line-height: 24px; letter-spacing: 1.2px; } .bottom-span { position: relative; bottom: 0; } ` } </style> <h2>{name} ({origin})</h2> <img src='/assets/airplane.jpg' alt={`${origin && origin}${destination && ` to ${destination}`}`}/> <span>Destination: {destination}</span> {children} <span className="bottom-span">{code}</span> </div> ) }
import React from 'react'; import {View,Text,StyleSheet} from 'react-native'; export default class DetailScreen extends React.Component{ constructor(){ super(); this.state={ data:{}, url: `http://localhost:5000/planet?name=${this.props.navigation.getParam("star_name" )}` } } getDetails=()=>{ const {url} = this.state; axios.get(url) .then(response=>{ this.setdetails(response.data.data) }) .catch(error=>{ Alert.alert(error.message) }) } setdetails = details=>{ this.setState({ details:details, }) } componentDidMount(){ this.getDetails() } render(){ return( <View style={{backgroundColor:'cyan',flex:1}}> <Text style={styles.output}>{"star Name: "+this.state.details.star_name}</Text> <Text style={styles.output}>{"Mass: "+this.state.details.mass}</Text> <Text style={styles.output}>{"distance: "+this.state.details.distance}</Text> <Text style={styles.output}>{"Radius: "+this.state.details.radius}</Text> </View> ) } } const styles = StyleSheet.create({ output:{ color:'yellow', fontSize:20 } })
"use strict"; /* Copyright [2014] [Diagramo] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /**This is the main JavaScript module. *We move it here so it will not clutter the index.php with a lot of JavaScript * *ALL VARIABLES DEFINED HERE WILL BE VISIBLE IN ALL OTHER MODULES AND INSIDE INDEX.PHP *SO TAKE CARE! **/ /**Diagramo namespace. We must place as much "global application" variables in here to avoid * conflict and to achieve better management*/ var DIAGRAMO = { /**Set it on true if you want visual debug clues. * Note: See to set the Connector's visualDebug (Connector.visualDebug) to false too **/ debug : false, /**Keeps temporary connector solution. * TODO: move to CONNECTOR_MANAGER?!*/ debugSolutions : [], /** enables/disables rendering of currentCloud * TODO: in further can be used for option like "Show Cloud" or "Highlight about to connect points" */ visualMagnet : true, /** enables/disables rendering fill color as gradient*/ gradientFill : true, /**On canvas fit action this will be the distance between canvas work area and it's border*/ CANVAS_FIT_PADDING : 10 }; /**Switch on/off debug * @param {Boolean} value optional value * */ DIAGRAMO.switchDebug = function(value) { if(value == undefined){ DIAGRAMO.debug = !DIAGRAMO.debug; } else{ DIAGRAMO.debug = value; } var iconDebug = document.getElementById('iconDebug'); if(DIAGRAMO.debug){ iconDebug.src = './assets/images/icon_debug_true.gif'; } else{ iconDebug.src = './assets/images/icon_debug_false.gif'; } draw(); }; /*Activate the bellow block of code if anything else fails *Helped me a lot on a remote iPad (https://bitbucket.org/scriptoid/diagramo/issue/118) *with no available OSX around. *TODO: Could be added as normal lister into a future verbosity option **/ if(false){ /**@see http://stackoverflow.com/questions/10197895/ipad-javascript-error-not-helpful*/ window.onerror = function (desc, page, line, chr){ alert('Description: ' + desc + ' Page: ' + page + ' Line: '+ line + ' Position: '+ chr ); }; } /**Describe the file version of the file * This will make easier to make upgrades in the future. * Any time change in file format will be appear this number * must be increased and also update the importer.js * library * */ DIAGRAMO.fileVersion = 4; /**Activate or deactivate the undo feature *@deprecated ***/ var doUndo = true; /**Usually an instance of a Command (see /lib/commands/*.js)*/ var currentMoveUndo = null; var CONNECTOR_MANAGER = new ConnectorManager(); var CONTAINER_MANAGER = new ContainerFigureManager(); /**An currentCloud - {Array} of 2 {ConnectionPoint} ids. * Cloud highlights 2 {ConnectionPoint}s whose are able to connect. */ var currentCloud = []; /**The width of grid cell. *Must be an odd number. *Must coincide with the size of the image used as canvas tile **/ var GRIDWIDTH = 30; /**The distance (from a snap line) that will trigger a snap*/ var SNAP_DISTANCE = 5; /**The half of light distance between upper and lower border for gradient filling*/ var gradientLightStep = 0.06; var fillColor=null; var strokeColor='#000000'; var currentText=null; /** Instance of Browser Class for defining browser */ var Browser = new Browser(); /**Default top&bottom padding of Text editor's textarea*/ var defaultEditorPadding = 6; /**Default border width of Text editor's textarea*/ var defaultEditorBorderWidth = 1; /** *Scrollbar width *19px is the width added to a scrollable area (Zack discovered this into Chrome) *We might compute this dimension too but for now it's fine *even if we are wrong by a pixel or two **/ var scrollBarWidth = 19; var FIGURE_ESCAPE_DISTANCE = 30; /**the distance by which the connectors will escape Figure's bounds*/ /**the distance by which the connectors will be able to connect with Figure*/ var FIGURE_CLOUD_DISTANCE = 4; /*It will store a reference to the function that will create a figure( ex: figureForKids:buildFigure3()) will be stored into this *variable so upon click on canvas this function will create the object*/ var createFigureFunction = null; /**A variable that tells us if CTRL is pressed*/ var CNTRL_PRESSED = false; /**A variable that tells us if SHIFT is pressed*/ var SHIFT_PRESSED = false; /**Current connector. It is null if no connector selected * @deprecated * TODO: we should base ONLY on selectedConnectorId **/ var connector = null; /**Connector type * TODO: this should not be present here but retrieved from Connector object **/ var connectorType = ''; /**It contains all the figure sets. Each figure set upon loading it will add a new * entry to this array*/ var figureSets = []; /**Used to generate nice formatted SVG files */ var INDENTATION = 0; /**Export the Canvas as SVG. It will descend to whole graph of objects and ask *each one to convert to SVG (and use the proper indentation) *Note: Placed out of editor.php so we can safelly add '<?...' string *@author Alex *@deprecated **/ function toSVG(){ return ''; /* Note: Support for SVG is suspended * var canvas = getCanvas(); //@see http://www.w3schools.com/svg/svg_example.asp var v2 = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; v2 += "\n" + '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' + canvas.width +'" height="' + canvas.height + '" viewBox="0 0 ' + canvas.width + ' ' + canvas.height + '" version="1.1">'; INDENTATION++; v2 += STACK.toSVG(); v2 += CONNECTOR_MANAGER.toSVG(); INDENTATION--; v2 += "\n" + '</svg>'; return v2; */ } /** *Supposelly stop any selection from happening */ function stopselection(ev){ /*If we are selecting text within anything with the className text, we allow it * This gives us the option of using textareas, inputs and any other item we * want to allow text selection in. **/ if(ev.target.className == "text"){ return true; } return false; } var STACK = new Stack(); /**keeps track if the MLB is pressed*/ var mousePressed = false; /**the default application state*/ var STATE_NONE = 'none'; /**we have figure to be created**/ var STATE_FIGURE_CREATE = 'figure_create'; /**we selected a figure (for further editing for example)*/ var STATE_FIGURE_SELECTED = 'figure_selected'; /**we are selecting the start of a connector*/ var STATE_CONNECTOR_PICK_FIRST = 'connector_pick_first'; /**we are selecting the end of a connector*/ var STATE_CONNECTOR_PICK_SECOND = 'connector_pick_second'; /**we selected a connector (for further editing for example)*/ var STATE_CONNECTOR_SELECTED = 'connector_selected'; /**move a connection point of a connector*/ var STATE_CONNECTOR_MOVE_POINT = 'connector_move_point'; /**we are dragging the mouse over a group of figures.*/ var STATE_SELECTING_MULTIPLE = 'selecting_multiple'; /**we have a group selected (either temporary or permanent)*/ var STATE_GROUP_SELECTED = 'group_selected'; /**we have a container selected*/ var STATE_CONTAINER_SELECTED = 'container_selected'; /**we have a text editing*/ //var STATE_TEXT_EDITING = STATE_FIGURE_SELECTED; var STATE_TEXT_EDITING = 'text_editing'; /**Keeps current state*/ var state = STATE_NONE; /**The (current) selection area*/ var selectionArea = new Polygon(); selectionArea.points.push(new Point(0,0)); selectionArea.points.push(new Point(0,0)); selectionArea.points.push(new Point(0,0)); selectionArea.points.push(new Point(0,0)); selectionArea.style.strokeStyle = 'grey'; selectionArea.style.gradientBounds = []; selectionArea.style.lineWidth = '1'; /**Toggle grid visible or not*/ var gridVisible = false; /**Makes figure snap to grid*/ var snapTo = false; /**Keeps last coodinates while dragging*/ var lastClick = []; /**Default line width*/ var defaultLineWidth = 2; /**Default handle line width*/ var defaultThinLineWidth = 1; /**Current instance of TextEditorPopup*/ var currentTextEditor = null; /**Current selected figure id ( -1 if none selected)*/ var selectedFigureId = -1; /**Currently selected figure thumbnail (for D&D)*/ var selectedFigureThumb = null /**Current selected group (-1 if none selected)*/ var selectedGroupId = -1; /**Current selecte connector (-1 if none selected)*/ var selectedConnectorId = -1; /**Current selectet container (-1 if none selected)*/ var selectedContainerId = -1; /**Currently selected ConnectionPoint (if -1 none is selected)*/ var selectedConnectionPointId = -1; /**Set on true while we drag*/ var dragging = false; /**Currently inserted image filename*/ var insertedImageFileName = null; /**Holds a wrapper around canvas object*/ var canvasProps = null; /**Currently holds two elements the type: figure|group and the id*/ var clipboardBuffer = []; /**Return current canvas. * Current canvas will ALWAYS have the 'a' as DOM id * @return {HTMLCanvasElement} the DOM element of <canvas> tag * @author Alex Gheorghiu <alex@scriptoid.com> **/ function getCanvas(){ var canvas = document.getElementById("a"); return canvas; } /**Return work area container. * Work area container will ALWAYS have the 'container' as DOM id * @return {HTMLElement} the DOM element of work area container * @author Artyom Pokatilov <artyom.pokatilov@gmail.com> **/ function getWorkAreaContainer(){ /**Id of work area HTML element, which includes canvas*/ var workAreaContainer = document.getElementById("container"); return workAreaContainer; } /**Return the 2D context of current canvas * @author Alex Gheorghiu <alex@scriptoid.com> **/ function getContext(){ var canvas = getCanvas(); if(canvas.getContext){ return canvas.getContext("2d"); } else{ alert('You need a HTML5 web browser. Any Safari,Firefox, Chrome or Explorer supports this.'); } } /**Keeps current figure set id*/ var currentSetId = 'basic'; /** * Reveals the figure set named by 'name' and hide previously displayed set * @param {String} id - the (div) id value of the set * @author Alex **/ function setFigureSet(id){ Log.info("main.js id = " + id); //alert(name); var div = document.getElementById(id); if(div != null){ if(currentSetId != null){ Log.info("main.js currentSetId = " + currentSetId); var currentFigureSet = document.getElementById(currentSetId); currentFigureSet.style.display = 'none'; } div.style.display = 'block'; currentSetId = id; } } /**Update an object (Figure or Connector) *@param {Number} shapeId - the id of the updating object *@param {String} property - (or an {Array} of {String}s). The 'id' under which the property is stored *TODO: is there any case where we are using property as an array ? *@param {String} newValue - the new value of the property *@param {Boolean} [skipCommand = false] - if true than current {Command} won't be added to the {History} *@param {String} [previousValue] - the previous value of the property *@author Zack, Alex, Artyom **/ function updateShape(shapeId, property, newValue, skipCommand, previousValue){ //Log.group("main.js-->updateFigure"); //Log.info("updateShape() figureId: " + figureId + " property: " + property + ' new value: ' + newValue); // set default values of optional params skipCommand = skipCommand || false; var obj = STACK.figureGetById(shapeId); //try to find it inside {Figure}s //TODO: this horror must dissapear if(!obj){ obj = CONNECTOR_MANAGER.connectorGetById(shapeId); } //container? if(!obj){ obj = STACK.containerGetById(shapeId); } var objSave = obj; //keep a reference to initial shape /*Example of property 'primitives.1.str' */ var props = property.split("."); //Log.info("Splitted props: " + props); /*Going down the object's hierarchy down to the property's parent *Example: * for props = ['primitives','1','str'] * figure * |_primitives * |_1 (it's a Text) * |_str */ //Log.info("Object before descend: " + obj.oType); var figure = obj; //TODO: Why this variable when we already have objSave? for(var i = 0; i<props.length-1; i++){ obj = obj[props[i]]; } //the property name var propName = props[props.length -1]; //Log.info("updateShape(): last property: " + propName); //Log.info("updateShape(): last object in hierarchy: " + obj.oType); /*Now we are located at Figure level or somewhere in a primitive or another object. *Here we will search for setXXX (where XXX is the property name) method first and if we find one we will use it *if not we will simply update the property directly. **/ /**Compute setXXX and getXXX*/ var propSet = "set" + Util.capitaliseFirstLetter(propName); var propGet = "get" + Util.capitaliseFirstLetter(propName); if(propSet in obj){ //@see https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/in_Operator /*If something is complicated enough to need a function, * likelyhood is it will need access to its parent figure. *So we will let the parent to do the update as it likes, if it has * a method of form set<property_name> in place */ if((typeof(previousValue) !== 'undefined' && previousValue != obj[propGet]) || (typeof(previousValue) === 'undefined' && newValue != obj[propGet]())){ //update ONLY if new value differ from the old one //Log.info('updateShape() : penultimate propSet: ' + propSet); var undo = new ShapeChangePropertyCommand(shapeId, property, newValue, previousValue); undo.execute(); if (!skipCommand) { History.addUndo(undo); } } //Log.info('updateShape() : call setXXX on object: ' + propSet + " new value: " + newValue); // obj[propSet](figure,newValue); //TODO: Do we really need this anymore? obj[propSet](newValue); } else{ if( (typeof(previousValue) !== 'undefined' && obj[propName] != previousValue) || (typeof(previousValue) === 'undefined' && obj[propName] != newValue)){ //try to change it ONLY if new value is different than the last one var undo = new ShapeChangePropertyCommand(shapeId, property, newValue, previousValue); undo.execute(); if (!skipCommand) { History.addUndo(undo); } obj[propName] = newValue; } } //connector's text special case if(objSave instanceof Connector && propName == 'str'){ //Log.info("updateShape(): it's a connector 2"); objSave.updateMiddleText(); } //Log.groupEnd(); draw(); } /**Setup the editor panel for a special shape. *@param shape - can be either Connector or Figure. If null is provided the *editor panel will be disabled **/ function setUpEditPanel(shape){ //var propertiesPanel = canvas.edit; //access the edit div var propertiesPanel = document.getElementById("edit"); propertiesPanel.innerHTML = ""; if(shape == null){ //do nothing } else{ switch(shape.oType){ case 'Group': //do nothing. We do not want to offer this to groups break; case 'Container': Builder.constructPropertiesPanel(propertiesPanel, shape); break; case 'CanvasProps': Builder.constructCanvasPropertiesPanel(propertiesPanel, shape); break; default: //both Figure and Connector Builder.constructPropertiesPanel(propertiesPanel, shape); } } } /**Setup edit mode for Text primitive. *@param shape - parent of Text primitive. Can be either {Connector} or {Figure}. *@param {Number} textPrimitiveId - the id value of Text primitive (from {Stack} *@author Artyom **/ function setUpTextEditorPopup(shape, textPrimitiveId) { // get elements of Text Editor and it's tools var textEditor = document.getElementById('text-editor'); //a <div> inside editor page var textEditorTools = document.getElementById('text-editor-tools'); //a <div> inside editor page // set current Text editor to use it further in code currentTextEditor = Builder.constructTextPropertiesPanel(textEditor, textEditorTools, shape, textPrimitiveId); } /**Setup the creation function (that -later, upon calling - will create the actual {Figure} * Note: It will also set the current state to STATE_FIGURE_CREATE * @param {Function} fFunction - the function used to create the figure * @param {String} thumbURL - the URL to the thumb of the image **/ function createFigure(fFunction, thumbURL){ //Log.info('createFigure (' + fFunction + ',' + thumbURL + ')'); createFigureFunction = fFunction; selectedFigureThumb = thumbURL; selectedFigureId = -1; selectedConnectorId = -1; selectedConnectionPointId = -1; if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } state = STATE_FIGURE_CREATE; draw(); } /* * Resets any state to STATE_NONE */ function resetToNoneState() { // clear text editing mode if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } // deselect everything selectedFigureId = -1; selectedConnectionPointId = -1; selectedConnectorId = -1; selectedContainerId = -1; // if group selected if (state == STATE_GROUP_SELECTED) { var selectedGroup = STACK.groupGetById(selectedGroupId); // if group is temporary then destroy it if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } //deselect current group selectedGroupId = -1; } state = STATE_NONE; } // Id of the DOM object for errors of image upload var uploadImageErrorDivId = 'upload-image-error'; /** Show "Insert image" dialog * Insert image dialog can be triggered in 1 case: * 1 - from quick toolbar * Description: * Call popup to get image from url or upload target image from local * @author Artyom Pokatilov <artyom.pokatilov@gmail.com> **/ function showInsertImageDialog(){ resetToNoneState(); draw(); setUploadedImagesList(); var dialogContent = document.getElementById('insert-image-dialog'); $.modal(dialogContent,{minWidth:'380px', containerId: 'upload-image-dialog', overlayClose: true}); // update dialog's position $.modal.setPosition(); // empty upload errors in dialog var errorDiv = document.getElementById(uploadImageErrorDivId); errorDiv.innerHTML = ''; } /** Show filenames of uploaded images in "Insert image" dialog * Get filenames from server and insert them into dialog * @author Artyom Pokatilov <artyom.pokatilov@gmail.com> **/ function setUploadedImagesList(){ //see: http://api.jquery.com/jQuery.get/ $.post("./common/controller.php", {action: 'getUploadedImageFileNames'}, function(data){ var list = document.getElementById('insert-image-reuse'); var reuseGroup = document.getElementById('insert-image-reuse-group'); data = JSON.parse(data); if (data != null && data.length) { var i, length = data.length, option; // add options with filenames to select for (i = 0; i < length; i++) { option = document.createElement('option'); option.value = data[i]; option.textContent = data[i]; list.appendChild(option); } // enable reuse select and group button list.disabled = false; reuseGroup.disabled = false; } else { // disable reuse select and group button list.disabled = true; reuseGroup.disabled = true; } } ); } /** Insert image into current diagram * Insert image can be triggered in 1 case: * 1 - from insert image dialog * * @param {String} imageFileName - filename of uploaded image * @param {String} errorMessage - error message * * Description: * 1) Call popup to get image from url or upload target image from local * 2) Save image to backend * 3) Close popup * 4) If there were errors - go to 5 else - go to 6 * 5) Alert error message * 6) Create figure with target image and text caption * * @author Artyom Pokatilov <artyom.pokatilov@gmail.com> **/ function insertImage(imageFileName, errorMessage){ if (errorMessage) { // set upload errors to dialog var errorDiv = document.getElementById(uploadImageErrorDivId); errorDiv.innerHTML = errorMessage; // update dialog's position $.modal.setPosition(); } else { // close current insert image dialog $.modal.close(); insertedImageFileName = imageFileName; action('insertImage'); } } /**Activate snapToGrip option*/ function snapToGrid(){ Log.info("snapToGrid called;"); snapTo =! snapTo; if(snapTo){ if(!gridVisible){ gridVisible = true; backgroundImage = null; // reset cached background image of canvas document.getElementById("gridCheckbox").checked = true; //trigger a repaint; draw(); } } } /**Makes grid visible or invisible, depedinding of previous value *If the "snap to" was active and grid made invisible the "snap to" *will be disabled **/ function showGrid(){ /**If grid was visible and snap to was check we need to take measures*/ if(gridVisible){ if(snapTo){ snapTo = false; document.getElementById("snapCheckbox").checked = false; } } gridVisible = !gridVisible; backgroundImage = null; // reset cached background image of canvas //trigger a repaint; draw(); } /**Click is disabled because we need to handle mouse down and mouse up....etc etc etc*/ function onClick(ev){ var coords = getCanvasXY(ev); var x = coords[0]; var y = coords[1]; //here is the problem....how do we know we clicked on canvas /*var fig=STACK.figures[STACK.figureGetMouseOver(x,y,null)]; if(CNTRL_PRESSED && fig!=null){ TEMPORARY_GROUP.addPrimitive(); STACK.figureRemove(fig); STACK.figureAdd(TEMPORARY_GROUP); } else if(STACK.figureGetMouseOver(x,y,null)!=null){ TEMPORARY_GROUP.primitives=[]; TEMPORARY_GROUP.addPrimitive(fig); STACK.figureRemove(fig); }*/ //draw(); } /** * @deprecated Does not seem to be used * */ function onDoubleClick(ev){ var coords = getCanvasXY(ev); var HTMLCanvas = getCanvas(); var x = coords[0]; var y = coords[1]; lastClick = [x,y]; // Log.info("onMouseDown at (" + x + "," + y + ")"); //alert('lastClick: ' + lastClick + ' state: ' + state); //mousePressed = true; alert("Double click triggered"); } /**Receives the ASCII character code but not the keyboard code *@param {Event} ev - the event generated when kay is pressed *@see <a href="http://www.quirksmode.org/js/keys.html">http://www.quirksmode.org/js/keys.html</a> **/ function onKeyPress(ev){ //ignore texts if(ev.target.className == "text"){ return true; } draw(); return false; } /** *Receives the key code of keyboard but not the ASCII *Treats the key pressed event *@param {Event} ev - the event generated when key is down *@see <a href="http://www.quirksmode.org/jskey/keys.html">http://www.quirksmode.org/js/keys.html</a> **/ function onKeyDown(ev){ //Log.info("main.js->onKeyDown()->function call. Event = " + ev.type + " IE = " + IE ); //Janis: comout because messes log on SHIFT //1 - avoid text elements (if you are on a text area and you press the arrow you do not want the figures to move on canvas) if( ev.target.className == "text"){ return true; } //2 - "enhance" event TODO: I'm not sure this is really necessary ev.KEY = ev.keyCode; //Log.info("e.keyCode = " + ev.keyCode + " ev.KEY = " + ev.KEY); //Janis: comout because messes log on SHIFT switch(ev.KEY){ case KEY.ESCAPE: //Esc //alert('So do you want to escape me'); //cancel any figure creation createFigureFunction = null; if(selectedFigureId != -1 || selectedConnectionPointId != -1 || selectedConnectorId!=-1){ redraw = true; } //deselect any figure selectedFigureId = -1; selectedConnectionPointId = -1; selectedConnectorId = -1; // clear current text editor if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } state = STATE_NONE; break; case KEY.DELETE: //Delete //delete any Figure or Group // alert('Delete pressed' + this); switch(state){ case STATE_FIGURE_SELECTED: //delete a figure ONLY when the figure is selected if(selectedFigureId != -1){ var cmdDelFig = new FigureDeleteCommand(selectedFigureId); cmdDelFig.execute(); History.addUndo(cmdDelFig); } break; case STATE_GROUP_SELECTED: if(selectedGroupId != -1){ var cmdDelGrp = new GroupDeleteCommand(selectedGroupId); cmdDelGrp.execute(); History.addUndo(cmdDelGrp); } break; case STATE_CONNECTOR_SELECTED: Log.group("Delete connector"); if(selectedConnectorId != -1){ var cmdDelCon = new ConnectorDeleteCommand(selectedConnectorId); cmdDelCon.execute(); History.addUndo(cmdDelCon); } Log.groupEnd(); break; case STATE_CONTAINER_SELECTED: Log.group("Delete container"); if(selectedContainerId != -1){ var cmdDelContainer = new ContainerDeleteCommand(selectedContainerId); cmdDelContainer.execute(); History.addUndo(cmdDelContainer); } Log.groupEnd(); break; } break; case KEY.SHIFT: //Shift SHIFT_PRESSED = true; break; case KEY.CTRL: //Ctrl case KEY.COMMAND_LEFT: case KEY.COMMAND_FIREFOX: CNTRL_PRESSED = true; break; case KEY.LEFT://Arrow Left action("left"); return false; break; case KEY.UP://Arrow Up // alert('up'); action("up"); return false; break; case KEY.RIGHT://Arrow Right action("right"); return false; break; case KEY.DOWN://Arrow Down action("down"); return false; break; case KEY.Z: if(CNTRL_PRESSED){ action('undo'); } break; // case KEY.Y: // if(CNTRL_PRESSED){ // action('redo'); // } // break; case KEY.G: if(CNTRL_PRESSED){ action('group'); } break; case KEY.U: if(CNTRL_PRESSED){ action('ungroup'); } break; case KEY.D: if(CNTRL_PRESSED){ if (ev.preventDefault){ ev.preventDefault(); } else { ev.returnValue = false; } action('duplicate'); } break; case KEY.C: if(CNTRL_PRESSED){ if(selectedFigureId != -1){ clipboardBuffer[0] = "figure"; clipboardBuffer[1] = selectedFigureId; } else if(selectedGroupId != -1){ clipboardBuffer[0] = "group"; clipboardBuffer[1] = selectedGroupId; } else { clipboardBuffer[0] = ""; clipboardBuffer[1] = -1; } } break; case KEY.V: if(CNTRL_PRESSED){ /*Description: * If figure or group copied here is what can happen: * - if no selection -> STATE_NONE: * - if figure copied then duplicate it * - if group copied then check if it`s not permanent, becase then we have lost it, and if not, then duplicate it * - if figure selected (ONLY if figure copied): * - if it is same figure as copied, then duplicate it * also because the duplicate will become selected, add it to the clipboard thus allowing another paste * - if it is another figure, then apply style to it * - if group selected: * //TODO: for Janis see comments/description on GroupCloneCommands * - if it is same group as copied, then duplicate it, in this case we can also duplicate permanent group * also because the duplicate will become selected, add it to the clipboard thus allowing another paste * - if it is another group, and if we have COPIED THE FIGURE, then apply its style to all group * */ if(clipboardBuffer[0]){// if something was copied switch(state){ case STATE_NONE: if(clipboardBuffer[0] == "figure"){ selectedFigureId = clipboardBuffer[1]; action('duplicate'); }else if(clipboardBuffer[0] == "group"){ selectedGroupId = clipboardBuffer[1]; if(STACK.groupGetById(selectedGroupId)){ //if this is true, then the group isn`t permanent action('duplicate'); } } break; case STATE_FIGURE_SELECTED: if(clipboardBuffer[0] == "figure"){ if(clipboardBuffer[1] == selectedFigureId){ action('duplicate'); //this means we add the copied to the clipboard, thus allowing another paste (it is ok, since the style is same) clipboardBuffer[1] = selectedFigureId; }else{ //apply style //TODO: I do think style should be applied by users directly. var copiedFigure = STACK.figureGetById(clipboardBuffer[1]); var selectedFigure = STACK.figureGetById(selectedFigureId); selectedFigure.applyAnotherFigureStyle(copiedFigure); } } break; case STATE_GROUP_SELECTED: if(clipboardBuffer[1] == selectedGroupId){ action('duplicate'); //this means we add the copied to the clipboard, thus allowing another paste (it is ok, since the style is same) clipboardBuffer[1] = selectedGroupId; }else{ //TODO: I do think style should be applied by users directly, even less to spread a figure's style to a whole group if(clipboardBuffer[0] == "figure"){ //if we have copied the figure, apply style to group var copiedFigure = STACK.figureGetById(clipboardBuffer[1]); var groupFigures = STACK.figureGetByGroupId(selectedGroupId); for(var i=0; i<groupFigures.length; i++ ){ groupFigures[i].applyAnotherFigureStyle(copiedFigure); } } } break; } } } break; case KEY.S: if(CNTRL_PRESSED){ //Log.info("CTRL-S pressed "); save(); ev.preventDefault(); } break; case KEY.P: if (currentDiagramId !== null) { if(CNTRL_PRESSED){ Log.info("CTRL-P pressed "); print_diagram(); ev.preventDefault(); } } break; } draw(); return false; } /** *Treats the key up event *@param {Event} ev - the event generated when key is up **/ function onKeyUp(ev){ switch(ev.keyCode){ case KEY.SHIFT: //Shift SHIFT_PRESSED = false; break; case KEY.ALT: //Alt CNTRL_PRESSED = false; break; case KEY.CTRL: //Ctrl CNTRL_PRESSED = false; break; } return false; } /** *Treats the mouse down event *@param {Event} ev - the event generated when button is pressed **/ function onMouseDown(ev){ var coords = getCanvasXY(ev); var HTMLCanvas = getCanvas(); var x = coords[0]; var y = coords[1]; lastClick = [x,y]; // Log.info("onMouseDown at (" + x + "," + y + ")"); //alert('lastClick: ' + lastClick + ' state: ' + state); mousePressed = true; //alert("onMouseDown() + state " + state + " none state is " + STATE_NONE); switch(state){ case STATE_TEXT_EDITING: /*Description: * If we have active text editor in popup and we click mouse. Here is what can happen: * - if we clicked inside current text editor that nothing is happening * - if we clicked canvas: * - we trigger onblur of text editor for IE and FF manually * - we will remove text editor * - we will switch to STATE_NONE * - we will run STATE_NONE case next (without break;) */ if (currentTextEditor.mouseClickedInside(ev)) { break; } else { // IE and Firefox doesn't trigger blur event when mouse clicked canvas // that is why we trigger this event manually if (Browser.msie || Browser.mozilla) { currentTextEditor.blurTextArea(); } currentTextEditor.destroy(); currentTextEditor = null; state = STATE_NONE; } // TODO: Further needs to be the same behaviour as for the STATE_NONE case // to avoid repeating of the code next "break" statement commented to let execution flow down // break; case STATE_NONE: //alert("onMouseDown() - STATE_NONE"); snapMonitor = [0,0]; /*Description: * We are in None state when no action was done....yet. Here is what can happen: * - if we clicked a Connector than that Connector should be selected * (Connectors are more important than Figures :p) * - if we clicked a Group: * - select the Group * - if we clicked a Figure: * - select the Figure * - if we clicked a Container (Figures more important than Container) * - select the Container * - if we did not clicked anything.... * - we will stay in STATE_NONE * - allow to edit canvas * */ var selectedObject = Util.getObjectByXY(x,y); // get object under cursor switch(selectedObject.type) { case 'Connector': selectedConnectorId = selectedObject.id; state = STATE_CONNECTOR_SELECTED; setUpEditPanel(CONNECTOR_MANAGER.connectorGetById(selectedConnectorId)); Log.info('onMouseDown() + STATE_NONE - change to STATE_CONNECTOR_SELECTED'); redraw = true; break; case 'Group': selectedGroupId = selectedObject.id; state = STATE_GROUP_SELECTED; setUpEditPanel(null); Log.info('onMouseDown() + STATE_NONE + group selected => change to STATE_GROUP_SELECTED'); break; case 'Figure': selectedFigureId = selectedObject.id; state = STATE_FIGURE_SELECTED; setUpEditPanel(STACK.figureGetById(selectedFigureId)); Log.info('onMouseDown() + STATE_NONE + lonely figure => change to STATE_FIGURE_SELECTED'); redraw = true; break; case 'Container': selectedContainerId = selectedObject.id; state = STATE_CONTAINER_SELECTED; setUpEditPanel(STACK.containerGetById(selectedContainerId)); Log.info('onMouseDown() + STATE_NONE - change to STATE_CONTAINER_SELECTED'); redraw = true; break; default: //DO NOTHING break; } break; case STATE_FIGURE_CREATE: // selectedConnectorId = -1; // createFigureFunction = null; // // mousePressed = false; // redraw = true; throw "canvas> onMouseDown> STATE_FIGURE_CREATE> : this should not happen"; break; case STATE_FIGURE_SELECTED: snapMonitor = [0,0]; /*Description: * If we have a figure selected and we do click here is what can happen: * - if we clicked a handle of current selected shape (it should be Figure) then just select that Handle * - if we clicked a Connector than it should be selected (Connectors are more important than Figures :p) * - if we clicked a Group: * - if SHIFT is pressed * create a new group of (selectedFigure + parent group of clicked figure) * - else (SHIFT not pressed) * select that group * - if we clicked a Figure: * - did we click same figure? * - do nothing * - did we clicked another figure? * - if SHIFT is pressed * create a new group of (selectedFigure + clicked figure) * - else (SHIFT not pressed) * select that figure * - if we clicked a Container than it should be selected * - if we click on nothing -> * - if SHIFT pressed then State none * - else just keep current state (maybe just missed what we needed) * */ //CONNECTOR if(HandleManager.handleGet(x, y) != null){ //Clicked a handler (of a Figure or Connector) Log.info("onMouseDown() + STATE_FIGURE_SELECTED - handle selected"); /*Nothing important (??) should happen here. We just clicked the handler of the figure*/ HandleManager.handleSelectXY(x, y); } else{ //We did not clicked a handler var selectedObject = Util.getObjectByXY(x,y); // get object under cursor switch(selectedObject.type) { case 'Connector': state = STATE_CONNECTOR_SELECTED; selectedConnectorId = selectedObject.id; selectedFigureId = -1; var con = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId); HandleManager.shapeSet(con); setUpEditPanel(con); Log.info('onMouseDown() + STATE_FIGURE_SELECTED - change to STATE_CONNECTOR_SELECTED'); redraw = true; break; case 'Group': if (SHIFT_PRESSED){ var figuresToAdd = []; /* TODO: for what reason we have this condition in STATE_FIGURE_SELECTED? * Seems like escaping of bigger problem */ if (selectedFigureId != -1){ //add already selected figure figuresToAdd.push(selectedFigureId); } var groupFigures = STACK.figureGetByGroupId(selectedObject.id); for(var i=0; i<groupFigures.length; i++ ){ figuresToAdd.push(groupFigures[i].id); } // create group for current figure joined with clicked group selectedGroupId = STACK.groupCreate(figuresToAdd); Log.info('onMouseDown() + STATE_FIGURE_SELECTED + SHIFT + another group => STATE_GROUP_SELECTED'); }else{ selectedGroupId = selectedObject.id; Log.info('onMouseDown() + STATE_FIGURE_SELECTED + group figure => change to STATE_GROUP_SELECTED'); } selectedFigureId = -1; state = STATE_GROUP_SELECTED; setUpEditPanel(null); redraw = true; break; case 'Figure': //lonely figure if (SHIFT_PRESSED){ var figuresToAdd = []; /* TODO: for what reason we have this condition in STATE_FIGURE_SELECTED? * Seems like escaping of bigger problem */ if (selectedFigureId != -1){ //add already selected figure figuresToAdd.push(selectedFigureId); } figuresToAdd.push(selectedObject.id); //add ONLY clicked selected figure selectedFigureId = -1; // we have two figures, create a group selectedGroupId = STACK.groupCreate(figuresToAdd); state = STATE_GROUP_SELECTED; setUpEditPanel(null); Log.info('onMouseDown() + STATE_FIGURE_SELECTED + SHIFT + min. 2 figures => STATE_GROUP_SELECTED'); }else{ selectedFigureId = selectedObject.id; HandleManager.clear(); setUpEditPanel(STACK.figureGetById(selectedFigureId)); Log.info('onMouseDown() + STATE_FIGURE_SELECTED + single figure => change to STATE_FIGURE_SELECTED (different figure)'); } redraw = true; break; case 'Container': selectedFigureId = -1; selectedContainerId = selectedObject.id; state = STATE_CONTAINER_SELECTED; Log.info('onMouseDown() + STATE_FIGURE_SELECTED + single container - change to STATE_CONTAINER_SELECTED'); setUpEditPanel(STACK.containerGetById(selectedContainerId)); redraw = true; break; default: //mouse down on empty space if (!SHIFT_PRESSED){ //if Shift isn`t pressed selectedFigureId = -1; state = STATE_NONE; setUpEditPanel(canvasProps); Log.info('onMouseDown() + STATE_FIGURE_SELECTED - change to STATE_NONE'); } redraw = true; break; } } break; case STATE_GROUP_SELECTED: /*Description: * If we have a selected group and we pressed the mouse this what can happen: * - if we clicked a handle of current selected shape (asset: it should be Group) then just select that Handle * - if we clicked a Connector than it should be selected (Connectors are more important than Figures or Groups :p) : * - deselect current group * - if current group is temporary (destroy it) * - select that Connector * - if we clicked a Group: * - Clicked the same group as current? * - do nothing * - Clicked another group * - SHIFT is pressed * if current group is temporary * destroy it * merge those 2 groups * - SHIFT not pressed * if current group is temporary * destroy it * clicked group become new selected group * - if we clicked a Figure: * - SHIFT is pressed * add figure to current group * - else (SHIFT not pressed) * if current group is temporary * destroy it * select that figure * - if we clicked a Container than it should be selected * - if we clicked on empty space * - SHIFT _NOT_ pressed * - current group is temporary * delete it * - move to state none */ //GROUPS //if selected group is temporary and we pressed outside of it's border we will destroy it var selectedGroup = STACK.groupGetById(selectedGroupId); if( HandleManager.handleGet(x,y) != null){ //handle ? HandleManager.handleSelectXY(x, y); redraw = true; Log.info('onMouseDown() + STATE_GROUP_SELECTED + handle selected => STATE_GROUP_SELECTED'); } else { // get object under cursor var selectedObject = Util.getObjectByXY(x,y); switch(selectedObject.type) { case 'Connector': //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } //deselect current group selectedGroupId = -1; selectedConnectorId = selectedObject.id; state = STATE_CONNECTOR_SELECTED; redraw = true; Log.info('onMouseDown() + STATE_GROUP_SELECTED + handle selected => STATE_CONNECTOR_SELECTED'); break; case 'Group': if(selectedObject.id != selectedGroupId){ if (SHIFT_PRESSED){ var figuresToAdd = []; //add figures from current group var groupFigures = STACK.figureGetByGroupId(selectedGroupId); for(var i=0; i<groupFigures.length; i++ ){ figuresToAdd.push(groupFigures[i].id); } //add figures from clicked group groupFigures = STACK.figureGetByGroupId(selectedObject.id); for(var i=0; i<groupFigures.length; i++ ){ figuresToAdd.push(groupFigures[i].id); } //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } selectedGroupId = STACK.groupCreate(figuresToAdd); }else{ //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } selectedGroupId = selectedObject.id; } redraw = true; Log.info('onMouseDown() + STATE_GROUP_SELECTED + (different) group figure => STATE_GROUP_SELECTED'); } else{ //figure from same group //do nothing } break; case 'Figure': //lonely figure if (SHIFT_PRESSED){ var figuresToAdd = []; var groupFigures = STACK.figureGetByGroupId(selectedGroupId); for(var i=0; i<groupFigures.length; i++ ){ figuresToAdd.push(groupFigures[i].id); } figuresToAdd.push(selectedObject.id); //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } selectedGroupId = STACK.groupCreate(figuresToAdd); Log.info('onMouseDown() + STATE_GROUP_SELECTED + SHIFT + add lonely figure to other'); }else{ //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } //deselect current group selectedGroupId = -1; state = STATE_FIGURE_SELECTED; selectedFigureId = selectedObject.id; Log.info('onMouseDown() + STATE_GROUP_SELECTED + lonely figure => STATE_FIGURE_SELECTED'); setUpEditPanel(STACK.figureGetById(selectedFigureId)); redraw = true; } break; case 'Container': //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } //deselect current group selectedGroupId = -1; state = STATE_CONTAINER_SELECTED; selectedContainerId = selectedObject.id; Log.info('onMouseDown() + STATE_GROUP_SELECTED + container => STATE_CONTAINER_SELECTED'); setUpEditPanel(STACK.containerGetById(selectedContainerId)); redraw = true; break; default: //mouse down on empty space if (!SHIFT_PRESSED){ //if Shift isn`t pressed if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } selectedGroupId = -1; state = STATE_NONE; setUpEditPanel(canvasProps); redraw = true; Log.info('onMouseDown() + STATE_GROUP_SELECTED + mouse on empty => STATE_NONE'); } break; } } break; case STATE_CONNECTOR_PICK_FIRST: //moved so it can be called from undo action connectorPickFirst(x,y,ev); break; case STATE_CONNECTOR_PICK_SECOND: state = STATE_NONE; break; case STATE_CONNECTOR_SELECTED: /* *Description: *If we have a connector selected and we press mouse here is what is happening: *- mouse down over a connection point? (trat first current connector) * - select connection point * - set state to STATE_CONNECTOR_MOVE_POINT * (and wait mouseMove to alter and mouseUp to finish the modification) * - store original state of the connector (to be able to create the undo command later) *- mouse down over a handler? * - select handle *- mouse down over a connector? * - same connector (do nothing) * - different connector? * - selected clicked connector *- mouse down over a group, figure, container? * - deselect connector * - select clicked object *- mouse down over empty space? * - deselect connector * - select canvasProps **/ var cps = CONNECTOR_MANAGER.connectionPointGetAllByParent(selectedConnectorId); var start = cps[0]; var end = cps[1]; var figureConnectionPointId; //did we click any of the connection points? if(start.point.near(x, y, 3)){ Log.info("Picked the start point"); selectedConnectionPointId = start.id; state = STATE_CONNECTOR_MOVE_POINT; HTMLCanvas.style.cursor = 'default'; //this acts like clone of the connector var undoCmd = new ConnectorAlterCommand(selectedConnectorId); History.addUndo(undoCmd); // check if current cloud for connection point figureConnectionPointId = CONNECTOR_MANAGER.connectionPointGetByXYRadius(x,y, FIGURE_CLOUD_DISTANCE, ConnectionPoint.TYPE_FIGURE, end); if (figureConnectionPointId !== -1) { currentCloud = [selectedConnectionPointId, figureConnectionPointId]; } } else if(end.point.near(x, y, 3)){ Log.info("Picked the end point"); selectedConnectionPointId = end.id; state = STATE_CONNECTOR_MOVE_POINT; HTMLCanvas.style.cursor = 'default'; //this acts like clone of the connector var undoCmd = new ConnectorAlterCommand(selectedConnectorId); History.addUndo(undoCmd); // check if current cloud for connection point figureConnectionPointId = CONNECTOR_MANAGER.connectionPointGetByXYRadius(x,y, FIGURE_CLOUD_DISTANCE, ConnectionPoint.TYPE_FIGURE, start); if (figureConnectionPointId !== -1) { currentCloud = [selectedConnectionPointId, figureConnectionPointId]; } } else{ //no connection point selected //see if handler selected if(HandleManager.handleGet(x,y) != null){ Log.info("onMouseDown() + STATE_CONNECTOR_SELECTED - handle selected"); HandleManager.handleSelectXY(x,y); //TODO: just copy/paste code ....this acts like clone of the connector var undoCmd = new ConnectorAlterCommand(selectedConnectorId); History.addUndo(undoCmd); } else{ // get object under cursor var selectedObject = Util.getObjectByXY(x,y); switch(selectedObject.type) { case 'Connector': if (selectedObject.id != selectedConnectorId) { // select another Connector selectedConnectorId = selectedObject.id; setUpEditPanel(CONNECTOR_MANAGER.connectorGetById(selectedConnectorId)); redraw = true; } break; case 'Group': selectedConnectorId = -1; selectedGroupId = selectedObject.id; // set Group as active element state = STATE_GROUP_SELECTED; setUpEditPanel(null); redraw = true; break; case 'Figure': selectedConnectorId = -1; selectedFigureId = selectedObject.id; // set Figure as active element state = STATE_FIGURE_SELECTED; setUpEditPanel(STACK.figureGetById(selectedFigureId)); redraw = true; break; case 'Container': selectedConnectorId = -1; selectedContainerId = selectedObject.id; // set Container as active element state = STATE_CONTAINER_SELECTED; setUpEditPanel(STACK.containerGetById(selectedContainerId)); redraw = true; break; default: // nothing else selected selectedConnectorId = -1; state = STATE_NONE; setUpEditPanel(canvasProps); // set canvas as active element redraw = true; break; } } } break; //end case STATE_CONNECTOR_SELECTED case STATE_CONTAINER_SELECTED: /*Description: * If we have a Container selected and we do click here is what can happen: * - if we clicked a handle of current selected shape (it should be Container) then just select that Handle * - if we clicked a Connector, Group or than it should be selected (Connectors, Groups and Figures are more important than Containers :p) * - if we clicked a Container: * - did we clicked another Container? * - select that Container * - did we click same Container? * - do nothing */ if(HandleManager.handleGet(x, y) != null){ //Clicked a handler (of a Figure or Connector) Log.info("onMouseDown() + STATE_CONTAINER_SELECTED - handle selected"); /*Nothing important (??) should happen here. We just clicked the handler of the figure*/ HandleManager.handleSelectXY(x, y); } else{ // get object under cursor var selectedObject = Util.getObjectByXY(x,y); switch(selectedObject.type) { case 'Connector': selectedContainerId = -1; selectedConnectorId = selectedObject.id; state = STATE_CONNECTOR_SELECTED; Log.info('onMouseDown() + STATE_CONTAINER_SELECTED - change to STATE_CONNECTOR_SELECTED'); setUpEditPanel(CONNECTOR_MANAGER.connectorGetById(selectedConnectorId)); redraw = true; break; case 'Group': selectedContainerId = -1; selectedGroupId = selectedObject.id; state = STATE_GROUP_SELECTED; Log.info('onMouseDown() + STATE_CONTAINER_SELECTED + group selected => change to STATE_GROUP_SELECTED'); setUpEditPanel(null); redraw = true; break; case 'Figure': selectedContainerId = -1; selectedFigureId = selectedObject.id; state = STATE_FIGURE_SELECTED; Log.info('onMouseDown() + STATE_CONTAINER_SELECTED + lonely figure => change to STATE_FIGURE_SELECTED'); setUpEditPanel(STACK.figureGetById(selectedFigureId)); redraw = true; break; case 'Container': if(selectedObject.id != selectedContainerId){ //a different one selectedContainerId = selectedObject.id; Log.info('onMouseDown() + STATE_NONE - change to STATE_CONTAINER_SELECTED'); setUpEditPanel(STACK.containerGetById(selectedContainerId)); redraw = true; } break; default: // nothing else selected selectedContainerId = -1; state = STATE_NONE; setUpEditPanel(canvasProps); HandleManager.clear(); Log.info('onMouseDown() + STATE_CONTAINER_SELECTED + click on nothing - change to STATE_NONE'); redraw = true; break; } } break; //end STATE_CONTAINER_SELECTED default: //alert("onMouseDown() - switch default - state is " + state); } draw(); return false; } /** *Treats the mouse up event *@param {Event} ev - the event generated when key is up **/ function onMouseUp(ev){ Log.info("main.js>onMouseUp()"); var coords = getCanvasXY(ev); var x = coords[0]; var y = coords[1]; lastClick = []; mousePressed = true; switch(state){ case STATE_NONE: /*Description: * TODO: Nothing should happen here */ if(HandleManager.handleGetSelected()){ HandleManager.clear(); } break; /* treated on the dragging figure case STATE_FIGURE_CREATE: Log.info("onMouseUp() + STATE_FIGURE_CREATE"); snapMonitor = [0,0]; //treat new figure //do we need to create a figure on the canvas? if(createFigureFunction){ Log.info("onMouseUp() + STATE_FIGURE_CREATE--> new state STATE_FIGURE_SELECTED"); var cmdCreateFig = new FigureCreateCommand(createFigureFunction, x, y); cmdCreateFig.execute(); History.addUndo(cmdCreateFig); HTMLCanvas.style.cursor = 'default'; selectedConnectorId = -1; createFigureFunction = null; mousePressed = false; redraw = true; } else{ Log.info("onMouseUp() + STATE_FIGURE_CREATE--> but no 'createFigureFunction'"); } break; */ case STATE_FIGURE_SELECTED: /*Description: * This means that we have a figure selected and just released the mouse: * - if we were altering (rotate/resize) the Figure that will stop (Handler will be deselected) * - if we were moving the figure .... that will stop (but figure remains selected) */ mousePressed = false; HandleManager.handleSelectedIndex = -1; //reset only the handler....the Figure is still selected break; case STATE_CONTAINER_SELECTED: /*Description: * This means that we have a Container selected and just released the mouse: * - if we were altering (rotate/resize) the Container that will stop (Handler will be deselected) * - if we were moving the Container .... that will stop (but figure remains selected) */ mousePressed = false; HandleManager.handleSelectedIndex = -1; //reset only the handler....the Figure is still selected break; case STATE_GROUP_SELECTED: Log.info('onMouseUp() + STATE_GROUP_SELECTED ...'); mousePressed = false; HandleManager.handleSelectedIndex = -1; //reset only the handler....the Group is still selected break; case STATE_SELECTING_MULTIPLE: /*Description *From figures select only those that do not belong to any group **/ Log.info('onMouseUp() + STATE_SELECTING_MULTIPLE => STATE_NONE'); Log.info('onMouseUp() selection area: ' + selectionArea); state = STATE_NONE; var figuresToAdd = []; /* * If SHIFT pressed add the new selection to the already selected figures, * so here add to array already selected ones */ if(SHIFT_PRESSED){ //if one figure already selected add it if (selectedFigureId != -1){ figuresToAdd.push(selectedFigureId); } //if group already selected add it if(selectedGroupId != -1){ var selectedGroup = STACK.groupGetById(selectedGroupId); var groupFigures = STACK.figureGetByGroupId(selectedGroupId); for(var i=0; i<groupFigures.length; i++ ){ figuresToAdd.push(groupFigures[i].id); } } } //add free figures (not belonging to any group) that overlaps with selection region /*TODO: * From Janis to Alex: Why we are selecting only figures that * doesn`t belong to any group, I think we must also add grouped * figures * From Alex to Janis: We do not support groups in groups neither * figures that belong to more than one group */ for(var i = 0; i < STACK.figures.length; i++){ if(STACK.figures[i].groupId == -1){ //we only want ungrouped items var points = STACK.figures[i].getPoints(); if(points.length == 0){ //if no point at least to add bounds TODO: lame 'catch all' condition points.push( new Point(STACK.figures[i].getBounds()[0], STACK.figures[i].getBounds()[1]) ); //top left points.push( new Point(STACK.figures[i].getBounds()[2], STACK.figures[i].getBounds()[3]) ); //bottom right points.push( new Point(STACK.figures[i].getBounds()[0], STACK.figures[i].getBounds()[3]) ); //bottom left points.push( new Point(STACK.figures[i].getBounds()[2], STACK.figures[i].getBounds()[1]) ); //top right } // flag shows if figure added to figuresToAdd array var figureAddFlag = false; /**Idea: We want to select both figures completely encompassed by * selection (case 1) and those that are intersected by selection (case 2)*/ //1 - test if any figure point inside selection for(var a = 0; a < points.length; a++){ if( Util.isPointInside(points[a], selectionArea.getPoints()) ){ figuresToAdd.push(STACK.figures[i].id); // set flag not to add figure twice figureAddFlag = true; break; } } //2 - test if any figure intersected by selection if(!figureAddFlag){ //run this ONLY if is not already proposed for addition figureAddFlag = Util.polylineIntersectsRectangle(points, selectionArea.getBounds(), true); } //select figures whose line intersects selectionArea if (figureAddFlag){ figuresToAdd.push(STACK.figures[i].id); } } //end if } //end for if(selectedGroupId != -1){ var selectedGroup = STACK.groupGetById(selectedGroupId); //destroy current group (if temporary) if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } } //See what to do with collected figures if(figuresToAdd.length >= 2){ //if we selected at least 2 figures then we can create a group selectedGroupId = STACK.groupCreate(figuresToAdd); state = STATE_GROUP_SELECTED; setUpEditPanel(null); //because of shift in this case we also need to reset the edit panel Log.info('onMouseUp() + STATE_SELECTING_MULTIPLE + min. 2 figures => STATE_GROUP_SELECTED'); } else if (figuresToAdd.length == 1){ // if we only select one figure, then it is not a group, it's a simple selection selectedFigureId = figuresToAdd[0]; selectedGroupId = -1; state = STATE_FIGURE_SELECTED; Log.info('onMouseUp() + STATE_SELECTING_MULTIPLE + 1 figure => STATE_FIGURE_SELECTED'); } break; case STATE_CONNECTOR_PICK_SECOND: //store undo command var cmdCreateCon = new ConnectorCreateCommand(selectedConnectorId); History.addUndo(cmdCreateCon); //reset all {ConnectionPoint}s' color CONNECTOR_MANAGER.connectionPointsResetColor(); //reset current connection cloud currentCloud = []; //select the current connector state = STATE_CONNECTOR_SELECTED; var con = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId); setUpEditPanel(con); redraw = true; break; case STATE_CONNECTOR_MOVE_POINT: /** *Description: *Simply alter the connector until mouse will be released **/ //reset all {ConnectionPoint}s' color CONNECTOR_MANAGER.connectionPointsResetColor(); //reset current connection cloud currentCloud = []; state = STATE_CONNECTOR_SELECTED; //back to selected connector selectedConnectionPointId = -1; //but deselect the connection point redraw = true; break; case STATE_CONNECTOR_SELECTED: if(currentMoveUndo){ var turns = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId).turningPoints; var newTurns = [turns.length]; for(var i = 0; i < turns.length; i ++){ newTurns[i] = turns[i].clone(); } currentMoveUndo.currentValue = newTurns; History.addUndo(currentMoveUndo); state = STATE_NONE; selectedConnectorId = -1; HandleManager.clear(); //clear current selection } break; } currentMoveUndo = null; mousePressed = false; draw(); } /**Remembers last move. Initially it's null but once set it's a [x,y] array*/ var lastMove = null; /**It will accumulate the changes on either X or Y coordinates for snap effect. *As we need to escape the "gravity/attraction" of the grid system we need to "accumulate" more changes *and if those changes become greater than a certain threshold we will initiate a snap action *Zack : "Because of the snap to grid function we need to move more than a certain amount of pixels *so we will not be snapped back to the old location" *Initially it's [0,0] but once more and more changes got added a snap effect will be triggered *and some of it's elements will be reset to 0. *So snapMonitor = [sumOfChagesOnX, sumOfChangesOnY] **/ var snapMonitor = [0,0]; /**Treats the mouse move event *@param {Event} ev - the event generated when key is up **/ function onMouseMove(ev){ // //resize canvas. // if(lastMousePosition != null){ // resize(ev); // } var redraw = false; var coords = getCanvasXY(ev); if(coords == null){ Log.error("main.js onMouseMove() null coordinates"); return; } var x = coords[0]; var y = coords[1]; var canvas = getCanvas(); /*change cursor *More here: http://www.javascriptkit.com/dhtmltutors/csscursors.shtml */ Log.debug("onMouseMoveCanvas: test if over a figure: " + x + "," + y); switch(state){ case STATE_NONE: /*Description: * We are in None state when no action was done....yet. Here is what can happen: * - if the mouse is pressed, through onMouseDown(), then it's the begining of a multiple selection * - if mouse is not pressed then change the cursor type to: * - "move" if over a figure or connector * - "default" if over "over a connector "empty" space */ if(mousePressed){ state = STATE_SELECTING_MULTIPLE; selectionArea.points[0] = new Point(x,y); selectionArea.points[1] = new Point(x,y); selectionArea.points[2] = new Point(x,y); selectionArea.points[3] = new Point(x,y);//the selectionArea has no size until we start dragging the mouse Log.debug('onMouseMove() - STATE_NONE + mousePressed = STATE_SELECTING_MULTIPLE'); } else{ if(STACK.figureIsOver(x,y)){ //over a figure canvas.style.cursor = 'move'; Log.debug('onMouseMove() - STATE_NONE - mouse cursor = move (over figure)'); } else if(CONNECTOR_MANAGER.connectorGetByXY(x, y) != -1){ //over a connector canvas.style.cursor = 'move'; Log.debug('onMouseMove() - STATE_NONE - mouse cursor = move (over connector)'); } else if(STACK.containerGetByXY(x,y) != -1){ //container has a lower priority than figure canvas.style.cursor = 'move'; Log.debug("onMouseMove() - STATE_NONE - mouse cursor = move (over container)"); } else{ //default cursor canvas.style.cursor = 'default'; Log.debug('onMouseMove() - STATE_NONE - mouse cursor = default'); } } break; case STATE_SELECTING_MULTIPLE: selectionArea.points[1].x = x; //top right selectionArea.points[2].x = x; //bottom right selectionArea.points[2].y = y; selectionArea.points[3].y = y;//bottom left redraw = true; break; case STATE_FIGURE_CREATE: if(createFigureFunction){ //creating a new figure canvas.style.cursor = 'crosshair'; } break; case STATE_FIGURE_SELECTED: /*Description: * We have a figure selected. Here is what can happen: * - if the mouse is pressed * - if over a Figure's Handler then execute Handler's action * - else (it is over the Figure) * if SHIFT _NOT_ pressed * then move figure * else (SHIFT pressed) * enter STATE_SELECTING_MULTIPLE state * - if mouse is not pressed then change the cursor type to : * - "move" if over a figure or connector * - "handle" if over current figure's handle * - "default" if over "nothing" */ if(mousePressed){ // mouse is (at least was) pressed if(lastMove != null){ //we are in dragging mode /*We need to use handleGetSelected() as if we are using handleGet(x,y) then *as we move the mouse....it can move faster/slower than the figure and we *will lose the Handle selection. **/ var handle = HandleManager.handleGetSelected(); if(handle != null){ //We are over a Handle of selected Figure canvas.style.cursor = handle.getCursor(); handle.action(lastMove,x,y); redraw = true; Log.info('onMouseMove() - STATE_FIGURE_SELECTED + drag - mouse cursor = ' + canvas.style.cursor); } else{ /*no handle is selected*/ if (!SHIFT_PRESSED){//just translate the figure canvas.style.cursor = 'move'; var translateMatrix = generateMoveMatrix(STACK.figureGetById(selectedFigureId), x, y); Log.info("onMouseMove() + STATE_FIGURE_SELECTED : translation matrix" + translateMatrix); var cmdTranslateFigure = new FigureTranslateCommand(selectedFigureId, translateMatrix); History.addUndo(cmdTranslateFigure); cmdTranslateFigure.execute(); /*Algorithm described: if figure belong to an existing container: if we moved it outside of current container (even partially?!) unglue it from container if figure dropped inside a container add it to the (new) container */ var figure = STACK.figureGetById(selectedFigureId); var figBounds = figure.getBounds(); var containerId = CONTAINER_MANAGER.getContainerForFigure(selectedFigureId); if(containerId !== -1){ //we are glued to a container var container = STACK.containerGetById(containerId); var contBounds = container.getBounds(); //Test if figure' bounds are inside container's bounds? if(Util.areBoundsInBounds(figBounds, contBounds)){ //do nothing we are still in same container } else{ //TODO: CONTAINER_MANAGER.removeFigure(containerId, selectedFigureId); //throw "main->onMouseMove->FigureSelected: removed from a container"; CONTAINER_MANAGER.removeFigure(containerId, selectedFigureId); } } else{ //not in any container var newContainerId = -1; for(var c=0; c<STACK.containers.length; c++){ var tempCont = STACK.containers[c]; if( Util.areBoundsInBounds(figBounds, tempCont.getBounds()) ){ newContainerId = STACK.containers[c].id; break; } } if(newContainerId !== -1){ //TODO: add figure to container //throw "main->onMouseMove->FigureSelected: add figure to container"; CONTAINER_MANAGER.addFigure(newContainerId, selectedFigureId); } } redraw = true; Log.info("onMouseMove() + STATE_FIGURE_SELECTED + drag - move selected figure"); }else{ //we are entering a figures selection sesssion state = STATE_SELECTING_MULTIPLE; selectionArea.points[0] = new Point(x,y); selectionArea.points[1] = new Point(x,y); selectionArea.points[2] = new Point(x,y); selectionArea.points[3] = new Point(x,y);//the selectionArea has no size until we start dragging the mouse redraw = true; Log.info('onMouseMove() - STATE_GROUP_SELECTED + mousePressed + SHIFT => STATE_SELECTING_MULTIPLE'); } } } } else{ //no mouse press (only change cursor) var handle = HandleManager.handleGet(x,y); //TODO: we should be able to replace it with .getSelectedHandle() if(handle != null){ //We are over a Handle of selected Figure canvas.style.cursor = handle.getCursor(); Log.info('onMouseMove() - STATE_FIGURE_SELECTED + over a Handler = change cursor to: ' + canvas.style.cursor); } else{ /*move figure only if no handle is selected*/ var tmpFigId = STACK.figureGetByXY(x, y); //pick first figure from (x, y) if(tmpFigId != -1){ canvas.style.cursor = 'move'; Log.info("onMouseMove() + STATE_FIGURE_SELECTED + over a figure = change cursor"); } else{ canvas.style.cursor = 'default'; Log.info("onMouseMove() + STATE_FIGURE_SELECTED + over nothin = change cursor to default"); } } } break; case STATE_TEXT_EDITING: /*Description: * We have a text editor. Here is what can happen: * - if the mouse is pressed * - this should never happen * - if mouse is not pressed then change the cursor type to : * - "move" if over a figure or connector * - "handle" if over current figure's handle * - "default" if over "nothing" */ if (!mousePressed) { var handle = HandleManager.handleGet(x,y); //TODO: we should be able to replace it with .getSelectedHandle() if(handle != null){ //We are over a Handle of selected Figure canvas.style.cursor = handle.getCursor(); Log.info('onMouseMove() - STATE_TEXT_EDITING + over a Handler = change cursor to: ' + canvas.style.cursor); } else{ /*move figure only if no handle is selected*/ var tmpFigId = STACK.figureGetByXY(x, y); //pick first figure from (x, y) if(tmpFigId != -1){ canvas.style.cursor = 'move'; Log.info("onMouseMove() + STATE_TEXT_EDITING + over a figure = change cursor"); } else{ canvas.style.cursor = 'default'; Log.info("onMouseMove() + STATE_TEXT_EDITING + over nothin = change cursor to default"); } } } else { throw "main:onMouseMove() - this should never happen"; } break; case STATE_CONTAINER_SELECTED: //throw "main.js onMouseMove() + STATE_CONTAINER_SELECTED: Not implemented"; //BRUTE COPY FROM FIGURE if(mousePressed){ // mouse is (at least was) pressed if(lastMove != null){ //we are in dragging mode /*We need to use handleGetSelected() as if we are using handleGet(x,y) then *as we move the mouse....it can move faster/slower than the figure and we *will lose the Handle selection. **/ var handle = HandleManager.handleGetSelected(); if(handle != null){ //We are over a Handle of selected Container canvas.style.cursor = handle.getCursor(); handle.action(lastMove,x,y); redraw = true; Log.info('onMouseMove() - STATE_CONTAINER_SELECTED + drag - mouse cursor = ' + canvas.style.cursor); } else{ /*no handle is selected*/ // if (!SHIFT_PRESSED){//just translate the figure canvas.style.cursor = 'move'; var translateMatrix = generateMoveMatrix(STACK.containerGetById(selectedContainerId), x, y); Log.info("onMouseMove() + STATE_CONTAINER_SELECTED : translation matrix" + translateMatrix); var cmdTranslateContainer = new ContainerTranslateCommand(selectedContainerId, translateMatrix); History.addUndo(cmdTranslateContainer); cmdTranslateContainer.execute(); redraw = true; Log.info("onMouseMove() + STATE_CONTAINER_SELECTED + drag - move selected container"); // }else{ //we are entering a figures selection sesssion // state = STATE_SELECTING_MULTIPLE; // selectionArea.points[0] = new Point(x,y); // selectionArea.points[1] = new Point(x,y); // selectionArea.points[2] = new Point(x,y); // selectionArea.points[3] = new Point(x,y);//the selectionArea has no size until we start dragging the mouse // redraw = true; // Log.info('onMouseMove() - STATE_CONTAINER_SELECTED + mousePressed + SHIFT => STATE_SELECTING_MULTIPLE'); // } } } } else{ //no mouse press (only change cursor) var handle = HandleManager.handleGet(x,y); //TODO: we should be able to replace it with .getSelectedHandle() if(handle != null){ //We are over a Handle of selected Figure canvas.style.cursor = handle.getCursor(); Log.info('onMouseMove() - STATE_CONTAINER_SELECTED + over a Handler = change cursor to: ' + canvas.style.cursor); } else{ // throw "main.js onMouseMove() + STATE_CONTAINER_SELECTED: Not implemented"; /*move figure only if no handle is selected*/ if(STACK.containerGetByXY(x, y) !== -1){//pick first container from (x, y) canvas.style.cursor = 'move'; Log.info("onMouseMove() + STATE_CONTAINER_SELECTED + over a container's edge = change cursor"); } else{ canvas.style.cursor = 'default'; Log.debug("onMouseMove() + STATE_CONTAINER_SELECTED + over nothing = change cursor to default"); } } } //END BRUTE COPY FROM FIGURE break; case STATE_GROUP_SELECTED: //Log.info('onMouseMove() - STATE_GROUP_SELECTED ...'); /*Description: *TODO: implement * We have a group selected. Here is what can happen: * - if the mouse is pressed * - if over a Group's Handler then execute Handler's action * - else (it is over one of Group's Figures): * if SHIFT _NOT_ pressed: * then move whole group * else (SHIFT pressed) * enter STATE_SELECTING_MULTIPLE state * - if mouse is not pressed then change the cursor type to : * - drag group? * - cursor ? * - "move" if over a figure or connector or group * - "handle" if over current group's handle * - "default" if over "nothing" */ if(mousePressed){ if(lastMove != null){ //Log.debug('onMouseMove() - STATE_GROUP_SELECTED + mouse pressed'); /*We need to use handleGetSelected() as if we are using handleGet(x,y) then *as we move the mouse....it can move faster/slower than the figure and we *will lose the Handle selection. **/ var handle = HandleManager.handleGetSelected(); if(handle != null){ //over a handle Log.info('onMouseMove() - STATE_GROUP_SELECTED + mouse pressed + over a Handle'); //HandleManager.handleSelectXY(x, y); canvas.style.cursor = handle.getCursor(); handle.action(lastMove, x, y); redraw = true; } else{ //not over any handle -so it must be translating if (!SHIFT_PRESSED){ Log.info('onMouseMove() - STATE_GROUP_SELECTED + mouse pressed + NOT over a Handle'); canvas.style.cursor = 'move'; var mTranslate = generateMoveMatrix(STACK.groupGetById(selectedGroupId), x, y); var cmdTranslateGroup = new GroupTranslateCommand(selectedGroupId, mTranslate); cmdTranslateGroup.execute(); History.addUndo(cmdTranslateGroup); redraw = true; }else{ state = STATE_SELECTING_MULTIPLE; selectionArea.points[0] = new Point(x,y); selectionArea.points[1] = new Point(x,y); selectionArea.points[2] = new Point(x,y); selectionArea.points[3] = new Point(x,y);//the selectionArea has no size until we start dragging the mouse redraw = true; Log.info('onMouseMove() - STATE_GROUP_SELECTED + mousePressed + SHIFT => STATE_SELECTING_MULTIPLE'); } } } } else{ //mouse not pressed (only change cursor) Log.debug('onMouseMove() - STATE_GROUP_SELECTED + mouse NOT pressed'); if(HandleManager.handleGet(x,y) != null){ canvas.style.cursor = HandleManager.handleGet(x,y).getCursor(); } else if(CONNECTOR_MANAGER.connectorGetByXY(x, y) != -1){ //nothing for now } else if(STACK.figureIsOver(x,y)){ canvas.style.cursor = 'move'; } else{ canvas.style.cursor = 'default'; } } break; case STATE_CONNECTOR_PICK_FIRST: //change FCP (figure connection points) color var fCpId = CONNECTOR_MANAGER.connectionPointGetByXY(x, y, ConnectionPoint.TYPE_FIGURE); //find figure's CP if(fCpId != -1){ //we are over a figure's CP var fCp = CONNECTOR_MANAGER.connectionPointGetById(fCpId); fCp.color = ConnectionPoint.OVER_COLOR; // canvas.style.cursor = 'crosshair'; selectedConnectionPointId = fCpId; } else{ //change back old connection point to normal color if(selectedConnectionPointId != -1){ var oldCp = CONNECTOR_MANAGER.connectionPointGetById(selectedConnectionPointId); oldCp.color = ConnectionPoint.NORMAL_COLOR; // canvas.style.cursor = 'normal'; selectedConnectionPointId = -1; } } redraw = true; break; case STATE_CONNECTOR_PICK_SECOND: //moved to allow undo to access it connectorPickSecond(x,y,ev); redraw = true; break; case STATE_CONNECTOR_SELECTED: /*Description: *In case you move the mouse and you have the connector selected: * - if adjusting the endpoints * - alter the shape of connector in real time (gluing and unglued it, etc) * (EXTRA option: do as little changes as possible to existing shape * - if adjusting the handlers * - alter the shape of connector in real time **/ //alert('Move but we have a connector'); //change cursor to move if over a connector's CP //var connector = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId); var cps = CONNECTOR_MANAGER.connectionPointGetAllByParent(selectedConnectorId); var start = cps[0]; var end = cps[1]; if(start.point.near(x, y, 3) || end.point.near(x, y, 3)){ canvas.style.cursor = 'move'; } else if(HandleManager.handleGet(x,y) != null){ //over a handle?. Handles should appear only for selected figures canvas.style.cursor = HandleManager.handleGet(x,y).getCursor(); } else{ canvas.style.cursor = 'default'; } /*if we have a handle action*/ if(mousePressed==true && lastMove != null && HandleManager.handleGetSelected() != null){ Log.info("onMouseMove() + STATE_CONNECTOR_SELECTED - trigger a handler action"); var handle = HandleManager.handleGetSelected(); // alert('Handle action'); /*We need completely new copies of the turningPoints in order to restore them, *this is simpler than keeping track of the handle used, the direction in which the handle edits *and the turningPoints it edits*/ //store old turning points var turns = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId).turningPoints; var oldTurns = [turns.length]; for(var i = 0; i < turns.length; i++){ oldTurns[i] = turns[i].clone(); } //DO the handle action handle.action(lastMove,x,y); //store new turning points turns = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId).turningPoints; var newTurns = [turns.length]; for(var i = 0; i < turns.length; i++){ newTurns[i] = turns[i].clone(); } //see if old turning points are the same as the new turning points var difference = false; for(var k=0;k<newTurns.length; k++){ if(! newTurns[k].equals(oldTurns[k])){ difference = true; } } // //store the Command in History // if(difference && doUndo){ // currentMoveUndo = new ConnectorHandleCommand(selectedConnectorId, History.OBJECT_CONNECTOR, null, oldTurns, newTurns); // History.addUndo(currentMoveUndo); // } redraw = true; } break; case STATE_CONNECTOR_MOVE_POINT: /** *Description: *Adjust on real time - WYSIWYG *-compute the solution *-update connector shape *-update glues *TODO: add description*/ Log.info("Easy easy easy....it's fragile"); if(mousePressed){ //only if we are dragging /*update connector - but not unglue/glue it (Unglue and glue is handle in onMouseUp) *as we want the glue-unglue to produce only when mouse is released*/ connectorMovePoint(selectedConnectionPointId, x, y, ev); redraw = true; } break; } lastMove = [x, y]; if(redraw){ draw(); } return false; } /**Treats the mouse double click event *@param {Event} ev - the event generated when key is clicked twice *@author Artyom, Alex **/ function onDblClick(ev) { var coords = getCanvasXY(ev); var x = coords[0]; var y = coords[1]; lastClick = [x,y]; // store clicked figure or connector var shape = null; // store id value (from Stack) of clicked text primitive var textPrimitiveId = -1; /*Description: *In case you double clicked the mouse: * - if clicked a connector * - save connector to shape * - save id value of text primitive (0 by default) to textPrimitiveId * - else * - if clicked a text inside connector * - save connector to shape * - save id value of text primitive (0 by default) to textPrimitiveId * - else * - if clicked a figure * - if clicked a text primitive of figure * - save figure to shape * - save id value of text primitive to textPrimitiveId * - if connector, text primitive inside connector or figure clicked * - if group selected * - if group is temporary then destroy it * - deselect current group * - deselect current figure * - deselect current connector * - set current state as STATE_TEXT_EDITING * - set up text editor and assign it to currentTextEditor variable * - else do nothing **/ //find Connector at (x,y) var cId = CONNECTOR_MANAGER.connectorGetByXY(x, y); var connector = null; // check if we clicked a connector if(cId != -1){ connector = CONNECTOR_MANAGER.connectorGetById(cId); shape = connector; textPrimitiveId = 0; // (0 by default) } else { cId = CONNECTOR_MANAGER.connectorGetByTextXY(x, y); // check if we clicked a text of connector if (cId != -1) { connector = CONNECTOR_MANAGER.connectorGetById(cId); shape = connector; textPrimitiveId = 0; // (0 by default) } else { //find Figure at (x,y) var fId = STACK.figureGetByXY(x,y); // check if we clicked a figure if (fId != -1) { var figure = STACK.figureGetById(fId); var tId = STACK.textGetByFigureXY(fId, x, y); // if we clicked text primitive inside of figure if (tId !== -1) { shape = figure; textPrimitiveId = tId; } } else { //find Container at (x,y) var contId = STACK.containerGetByXY(x, y); // check if we clicked a container if(contId !== -1){ var container = STACK.containerGetById(contId); var tId = STACK.textGetByContainerXY(contId, x, y); // if we clicked text primitive inside of figure if (tId !== -1) { shape = container; textPrimitiveId = tId; } } } } } // check if we clicked a text primitive inside of shape if (textPrimitiveId != -1) { // if group selected if (state == STATE_GROUP_SELECTED) { var selectedGroup = STACK.groupGetById(selectedGroupId); // if group is temporary then destroy it if(!selectedGroup.permanent){ STACK.groupDestroy(selectedGroupId); } //deselect current group selectedGroupId = -1; } // deselect current figure selectedFigureId = -1; // deselect current container selectedContainerId = -1; // deselect current connector selectedConnectorId = -1; // set current state state = STATE_TEXT_EDITING; // set up text editor setUpTextEditorPopup(shape, textPrimitiveId); redraw = true; } draw(); return false; } /**Pick the first connector we can get at (x,y) position *@param {Number} x - the x position *@param {Number} y - the y position *@param {Event} ev - the event triggered *@author Alex, Artyom **/ function connectorPickFirst(x, y, ev){ Log.group("connectorPickFirst"); //create connector var conId = CONNECTOR_MANAGER.connectorCreate(new Point(x, y),new Point(x+10,y+10) /*fake cp*/, connectorType); selectedConnectorId = conId; var con = CONNECTOR_MANAGER.connectorGetById(conId); //TRY TO GLUE IT //1.get CP of the connector var conCps = CONNECTOR_MANAGER.connectionPointGetAllByParent(conId); //get Figure's id if over it var fOverId = STACK.figureGetByXY(x,y); //get the ConnectionPoint's id if we are over it (and belonging to a figure) var fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXY(x, y, ConnectionPoint.TYPE_FIGURE); //find figure's CP //see if we can snap to a figure if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? var fCp = CONNECTOR_MANAGER.connectionPointGetById(fCpOverId); //update connector' cp conCps[0].point.x = fCp.point.x; conCps[0].point.y = fCp.point.y; //update connector's turning point con.turningPoints[0].x = fCp.point.x; con.turningPoints[0].y = fCp.point.y; var g = CONNECTOR_MANAGER.glueCreate(fCp.id, conCps[0].id, false); Log.info("First glue created : " + g); //alert('First glue ' + g); } else if (fOverId !== -1) { //Are we, at least, over the {Figure}? /*As we are over a {Figure} but not over a {ConnectionPoint} we will switch * to automatic connection*/ var point = new Point(x,y); var candidate = CONNECTOR_MANAGER.getClosestPointsOfConnection( true, // automatic start true, // automatic end fOverId, //start figure's id point, //start point fOverId, //end figure's id point //end point ); var connectionPoint = candidate[0]; //update connector' cp conCps[0].point.x = conCps[1].point.x = connectionPoint.x; conCps[0].point.y = conCps[1].point.y = connectionPoint.y; //update connector's turning point con.turningPoints[0].x = con.turningPoints[1].x = connectionPoint.x; con.turningPoints[0].y = con.turningPoints[1].y = connectionPoint.y; var g = CONNECTOR_MANAGER.glueCreate(candidate[2], conCps[0].id, true); Log.info("First glue created : " + g); } state = STATE_CONNECTOR_PICK_SECOND; Log.groupEnd(); } /**Pick the second {ConnectorPoint} we can get at (x,y) position *@param {Number} x - the x position *@param {Number} y - the y position *@param {Event} ev - the event triggered **/ function connectorPickSecond(x, y, ev){ Log.group("main: connectorPickSecond"); //current connector var con = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId); //it should be the last one var cps = CONNECTOR_MANAGER.connectionPointGetAllByParent(con.id); //get the ConnectionPoint's id if we are over it (and belonging to a figure) var fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXY(x, y, ConnectionPoint.TYPE_FIGURE); //find figure's CP //get Figure's id if over it var fOverId = STACK.figureGetByXY(x,y); //TODO: remove //play with algorithm { //We will try to find the startFigure, endFigure, startPoint, endPoint, etc //start point var rStartPoint = con.turningPoints[0].clone(); var rStartGlues = CONNECTOR_MANAGER.glueGetBySecondConnectionPointId(cps[0].id); var rStartFigure = STACK.figureGetAsFirstFigureForConnector(con.id); if(rStartFigure){ Log.info(":) WE HAVE A START FIGURE id = " + rStartFigure.id); } else{ Log.info(":( WE DO NOT HAVE A START FIGURE"); } //end point var rEndPoint = new Point(x, y); var rEndFigure = null; if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? var r_figureConnectionPoint = CONNECTOR_MANAGER.connectionPointGetById(fCpOverId); Log.info("End Figure's ConnectionPoint present id = " + fCpOverId); //As we found the connection point by a vicinity (so not exactly x,y match) we will adjust the end point too rEndPoint = r_figureConnectionPoint.point.clone(); rEndFigure = STACK.figureGetById(r_figureConnectionPoint.parentId); Log.info(":) WE HAVE AN END FIGURE id = " + rEndFigure.id); } else if (fOverId != -1) { //Are we, at least, over a Figure? Log.info("End Figure connected as automatic"); rEndPoint = new Point(x,y); rEndFigure = STACK.figureGetById(fOverId); Log.info(":) WE HAVE AN END FIGURE id = " + rEndFigure.id); } else{ Log.info(":( WE DO NOT HAVE AN END FIGURE " ); } var rStartBounds = rStartFigure ? rStartFigure.getBounds() : null; var rEndBounds = rEndFigure ? rEndFigure.getBounds() : null; // if start point has automatic glue => connection has automatic start var automaticStart = rStartGlues.length > 0 && rStartGlues[0].automatic; // if end point is over a {Figure}'s {ConnectionPoint} => connection is not automatic // else if end point is over a {Figure} -> connection has automatic end // else -> connection has no automatic end var automaticEnd = fCpOverId != -1 ? false : fOverId != -1; var candidate = CONNECTOR_MANAGER.getClosestPointsOfConnection( automaticStart, //start automatic automaticEnd, //end automatic rStartFigure ? rStartFigure.id : -1, //start figure's id rStartPoint, //start figure's point rEndFigure ? rEndFigure.id : -1, //end figure's id rEndPoint //end figure's point ); DIAGRAMO.debugSolutions = CONNECTOR_MANAGER.connector2Points( con.type, candidate[0], /*Start point*/ candidate[1], /*End point*/ rStartBounds, rEndBounds ); } //end remove block //COLOR MANAGEMENT FOR {ConnectionPoint} //Find any {ConnectionPoint} from a figure at (x,y). Change FCP (figure connection points) color if (fCpOverId != -1 || fOverId != -1) { //Are we over a ConnectionPoint from a Figure or over a Figure? cps[1].color = ConnectionPoint.OVER_COLOR; } else { cps[1].color = ConnectionPoint.NORMAL_COLOR; } var firstConPoint = CONNECTOR_MANAGER.connectionPointGetFirstForConnector(selectedConnectorId); var secConPoint = CONNECTOR_MANAGER.connectionPointGetSecondForConnector(selectedConnectorId); //adjust connector Log.info("connectorPickSecond() -> Solution: " + DIAGRAMO.debugSolutions[0][2]); con.turningPoints = Point.cloneArray(DIAGRAMO.debugSolutions[0][2]); //CONNECTOR_MANAGER.connectionPointGetFirstForConnector(selectedConnectorId).point = con.turningPoints[0].clone(); firstConPoint.point = con.turningPoints[0].clone(); secConPoint.point = con.turningPoints[con.turningPoints.length-1].clone(); // MANAGE TEXT // update position of connector's text con.updateMiddleText(); // before defining of {ConnectionPoint}'s position we reset currentCloud currentCloud = []; //GLUES MANAGEMENT //remove all previous glues to {Connector}'s second {ConnectionPoint} CONNECTOR_MANAGER.glueRemoveAllBySecondId(secConPoint.id); //recreate new glues and currentCloud if available if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? CONNECTOR_MANAGER.glueCreate(fCpOverId, CONNECTOR_MANAGER.connectionPointGetSecondForConnector(selectedConnectorId).id, false); } else if(fOverId != -1){ //Are we, at least, over a Figure? CONNECTOR_MANAGER.glueCreate(candidate[3]/*end Figure's ConnectionPoint Id*/, CONNECTOR_MANAGER.connectionPointGetSecondForConnector(selectedConnectorId).id, true); } else { //No ConnectionPoint, no Figure (I'm lonely) fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXYRadius(x,y, FIGURE_CLOUD_DISTANCE, ConnectionPoint.TYPE_FIGURE, firstConPoint); if(fCpOverId !== -1){ currentCloud = [fCpOverId, secConPoint.id]; } } Log.groupEnd(); } /** *Alter the {Connector} in real time *@param {Number} connectionPointId - the id of the current dragged {ConnectionPoint} *@param {Number} x - the x position *@param {Number} y - the y position *@param {Event} ev - the event triggered **/ function connectorMovePoint(connectionPointId, x, y, ev){ Log.group("main: connectorMovePoint"); //current connector var con = CONNECTOR_MANAGER.connectorGetById(selectedConnectorId); var cps = CONNECTOR_MANAGER.connectionPointGetAllByParent(con.id); //get the ConnectionPoint's id if we are over it (and belonging to a figure) var fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXY(x,y, ConnectionPoint.TYPE_FIGURE); //get Figure's id if over it var fOverId = STACK.figureGetByXY(x,y); // MANAGE TEXT // update position of connector's text con.updateMiddleText(); //MANAGE COLOR //update cursor if over a figure's cp if(fCpOverId != -1 || fOverId != -1){ //Are we over a ConnectionPoint from a Figure or over a Figure? //canvas.style.cursor = 'default'; if(cps[0].id == selectedConnectionPointId){ cps[0].color = ConnectionPoint.OVER_COLOR; } else{ cps[1].color = ConnectionPoint.OVER_COLOR; } } else{ //canvas.style.cursor = 'move'; if(cps[0].id == selectedConnectionPointId){ cps[0].color = ConnectionPoint.NORMAL_COLOR; } else{ cps[1].color = ConnectionPoint.NORMAL_COLOR; } } /*Variables used in finding solution. As we only know the ConnectionPoint's id * (connectionPointId) and the location of event (x,y) we need to find * who is the start Figure, end Figure, starting Glue, ending Glue, etc*/ var rStartPoint = con.turningPoints[0].clone(); var rStartFigure = null; //starting figure (it can be null - as no Figure) var rEndPoint = con.turningPoints[con.turningPoints.length-1].clone(); var rEndFigure = null; //ending figure (it can be null - as no Figure) var rStartGlues = CONNECTOR_MANAGER.glueGetBySecondConnectionPointId(cps[0].id); var rEndGlues = CONNECTOR_MANAGER.glueGetBySecondConnectionPointId(cps[1].id); // before solution we reset currentCloud currentCloud = []; if(cps[0].id == connectionPointId){ //FIRST POINT if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? var r_figureConnectionPoint = CONNECTOR_MANAGER.connectionPointGetById(fCpOverId); //start point and figure rStartPoint = r_figureConnectionPoint.point.clone(); rStartFigure = STACK.figureGetById(r_figureConnectionPoint.parentId); } else if (fOverId != -1) { //Are we, at least, over a Figure? //start point and figure rStartPoint = new Point(x, y); rStartFigure = STACK.figureGetById(fOverId); } else { rStartPoint = new Point(x, y); } //end figure rEndFigure = STACK.figureGetAsSecondFigureForConnector(con.id); var rStartBounds = rStartFigure ? rStartFigure.getBounds() : null; var rEndBounds = rEndFigure ? rEndFigure.getBounds() : null; /** define connection type **/ // if end point has automatic glue -> connection has automatic end var automaticEnd = rEndGlues.length && rEndGlues[0].automatic; // if start point is over figure's connection point -> connection has no automatic start // else if start point is over figure -> connection has automatic start // else -> connection has no automatic start var automaticStart = fCpOverId != -1 ? false : fOverId != -1; var candidate = CONNECTOR_MANAGER.getClosestPointsOfConnection( automaticStart, //start automatic automaticEnd, //end automatic rStartFigure ? rStartFigure.id : -1, //start figure's id rStartPoint, //start figure's point rEndFigure ? rEndFigure.id : -1, //end figure's id rEndPoint //end figure's point ); //solutions DIAGRAMO.debugSolutions = CONNECTOR_MANAGER.connector2Points(con.type, candidate[0], candidate[1], rStartBounds, rEndBounds); //UPDATE CONNECTOR var firstConPoint = CONNECTOR_MANAGER.connectionPointGetFirstForConnector(selectedConnectorId); var secondConPoint = CONNECTOR_MANAGER.connectionPointGetSecondForConnector(selectedConnectorId); //adjust connector Log.info("connectorMovePoint() -> Solution: " + DIAGRAMO.debugSolutions[0][2]); con.turningPoints = Point.cloneArray(DIAGRAMO.debugSolutions[0][2]); firstConPoint.point = con.turningPoints[0].clone(); secondConPoint.point = con.turningPoints[con.turningPoints.length - 1].clone(); //GLUES MANAGEMENT //remove all previous glues to {Connector}'s second {ConnectionPoint} CONNECTOR_MANAGER.glueRemoveAllBySecondId(firstConPoint.id); //recreate new glues and currentCloud if available if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? CONNECTOR_MANAGER.glueCreate(fCpOverId, firstConPoint.id, false); } else if(fOverId != -1){ //Are we, at least, over a Figure? CONNECTOR_MANAGER.glueCreate(candidate[2], firstConPoint.id, true); } else { fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXYRadius(x,y, FIGURE_CLOUD_DISTANCE, ConnectionPoint.TYPE_FIGURE, secondConPoint); if(fCpOverId !== -1){ currentCloud = [fCpOverId, firstConPoint.id]; } } } else if (cps[1].id == connectionPointId){ //SECOND POINT if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? var r_figureConnectionPoint = CONNECTOR_MANAGER.connectionPointGetById(fCpOverId); //end point and figure rEndPoint = r_figureConnectionPoint.point.clone(); rEndFigure = STACK.figureGetById(r_figureConnectionPoint.parentId); } else if (fOverId != -1) { //Are we, at least, over a Figure? //end point and figure rEndPoint = new Point(x, y); rEndFigure = STACK.figureGetById(fOverId); } else { rEndPoint = new Point(x, y); } //start figure rStartFigure = STACK.figureGetAsFirstFigureForConnector(con.id); var rStartBounds = rStartFigure ? rStartFigure.getBounds() : null; var rEndBounds = rEndFigure ? rEndFigure.getBounds() : null; /** define connection type **/ // if start point has automatic glue -> connection has automatic start var automaticStart = rStartGlues.length && rStartGlues[0].automatic; // if end point is over figure's connection point -> connection has no automatic end // else if end point is over figure -> connection has automatic end // else -> connection has no automatic end var automaticEnd = fCpOverId != -1 ? false : fOverId != -1; var candidate = CONNECTOR_MANAGER.getClosestPointsOfConnection( automaticStart, //start automatic automaticEnd, //end automatic rStartFigure ? rStartFigure.id : -1, //start figure's id rStartPoint, //start figure's point rEndFigure ? rEndFigure.id : -1, //end figure's id rEndPoint //end figure point ); //solutions DIAGRAMO.debugSolutions = CONNECTOR_MANAGER.connector2Points(con.type, candidate[0], candidate[1], rStartBounds, rEndBounds); //UPDATE CONNECTOR var firstConPoint = CONNECTOR_MANAGER.connectionPointGetFirstForConnector(selectedConnectorId); var secondConPoint = CONNECTOR_MANAGER.connectionPointGetSecondForConnector(selectedConnectorId); //adjust connector Log.info("connectorMovePoint() -> Solution: " + DIAGRAMO.debugSolutions[0][2]); con.turningPoints = Point.cloneArray(DIAGRAMO.debugSolutions[0][2]); firstConPoint.point = con.turningPoints[0].clone(); secondConPoint.point = con.turningPoints[con.turningPoints.length - 1].clone(); //GLUES MANAGEMENT //remove all previous glues to {Connector}'s second {ConnectionPoint} CONNECTOR_MANAGER.glueRemoveAllBySecondId(secondConPoint.id); //recreate new glues and currentCloud if available if(fCpOverId != -1){ //Are we over a ConnectionPoint from a Figure? CONNECTOR_MANAGER.glueCreate(fCpOverId, secondConPoint.id, false); } else if(fOverId != -1){ //Are we, at least, over a Figure? CONNECTOR_MANAGER.glueCreate(candidate[3], secondConPoint.id, true); } else { fCpOverId = CONNECTOR_MANAGER.connectionPointGetByXYRadius(x,y, FIGURE_CLOUD_DISTANCE, ConnectionPoint.TYPE_FIGURE, firstConPoint); if(fCpOverId !== -1){ currentCloud = [fCpOverId, secondConPoint.id]; } } } else{ throw "main:connectorMovePoint() - this should never happen"; } Log.groupEnd(); } /** Creates a moving matrix taking into consideration the snapTo option * The strange stuff is that Dia (http://projects.gnome.org/dia/) is using a top/left align * but OpenOffice's Draw is using something similar to Diagramo * @return {Matrix} - translation matrix * @param {Object} fig - could be a figure, or a Connector * @param {Number} x - mouse position * @param {Number} y - mouse position * @author Zack Newsham * @author Alex Gheorghiu */ function generateMoveMatrix(fig, x,y){ // Log.group("generateMoveMatrix"); if(typeof x === 'undefined'){ throw "Exception in generateMoveMatrix, x is undefined"; } if(typeof y === 'undefined'){ throw "Exception in generateMoveMatrix, is undefined"; } Log.info("main.js --> generateMoveMatrix x:" + x + ' y:' + y + ' lastMove=[' + lastMove + ']' ); var dx = x - lastMove[0]; var dy = y - lastMove[1]; // Log.info("generateMoveMatrix() - delta " + dx + ', ' + dy); var moveMatrix = null; if(snapTo){ //snap effect moveMatrix = [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; //Log.info("generateMoveMatrix() - old snapMonitor : " + snapMonitor); //Log.info("generateMoveMatrix() - dx : " + dx + " dy: " + dy); snapMonitor[0] += dx; snapMonitor[1] += dy; //Log.info("generateMoveMatrix() - new snapMonitor : " + snapMonitor); //Log.info("generateMoveMatrix() - figure bounds : " + fig.getBounds()); var jump = GRIDWIDTH / 2; //the figure will jump half of grid cell width //HORIZONTAL if(dx != 0){ //dragged to right /*Idea: *As you move the shape to right it might snap to next snap line *regarding figure's start bounds (startNextGridX) *or snap to the snap line regarding figure's end bounds (endNextGridX) *We just need to see to which snap line will actually snap (the one that is closer) **/ var startGridX = ( Math.floor( (fig.getBounds()[0] + snapMonitor[0]) / jump ) + 1 ) * jump; var deltaStart = startGridX - fig.getBounds()[0]; // Log.info("snapMonitor: [" + snapMonitor + "] Start grid X: " + startGridX + "Figure start x: " + fig.getBounds()[0] + " deltaStart: " + deltaStart ); var endGridX = (Math.floor( (fig.getBounds()[2] + snapMonitor[0]) / jump ) + 1) * jump; var deltaEnd = endGridX - fig.getBounds()[2]; if(deltaStart < deltaEnd){ if( fig.getBounds()[0] + snapMonitor[0] >= startGridX - SNAP_DISTANCE ){ moveMatrix[0][2] = deltaStart; snapMonitor[0] -= deltaStart; } else if( fig.getBounds()[2] + snapMonitor[0] >= endGridX - SNAP_DISTANCE ){ moveMatrix[0][2] = deltaEnd; snapMonitor[0] -= deltaEnd; } } else{ if( fig.getBounds()[2] + snapMonitor[0] >= endGridX - SNAP_DISTANCE ){ moveMatrix[0][2] = deltaEnd; snapMonitor[0] -= deltaEnd; } else if( fig.getBounds()[0] + snapMonitor[0] >= startGridX - SNAP_DISTANCE ){ moveMatrix[0][2] = deltaStart; snapMonitor[0] -= deltaStart; } } } //VERTICAL if(dy != 0){ //dragged to bottom var upperGridY = ( Math.floor( (fig.getBounds()[1] + snapMonitor[1]) / jump ) + 1 ) * jump; var deltaUpper = upperGridY - fig.getBounds()[1]; // Log.info("snapMonitor: [" + snapMonitor + "] Upper grid Y: " + upperGridY + "Figure start y: " + fig.getBounds()[1] + " deltaUpper: " + deltaUpper ); var lowerGridY = (Math.floor( (fig.getBounds()[3] + snapMonitor[1]) / jump ) + 1) * jump; var deltaLower = lowerGridY - fig.getBounds()[3]; if(deltaUpper < deltaLower){ if( fig.getBounds()[1] + snapMonitor[1] >= upperGridY - SNAP_DISTANCE ){ moveMatrix[1][2] = deltaUpper; snapMonitor[1] -= deltaUpper; } else if( fig.getBounds()[3] + snapMonitor[1] >= lowerGridY - SNAP_DISTANCE ){ moveMatrix[1][2] = deltaLower; snapMonitor[1] -= deltaLower; } } else{ if( fig.getBounds()[3] + snapMonitor[1] >= lowerGridY - SNAP_DISTANCE ){ moveMatrix[1][2] = deltaLower; snapMonitor[1] -= deltaLower; } else if( fig.getBounds()[1] + snapMonitor[1] >= upperGridY - SNAP_DISTANCE ){ moveMatrix[1][2] = deltaUpper; snapMonitor[1] -= deltaUpper; } } } //Log.info("generateMoveMatrix() - 'trimmed' snapMonitor : " + snapMonitor); } else{ //normal move moveMatrix = [ [1, 0, dx], [0, 1, dy], [0, 0, 1] ]; } Log.groupEnd(); return moveMatrix; } /**Computes the bounds of the canvas **@return {Array} of {Integer} - [xStart, yStart, xEnd, yEnd] **/ function getCanvasBounds(){ var canvasMinX = $("#a").offset().left; var canvasMaxX = canvasMinX + $("#a").width(); var canvasMinY = $("#a").offset().top; var canvasMaxY = canvasMinY + $("#a").height(); return [canvasMinX, canvasMinY, canvasMaxX, canvasMaxY]; } /**Computes the (x,y) coordinates of an event in page *@param {Event} ev - the event **/ function getBodyXY(ev){ return [ev.pageX,ev.pageY];//TODO: add scroll } /** *Extracts the X and Y from an event (for canvas) *@param {Event} ev - the event *@return {Array} of {Integer} - or null if event not inside the canvas **/ function getCanvasXY(ev){ var position = null; var canvasBounds = getCanvasBounds(); // Log.group("main.js->getCanvasXY()"); Log.debug("Canvas bounds: [" + canvasBounds + ']'); var tempPageX = null; var tempPageY = null; if(ev.touches){ //iPad if(ev.touches.length > 0){ tempPageX = ev.touches[0].pageX; tempPageY = ev.touches[0].pageY; } } else{ //normal Desktop tempPageX = ev.pageX; //Retrieves the x-coordinate of the mouse pointer relative to the top-left corner of the document. tempPageY = ev.pageY; //Retrieves the y-coordinate of the mouse pointer relative to the top-left corner of the document. Log.debug("ev.pageX:" + ev.pageX + " ev.pageY:" + ev.pageY); } if(canvasBounds[0] <= tempPageX && tempPageX <= canvasBounds[2] && canvasBounds[1] <= tempPageY && tempPageY <= canvasBounds[3]) { // Log.info('Inside canvas'); position = [tempPageX - $("#a").offset().left, tempPageY - $("#a").offset().top]; //alert("getXT : " + position); } // Log.groupEnd(); return position; } /**Buffered image for background of canvas * It is set to null in CanvasProps::sync() method*/ var backgroundImage = null; /**Adds a background to a canvas * @param {HTMLCanvasElement} canvasElement the <canvas> DOM element * */ function addBackground(canvasElement){ Log.info("addBackground: called"); var ctx = canvasElement.getContext('2d'); // set background image if backgroundImage is null if (!backgroundImage) { // fill canvas with fill color ctx.rect(0,0,canvasElement.width,canvasElement.height); ctx.fillStyle = canvasProps.getFillColor(); ctx.fill(); // draw grid if it's visible if(gridVisible){ var columns = Math.floor(canvasElement.width / GRIDWIDTH) + 1; //console.info("Columns: " + columns ); var rows = Math.floor(canvasElement.height / GRIDWIDTH) + 1; //console.info("Rows: " + rows ); for(var i=0;i<rows; i++){ for(var j=0; j<columns; j++){ ctx.beginPath(); ctx.strokeStyle = '#C0C0C0'; //big cross ctx.moveTo(j * GRIDWIDTH - 2, i * GRIDWIDTH); ctx.lineTo(j * GRIDWIDTH + 2, i * GRIDWIDTH); ctx.moveTo(j * GRIDWIDTH, i * GRIDWIDTH - 2); ctx.lineTo(j * GRIDWIDTH, i * GRIDWIDTH + 2); //small dot ctx.moveTo(j * GRIDWIDTH + GRIDWIDTH/2 - 1, i * GRIDWIDTH + GRIDWIDTH/2); ctx.lineTo(j * GRIDWIDTH + GRIDWIDTH/2 + 1, i * GRIDWIDTH + GRIDWIDTH/2); ctx.stroke(); } } } // set new buffered background image backgroundImage = new Image(); backgroundImage.src = canvasElement.toDataURL(); } else { // backgroundImage.onload = function(e){ // ctx.drawImage(this, 0, 0); // } //end onload // draw buffered background image on canvas ctx.drawImage(backgroundImage, 0, 0); } }//end function /**Cleans up the canvas. It also add a white background to avoid "transparent" *background issue in PNG *@param {HTMLCanvasElement} canvas - the canvas to reset *@author Alex **/ function reset(canvas){ var ctx = canvas.getContext('2d'); ctx.clearRect(0,0,canvas.width,canvas.height); ctx.fillStyle = '#FFFFFF'; ctx.fillRect(0,0,canvas.width,canvas.height); } /**Draws all the stuff on the canvas*/ function draw(){ var ctx = getContext(); // Log.group("A draw started"); //alert('Paint 1') reset(getCanvas()); //if grid visible paint it // if(gridVisible){ //paint grid addBackground(getCanvas()); // } //alert('Paint 2') STACK.paint(ctx); minimap.updateMinimap(); // Log.groupEnd(); //alert('Paint 3') } /** *Returns the canvas data but without the selections and grid. *@return {DOMString} - the result of a toDataURL() call on the temporary canvas *@author Alex *@author Artyom **/ function renderedCanvas(){ var canvas = getCanvas(); //render the canvas without the selection and stuff var tempCanvas = document.getElementById('tempCanvas'); if(tempCanvas === null){ tempCanvas = document.createElement('canvas'); tempCanvas.setAttribute('id', 'tempCanvas'); tempCanvas.style.display = 'none'; //it seems that there is no need to actually add it to the dom tree to be able to render (tested: IE9, FF9, Chrome 19) //canvas.parentNode.appendChild(tempCanvas); } //adjust temp canvas size to main canvas (as it migh have been changed) tempCanvas.setAttribute('width', canvas.width); tempCanvas.setAttribute('height', canvas.height); reset(tempCanvas); addBackground(tempCanvas); STACK.paint(tempCanvas.getContext('2d'), true); //end render return tempCanvas.toDataURL(); } /*Returns a text containing all the URL in a diagram */ function linkMap(){ var csvBounds = ''; var first = true; for(f in STACK.figures){ var figure = STACK.figures[f]; if(figure.url != ''){ var bounds = figure.getBounds(); if(first){ first = false; } else{ csvBounds += "\n"; } csvBounds += bounds[0] + ',' + bounds[1] + ',' + bounds[2] + ',' + bounds[3] + ',' + figure.url; } } Log.info("editor.php->linkMap()->csv bounds: " + csvBounds); return csvBounds; } /** Save current diagram * Save can be triggered in 3 cases: * 1 - from menu * 2 - from quick toolbar * 3 - from shortcut Ctrl-S (onKeyDown) *See: *http://www.itnewb.com/renderedCanvasv/Introduction-to-JSON-and-PHP/page3 *http://www.onegeek.com.au/articles/programming/javascript-serialization.php **/ function save(){ //alert("save triggered! diagramId = " + diagramId ); Log.info('Save pressed'); if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; state = STATE_NONE; } var dataURL = null; try{ dataURL = renderedCanvas(); } catch(e){ if(e.name === 'SecurityError' && e.code === 18){ /*This is usually happening as we load an image from another host than the one Diagramo is hosted*/ alert("A figure contains an image loaded from another host. \ \n\nHint: \ \nPlease make sure that the browser's URL (current location) is the same as the one saved in the DB."); } } // Log.info(dataURL); // return false; if(dataURL == null){ Log.info('save(). Could not save. dataURL is null'); alert("Could not save. \ \n\nHint: \ \nCanvas's toDataURL() did not functioned properly "); return; } var diagram = { c: canvasProps, s:STACK, m:CONNECTOR_MANAGER, p:CONTAINER_MANAGER, v: DIAGRAMO.fileVersion }; //Log.info('stringify ...'); // var serializedDiagram = JSON.stringify(diagram, Util.operaReplacer); var serializedDiagram = JSON.stringify(diagram); // Log.error("Using Util.operaReplacer() somehow break the serialization. o[1,2] \n\ // is transformed into o.['1','2']... so the serialization is broken"); // var serializedDiagram = JSON.stringify(diagram); //Log.info('JSON stringify : ' + serializedDiagram); var svgDiagram = toSVG(); // alert(serializedDiagram); // alert(svgDiagram); //Log.info('SVG : ' + svgDiagram); //save the URLs of figures as a CSV var lMap = linkMap(); //see: http://api.jquery.com/jQuery.post/ $.post("./common/controller.php", {action: 'save', diagram: serializedDiagram, png:dataURL, linkMap: lMap, svg: svgDiagram, diagramId: currentDiagramId}, function(data){ if(data === 'firstSave'){ Log.info('firstSave!'); window.location = './saveDiagram.php'; } else if(data === 'saved'){ //Log.info('saved!'); alert('saved!'); } else{ alert('Unknown: ' + data ); } } ); } /** Print current diagram * Print can be triggered in 3 cases only after diagram was saved: * 1 - from menu * 2 - from quick toolbar * 3 - from Ctrl + P shortcut * * Copy link to saved diagram's png file to src of image, * add it to iframe and call print of last. * * @author Artyom Pokatilov <artyom.pokatilov@gmail.com> **/ function print_diagram() { var printFrameId = "printFrame"; var iframe = document.getElementById(printFrameId); // if iframe isn't created if (iframe == null) { iframe = document.createElement("IFRAME"); iframe.id = printFrameId; document.body.appendChild(iframe); } // get DOM of iframe var frameDoc = iframe.contentDocument; var diagramImages = frameDoc.getElementsByTagName('img'); var diagramImage; if(diagramImages.length > 0) { // if image is already added diagramImage = diagramImages[0]; // set source of image to png of saved diagram diagramImage.setAttribute('src', "data/diagrams/" + currentDiagramId + ".png"); } else { // if image isn't created yet diagramImage = frameDoc.createElement('img'); // set source of image to png of saved diagram diagramImage.setAttribute('src', "data/diagrams/" + currentDiagramId + ".png"); if (frameDoc.body !== null) { frameDoc.body.appendChild(diagramImage); } else { // IE case for more details // @see http://stackoverflow.com/questions/8298320/correct-access-of-dynamic-iframe-in-ie // create body of iframe frameDoc.src = "javascript:'<body></body>'"; // append image through html of <img> frameDoc.write(diagramImage.outerHTML); frameDoc.close(); } } // adjust iframe size to main canvas (as it might have been changed) iframe.setAttribute('width', canvasProps.getWidth()); iframe.setAttribute('height', canvasProps.getHeight()); // print iframe iframe.contentWindow.print(); } /**Exports current canvas as SVG*/ function exportCanvas(){ //export canvas as SVG var v = '<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">\ <rect x="0" y="0" height="200" width="300" style="stroke:#000000; fill: #FFFFFF"/>\ <path d="M100,100 C200,200 100,50 300,100" style="stroke:#FFAAFF;fill:none;stroke-width:3;" />\ <rect x="50" y="50" height="50" width="50"\ style="stroke:#ff0000; fill: #ccccdf" />\ </svg>'; //get svg var canvas = getCanvas(); var v2 = '<svg width="' + canvas.width +'" height="' + canvas.height + '" xmlns="http://www.w3.org/2000/svg" version="1.1">'; v2 += STACK.toSVG(); v2 += CONNECTOR_MANAGER.toSVG(); v2 += '</svg>'; alert(v2); //save SVG into session //see: http://api.jquery.com/jQuery.post/ $.post("../common/controller.php", {action: 'saveSvg', svg: escape(v2)}, function(data){ if(data == 'svg_ok'){ //alert('SVG was save into session'); } else if(data == 'svg_failed'){ Log.info('SVG was NOT save into session'); } } ); //open a new window that will display the SVG window.open('./svg.php', 'SVG', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); } /**Loads a saved diagram *@param {Number} diagramId - the id of the diagram you want to load **/ function load(diagramId){ //alert("load diagram [" + diagramId + ']'); $.post("./common/controller.php", {action: 'load', diagramId: diagramId}, function(data){ // alert(data); try{ var obj = eval('(' + data + ')'); if( !('v' in obj) || obj.v != DIAGRAMO.fileVersion){ Importer.importDiagram(obj);//import 1st version of Diagramo files } STACK = Stack.load(obj['s']); canvasProps = CanvasProps.load(obj['c']); canvasProps.sync(); setUpEditPanel(canvasProps); CONNECTOR_MANAGER = ConnectorManager.load(obj['m']); CONTAINER_MANAGER = ContainerFigureManager.load(obj['p']); draw(); //alert("loaded"); } catch(error) { alert("main.js:load() Exception: " + error); } } ); } /**Loads a saved diagram *@param {String} tempDiagramName - the name of temporary diagram **/ function loadTempDiagram(tempDiagramName){ // alert("load diagram [" + tempDiagramName + ']'); $.post("./common/controller.php", {action: 'loadTemp', tempName: tempDiagramName}, function(data){ // alert(data); try{ var obj = eval('(' + data + ')'); if( !('v' in obj) || obj.v != DIAGRAMO.fileVersion){ Importer.importDiagram(obj);//import 1st version of Diagramo files } STACK = Stack.load(obj['s']); canvasProps = CanvasProps.load(obj['c']); canvasProps.sync(); setUpEditPanel(canvasProps); CONNECTOR_MANAGER = ConnectorManager.load(obj['m']); CONTAINER_MANAGER = ContainerFigureManager.load(obj['p']); draw(); //alert("loaded"); } catch(error) { alert("main.js:load() Exception: " + error); } } ); } function loadQuickStartDiagram(){ $.post("./common/controller.php", {action: 'loadQuickStart'}, function(data){ // alert(data); try{ var obj = eval('(' + data + ')'); if( !('v' in obj) || obj.v != DIAGRAMO.fileVersion){ Importer.importDiagram(obj);//import 1st version of Diagramo files } STACK = Stack.load(obj['s']); canvasProps = CanvasProps.load(obj['c']); canvasProps.sync(); setUpEditPanel(canvasProps); CONNECTOR_MANAGER = ConnectorManager.load(obj['m']); CONTAINER_MANAGER = ContainerFigureManager.load(obj['p']); draw(); //alert("loaded"); } catch(error) { alert("main.js:load() Exception: " + error); } } ); } /**Saves a diagram. Actually send the serialized version of diagram *for saving **/ function saveAs(){ var dataURL = renderedCanvas(); // var $diagram = {c:canvas.save(), s:STACK, m:CONNECTOR_MANAGER}; var $diagram = {c:canvasProps, s:STACK, m:CONNECTOR_MANAGER, p:CONTAINER_MANAGER, v: DIAGRAMO.fileVersion }; var $serializedDiagram = JSON.stringify($diagram); // $serializedDiagram = JSON.stringify($diagram, Util.operaReplacer); var svgDiagram = toSVG(); //save the URLs of figures as a CSV var lMap = linkMap(); //alert($serializedDiagram); //see: http://api.jquery.com/jQuery.post/ $.post("./common/controller.php", {action: 'saveAs', diagram: $serializedDiagram, png:dataURL, linkMap: lMap, svg: svgDiagram}, function(data){ if(data == 'noaccount'){ Log.info('You must have an account to use that feature'); //window.location = '../register.php'; } else if(data == 'step1Ok'){ Log.info('Save as...'); window.location = './saveDiagram.php'; } } ); } /**Add listeners to elements on the page*/ // TODO: set dblclick handler for mobile (touches) function addListeners(){ var canvas = getCanvas(); //add event handlers for Document document.addEventListener("keypress", onKeyPress, false); document.addEventListener("keydown", onKeyDown, false); document.addEventListener("keyup", onKeyUp, false); document.addEventListener("selectstart", stopselection, false); //add event handlers for Canvas canvas.addEventListener("mousemove", onMouseMove, false); canvas.addEventListener("mousedown", onMouseDown, false); canvas.addEventListener("mouseup", onMouseUp, false); canvas.addEventListener("dblclick", onDblClick, false); if(false){ //add listeners for iPad/iPhone //As this was only an experiment (for now) it is not well supported nor optimized ontouchstart="touchStart(event);" ontouchmove="touchMove(event);" ontouchend="touchEnd(event);" ontouchcancel="touchCancel(event);" } } /**Minimap section*/ var minimap; //stores a refence to minimap object (see minimap.js) //TODO: remove reference to JQuery and add a normal listener (for "onmouseup" event) $(document).mouseup( function(){ minimap.selected = false; } ); //TODO: convert to a normal listener (for "onresize" event) window.onresize = function(){ minimap.initMinimap() }; var currentDiagramId = null; /**Initialize the page * @param {Integer} diagramId (optional) the diagram Id to load * */ function init(diagramId){ var canvas = getCanvas(); minimap = new Minimap(canvas, document.getElementById("minimap"), 115); minimap.updateMinimap(); //Canvas properties (width and height) if(canvasProps == null){//only create a new one if we have not already loaded one canvasProps = new CanvasProps(CanvasProps.DEFAULT_WIDTH, CanvasProps.DEFAULT_HEIGHT, CanvasProps.DEFAULT_FILL_COLOR); } //lets make sure that our canvas is set to the correct values canvasProps.setWidth(canvasProps.getWidth()); canvasProps.setHeight(canvasProps.getHeight()); //Browser support and warnings if(isBrowserReady() == 0){ //no support at all modal(); } //Edit panel setUpEditPanel(canvasProps); //loads diagram ONLY if the parameter is numeric if(isNumeric(diagramId)){ currentDiagramId = diagramId; load(diagramId); } else if(diagramId.substring && diagramId.substring(0, 3) === 'tmp'){ //it is a string and starts with "tmp" loadTempDiagram(diagramId); } else if(diagramId === 'quickstart'){ loadQuickStartDiagram(); } // close layer when click-out addListeners(); window.addEventListener("mousedown", documentOnMouseDown, false); window.addEventListener("mousemove", documentOnMouseMove, false); window.addEventListener("mouseup", documentOnMouseUp, false); } /**Flag to inform if to drew or not the diagram. Similar to "Dirty pattern" */ var redraw = false; /** *Dispatch actions. Detect the action needed and trigger it. *@param {String} action - the action name **/ function action(action){ redraw = false; switch(action){ case 'undo': Log.info("main.js->action()->Undo. Nr of actions in the STACK: " + History.COMMANDS.length); History.undo(); redraw = true; break; // case 'redo': // Log.info("main.js->action()->Redo. Nr of actions in the STACK: " + History.COMMANDS.length); // History.redo(); // redraw = true; // break; case 'group': /*After we pressed Ctrl-G any temporary group will became permanent*/ if(selectedGroupId != -1){ var group = STACK.groupGetById(selectedGroupId); if(!group.permanent){ //group only temporary groups var cmdGroup = new GroupCreateCommand(selectedGroupId); cmdGroup.execute(); History.addUndo(cmdGroup); Log.info("main.js->action()->Group. New group made permanent. Group id = " + selectedGroupId); } else{ Log.info("main.js->action()->Group. Group ALREADY permanent. Group id = " + selectedGroupId); } } redraw = true; break; case 'container': Log.info("main.js->action()->container. Nr of actions in the STACK: " + History.COMMANDS.length); if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } //creates a container var cmdContainerCreate = new ContainerCreateCommand(300, 300); cmdContainerCreate.execute(); History.addUndo(cmdContainerCreate); redraw = true; break; case 'insertImage': Log.info("main.js->action()->insertImage. Nr of actions in the STACK: " + History.COMMANDS.length); if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } //creates a container var cmdFigureCreate = new InsertedImageFigureCreateCommand(insertedImageFileName, 100, 100); cmdFigureCreate.execute(); History.addUndo(cmdFigureCreate); redraw = true; break; case 'ungroup': if(selectedGroupId != -1){ var group = STACK.groupGetById(selectedGroupId); if(group.permanent){ //split only permanent groups var cmdUngroup = new GroupDestroyCommand(selectedGroupId); cmdUngroup.execute(); History.addUndo(cmdUngroup); Log.info("main.js->action()->Ungroup. New group made permanent. Group id = " + selectedGroupId); } else{ Log.info("main.js->action()->Ungroup. Ignore. Group is not permanent. Group id = " + selectedGroupId); } redraw = true; } break; case 'connector-jagged': if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } selectedFigureId = -1; state = STATE_CONNECTOR_PICK_FIRST; connectorType = Connector.TYPE_JAGGED; redraw = true; break; case 'connector-straight': if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } selectedFigureId = -1; state = STATE_CONNECTOR_PICK_FIRST; connectorType = Connector.TYPE_STRAIGHT; redraw = true; break; case 'connector-organic': if (state == STATE_TEXT_EDITING) { currentTextEditor.destroy(); currentTextEditor = null; } selectedFigureId = -1; state = STATE_CONNECTOR_PICK_FIRST; connectorType = Connector.TYPE_ORGANIC; redraw = true; break; case 'rotate90': case 'rotate90A': if(selectedFigureId){ //alert("Selected figure index: " + STACK.figureSelectedIndex); var figure = STACK.figureGetById(selectedFigureId); var bounds = figure.getBounds(); var dx = bounds[0] + (bounds[2] - bounds[0]) / 2 var dy = bounds[1] + (bounds[3] - bounds[1]) / 2 //alert(dx + ' ' + dy); //alert("Selected figure is: " + figure); var TRANSLATE = [ [1, 0, dx * -1], [0, 1, dy * -1], [0, 0, 1] ] /* var dx = bounds[0] + (bounds[3] - bounds[1]) / 2 var dy = bounds[1] + (bounds[2] - bounds[0]) / 2 */ //TODO: figure out why we have to -1 off the dx, we have to do this regardless of rotation angle var TRANSLATEBACK = [ [1, 0, dx], [0, 1, dy], [0, 0, 1] ] figure.transform(TRANSLATE); if(action=="rotate90"){ figure.transform(R90); } else{ figure.transform(R90A); } figure.transform(TRANSLATEBACK); redraw = true; } break; case 'up': //decrease Y switch(state){ case STATE_FIGURE_SELECTED: var cmdFigUp = new FigureTranslateCommand(selectedFigureId, Matrix.UP); History.addUndo(cmdFigUp); cmdFigUp.execute(); redraw = true; break; case STATE_GROUP_SELECTED: var cmdGrpUp = new GroupTranslateCommand(selectedGroupId, Matrix.UP); History.addUndo(cmdGrpUp); cmdGrpUp.execute(); redraw = true; break; case STATE_CONTAINER_SELECTED: var cmdContUp = new ContainerTranslateCommand(selectedContainerId, Matrix.UP); History.addUndo(cmdContUp); cmdContUp.execute(); redraw = true; break; } break; case 'down': //increase Y switch(state){ case STATE_FIGURE_SELECTED: var cmdFigDown = new FigureTranslateCommand(selectedFigureId, Matrix.DOWN); History.addUndo(cmdFigDown); cmdFigDown.execute(); redraw = true; break; case STATE_GROUP_SELECTED: var cmdGrpDown = new GroupTranslateCommand(selectedGroupId, Matrix.DOWN); History.addUndo(cmdGrpDown); cmdGrpDown.execute(); redraw = true; break; case STATE_CONTAINER_SELECTED: var cmdContDown = new ContainerTranslateCommand(selectedContainerId, Matrix.DOWN); History.addUndo(cmdContDown); cmdContDown.execute(); redraw = true; break; } break; case 'right': //increase X switch(state){ case STATE_FIGURE_SELECTED: var cmdFigRight = new FigureTranslateCommand(selectedFigureId, Matrix.RIGHT); History.addUndo(cmdFigRight); cmdFigRight.execute(); redraw = true; break; case STATE_GROUP_SELECTED: var cmdGrpRight = new GroupTranslateCommand(selectedGroupId, Matrix.RIGHT); History.addUndo(cmdGrpRight); cmdGrpRight.execute(); redraw = true; break; case STATE_CONTAINER_SELECTED: var cmdContRight = new ContainerTranslateCommand(selectedContainerId, Matrix.RIGHT); History.addUndo(cmdContRight); cmdContRight.execute(); redraw = true; break; } break; case 'left': //decrease X switch(state){ case STATE_FIGURE_SELECTED: var cmdFigLeft = new FigureTranslateCommand(selectedFigureId, Matrix.LEFT); History.addUndo(cmdFigLeft); cmdFigLeft.execute(); redraw = true; break; case STATE_GROUP_SELECTED: var cmdGrpLeft = new GroupTranslateCommand(selectedGroupId, Matrix.LEFT); History.addUndo(cmdGrpLeft); cmdGrpLeft.execute(); redraw = true; break; case STATE_CONTAINER_SELECTED: var cmdContLeft = new ContainerTranslateCommand(selectedContainerId, Matrix.LEFT); History.addUndo(cmdContLeft); cmdContLeft.execute(); redraw = true; break; } break; case 'grow': if(selectedFigureId != -1){ //alert("Selected figure index: " + STACK.figureSelectedIndex); var figure = STACK.figureGetById(selectedFigureId); var bounds = figure.getBounds(); var dx = bounds[0] + (bounds[2] - bounds[0]) / 2 var dy = bounds[1] + (bounds[3] - bounds[1]) / 2 //alert(dx + ' ' + dy); //alert("Selected figure is: " + figure); var TRANSLATE = [ [1, 0, dx * -1], [0, 1, dy * -1], [0, 0, 1] ] /* var dx = bounds[0] + (bounds[3] - bounds[1]) / 2 var dy = bounds[1] + (bounds[2] - bounds[0]) / 2 */ var TRANSLATEBACK = [ [1, 0, dx], [0, 1, dy], [0, 0, 1] ] var GROW = [ [1 + 0.2, 0, 0], [0, 1 + 0.2, 0], [0, 0, 1] ] figure.transform(TRANSLATE); figure.transform(GROW); figure.transform(TRANSLATEBACK); redraw = true; } break; case 'shrink': if(selectedFigureId != -1){ //alert("Selected figure index: " + STACK.figureSelectedIndex); var figure = STACK.figureGetById(selectedFigureId); var bounds = figure.getBounds(); var dx = bounds[0] + (bounds[2] - bounds[0]) / 2 var dy = bounds[1] + (bounds[3] - bounds[1]) / 2 //alert(dx + ' ' + dy); //alert("Selected figure is: " + figure); var TRANSLATE = [ [1, 0, dx * -1], [0, 1, dy * -1], [0, 0, 1] ] /* var dx = bounds[0] + (bounds[3] - bounds[1]) / 2 var dy = bounds[1] + (bounds[2] - bounds[0]) / 2 */ var TRANSLATEBACK = [ [1, 0, dx], [0, 1, dy], [0, 0, 1] ] var SHRINK = [ [1 - 0.2, 0, 0], [0, 1 - 0.2, 0], [0, 0, 1] ] figure.transform(TRANSLATE); figure.transform(SHRINK); figure.transform(TRANSLATEBACK); redraw = true; } break; case 'duplicate': //TODO: From Janis: Connectors are not cloned if(selectedFigureId != -1){ //duplicate one figure var cmdDupl = new FigureCloneCommand(selectedFigureId); cmdDupl.execute(); History.addUndo(cmdDupl); } if(selectedGroupId != -1){ //copies a group or multiple figures var cmdDupl = new GroupCloneCommand(selectedGroupId); cmdDupl.execute(); History.addUndo(cmdDupl); } getCanvas().style.cursor = "default"; redraw = true; break; case 'back': if(selectedFigureId != -1){ var cmdBack = new FigureZOrderCommand(selectedFigureId, 0); cmdBack.execute(); History.addUndo(cmdBack); //STACK.setPosition(selectedFigureId, 0); redraw = true; } break; case 'front': if(selectedFigureId != -1){ var cmdFront = new FigureZOrderCommand(selectedFigureId, STACK.figures.length-1); cmdFront.execute(); History.addUndo(cmdFront); redraw = true; } break; case 'moveback': if(selectedFigureId != -1){ var cmdMoveBack = new FigureZOrderCommand(selectedFigureId, STACK.idToIndex[selectedFigureId] - 1); cmdMoveBack.execute(); History.addUndo(cmdMoveBack); redraw = true; } break; case 'moveforward': if(selectedFigureId != -1){ var cmdMoveForward = new FigureZOrderCommand(selectedFigureId, STACK.idToIndex[selectedFigureId] + 1); cmdMoveForward.execute(); History.addUndo(cmdMoveForward); redraw = true; } break; }//end switch if(redraw){ draw(); } } /**Stores last mouse position. Null initially.*/ var lastMousePosition = null; //function startResize(ev){ // lastMousePosition = getBodyXY(ev); // currentMoveUndo = new Action(null, null, History.ACTION_CANVAS_RESIZE, null, lastMousePosition, null); //} // // //function stopResize(ev){ // if(lastMousePosition != null){ // currentMoveUndo.currentValue = [lastMousePosition[0],lastMousePosition[1]]; // History.addUndo(currentMoveUndo); // currentMoveUndo = null; // lastMousePosition = null; // } //} //function resize(ev){ // if(lastMousePosition != null){ // var currentMousePosition // if(ev instanceof Array){ // //we are undoing this // currentMousePosition = ev; // } // else{ // currentMousePosition = getBodyXY(ev); // } // var width = canvas.getwidth() - (lastMousePosition[0] - currentMousePosition[0]); // var height = canvas.getheight() - (lastMousePosition[1] - currentMousePosition[1]); // canvas.setwidth(canvas,width); // canvas.setheight(canvas, height); // setUpEditPanel(canvas); // lastMousePosition = currentMousePosition; // /*if(canvas.width >= document.body.scrollWidth-370){ // } // else { // //document.getElementById("container").style.width = ""; // }*/ // draw(); // } //} function documentOnMouseDown(evt){ //Log.info("documentOnMouseDown"); //evt.preventDefault(); } var draggingFigure = null; function documentOnMouseMove(evt){ //Log.info("documentOnMouseMove"); switch(state){ case STATE_FIGURE_CREATE: //Log.info("documentOnMouseMove: trying to draw the D'n'D figure"); if(!draggingFigure){ draggingFigure = document.createElement('img'); draggingFigure.setAttribute('id', 'draggingThumb'); draggingFigure.style.position = 'absolute'; draggingFigure.style.zIndex = 3; // set it in front of editor body.appendChild(draggingFigure); } //Log.info("editor.php>documentOnMouseMove>STATE_FIGURE_CREATE: selectedFigureThumb=" + selectedFigureThumb); draggingFigure.setAttribute('src', selectedFigureThumb); draggingFigure.style.width = '100px'; draggingFigure.style.height = '100px'; draggingFigure.style.left = (evt.pageX - 50) + 'px'; draggingFigure.style.top = (evt.pageY - 50) + 'px'; //draggingFigure.style.backgroundColor = 'red'; draggingFigure.style.display = 'block'; draggingFigure.addEventListener('mousedown', function (event){ //Log.info("documentOnMouseMove: How stupid. Mouse down on dragging figure"); }, false); draggingFigure.addEventListener('mouseup', function (ev){ var coords = getCanvasXY(ev); if(coords == null){ return; } var x = coords[0]; var y = coords[1]; switch(state){ case STATE_FIGURE_CREATE: Log.info("draggingFigure>onMouseUp() + STATE_FIGURE_CREATE"); snapMonitor = [0,0]; //treat new figure //do we need to create a figure on the canvas? if(window.createFigureFunction){ //Log.info("draggingFigure>onMouseUp() + STATE_FIGURE_CREATE--> new state STATE_FIGURE_SELECTED + createFigureFunction = " + window.createFigureFunction); var cmdCreateFig = new FigureCreateCommand(window.createFigureFunction, x, y); cmdCreateFig.execute(); History.addUndo(cmdCreateFig); //HTMLCanvas.style.cursor = 'default'; selectedConnectorId = -1; createFigureFunction = null; mousePressed = false; redraw = true; draw(); //TODO: a way around to hide this dragging DIV document.getElementById('draggingThumb').style.display = 'none'; //TODO: the horror //body.removeChild(document.getElementById('draggingThumb')); } else{ Log.info("draggingFigure>onMouseUp() + STATE_FIGURE_CREATE--> but no 'createFigureFunction'"); } break; } //stop canvas from gettting this event evt.stopPropagation(); }, false); break; case STATE_NONE: //document.removeChild(document.getElementById('draggingThumb')); break; } } function documentOnMouseUp(evt){ Log.info("documentOnMouseUp"); switch(state){ case STATE_FIGURE_CREATE: var eClicked = document.elementFromPoint(evt.clientX, evt.clientY); if(eClicked.id != 'a'){ if(draggingFigure){ //draggingFigure.style.display = 'none'; draggingFigure.parentNode.removeChild(draggingFigure); state = STATE_NONE; draggingFigure = null; //evt.stopPropagation(); } } break; } } /*Returns a text containing all the URL in a diagram */ function linkMap(){ var csvBounds = ''; var first = true; for(var f in STACK.figures){ var figure = STACK.figures[f]; if(figure.url != ''){ var bounds = figure.getBounds(); if(first){ first = false; } else{ csvBounds += "\n"; } csvBounds += bounds[0] + ',' + bounds[1] + ',' + bounds[2] + ',' + bounds[3] + ',' + figure.url; } } Log.info("editor.php->linkMap()->csv bounds: " + csvBounds); return csvBounds; } /*======================APPLE=====================================*/ /**Triggered when an touch is initiated (iPad/iPhone). *Simply forward to onMouseDown *@param {Event} event - the event triggered **/ function touchStart(event){ event.preventDefault(); onMouseDown(event); } /**Triggered while touching and moving is in progress (iPad/iPhone). *Simply forward to onMouseMove *@param {Event} event - the event triggered **/ function touchMove(event){ event.preventDefault(); onMouseMove(event); } /**Triggered when touch ends (iPad/iPhone). *Simply forward to onMouseUp *@param {Event} event - the event triggered **/ function touchEnd(event){ onMouseUp(event); } /**Triggered when touch is canceled (iPad/iPhone). *@param {Event} event - the event triggered **/ function touchCancel(event){ //nothing } /*======================END APPLE=================================*/
app.controller('loginNavController', function ($scope, $state, loginModal, $rootScope, $cookieStore) { var _Club = 1; var _CommISTO = 2; var _ScoreKeeper = 3; var _ClubText = "Club"; var _CommISTOText = "CommISTO"; var _ScoreKeeperText = "ScoreKeeper"; $scope.logOut = function () { $rootScope.currentUser = null; $cookieStore.remove('istoUserId'); $cookieStore.remove('istoUserClub'); $cookieStore.remove('istoUserName'); $cookieStore.remove('istoUserType'); $state.go('home'); location.reload(); } $scope.logModal = function () { loginModal() .then(function () { $state.go('dashboard'); }) } $scope.getUserType = function (User) { var tmp = ''; if(User !== 'undefined' && User.userType !== 'undefined'){ switch(User.userType) { case _Club: tmp = _ClubText; break; case _CommISTO: tmp = _CommISTOText; break; case _ScoreKeeper: tmp = _ScoreKeeperText; break; default: tmp = ''; } } return tmp; } })
// Authentications const { Router } = require('express'); const router = Router(); const pool = require('../database'); const { isLoggedIn, isNotLoggedIn, verifyAdmin, isUser } = require('../lib/auth'); // add order router.post('/add', isUser, async (req, res) => { // generate order try { // get id user const id_user = req.user.id; const { id_payment_method } = req.body; const newOrder = { id_user, id_payment_method } // generate order await pool.query('INSERT INTO orders SET ?', [newOrder]); // search order const searchIdOrder = await pool.query('SELECT MAX(id) FROM orders WHERE id_user = ?',[id_user]); const id_order = Object.values(searchIdOrder[0].valueOf('MAX(id)')); // add order details req.body.products.forEach(async item => { const id_product = item.id_product; const amount = item.amount; const newOrderDetails = { id_order, id_product, amount, } await pool.query('INSERT INTO order_details SET ?', [newOrderDetails]); }); res.status(200); res.json({Message:'Order added'}); } catch (error) { res.status(400); res.json({Message:'verify the data and try again'}); } }); // all orders router.get('/', verifyAdmin, async (req, res) => { const data = await pool.query(` SELECT orders.id , status.state, orders.order_date, order_details.amount, products.name AS product, products.description, payment_method.description AS payment_method,products.price, users.username, users.fullname, users.address, users.phone_number, users.email FROM orders INNER JOIN order_details ON orders.id = order_details.id INNER JOIN products ON order_details.id_product = products.id INNER JOIN users ON orders.id_user = users.id INNER JOIN payment_method ON orders.id_payment_method = payment_method.id INNER JOIN status ON orders.id_state = status.id`); if(data == ""){ res.status(204); res.json({Message:'There are no orders to show'}); } else { res.status(200); res.json(data); } }); // one order router.get('/:id', verifyAdmin, async (req, res) => { const { id } = req.params; const id_user = req.user.id; const data = await pool.query(` SELECT orders.id , status.state, orders.order_date, order_details.amount, products.name AS product, products.description, payment_method.description AS payment_method,products.price, users.username, users.fullname, users.address, users.phone_number, users.email FROM orders INNER JOIN order_details ON orders.id = order_details.id INNER JOIN products ON order_details.id_product = products.id INNER JOIN users ON orders.id_user = users.id INNER JOIN payment_method ON orders.id_payment_method = payment_method.id INNER JOIN status ON orders.id_state = status.id WHERE orders.id = ? AND users.id = ?`,[id, id_user]); if(data == "") { res.status(204); res.json({Message:'the order you are looking for does not exist in the system'}); } else { res.status(200); res.json(data); } }); // update order router.put('/edit/:id', verifyAdmin, async (req, res) => { try { const { id } = req.params; const { state } = req.body; const data = await pool.query('SELECT * FROM orders WHERE id = ?',[id]); if(data == "") { res.status(204); res.json({Message:"The order you are looking for does not exist"}); } else { await pool.query('UPDATE orders SET id_state = ? WHERE id = ?', [state, id]); res.status(200); res.json({state:"Order Updated"}); } } catch (error) { res.status(500); res.json({Error:"Internal Server Error"}); } }); // delete order router.delete('/delete/:id', verifyAdmin, async (req, res) => { const { id } = req.params; const data = await pool.query(`SELECT * FROM orders WHERE id = ?`, [id]); if(data == "") { res.status(204); res.json({Message:"The order you are looking for does not exist"}); } else { if(data[0].id_state === 1){ await pool.query('DELETE FROM orders WHERE id = ?', [id]); await pool.query('DELETE FROM order_details WHERE id = ?', [id]); res.status(200); res.json({order:"Order Deleted"}); }else { res.status(400); res.json({Message:"You cannot delete an order already in process, change the status to canceled"}); } } }); module.exports = router;
function solve() { let convertElement = document.querySelector('#container button'); let toElement = document.querySelector('#selectMenuTo'); let binaryOption = document.createElement('option'); binaryOption.value = 'binary'; binaryOption.textContent = 'Binary'; toElement.appendChild(binaryOption); let hexaOption = document.createElement('option'); hexaOption.textContent = 'Hexadecimal'; hexaOption.value = 'hexadecimal'; toElement.appendChild(hexaOption); convertElement.addEventListener('click', () => { let input = document.querySelector('#input'); let inputValue = Number(input.value); let resultElement = document.querySelector('#result'); let toDroplist = document.querySelector('#selectMenuTo'); let selectedFormat = toDroplist.value; if (selectedFormat == 'binary') { let result = inputValue.toString(2); resultElement.value = result; } else if (selectedFormat == 'hexadecimal') { let result = inputValue.toString(16).toUpperCase(); resultElement.value = result; } }); }
window.onload=function (){ function loadTree() { $.post(window.location.href + '?getTree', {data: null}, function (response) { response = (JSON.parse(response)).reverse(); var Tree = ""; for (var i = 0; i < response.length; i += 1) { if (response[i].company_parent == false) { Tree += response[i].company_name + "| " + response[i].company_earnings + (hasSubTree(response[i],response) ? "| " + getSubEarnings(response[i], response) : "") + "<br>"; Tree += getSubTree(response[i], response, 1); } } $('#companyTree').html(Tree); function getSubEarnings(parentNode, dataTable) { var money = 0; for (var i = 0; i < dataTable.length; i += 1) { if (parentNode.company_id == dataTable[i].company_parent) { money += getSubEarnings(dataTable[i], dataTable); } } money += parseInt(parentNode.company_earnings); return money; } function getSubTree(parentNode, dataTable, level) { var Tree = ""; for (var i = 0; i < dataTable.length; i += 1) { if (parentNode.company_id == dataTable[i].company_parent) { for (var j = 0; j < level; j += 1) { Tree += "-"; } Tree += dataTable[i].company_name + "| " + dataTable[i].company_earnings + (hasSubTree(dataTable[i], dataTable) ? "| " + getSubEarnings(dataTable[i], dataTable) : "") + "<br>"; Tree += getSubTree(dataTable[i], dataTable, level + 1); } } return Tree; } function hasSubTree(parentNode, dataTable) { for(var i = 0; i < dataTable.length; i += 1) { if (parentNode.company_id == dataTable[i].company_parent) { return true; } } return false; } }); } loadTree(); $('#createCompany').on('click', function() { var data={ name:$('#newCompanyName').val(), earnings:$('#newCompanyEarnings').val(), parent:$('#newCompanyParent').val() }; $.post(window.location.href + '?createCompany', {data: data}, function(response) { if (!parseInt(response)) { alert('Error while creating company'); } else loadTree(); }); }); $('#DeleteCompanyButton').on('click', function(){ $.post(window.location.href+'?deleteCompany',{data:$('#deleteCompany').val()}, function (response){ if(!parseInt(response)) { alert('Error while deleting company'); } else loadTree(); }); }); $('#ShowCompanyButton').on('click', function() { $.post(window.location.href+'?showCompany',{data:$('#showCompany').val()}, function (response){ response=JSON.parse(response); response['child_companies']=response['child_companies'].reverse(); var child_comps=""; for (var i=0; i< response['child_companies'].length; i+=1) { child_comps +=response['child_companies'][i].company_name+" "; } if(response) { $('#ShowCompanyField').html("Company earnings: " + response.company_earnings + "," + ' ' + "subsidiary companies: " + child_comps); } else{ alert("No such company"); } }); }); $('#EditCompanyButton').on('click', function() { var data={ oldName:$('#editCompanyName').val(), name:$('#editedCompanyName').val(), earnings:$('#editedCompanyEarnings').val() }; $.post(window.location.href+'?editCompany',{data:data}, function (response) { if(!parseInt(response)) { alert('Error while editing company'); } else loadTree(); }); }); };
import $ from 'jquery'; // const openNav = () => { // document.getElementById('myNav').style.width = '100%'; // }; // const closeNav = () => { // document.getElementById('myNav').style.width = '0%'; // }; // const openNav_1 = () => { // document.getElementById('myNav_1').style.height = '100%'; // }; // const closeNav_1 = () => { // document.getElementById('myNav_1').style.height = '0%'; // }; $(document).ready(function () { $(window).on('scroll', function () { if (window.scrollY > 800) { $('.topnav').addClass('topnav_fixed'); $('.topnav').css('top', '-200px'); $('.topnav').css('transition', '0.4s'); $('.scrollTop').addClass('scroll_fixed'); } else { $('.topnav').removeClass('topnav_fixed'); $('.scrollTop').removeClass('scroll_fixed'); } }); });
import { CREATE_USER, GET_USER } from '../actions/action'; let initialState = []; export default (state = initialState, action) => { switch (action.type) { case CREATE_USER: return [...state, action.payload]; case GET_USER: return action.payload; default: return state; } };
var crypto = require('crypto') function hash256 (buffer) { return sha256(sha256(buffer)) } function sha256 (buffer) { return crypto.createHash('sha256').update(buffer).digest() } module.exports = { sha256: sha256, hash256: hash256 }
'use strict'; let chalk = require('chalk'); let events = { eventRegistry: function () { this.sigint(); }, sigint: function () { process.on('SIGINT', function() { console.log(chalk.red('\nNano has shutdown')); process.exit(0); }); } } module.exports = events;
var path = require('path'); var webpack = require('webpack'); var env = require('./env.json') || {}; module.exports = { cache: true, progress: true, entry: { infinigui: './src/scripts/infinigui.es6' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { loaders: [ // Expose jQuery to the "true" window - for Selenium { test: /jquery\.js$/, loader: 'expose?$' }, { test: /\.(html)$/, loader: 'html' }, { test: /\.(json)$/, loader: 'text' }, { test: /\.es6$/, loader: 'babel?optional[]=es7.classProperties', exclude: /(node_modules|bower_components)/ }, { test: /\.(png|jpg|woff|eot|ttf|svg)$/, loader: 'file?name=static/[name]-[hash:6].[ext]' } ] }, resolve: { alias: { 'igui_root': __dirname, 'underscore': 'lodash' }, root: [ __dirname, path.join(__dirname, 'lib') ], extensions: ['', '.js', '.es6'] }, plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) ), // Make those plugins globals new webpack.ProvidePlugin({ //_: 'lodash', $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }) ], devtool: [env.sourcemap_js === true || process.env['SOURCEMAP_JS'] ? 'sourcemap' : 'eval'], devServer: { progress: true, port: env.port, inline: env.live_reload !== false } };
import React from 'react'; import cohort from '../cohort'; import StudentForm from './StudentForm'; import PairForm from './PairForm'; const App = () => { return ( <> <PairForm cohort={cohort} /> <StudentForm cohort={cohort} /> </> ); }; export default App;
import {createSlice} from '@reduxjs/toolkit' const userSlice = createSlice({ name:'user', initialState:null, reducers: { login:(state, action) => { return action.payload }, logout:(state) => { return null } } }) export const selectUser = state => state.user export const {login, logout} = userSlice.actions export default userSlice.reducer
const CreditReducer = ( state = { amount: 0 , currency: "", duedate:0 , repay:0} , action ) => { switch(action.type){ case 'SET_CREDIT': return { amount: action.payload.amount , currency: action.payload.currency, duedate:action.payload.duedate , repay: action.payload.repay }; default : return state; } } export default CreditReducer
/** * Copyright 2021-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * Messenger For Original Coast Clothing * https://developers.facebook.com/docs/messenger-platform/getting-started/sample-apps/original-coast-clothing */ "use strict"; // Use dotenv to read .env vars into Node require("dotenv").config(); // Required environment variables const ENV_VARS = [ "PAGE_ID", "APP_ID", "PAGE_ACCESS_TOKEN", "APP_SECRET", "VERIFY_TOKEN", "APP_URL", "SHOP_URL" ]; module.exports = { // Messenger Platform API apiDomain: "https://graph.facebook.com", apiVersion: "v11.0", // Page and Application information pageId: process.env.PAGE_ID, appId: process.env.APP_ID, pageAccesToken: process.env.PAGE_ACCESS_TOKEN, appSecret: process.env.APP_SECRET, verifyToken: process.env.VERIFY_TOKEN, // URL of your app domain appUrl: process.env.APP_URL, // URL of your website shopUrl: process.env.SHOP_URL, // Persona IDs personas: {}, // Preferred port (default to 3000) port: process.env.PORT || 3000, // Base URL for Messenger Platform API calls get apiUrl() { return `${this.apiDomain}/${this.apiVersion}`; }, // URL of your webhook endpoint get webhookUrl() { return `${this.appUrl}/webhook`; }, get newPersonas() { return [ { name: "Jorge", picture: `${this.appUrl}/personas/sales.jpg` }, { name: "Laura", picture: `${this.appUrl}/personas/billing.jpg` }, { name: "Riandy", picture: `${this.appUrl}/personas/order.jpg` }, { name: "Daniel", picture: `${this.appUrl}/personas/care.jpg` } ]; }, pushPersona(persona) { this.personas[persona.name] = persona.id; }, get personaSales() { let id = this.personas["Jorge"] || process.env.PERSONA_SALES; return { name: "Jorge", id: id }; }, get personaBilling() { let id = this.personas["Laura"] || process.env.PERSONA_BILLING; return { name: "Laura", id: id }; }, get personaOrder() { let id = this.personas["Riandy"] || process.env.PERSONA_ORDER; return { name: "Riandy", id: id }; }, get personaCare() { let id = this.personas["Daniel"] || process.env.PERSONA_CARE; return { name: "Daniel", id: id }; }, get whitelistedDomains() { return [this.appUrl, this.shopUrl]; }, checkEnvVariables: function () { ENV_VARS.forEach(function (key) { if (!process.env[key]) { console.warn("WARNING: Missing the environment variable " + key); } else { // Check that urls use https if (["APP_URL", "SHOP_URL"].includes(key)) { const url = process.env[key]; if (!url.startsWith("https://")) { console.warn( "WARNING: Your " + key + ' does not begin with "https://"' ); } } } }); } };