text
stringlengths 7
3.69M
|
|---|
import {createStore, combineReducers, applyMiddleware} from 'redux'
import {createLogger} from 'redux-logger'
import thunkMiddleware from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension'
import user from './user'
import allProducts from './allProducts'
import singleProduct from './singleProduct'
import currentCart from './currentCart'
import pastCarts from './pastCarts'
const reducer = combineReducers({
currentCart,
user,
allProducts,
singleProduct,
pastCarts
})
const middleware = composeWithDevTools(
applyMiddleware(thunkMiddleware, createLogger({collapsed: true}))
)
const store = createStore(reducer, middleware)
export default store
export * from './user'
export * from './allProducts'
export * from './singleProduct'
export * from './currentCart'
export * from './pastCarts'
|
import { IndexRoute, Route } from 'react-router'
import HomePage from '../src/home/Homepage'
import Layout from '../src/layouts/layout'
import ProductPage from '../src/home/productPage'
import React from 'react'
import StorePage from '../src/home/StorePage'
export default (
<Route path='/' component={Layout}>
<IndexRoute component={HomePage} />
<Route path='product' component={ProductPage} />
<Route path='store' component={StorePage} />
</Route>
)
|
import React, { useState, useEffect } from "react";
import CompletedCardContent from "./CompletedCardContent";
import db from "../firebaseConfig";
import { Button, Col, Row } from "react-bootstrap";
export const Completed = () => {
const [cards, setCards] = useState([]);
const fetchCards = async () => {
await db.collection("completed").onSnapshot(function (querySnapshot) {
setCards(
querySnapshot.docs.map((card, index) => {
return {
id: card.id,
key: index,
...card.data(),
};
})
);
});
};
//control argument needs to be figured out.
useEffect(() => {
fetchCards();
}, []);
console.log(cards);
return (
<div style={{ margin: "20px"}}>
<h1 style = {{ textAlign: "center", fontWeight: "bold"}}> Completed Tasks </h1> <br></br>
<Row>
{cards.map((card) => {
return (
<CompletedCardContent
id={card.id}
title={card.title}
status={card.status}
shippingDate={card.shippingDate}
responsibility={card.responsibility}
description={card.description}
destination={card.destination}
quantity={card.quantity}
/>
);
})}
</Row>
</div>
);
};
export default Completed;
|
const db = require("../models");
//Define methods for the Comments controller
module.exports = {
findAll: function(req, res){
db.Comment
.find(req.query)
.sort({ date: -1 }) // sort by date added
.then( dbModel => res.json(dbModel))
.catch( err => res.status(422).json(err));
},
findById: function(req, res){
db.Comment
.findOne({_id:req.params.id})
.then( dbModel => res.json(dbModel))
.catch( err => res.json(err))
},
create: function(req, res){
db.Campground.findOne({_id:req.params.id}).populate("comments").exec(
function(err, campground){
if(err){
res.status(422).json(err)
}else {
// console.log("what is campground?: ")
// console.log(campground)
db.Comment
.create(req.body)
.then(dbModel => {
campground.comments.push(dbModel);
campground.save();
res.json(campground);
})
.catch(err => res.status(422).json(err))
}}
)
},
update: function(req, res) {
db.Comment
.findOneAndUpdate({ _id: req.params.id }, req.body)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
remove: function(req, res) {
db.Comment
.findById({ _id: req.params.id })
.then(dbModel => dbModel.remove())
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
}
|
import { Dimensions, Platform } from 'react-native'
import React, { createContext, useState } from 'react'
const windowDimensions = Dimensions.get('screen');
const platform = Platform.OS;
export const DimensionContext = createContext();
export function DimensionContextProvider(props) {
const dimensions = {
windowWidth: windowDimensions.width,
windowHeight: windowDimensions.height,
platform: platform,
}
return (
<DimensionContext.Provider value={{ ...dimensions }}>
{props.children}
</DimensionContext.Provider>
)
}
|
const chalk = require('chalk');
const axios = require('axios');
const url = "https://jsonplaceholder.typicode.com/users";
axios
.get(url)
.then(respose => console.log(chalk.bgRed(respose.data[0].email)));
|
/*
Imports
*/
import React from "react"; // React
import "./../../../scss/editItemDisplay.scss"; // SCSS
/*
EditItemDisplay Component
*/
const EditItemDisplay = props => {
return (
<div className="edit-item-container">
<h6 className="name">{props.itemName}</h6>
<button
className="delete-item-button"
id={props.id}
onClick={props.handleDeleteButton}
>
❌
</button>
</div>
);
}
export default EditItemDisplay;
|
var networkInterfaces = require('os').networkInterfaces()
var localIP = function ()
{
for(var k in networkInterfaces)
{
var networkInterface = networkInterfaces[k];
for(var j in networkInterface)
{
if(networkInterface[j].family === 'IPv4' && !networkInterface[j].internal)
{
return networkInterface[j].address;
}
}
}
return undefined;
}
var args = process.argv.slice(2);
var PORT = 7777;
for (var i = 0; i < args.length; i++) {
if (args[i] === "-p") {
if (++i < args.length) PORT = args[i];
console.log(PORT);
break;
}
}
var PATH = undefined;
for (var i = 0; i < args.length; i++) {
if (args[i] === "-OPEN") {
args.splice(i, 1);
if (i < args.length) {
PATH = args[i];
args.splice(i, 1);
}
console.log(PATH);
break;
}
}
var LOGFILE = undefined;
for (var i = 0; i < args.length; i++) {
if (args[i] === "-LOGFILE") {
args.splice(i, 1);
if (i < args.length) {
LOGFILE = args[i];
args.splice(i, 1);
}
console.log(LOGFILE);
break;
}
}
var IP = undefined;
// For example, command line parameter after "npm run SCRIPT_NAME":
//--readium-js-viewer:RJS_HTTP_IP=0.0.0.0
// or:
//--readium-js-viewer:RJS_HTTP_IP=127.0.0.1
//
// ... or ENV shell variable, e.g. PowerShell:
//Set-Item Env:RJS_HTTP_IP 0.0.0.0
// e.g. MS-DOS:
//SET RJS_HTTP_IP=0.0.0.0
// e.g. OSX terminal:
//RJS_HTTP_IP=0.0.0.0 npm run SCRIPT_NAME
//(temporary, command / process-specific ENV variable)
// or:
// export RJS_HTTP_IP="0.0.0.0"; npm run SCRIPT_NAME
//(permanent env var)
console.log('process.env.npm_package_config_RJS_HTTP_IP:');
console.log(process.env.npm_package_config_RJS_HTTP_IP);
console.log('process.env[RJS_HTTP_IP]:');
console.log(process.env['RJS_HTTP_IP']);
if (process.env.npm_package_config_RJS_HTTP_IP)
process.env['RJS_HTTP_IP'] = process.env.npm_package_config_RJS_HTTP_IP;
if (typeof process.env['RJS_HTTP_IP'] !== "undefined" && process.env['RJS_HTTP_IP'].trim().length) {
IP = process.env['RJS_HTTP_IP'];
var ipfound = false;
for (var i = 0; i < args.length; i++) {
if (args[i] === "-a") {
if (++i < args.length) {
args[i] = IP;
ipfound = true;
}
break;
}
}
if (!ipfound) {
args.unshift(IP);
args.unshift("-a");
}
}
if (!IP) {
for (var i = 0; i < args.length; i++) {
if (args[i] === "-a") {
if (++i < args.length) IP = args[i];
break;
}
}
}
var localIP = localIP();
if (!IP) {
IP = localIP;
args.unshift(IP);
args.unshift("-a");
}
console.log(IP);
console.log("http-server.js arguments: ");
console.log(args);
var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
args.unshift(path.join(process.cwd(), 'node_modules', 'http-server', 'bin', 'http-server'));
// fs.existsSync is marked as deprecated, so accessSync is used instead (if it's available in the running version of Node).
function doesFileExist(path) {
var exists;
if (fs.accessSync) {
try {
fs.accessSync(path);
exists = true;
} catch (ex) {
exists = false;
}
} else {
exists = fs.existsSync(path);
}
return exists;
}
if (LOGFILE) {
LOGFILE = path.join(process.cwd(), LOGFILE);
if (doesFileExist(LOGFILE)) {
console.log("~~ delete: " + LOGFILE);
fs.unlinkSync(LOGFILE);
}
}
var child = child_process.spawn('node', args);
child.stdout.on('data', function(data) {
if (LOGFILE) {
fs.appendFileSync(LOGFILE, data.toString());
} else {
console.log(data.toString());
}
});
child.stderr.on('data', function(data) {
if (LOGFILE) {
fs.appendFileSync(LOGFILE, data.toString());
} else {
console.log(data.toString());
}
});
child.on('close', function(code) {
console.log('HTTP child process exit code: ' + code);
if (LOGFILE) {
console.log("HTTP log: " + LOGFILE);
}
});
if (PATH) {
var child2 = child_process.spawn('node', ['node_modules/opener/bin/opener-bin.js', 'http://'+(IP=="0.0.0.0"?localIP:IP)+':'+PORT+PATH]);
child2.stdout.on('data', function(data) {
console.log(data.toString());
});
child2.stderr.on('data', function(data) {
console.log(data.toString());
});
child2.on('close', function(code) {
console.log('OPENER child process exit code: ' + code);
});
}
|
// import picturefill from 'picturefill';
// picturefill();
// const img = document.createElement('img');
// const isWSupported = 'sizes' in img;
const isPictureSupported = !!window.HTMLPictureElement;
// TODO: add error handlers
// TODO: add is-loading
// TODO: explore lazy with intersection observer
const isImageValid = ($image) => {
if (isPicture($image)) {
return isPictureValid($image);
}
return isImgValid($image);
};
const isImgValid = ($image) => {
const nodeName = $image.nodeName.toLowerCase();
return (
($image.hasAttribute('data-src') || $image.hasAttribute('data-srcset')) &&
(nodeName === 'img' || nodeName === 'source')
);
};
const isPictureValid = ($image) => {
const parent = $image.parentNode;
let isSourcesValid = true;
const sourceTags = getSourceTags(parent);
sourceTags.forEach((sourceTag) => {
if (!isImgValid(sourceTag)) isSourcesValid = false;
});
return isSourcesValid;
};
const isPicture = ($image) => {
const parent = $image.parentNode;
return parent && parent.tagName === 'PICTURE';
};
const getSourceTags = (parentTag) => {
let sourceTags = [];
let childTag;
for (let i = 0; (childTag = parentTag.children[i]); i += 1) {
if (childTag.tagName === 'SOURCE') {
sourceTags.push(childTag);
}
}
return sourceTags;
};
export const loadImage = ($image) => {
return new Promise((resolve) => {
const onLoad = (event) => {
// If the image is setting a background image, add loaded class to parent.
// ImageLoader won't reset background image if the 'src' exists, so remove after load.
// this will only works with data-src
if ($image.hasAttribute('data-use-bg-image')) {
$image.parentNode.classList.add('is-loaded');
$image.removeAttribute('src');
$image.style.display = 'none';
} else {
$image.classList.add('is-loaded');
}
// remove load event listener to prevent duplicates
$image.removeEventListener('load', onLoad);
resolve($image);
};
$image.addEventListener('load', onLoad);
if (isPicture($image)) {
const sourceTags = getSourceTags($image.parentNode);
sourceTags.forEach((sourceTag) => {
setImageAttributes(sourceTag);
});
// load fallback if not supported
// we added this because otherwise fallback will be loaded with the source
if (!isPictureSupported) {
setImageAttributes($image);
}
} else {
setImageAttributes($image);
}
});
};
const setImageAttributes = ($image) => {
if ($image.hasAttribute('data-sizes')) {
if (!$image.hasAttribute('sizes')) {
$image.setAttribute('sizes', $image.dataset.sizes);
}
}
if ($image.hasAttribute('data-srcset')) {
$image.setAttribute('srcset', $image.dataset.srcset);
}
if ($image.hasAttribute('data-src')) {
$image.setAttribute('src', $image.dataset.src);
}
};
/**
* Image load one or more images using Promise.all.
* @param {DOMElement[]} $images An array of images to load.
* @param {function} afterImageLoad A function to be called after every image load
* @return {Promise} Promise that resolves when all images are loaded
*/
export const loadImages = ($images, afterImageLoad) => {
if (!Array.isArray($images)) {
console.warn('Load images promise should take an array of images, instead got type', typeof $images);
return;
}
if (Array.isArray($images) && $images.length === 0) {
console.warn('Empty Array', typeof $images);
return;
}
const imagePromises = $images.map(($image) => {
if (!$image) return false;
return new Promise((resolve) => {
// check if image is image and has proper attributes
if (!isImageValid($image)) {
console.warn('ImageLoader: Missing proper attribute data-*');
resolve($image);
return;
}
loadImage($image).then(($image) => {
typeof afterImageLoad === 'function' && afterImageLoad($image);
resolve($image);
});
});
});
return Promise.all(imagePromises);
};
export default loadImages;
|
const express=require("express");
const mysql=require("mysql");
const DATA_BASE=require("../CONFIG/DATA_BASE.js")
const link=mysql.createPool(DATA_BASE)
module.exports=function(){
const server=express.Router()
server.use("/",function(request,response){
const {condition}=request.query
const {userMSG}=Object.assign({},request.session)
const PASS=(function(){
switch(condition){
case "all":
return "";
break;
case "pass":
return `AND Pass='1'`;
break;
case "unpass":
return `AND Pass='0'`;
break;
}
})()
const sql=`
SELECT * from achievement
where uid=${userMSG.uid}
${PASS}
ORDER BY time
DESC
`;
link.query(sql,function(err,data){
if(!err){
response.send(data)
}else{
console.log(err)
}
//response.send({a:0})
})
})
return server
}
|
import React, {Component, Fragment} from "react";
import {Link} from 'react-router-dom';
import PropTypes from 'prop-types';
class UserCard extends Component {
render() {
const {personResult}=this.props;
const personId=this.props.match.params.id;
if (personResult.length ===0 || personId >=personResult.length){
return <p>no hay datos que pintar</p>;
}else{
const selectedPerson=personResult[personId];
const fullName=`${selectedPerson.name.first} ${selectedPerson.name.last}`;
const image=selectedPerson.picture.large;
const age=selectedPerson.dob.age;
const city=selectedPerson.location.city;
return (
<Fragment>
<div className="person">
<h2 className="person__name">{fullName}</h2>
<img src={image} alt={fullName}/>
<div className="person__age">{age}</div>
<div className="person__city">{city}</div>
</div>
<div className="app__go--back">
<Link className="app__go--back-link" to="/" >Volver al listado</Link>
</div>
</Fragment>
);
}}
}
UserCard.PropTypes={
fullName: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
city:PropTypes.string.isRequired,
}
export default UserCard;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsPeople = {
name: 'people',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M16.67 13.13C18.04 14.06 19 15.32 19 17v3h4v-3c0-2.18-3.57-3.47-6.33-3.87z"/><circle cx="9" cy="8" r="4"/><path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4c-.47 0-.91.1-1.33.24a5.98 5.98 0 010 7.52c.42.14.86.24 1.33.24zM9 13c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/></svg>`
};
|
import httpClient from '@/datasources/http/httpClient'
const authenticate = (credential) => {
return httpClient.request().post('/signin', credential)
}
export default {
authenticate
}
|
const Electron = require('./electronService.js');
const Windows = require('./windowService.js');
// Ready
Electron.App.on('ready', Windows.CreateMainWindow);
// Window all closed
Electron.App.on('window-all-closed', function ()
{
if (process.platform !== 'darwin')
{
Electron.App.quit();
}
});
// Activated
Electron.App.on('activate', function ()
{
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (Windows.MainWindow === null)
{
Windows.CreateMainWindow();
}
});
// Closed
Electron.App.on('closed', function ()
{
Windows.MainWindow = null;
});
|
import { usersCheck } from '../../api';
import { Form, Input } from 'antd';
import React, { useState } from 'react';
const InternalRecipientFields = ({ form }) => {
const [user, setUser] = useState();
const { getFieldDecorator } = form;
const formatPhone = value => value && value.replace(/\+65|65/g, '');
const validatePhone = async (rule, value, callback) => {
console.log(value);
const fetchedUser = await usersCheck(`65${value}`, false);
setUser(fetchedUser);
if (fetchedUser && fetchedUser.phone === value) {
callback();
} else {
callback('Phone not found');
}
};
return (
<Form.Item label="Phone Number" hasFeedback extra={user ? user.name : null}>
{getFieldDecorator('phone', {
rules: [
{ required: true, message: 'Please input recipient phone number!' },
{ validator: validatePhone }
],
normalize: formatPhone
})(<Input inputMode={'tel'} addonBefore={'+65'} pattern={'[0-9]*'} />)}
</Form.Item>
);
};
export default InternalRecipientFields;
|
const moment = require('moment');
const a = moment([2021, 5, 21]);
const b = moment([2000, 9, 05]);
const res1 = a.diff(b, 'years');
const res2 = a.diff(b, 'days');
const res3 = a.diff(b, 'seconds');
console.log(res1 + " years old");
console.log(res2 + " days ago");
console.log(res3 + " seconds is gone");
|
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("file:src/test/resources/features/userSearchesNearestGym.feature");
formatter.feature({
"name": "Search postcode",
"description": "",
"keyword": "Feature"
});
formatter.scenario({
"name": "I search my postocde",
"description": "",
"keyword": "Scenario"
});
formatter.before({
"status": "passed"
});
formatter.step({
"name": "I go to the website \"https://www.nuffieldhealth.com/\"",
"keyword": "Given "
});
formatter.match({
"location": "SearchSteps.i_go_to_website(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "I click on \"Gym tab\"",
"keyword": "And "
});
formatter.match({
"location": "SearchSteps.i_click_on(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "I find and click on the link \"join a gym\"",
"keyword": "And "
});
formatter.match({
"location": "SearchSteps.i_find_and_click_on_the_link(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "I input \"SE1 9AA\" to the field \"Search Gym\"",
"keyword": "And "
});
formatter.match({
"location": "SearchSteps.i_input_to_the_field(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "I can see the link with text \"arrange a visit\"",
"keyword": "And "
});
formatter.match({
"location": "SearchSteps.i_can_see_the_link_with_text(String)"
});
formatter.result({
"status": "passed"
});
formatter.after({
"status": "passed"
});
});
|
function takeANumber(katzDeliLine, name) {
katzDeliLine.push(name)
return `Welcome, ${name}. You are number ${katzDeliLine.length} in line.`
}
function nowServing(katzDeliLine) {
var beingServed
if (katzDeliLine.length > 0) {
beingServed = `Currently serving ${katzDeliLine[0]}.`
katzDeliLine.shift()
} else {
beingServed = "There is nobody waiting to be served!"
}
return beingServed
}
function currentLine(katzDeliLine) {
var fullLine
if (katzDeliLine.length > 0) {
fullLine = "The line is currently:"
for (let i = 0; i < katzDeliLine.length; i += 1) {
fullLine = fullLine + ` ${i + 1}. ${katzDeliLine[i]}`
if (i + 1 < katzDeliLine.length) {
fullLine = fullLine + ","
}
}
} else {
fullLine = "The line is currently empty."
}
return fullLine
}
|
import React from 'react'
import { Typography, Button, Card, CardActions, CardContent, CardMedia, Grow } from '@material-ui/core'
import useStyles from './styles'
import { useDispatch } from 'react-redux'
import { removeFromCart, updateItemQty } from '../../../redux/actions/cartActions'
export default function CartItem ({ item }){
const classes = useStyles()
const dispatch = useDispatch()
const handleRemove = (id)=> {
dispatch(removeFromCart(id))
}
const handleItemQty = (id, qty)=> {
dispatch(updateItemQty(id, qty))
}
return (
<Grow in >
<Card className={classes.card} elevation={4}>
<CardMedia image={item.imageUrl} alt={item.name} className={classes.media} />
<CardContent className={classes.cardContent}>
<Typography variant="h5">{item.name}</Typography>
<Typography variant="h6">${item.price}</Typography>
</CardContent>
<CardActions className={classes.cartActions}>
<div className={classes.buttons}>
<Button type="button" size="small" onClick={()=> handleItemQty(item._id, item.qty-1)}>-</Button>
<Typography> {item.qty} </Typography>
<Button type="button" size="small" onClick={()=> handleItemQty(item._id, item.qty+1)}>+</Button>
</div>
<Button variant="contained" type="button" color="secondary" onClick={() => handleRemove(item._id)}>Remove</Button>
</CardActions>
</Card>
</Grow>
)
}
|
// hoisting
console.log(name); // undefined
var name = 'Mike';
// var는 선언하기 전에 사용이 가능하다 => hoisting
// TDZ(Temporal Dead Zone)
// console.log(HELLO)
const HELLO = '안녕하세요';
// 호이스팅은 일어나지만 코드를 예측하여 에러를 발생시킨다.
// let과 const는 TDZ의 영항을 받는다. -> 블록스코프이기때문
let age = 30;
showAge = () => {
console.log(age);
let age = 20;
}
// showAge();
// 호이스팅은 스코프단위로 일어난다.
// 변수의 생성과정
// 1. 선언
// 2. 초기화 단계
// 3. 할당 단계
// var는 선언과 초기화가 동시에 이루어진다.
//
// let은 선언과 초기화가 따로 이루어진다.
//
// const 선언 초기화 할당이 모두 동시에 이루어진다.
// const GENDER;
// GENDER = 'male';
// 에러발생 => Uncaught SyntaxError: Missing initializer in const declaration
// var: 함수 스코프(function-scoped)
// let, const : 블록 스코프(block-scoped)
// 함수뿐아니라 if, for/while, try/catch 안에서만 사용가능
const AGE = 30;
if(AGE>19){
var txt = AGE.toString();
}
console.log(txt);
// const와 let은 if밖에서 사용불가능!
|
// @ts-check
function showTime() {
// get current time
let currentTime = new Date();
// set current time to innerText of the myClock div
document.getElementById("myClock").innerText = currentTime.toLocaleTimeString();
setTimeout(showTime, 200);
};
|
import React from 'react'
export default class HelpContainer extends React.Component {
render() {
return(
<React.Fragment><br></br>
<section className="container">
<div className="float-center">
<h1>What type of help do you require?</h1>
</div>
</section>
</React.Fragment>
)
}
}
|
$(function() {
'use strict';
var controller,
appView,
views = views || {};
moment.locale('ru');
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
window.reqres = new Backbone.Wreqr.RequestResponse();
window.collection = Backbone.Collection.extend({
model: Backbone.Model,
localStorage: new Backbone.LocalStorage('tasksCollection'),
comparator: function comparator(model) {
return model.get('timestamp');
}
});
appView = Backbone.View.extend({
className: 'wrapper',
template: '#wrapper',
keys: {
'right left up down enter': 'navigate',
'right+alt': function() {
this.changeDate(1);
},
'left+alt': function() {
this.changeDate(-1);
}
},
events: {
'click .header__arrow_right': function() {
this.changeDate(1);
},
'click .header__arrow_left': function() {
this.changeDate(-1);
}
},
initialize: function initialize() {
this.collection = new window.collection();
this.currentDate = moment().startOf('month');
this.subViews = [];
this.needSelectDate = null;
this.firstStart = true;
this.collection.fetch();
reqres.setHandlers({
'get:collection': {
callback: function() {
return this.collection;
},
context: this
},
'get:change:direction': {
callback: function() {
return this.direction;
},
context: this
}
});
if (window.addEventListener) {
window.addEventListener('storage', _.bind(this.storage, this), false);
} else {
window.attachEvent('onstorage', _.bind(this.storage, this));
}
this.render();
},
render: function render() {
var template = window.templateCache.get(this.template),
view;
$('body').prepend(this.$el.html(template({
month: this.currentDate.format('MMMM'),
year: this.currentDate.format('YYYY'),
})));
this.createCalendar();
return this;
},
changeDate: function changeDate(action) {
this.currentDate.add(action, 'month');
this.direction = action;
this.createCalendar();
},
createCalendar: function createCalendar() {
var startDate = this.currentDate.clone().startOf('month').startOf('week'),
endDate = startDate.clone().add(5, 'week').endOf('week'),
weekArray;
if (startDate.week() < endDate.week() + 1) {
weekArray = _.range(startDate.week(), endDate.week() + 1);
} else {
weekArray = _.range(startDate.week(), startDate.weeksInYear() + 1)
_.each(_.range(1, endDate.week() + 1), function(week) {
weekArray.push(week);
});
}
this.calendar = _.map(weekArray, function(weekNumber) {
var startOfWeek;
if (weekNumber < _.first(weekArray)) {
startOfWeek = this.currentDate.clone().week(weekNumber).add(1, 'year').startOf('week');
} else {
startOfWeek = this.currentDate.clone().week(weekNumber).startOf('week')
}
return {
week: weekNumber,
days: _.map(_.range(startOfWeek.day(), startOfWeek.day() + 7), function(date) {
var timeStamp = startOfWeek.clone().day(date).startOf('day').unix(),
model = this.collection.findWhere({timestamp: timeStamp});
if (model) {
return model;
} else {
return new Backbone.Model({
timestamp: timeStamp,
note: ''
});
}
return startOfWeek.clone().day(date).toDate();
}, this)
};
}, this);
this.renderWeeks();
},
renderWeeks: function renderWeeks() {
var self = this;
_.invoke(this.subViews, 'remove');
setTimeout(function(){
self.firstStart = false;
_.each(self.calendar, function(week) {
var weekView = new window.week({
week: week,
parent: self
});
self.$el.find('.calendar-body').append(weekView.render().el);
self.subViews.push(weekView);
}, self);
self.$('.header-date__month').text(self.currentDate.format('MMMM'))
.siblings('.header-date__year').text(self.currentDate.format('YYYY'));
}, this.firstStart ? 0 : 1200);
},
storage: function storage(e) {
var model;
if (!e) {
e = window.event;
}
if (e.key !== 'tasksCollection' && e.oldValue && e.newValue) {
this.collection.findWhere({id: JSON.parse(e.newValue).id}).fetch();
} else if (e.key !== 'tasksCollection' && !e.oldValue) {
model = new Backbone.Model(JSON.parse(localStorage.getItem(e.key)));
this.collection.add(model);
if (this.state === 'list') {
this.currentView.renderPost(model);
}
} else if (e.key !== 'tasksCollection' && !e.newValue) {
this.collection.findWhere({id: JSON.parse(e.oldValue).id}).destroy();
}
},
navigate: function navigate(e, name) {
if (this.$('.selected.opened').length) return;
var $selectedNote = this.$('.selected'),
$selectedDay = $selectedNote.closest('.calendar-week-day'),
$selectedWeek = $selectedDay.closest('.calendar-week'),
self = this;
$selectedNote.removeClass('selected');
if (name === 'right') {
if ($selectedDay.next().length) {
if ($selectedDay.next().hasClass('current')) {
$selectedDay.next().children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedDay.next().children('.calendar-week-day__date').text();
this.changeDate(1);
}
} else if ($selectedWeek.next().length) {
if ($selectedWeek.next().children('.current:first-child').length) {
$selectedWeek.next().children(':first-child').children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedWeek.next().children(':first-child').children('.calendar-week-day__date').text();
this.changeDate(1);
}
}
} else if (name === 'left') {
if ($selectedDay.prev().length) {
if ($selectedDay.prev().hasClass('current')) {
$selectedDay.prev().children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedDay.prev().children('.calendar-week-day__date').text();
this.changeDate(-1);
}
} else if ($selectedWeek.prev().length) {
if ($selectedWeek.prev().children('.current:last-child').length) {
$selectedWeek.prev().children(':last-child').children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedWeek.prev().children(':last-child').children('.calendar-week-day__date').text();
this.changeDate(-1);
}
}
} else if (name === 'up') {
$selectedNote.removeClass('selected');
if ($selectedWeek.prev().length) {
if ($selectedWeek.prev().children().eq($selectedDay.index()).hasClass('current')) {
$selectedWeek.prev().children().eq($selectedDay.index()).children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedWeek.prev().children().eq($selectedDay.index()).children('.calendar-week-day__date').text();
this.changeDate(-1);
}
} else {
this.needSelectDate = this.currentDate.clone().date($selectedNote.siblings('.calendar-week-day__date').text()).add(-1, 'week').date();
this.changeDate(-1);
}
} else if (name === 'down') {
$selectedNote.removeClass('selected');
if ($selectedWeek.next().length) {
if ($selectedWeek.next().children().eq($selectedDay.index()).hasClass('current')) {
$selectedWeek.next().children().eq($selectedDay.index()).children('.calendar-week-day__note').addClass('selected');
} else {
this.needSelectDate = $selectedWeek.next().children().eq($selectedDay.index()).children('.calendar-week-day__date').text();
this.changeDate(1);
}
} else {
this.needSelectDate = this.currentDate.clone().date($selectedNote.siblings('.calendar-week-day__date').text()).add(1, 'week').date();
this.changeDate(1);
}
} else if (name === 'enter') {
$selectedDay.trigger('dblclick').children('.calendar-week-day__note').addClass('selected');
}
if (this.needSelectDate) {
this.$('.current').children('.calendar-week-day__date').filter(function() {
return $(this).text() == (self.needSelectDate === 1 ? self.currentDate.format('D MMMM') : self.needSelectDate);
}).trigger('click');
this.needSelectDate = null;
}
},
remove: function remove() {
_.invoke(this.subViews, 'remove');
if(window.removeEventListener) {
window.removeEventListener('storage', this.storage)
} else {
window.detachEvent('onstorage', this.storage);
}
this.$el.empty();
return Backbone.View.prototype.remove.call(this);
}
});
window.week = Backbone.View.extend({
className: 'calendar-week',
events: {
'click .calendar-week-day': function(e) {
this.options.parent.$el.find('.selected').removeClass('selected');
$(e.currentTarget).children('.calendar-week-day__note').addClass('selected');
}
},
initialize: function initialize(options) {
this.options = options || {};
this.subViews = [];
},
render: function render() {
this.renderDays();
return this;
},
renderDays: function renderDays() {
_.each(this.options.week.days, function(day) {
var dayView = new window.day({
model: day,
currentDate: this.options.parent.currentDate
});
this.$el.append(dayView.render().el);
this.subViews.push(dayView);
}, this);
},
remove: function remove() {
var self = this;
this.$('.calendar-week-day').each(function(index) {
if (reqres.request('get:change:direction') > 0) {
$(this).addClass('go-left');
} else {
$(this).addClass('go-right');
}
});
setTimeout(function() {
_.invoke(self.subViews, 'remove');
self.$el.empty();
return Backbone.View.prototype.remove.call(self);
}, 1170);
}
});
window.day = Backbone.View.extend({
className: 'calendar-week-day',
keys: {
'backspace': function(e) {
if (this.$('.calendar-week-day__note').hasClass('selected') && !this.$('.calendar-week-day__note').hasClass('opened')) {
e.preventDefault();
this.model.save('note', '');
this.$('.calendar-week-day__note').addClass('selected').focus();
}
}
},
events: {
'click': function() {
Backbone.trigger('remove:note:view');
},
'dblclick': function(e) {
Backbone.trigger('remove:note:view');
var noteView = new window.note({
model: this.model,
event: e,
parent: this
});
$('.wrapper').append(noteView.render().el);
this.$('.calendar-week-day__note').addClass('opened');
}
},
template: _.template('<span class="calendar-week-day__date">{{- date }}</span><span class="calendar-week-day__note {{- hasNote }}" title="{{- note }}">{{- note }}</span>'),
initialize: function initialize(options) {
var self = this;
this.options = options || {};
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'textchange', function() {
this.$('.calendar-week-day__note').attr('title', this.model.get('note')).text(this.model.get('note'));
if (this.model.get('note') && this.model.get('note').length) {
this.$('.calendar-week-day__note').addClass('contained');
} else {
this.$('.calendar-week-day__note').removeClass('contained');
}
});
},
render: function render() {
var extModel = $.extend({}, this.model.attributes),
date = moment(this.model.get('timestamp'), 'X');
extModel.date = date.date() === 1 ? date.format('D MMMM') : date.date();
extModel.hasNote = this.model.get('note') && this.model.get('note').length ? 'contained' : '';
if (this.options.currentDate.month() === date.month()) {
this.$el.addClass('current');
}
if (date.day() === 6 || date.day() === 0) {
this.$el.addClass('holiday');
}
this.$el.html(this.template(extModel));
return this;
},
remove: function remove() {
this.$el.empty();
return Backbone.View.prototype.remove.call(this);
}
});
window.note = Backbone.View.extend({
tagName: 'form',
className: 'note',
keys: {
'esc': function() {
this.model.set('note', this.oldNote);
this.remove();
}
},
events: {
'input .note__text': function(e) {
this.model.set('note', $(e.currentTarget).val(), {silent: true});
this.model.trigger('textchange');
},
'focusout .note__text': 'save',
'submit': function(e) {
e.preventDefault();
this.save();
}
},
template: _.template('<input class="note__text" value="{{- note }}" placeholder="Новое событие">'),
initialize: function initialize(options) {
this.options = options || {};
this.event = this.options.event;
this.collection = reqres.request('get:collection');
this.oldNote = this.model.get('note');
this.listenTo(Backbone, 'remove:note:view', function() {
if (this.$('.note__text').val().length) {
this.save();
} else {
this.remove();
this.options.parent.$('.calendar-week-day__note').removeClass('opened');
}
});
},
render: function render() {
var self = this,
extModel = $.extend({}, this.model.attributes),
$note = $(this.event.currentTarget).children('.calendar-week-day__note');
this.$el.html(this.template(extModel));
setTimeout(function() {
self.$el.css({
top: $(self.event.currentTarget).position().top + $note.position().top + $note.height() / 2 + 4
});
if ($(self.event.currentTarget).offset().left + $(self.event.currentTarget).width() + self.$el.outerWidth() > $(window).width()) {
self.$el.css({
left: $(self.event.currentTarget).position().left - self.$el.outerWidth() + 5
}).addClass('left');
} else {
self.$el.css({
left: $(self.event.currentTarget).position().left + $(self.event.currentTarget).width()
});
}
self.$('.note__text').select();
}, 0);
return this;
},
save: function save() {
this.model.set({
note: this.$('.note__text').val()
});
if (this.model.isNew()) this.collection.add(this.model);
this.model.save();
this.remove();
this.options.parent.$('.calendar-week-day__note').removeClass('opened');
},
remove: function remove() {
this.$el.empty();
return Backbone.View.prototype.remove.call(this);
}
});
window.templateCache = {
ajaxGet: function(template) {
var data = '<h3> failed to load template : ' + template + '</h3>',
file = template.substring(1);
$.ajax({
async: false,
cache: true,
url: '/templates/' + file + '.html',
success: function(response) {
data = response;
}
});
return data;
},
get: function(selector) {
if (!this.templates) {
this.templates = {};
}
var template = this.templates[selector],
tmpl;
if (!template) {
tmpl = $(selector).html() || this.ajaxGet(selector);
template = _.template(tmpl);
this.templates[selector] = template;
}
return template;
}
};
window.app = new appView();
Backbone.history.start({pushState: true, root: '/'});
});
|
import React, { Component } from 'react';
import { Select } from 'antd';
const Option = Select.Option;
const MIN_YEAR = 2015;
class YearSelect extends Component {
constructor(props) {
super(props);
const value = this.props.value;
const currentYear = (new Date()).getFullYear();
const years = [];
for (let i = MIN_YEAR; i <= currentYear; i += 1) {
years.push(i);
}
this.state = {
value,
years,
};
}
componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
const value = nextProps.value;
this.setState({ value });
}
}
handleChange = (value) => {
if (!('value' in this.props)) {
this.setState({ value });
}
this.triggerChange(value);
}
triggerChange = (changedValue) => {
const onChange = this.props.onChange;
if (onChange) {
onChange(changedValue);
}
}
render() {
return (
<Select
placeholder="Year"
onChange={this.handleChange}
value={this.state.value}
style={{ width: '100%' }}
>
{this.state.years.map(obj => (
<Option value={obj}>{obj}</Option>
))}
</Select>
);
}
}
export default YearSelect;
|
var gulp = require('gulp')
var path = require('path')
var connect = require('gulp-connect')
var del = require('del')
var CONFIG = require('./build-tasks/config')
require('./build-tasks/styles')
require('./build-tasks/scripts')
require('./build-tasks/containers')
gulp.task("clean:web", function () {
return del([CONFIG.paths.buildWeb])
})
gulp.task("devServer", function () {
connect.server({
root: CONFIG.paths.buildWeb,
livereload: true,
fallback: path.resolve(__dirname, "./" + CONFIG.paths.buildWeb + "/index.html"),
})
})
gulp.task("build", ["clean:web"], function () {
return gulp.start(["scripts", "styles", "containers"])
})
gulp.task("dev", ["build"], function () {
gulp.watch(CONFIG.paths.clientSrc + "/**/*.pug", ["containers"])
gulp.watch(CONFIG.paths.clientSrc + "/**/*.less", ["styles"])
gulp.start("devServer")
})
gulp.task("default", function () {
CONFIG.watching = true
gulp.start("dev")
})
|
import { CHANGE_FIELD } from './constants'
const INITIAL_STATE = {
emailField: ''
}
const reducer = (state = INITIAL_STATE, action) => {
switch(action.type){
case CHANGE_FIELD:
return { ...state, emailField: action.payload}
default:
return state
}
}
export default reducer
|
const main = document.querySelector('main');
const idUrl = new URLSearchParams(window.location.search).get("id");
const nameInner = document.querySelector('.nameInner');
const articleInner = document.querySelector('article');
const userNamerInnerHtml = () => {
fetch('http://localhost:3000/users/' + idUrl)
.then(response => response.json())
.then(json => {
nameInner.innerHTML = json.name;
})
}
const userArticles = () => {
fetch('http://localhost:3000/posts?userId=' + idUrl)
.then(response => response.json())
.then(json => {
for (let i = 0; i < json.length; i++) {
const divCreaTitle = document.createElement('div');
divCreaTitle.className = "titleArticle p-3";
articleInner.appendChild(divCreaTitle);
let articleTitleInner = document.querySelectorAll('.titleArticle');
const divCreaBody = document.createElement('div');
divCreaBody.className = "bodyArticle p-3";
articleInner.appendChild(divCreaBody);
let articleBodyInner = document.querySelectorAll('.bodyArticle');
articleTitleInner[i].innerHTML = json[i].title;
articleBodyInner[i].innerHTML = json[i].body;
}
})
}
userNamerInnerHtml()
userArticles()
|
var opa_screen_initialized = false;
initScreen = function () {
// Do nothing if screen has previously been initalized.
if (opa_screen_initialized == true) {
return;
}
// Override main form submit
$("#owdInterviewForm").submit(function (e) {
e.preventDefault();
jsPost(this);
});
//handle back button
$("#owdInterviewForm").on("click", ".owd-back", function() {
jsGet(opa.screenInfo.backButtonURL);
});
// Override internal links
$("a.internalLink").click(function (e) {
e.preventDefault();
jsGet($(this).attr('href'));
});
// Add 'clicked' attribute to track which button is clicked
$("button[type=submit]").click(function () {
$(this).attr("clicked", true);
});
// Evaluate screen model
try {
var json = $("#interviewScreenObjects").html();
opa = eval("(" + json + ")"); // JSON.parse(json);
} catch (e) {
alert(e.name + ": " + e.message);
}
for (var i=0; i < opa.screenInfo.controls.length; i++) {
opa.screenInfo.controlsByName[opa.screenInfo.controls[i].name] = opa.screenInfo.controls[i];
}
// Set active tab in each tab group
//$("#instanceTabs li").last().addClass("active");
$(".instanceTabs").each(function() {
$(this).children("li").last().addClass("active");
});
$(".instanceViews").each(function() {
$(this).children(".entity-instance-group").last().addClass("active");
});
// Textbox onFocus styling
$('.select-style-text input[type="text"]').blur(function () {
$(this).parent().removeClass("text-selected");
});
$('.select-style-text input[type="text"]').focus(function () {
$(this).parent().addClass("text-selected");
});
// Sidebar button
/*
$('#sidebarButton').off(clickEvent).on(clickEvent, function () {
$('#interviewWrapper').removeClass('startOpen');
$('#interviewWrapper').toggleClass('sidebarOpen');
if ($('#interviewWrapper').hasClass('sidebarOpen')) {
}
else {
}
return false;
});
*/
// Swipe
/*$('#content').os_swipe( {
os_swipeLeft : function (event, direction, distance, duration, fingerCount) {
$('#interviewWrapper').removeClass('sidebarOpen startup');
},
os_swipeRight : function (event, direction, distance, duration, fingerCount) {
$('#interviewWrapper').removeClass('startup');
$('#interviewWrapper').addClass('sidebarOpen');
},
threshold : 30, fingers : 'all'
});
$('#progress-stages').os_swipe( {
os_swipeLeft : function (event, direction, distance, duration, fingerCount) {
$('#interviewWrapper').removeClass('sidebarOpen startup');
},
os_swipeRight : function (event, direction, distance, duration, fingerCount) {
$('#interviewWrapper').addClass('sidebarOpen');
},
threshold : 40, fingers : 'all'
});*/
//initFade()
initDirtyCheck();
try {
initDynamicControlState();
} catch(e) {
alert(e.name + ": " + e.message);
}
initCheckboxes();
initExplanations();
$('.sigPad').each(function() {
var id = $(this).attr('id');
var canvasWidth = Math.min($(this).closest('form').width() - (parseInt($(this).parent().css('padding-left').replace("px", "")) * 2), 600);
$(this).width(canvasWidth);
$(this).find("canvas").attr('width', canvasWidth);
$(this).signaturePad({drawOnly:true, lineTop:185, onDrawEnd: function() { processSignature(id) } });
});
Log.info("Interview page ready");
opa_screen_initialized = true
};
function navigationButtonPress() {
if ($('#interviewWrapper').hasClass('sidebarOpen')) {
$('#interviewWrapper').removeClass('sidebarOpen startup');
} else {
$('#interviewWrapper').removeClass('startup')
$('#interviewWrapper').addClass('sidebarOpen');
}
}
function getEnteredFormValues() {
return $("#owdInterviewForm").serializeObject();
}
function jsPost(form) {
adf.mf.api.amx.showLoadingIndicator();
var $button = $('button[type=submit][clicked=true]');
var buttonName = $button.attr('name');
var $form = $(form);
var postParams = $form.serializeObject();
var uri = $form.attr('action');
var attachmentsMap = {};
if ($('.new_image_file').length > 0 || $('.new_signature').length > 0) {
attachmentsMap = getNewImageAttachments();
}
if (buttonName.indexOf('ADDACTION_') == 0) {
var containmentRelCtrlId = buttonName.substring(10);
try {
opa_screen_initialized = false;
adf.mf.el.invoke( "#{applicationScope.august2016Interview.addEntityInstance}", [uri, containmentRelCtrlId, postParams, attachmentsMap], "", ["java.lang.String", "java.lang.String", "java.util.HashMap", "java.util.HashMap"],
function success() {
adf.mf.api.amx.hideLoadingIndicator();
},
function fail() {
Log.severe("INVOCATION ERROR");
adf.mf.api.amx.hideLoadingIndicator();
}
);
} catch (err) {
Log.severe("CORDOVA ERROR");
}
} else if (buttonName.indexOf('DELETEACTION_') == 0) {
var entityInstCtrlId = buttonName.substring(13);
try {
opa_screen_initialized = false;
adf.mf.el.invoke( "#{applicationScope.august2016Interview.deleteEntityInstance}", [uri, entityInstCtrlId, postParams, attachmentsMap], "", ["java.lang.String", "java.lang.String", "java.util.HashMap", "java.util.HashMap"],
function success() {
adf.mf.api.amx.hideLoadingIndicator();
},
function fail() {
Log.severe("INVOCATION ERROR");
adf.mf.api.amx.hideLoadingIndicator();
}
);
} catch (err) {
Log.severe("CORDOVA ERROR");
}
} else {
try {
opa_screen_initialized = false;
adf.mf.el.invoke( "#{applicationScope.august2016Interview.post}", [uri, postParams, attachmentsMap], "", ["java.lang.String", "java.util.HashMap", "java.util.HashMap"],
function success() {
adf.mf.api.amx.hideLoadingIndicator();
},
function fail() {
Log.severe("INVOCATION ERROR");
adf.mf.api.amx.hideLoadingIndicator();
}
);
} catch (err) {
//alert(err)
Log.severe("CORDOVA ERROR");
}
}
}
function getNewImageAttachments() {
var attachmentsMap = {};
$('.new_image_file').each(function() {
var fileURI = this.src;
var attachmentControlId = this.parentNode.parentNode.id.slice(11);
if (attachmentControlId in attachmentsMap) {
var listForAttachmentControl = attachmentsMap[attachmentControlId];
listForAttachmentControl.push(fileURI);
} else {
var newListForAttachmentControl = [ fileURI ];
attachmentsMap[attachmentControlId] = newListForAttachmentControl;
}
});
$('.new_signature').each(function() {
var signatureID = this.textContent;
var attachmentControlId = this.parentNode.id.slice(22);
if (attachmentControlId in attachmentsMap) {
var listForAttachmentControl = attachmentsMap[attachmentControlId];
listForAttachmentControl.push(signatureID);
} else {
var newListForAttachmentControl = [ signatureID ];
attachmentsMap[attachmentControlId] = newListForAttachmentControl;
}
});
return attachmentsMap;
}
function getNewImageAttachmentsSerialized() {
return JSON.stringify(getNewImageAttachments());
}
function jsGet(uri) {
adf.mf.api.amx.showLoadingIndicator();
if(owdPageIsDirty) {
if(!confirm(opa.unsubmittedDataWarning.warningMsg)) {
adf.mf.api.amx.hideLoadingIndicator();
return;
}
}
try {
opa_screen_initialized = false;
adf.mf.el.invoke( "#{applicationScope.august2016Interview.get}", [uri], "", ["java.lang.String"],
function success() {
adf.mf.api.amx.hideLoadingIndicator();
},
function fail() {
Log.severe("INVOCATION ERROR");
adf.mf.api.amx.hideLoadingIndicator();
}
);
} catch (err) {
Log.severe("CORDOVA ERROR");
}
}
$.fn.serializeObject = function () {
var o = {
};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else {
o[this.name] = this.value || '';
}
});
return o;
};
function initFade() {
if (fadeAnimation.fadeInDuration > 0) {
jQuery("#wrapper").hide();
jQuery("#wrapper").fadeIn(fadeAnimation.fadeInDuration);
}
if (fadeAnimation.fadeOutDuration > 0) {
var doingActualSubmit = false;
var buttonClicked;
jQuery("#owdInterviewForm").submit(function () {
if (!doingActualSubmit) {
buttonClicked = jQuery("button[type=submit][clicked=true]")[0];
if (buttonClicked != null && buttonClicked != undefined) {
jQuery("#wrapper").fadeOut(fadeAnimation.fadeOutDuration, actualSubmit);
actualSubmit();
}
return false;
}
});
function actualSubmit() {
doingActualSubmit = true;
buttonClicked.click();
}
}
}
function initDirtyCheck() {
owdPageIsDirty = false;
var owdMarkPageAsDirty;
if (opa.unsubmittedDataWarning.isEnabled) {
var owdPageIsAlwaysDirty = opa.unsubmittedDataWarning.hasUnsubmitted;
var owdInputControls = [];
var owdInputKinds = [];
var owdInputDefaults = [];
function owdControlValue(ctl, kind) {
if (kind == "input" && (ctl.type == "radio" || ctl.type == "checkbox"))
return ctl.checked;
return ctl.value;
}
function owdMakeDirty() {
var pageIsActuallyDirty = owdPageIsAlwaysDirty;
var idx, ctl;
for (idx = 0; idx < owdInputControls.length; idx++) {
ctl = owdInputControls[idx];
if (owdControlValue(ctl, owdInputKinds[idx]) !== owdInputDefaults[idx]) {
pageIsActuallyDirty = true;
break;
}
}
if (!owdPageIsDirty && pageIsActuallyDirty) {
window.onbeforeunload = function () {
return opa.unsubmittedDataWarning.warningMsg;
}
} else if (owdPageIsDirty && !pageIsActuallyDirty) {
window.onbeforeunload = null;
}
owdPageIsDirty = pageIsActuallyDirty;
}
owdMarkPageAsDirty = function() {
owdPageIsAlwaysDirty = true;
owdMakeDirty();
}
//attach event handlers
jQuery("#owdInterviewForm").submit(function () {
if (owdPageIsDirty) {
owdPageIsDirty = false;
window.onbeforeunload = null;
}
});
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].className.indexOf("owd-input") >= 0) {
owdInputControls.push(inputs[i]);
owdInputKinds.push("input");
owdInputDefaults.push(owdControlValue(inputs[i], "input"));
inputs[i].onchange = function () {
owdMakeDirty();
};
}
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
if (selects[i].className.indexOf("owd-input") >= 0) {
owdInputControls.push(selects[i]);
owdInputKinds.push("select");
owdInputDefaults.push(owdControlValue(selects[i], "select"));
selects[i].onchange = function () {
owdMakeDirty();
}
}
}
if (owdPageIsAlwaysDirty && owdInputControls.length > 0) {
owdMakeDirty();
}
}
}
function htmlDecode(encodedhtml) {
return $("<div/>").html(encodedhtml).text();
}
function htmlEncode(rawText) {
return $("<div/>").text(rawText).html();
}
function initDynamicControlState() {
function changeCtrlState(ctrlInfo, state){
var div = $("#cd-" + ctrlInfo.id.replace(".", "\\."));
var ctrlType = ctrlInfo.type;
var inputType = ctrlInfo.inputType;
if (state === "hidden") {
if (div.hasClass("owd-entity-table-cell")) {
div.children("div").hide();
div.addClass("owd-responsive-hide");
var msgCell = $("#cmc-" + ctrlInfo.id.replace(".", "\\."));
if (msgCell.length > 0) {
msgCell.children("div").hide();
msgCell.addClass("owd-responsive-hide")
}
} else {
div.hide();
}
div.find("[aria-hidden]").attr("aria-hidden", "true").attr("aria-disabled", "false").attr("aria-required", "false");
} else {
if (state === "enabled") {
div.find("img.mandatory").show();
div.find("img.mandatory-table").show();
if (ctrlType === "BooleanInputControl") {
var uncertainOpt = div.find('input[type="radio"][value=""]');
if (uncertainOpt) {
uncertainOpt.attr("style", "display: none");
uncertainOpt.hide();
div.find('label[id="' + uncertainOpt.attr('aria-labelledby') + '"]').hide();
}
}
div.find("[aria-hidden]").attr("aria-hidden", "false").attr("aria-disabled", "false").attr("aria-required", "true");
} else {
div.find("img.mandatory").hide();
div.find("img.mandatory-table").hide();
if (ctrlType === "BooleanInputControl") {
var uncertainOpt = div.find('input[type="radio"][value=""]');
if (uncertainOpt) {
uncertainOpt.attr("style", "");
uncertainOpt.show();
div.find('label[id="' + uncertainOpt.attr('aria-labelledby') + '"]').show();
}
}
div.find("[aria-hidden]").attr("aria-hidden", "false").attr("aria-required", "false");
}
var isReadOnly = state === "readonly";
if(isReadOnly) {
div.find("[aria-hidden]").attr("aria-disabled", "true")
resetValue(ctrlInfo);
} else {
div.find("[aria-hidden]").attr("aria-disabled", "false")
}
if (inputType === "Calendar") {
var input = $('[name="' + ctrlInfo.name + '"]');
if (isReadOnly) {
input.attr("disabled", true);
} else {
input.removeAttr("readonly");
}
} else if (inputType === "dmy-inputs") {
var dayInput = $('[name="' + ctrlInfo.dayName + '"]');
var monthInput = $('[name="' + ctrlInfo.monthName + '"]');
var yearInput = $('[name="' + ctrlInfo.yearName + '"]');
if (isReadOnly) {
dayInput.attr("disabled", true);
monthInput.attr("disabled", true);
yearInput.attr("readonly", true);
} else {
dayInput.removeAttr("disabled");
monthInput.removeAttr("disabled");
yearInput.removeAttr("readonly");
}
} else {
div.find(":input").each(function () {
var input = $(this);
if (input.is('input[type="text"]') || input.is('textarea')) {
if (isReadOnly) {
input.attr("readonly", true);
} else {
input.removeAttr("readonly");
}
} else {
if (isReadOnly) {
input.attr("disabled", true);
} else {
input.removeAttr("disabled");
}
}
});
}
if (div.hasClass("owd-entity-table-cell")) {
div.children("div").show();
div.removeClass("owd-responsive-hide");
var msgCell = $("#cmc-" + ctrlInfo.id.replace(".", "\\."));
if (msgCell.length > 0) {
msgCell.children("div").show();
msgCell.removeClass("owd-responsive-hide")
}
} else {
div.show();
}
div.show();
}
}
function resetValue(ctrlInfo){
//reset value back to the current tactual value
if(ctrlInfo.inputType === "dmy-inputs"){
$('[name="' + ctrlInfo.dayName + '"]').val(ctrlInfo.actDayVal);
$('[name="' + ctrlInfo.monthName + '"]').val(ctrlInfo.actMonthVal);
$('[name="' + ctrlInfo.yearName + '"]').val(ctrlInfo.actYearVal);
} else if(ctrlInfo.inputType === "checkbox"){
var jCtrl = $('#' + ctrlInfo.id.replace(".", "\\."));
if(ctrlInfo.actValue === "true")
jCtrl.attr("checked", "");
else
jCtrl.removeAttr("checked");
jCtrl.trigger("change");
} else if(ctrlInfo.inputType === "Calendar") {
var val = ctrlInfo.actYearVal != "" ? new Date(ctrlInfo.actYearVal, ctrlInfo.actMonthVal - 1, ctrlInfo.actDayVal, 0, 0, 0, 0) : null;
$('[name="' + ctrlInfo.name + '"]').val(val);
} else if(ctrlInfo.inputType === "Radiobutton"){
var jCtrl = $('[name="' + ctrlInfo.id + '"]');
var changed = false;
for(var i =0; i < jCtrl.length; ++i){
var radio = jCtrl[i];
if(radio.value === ctrlInfo.actValue && !radio.checked){
radio.checked = true;
changed = true;
break;
}
}
if(changed)
jCtrl.trigger("change");
} else {
var jCtrl = $('[name="' + ctrlInfo.id + '"]');
jCtrl.val(ctrlInfo.actValue);
jCtrl.trigger("change");
}
}
function getCtrlState(ctrlId){
var div = $("#cd-" + ctrlId.replace(".", "\\."));
if(div.length == 0 || div.find('[aria-hidden="true"]').length > 0)
return "hidden";
if( div.find('[aria-disabled="true"]').length > 0)
return "readonly";
if( div.find('[aria-required="false"]').length > 0)
return "optional";
return "enabled";
}
function getValue(ctrl, dataType, asString) {
var stringVal;
if (ctrl.is('input[type="radio"]')) {
for (var i = 0; i < ctrl.length; ++i) {
var el = ctrl[i];
if (el.checked) {
stringVal = el.value;
break;
}
}
} else if (ctrl.is('input[type="checkbox"]')) {
stringVal = ctrl.is(":checked") ? "true" : "false";
} else {
stringVal = ctrl.val();
}
stringVal = $.trim(stringVal);
if(asString === true)
return stringVal;
if (dataType === 1) {
//boolean val
if (stringVal === "true" || stringVal.toLowerCase() === opa.dataFormats.bool.trueVal.toLowerCase()) {
return true;
} else if (stringVal === "false" || stringVal.toLowerCase() === opa.dataFormats.bool.falseVal.toLowerCase()) {
return false;
} else {
return "";
}
} else if (dataType === 2) {
return stringVal;
} else if (dataType === 4 || dataType === 8) {
//number val
if (stringVal === "")
return "";
var doubleVal = parseFloat(stringVal);
return isNaN(doubleVal) ? null : doubleVal;
} else {
throw "Only booleans, strings and numbers are currently supported";
}
}
function filterChildEnumOptions(parentCtrlName) {
var parentCtrlInfo = opa.screenInfo.controlsByName[parentCtrlName];
var filterRules = filterRulesHash[parentCtrlName];
var parentCtrlState = getCtrlState(parentCtrlInfo.id);
var parentCtrl = $('[name="' + parentCtrlName + '"]');
var parentVal = parentCtrlState !== "hidden" ? getValue(parentCtrl, parentCtrlInfo.dataType, true) : "";
for(var i = 0; i < filterRules.length; ++i) {
var rule = filterRules[i];
var childCtrlInfo = opa.screenInfo.controlsByName[rule.childCtrlName];
var childCtrl = $('[name="' + rule.childCtrlName + '"]');
var currentVal = getValue(childCtrl, childCtrlInfo.dataType);
var childVals = rule.values[parentVal];
if (childCtrlInfo.inputType == "Radiobutton") {
var parent = $(childCtrl[0].parentElement);
parent.empty();
var defaultRadio;
var found = false;
for (var j = 0; j < childVals.length; ++j) {
var val = childVals[j];
var radio = $('<input class="owd-input" type="radio">')
.attr("name", childCtrlInfo.name)
.attr("id", childCtrlInfo.id + j)
.attr("value", val.value)
.attr("aria-labelledby", "lbl-" + childCtrlInfo.id + j);
parent.append(radio);
var radioRules = filterRulesHash[childCtrlInfo.name];
if(radioRules !== undefined) {
radio.change(function () {
filterChildEnumOptions(childCtrlInfo.name)
});
}
if(val.value === "")
defaultRadio = radio;
if (val.value == currentVal){
found = true;
radio.attr("checked", true);
}
var lbl = $("<label>")
.attr("for", childCtrlInfo.id + j)
.attr("id", "lbl-" + childCtrlInfo.id + j)
.text(htmlDecode(val.display));
lbl.insertAfter(radio);
lbl.prepend("<span></span>")
$("<br>").insertAfter(lbl);
}
if(!found)
defaultRadio.attr("checked", true);
} else {
if (childCtrl.length == 0)
return;
childCtrl.empty();
var found = false;
for (var j = 0; j < childVals.length; ++j) {
var item = childVals[j];
var display = item.display === "" ? " " : item.display;
var opt = new Option(htmlDecode(display));
opt.value = item.value;
if (item.value === currentVal) {
opt.selected = true;
found = true;
}
childCtrl.append(opt);
}
if (!found) {
childCtrl.val("");
childCtrl.trigger("change");
}
if (childCtrl.data("ui-combobox") !== undefined) {
childCtrl.data("ui-combobox").initOptions();
}
}
var ctrlState = controlStates[childCtrlInfo.id];
ctrlState.filtered = (parentCtrlState === 'hidden' || parentVal == "") ? "readonly" : "enabled";
var currentState = getCtrlState(childCtrlInfo.id);
var newState;
if(ctrlState.calculated === "hidden")
newState = "hidden";
else if(ctrlState.filtered === "readonly")
newState = "readonly";
else
newState == ctrlState.calculated;
if(newState !== currentState){
changeCtrlState(childCtrlInfo, newState);
if(newState === "readonly")
resetValue(childCtrlInfo);
}
}
}
//init dynamic conditions
function initCtrlStateExpr(exprDef) {
if (exprDef.isConstant) {
return new OPAControlStateEvaluator.ConstantExpression(exprDef.result);
} else {
var ctrl = ctrlsById[exprDef.attrCtrlName];
if (!ctrl) {
var state = opa.screenInfo.controlsByName[exprDef.attrCtrlName].state;
ctrl = new OPAControlStateEvaluator.Control(exprDef.attrCtrlName, state);
controls.push(ctrl);
ctrlsById[ctrl.id] = ctrl;
}
if (!ctrl.initForExpr) {
ctrl.initForExpr = true;
var jqCtrl = $("[name=\"" + exprDef.attrCtrlName + "\"]");
ctrl.value = getValue(jqCtrl, exprDef.exprValType);
jqCtrl.change(function () {
stateEngine.setControlValue(exprDef.attrCtrlName, getValue(jqCtrl, exprDef.exprValType));
stateEngine.evaluate();
});
}
return new OPAControlStateEvaluator.DynamicExpression(exprDef.attrCtrlName, exprDef.exprType, exprDef.exprOp, exprDef.exprVals);
}
}
var rules = [];
var controls = [];
var ctrlsById = {};
var stateEngine;
var controlStates = {};
for(var i = 0; i < opa.screenInfo.controls.length; ++i){
var ctrlInfo = opa.screenInfo.controls[i];
controlStates[ctrlInfo.id] = {"calculated": ctrlInfo.state, "filtered": "enabled"};
}
for (var i = 0; i < opa.controlRules.length; ++i) {
var ruleDef = opa.controlRules[i];
var hideIfExpr = initCtrlStateExpr(ruleDef.hideIfExpr);
var readOnlyIfExpr = initCtrlStateExpr(ruleDef.readOnlyIfExpr);
var optionalIfExpr = initCtrlStateExpr(ruleDef.optionalIfExpr);
var rule = new OPAControlStateEvaluator.ControlStateRule(ruleDef.ctrlName, hideIfExpr, readOnlyIfExpr, optionalIfExpr, ruleDef.defaultState);
rules.push(rule);
if (!ctrlsById[ruleDef.ctrlName]) {
var state = opa.screenInfo.controlsByName[ruleDef.ctrlName].state;
var ctrl = new OPAControlStateEvaluator.Control(ruleDef.ctrlName, state);
controls.push(ctrl);
ctrlsById[ctrl.id] = ctrl;
}
}
stateEngine = new OPAControlStateEvaluator.Engine(rules, controls);
stateEngine.onStateChange = function (controls) {
for (var i = 0; i < controls.length; ++i) {
var ctrl = controls[i];
var ctrlInfo = opa.screenInfo.controlsByName[ctrl.id];
var ctrlState = controlStates[ctrlInfo.id];
var state = ctrl.state;
if(ctrl.state === "enabled" && ctrlState.filtered === "readonly")
state= "readonly";
changeCtrlState(ctrlInfo, state);
ctrlState.calculated = ctrl.state;
}
for(var i = 0; i < controls.length; ++i){
if(filterRulesHash[ctrl.id] != undefined){
filterChildEnumOptions(ctrl.id);
}
}
stateEngine.evaluate();
}
$("#owdInterviewForm").append($('<input name="__DYNAMIC_CONTROL_STATE" type="hidden" value="true"/>'));
var filterRulesHash = {};
//init enumeration filters
for(var i =0; i < opa.listFilterRules.length; ++i){
var filterRule = opa.listFilterRules[i];
var parentCtrl = $('[name="' + filterRule.parentCtrlName + '"]');
if(parentCtrl.length > 0) {
var filters = filterRulesHash[filterRule.parentCtrlName];
if(filters === undefined){
filters = [];
filterRulesHash[filterRule.parentCtrlName] = filters;
}
filters.push(filterRule);
parentCtrl.change(function () {
filterChildEnumOptions(this.name)
});
}
}
for(var key in filterRulesHash){
filterChildEnumOptions(key);
}
stateEngine.evaluate();
}
function initCheckboxes() {
//boolean attribute checkbox controls
var ctrls = opa.screenInfo.controls;
for(var i = 0; i < ctrls.length; ++i){
var ctrlInfo = ctrls[i];
if(ctrlInfo.type === "BooleanInputControl" && ctrlInfo.inputType === "checkbox"){
var checkbox = $('#' + ctrlInfo.id.replace(".", "\\."));
checkbox.attr('name', ctrlInfo.name + "-cb");
var val = checkbox.is(':checked') ? "true" : "false";
checkbox.parent().append('<input type="hidden" value="' + val + '" name="' + ctrlInfo.name + '" id="__cbHiddenInput__' + ctrlInfo.id + '">');
checkbox.on("change", function(){
var $this = $(this);
var shadowCtrl = $('#__cbHiddenInput__' + $this.attr('id').replace(".", "\\."));
var val = $this.is(':checked') ? "true" : "false";
shadowCtrl.attr("value", val);
});
}
}
}
function initExplanations() {
jQuery('.explanation').each(function () {
var caption = jQuery('.explanation_caption', this);
var imgNode = caption.children('img').first();
var details = jQuery('.explanation_details', this);
//non-empty decision report
if (details.length !== 0) {
details.hide();
var anchor = caption.children('.explanation-node-text').first();
//initialise the caption
anchor.addClass('explanation-tree-parent');
caption.click(function (event) {
details.toggle('blind');
var src = imgNode.attr('src') == explanationParams.captionCollapseImage ? explanationParams.captionExpandImage : explanationParams.captionCollapseImage;
var alt = src == explanationParams.captionCollapseImage ? explanationParams.nodeCollapseAlt : explanationParams.nodeExpandAlt
imgNode.attr('src', src);
imgNode.attr('alt', alt);
//Oliver:
$(this).toggleClass('treeOpen');
});
anchor.keydown(function (event) {
// handle cursor keys
if (event.keyCode == 37) {
details.hide('blind');
imgNode.attr('src', explanationParams.captionExpandImage).attr('alt', explanationParams.nodeExpandAlt);
}
if (event.keyCode == 39) {
details.show('blind');
imgNode.attr('src', explanationParams.captionCollapseImage).attr('alt', explanationParams.nodeCollapseAlt);
}
});
anchor.click(function (event) {
event.preventDefault();
})
//initialise every node in the decision report
jQuery('li', details).each(function () {
var node = jQuery(this);
var childContent = jQuery(this).children('ul').first();
var imgNode = node.children("img").first();
if (childContent.length !== 0) {
childContent.hide();
imgNode.attr('src', explanationParams.nodeExpandImage).attr('alt', explanationParams.nodeExpandAlt);
node.click(function (event) {
childContent.toggle('blind');
var src = imgNode.attr('src') === explanationParams.nodeExpandImage ? explanationParams.nodeCollapseImage : explanationParams.nodeExpandImage;
var alt = imgNode.attr('alt') === explanationParams.nodeExpandImage ? explanationParams.nodeExpandAlt : explanationParams.nodeCollapseAlt;
imgNode.attr('src', src).attr('alt', alt);
event.stopPropagation();
//Oliver:
$(this).toggleClass('treeOpen');
});
var anchor = node.children('.explanation-node-text').first();
anchor.addClass('explanation-tree-parent');
anchor.keydown(function (event) {
// handle cursor keys
if (event.keyCode == 37) {
childContent.hide('blind');
imgNode.attr('src', explanationParams.nodeExpandImage).attr('alt', explanationParams.nodeExpandAlt);
event.stopPropagation()
} else if (event.keyCode == 39) {
childContent.show('blind');
imgNode.attr('src', explanationParams.nodeCollapseImage).attr('alt', explanationParams.nodeCollapseAlt);
event.stopPropagation()
}
});
anchor.click(function (event) {
//this will stop the browser history from expand/contract something
event.preventDefault();
});
} else {
//add dummy click handler to stop events from propagating
node.click(function (event) {
event.stopPropagation();
})
}
//handling for the "see above for proof"
var prevNodeRef = node.children('.explanation-proven-ref');
if (prevNodeRef.length !== 0) {
prevNodeRef.click(function (event) {
//ie #somenodeid
var refNodeId = prevNodeRef.attr('href');
var referencedNode = jQuery(refNodeId, details);
var listNode = referencedNode.children('ul').first();
var imgNode = referencedNode.children('img').first();
var owningList = referencedNode.parent();
//if the node isn't currently visible we'll animate its expansion
if (owningList.is('ul') && !owningList.is(":visible") && listNode.length === 1) {
listNode.hide();
imgNode.attr('src', explanationParams.nodeExpandImage).attr('alt', explanationParams.nodeExpandAlt);
}
//make sure the node is visible
while (owningList.is('ul') && !owningList.is(":visible")) {
owningList.show();
owningList.parent().children('img').first().attr('src', explanationParams.nodeCollapseImage).attr('alt', explanationParams.nodeCollapseAlt);
owningList = owningList.parent().parent();
}
//go to it
jQuery('html, body').animate(
{scrollTop:referencedNode.offset().top},
1, "swing",
function () {
if (listNode.length === 1) {
//auto expand node
listNode.show('blind');
imgNode.attr('src', explanationParams.nodeCollapseImage).attr('alt', explanationParams.nodeCollapseAlt);
}
});
//stop the link going into the browser history
event.preventDefault();
});
}
});
}
});
}
$( document ).ready(function() {
initScreen();
});
|
const electron = require('electron');
const config = require('./config');
const openAboutWindow = require('electron-about-window').default;
const { app, shell, mainWindow, BrowserWindow } = electron;
let win;
const appMenu = [
{
label: 'About Mio',
click: () =>
openAboutWindow({
icon_path: `${__dirname}/assets/icon.png`,
copyright: `Copyright (c) ${new Date().getFullYear()} Jonas Johansson`,
homepage: 'https://jonasjohansson.itch.io/mio',
win_options: {
titleBarStyle: 'hidden'
},
package_json_dir: __dirname
})
},
{ type: 'separator' },
{
label: 'Preferences…',
accelerator: 'Cmd+,',
click() {
config.openInEditor();
}
},
{
label: 'Ghost',
accelerator: 'Cmd+G',
type: 'checkbox',
checked: false,
click: function (item, BrowserWindow) {
if (item.checked) {
BrowserWindow.setOpacity(0);
} else {
BrowserWindow.setOpacity(1);
}
}
},
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
];
const windowMenu = [{ role: 'minimize' }, { role: 'close' }];
const helpMenu = [
{
label: 'Website',
click() {
shell.openExternal('https://jonasjohansson.se');
}
},
{
label: 'Source Code',
click() {
shell.openExternal('https://github.com/jonasjohansson/mio');
}
},
{ type: 'separator' },
{
label: 'Open Developer Tools',
click() {
win = BrowserWindow.getAllWindows()[0];
win.webContents.openDevTools({ mode: 'detach' });
}
},
{
label: 'Reset',
click() {
config.clear();
win = BrowserWindow.getAllWindows()[0];
win.webContents.session.clearCache(function () {});
}
},
{ role: 'reload' }
];
const menu = [
{
label: app.name,
submenu: appMenu
},
{
role: 'window',
submenu: windowMenu
},
{
role: 'help',
submenu: helpMenu
}
];
module.exports = electron.Menu.buildFromTemplate(menu);
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/packageB/consultant_topic/main" ], {
"05e5": function(n, e, t) {},
"0d7a": function(n, e, t) {
function a(n) {
return n && n.__esModule ? n : {
default: n
};
}
function i(n, e) {
var t = Object.keys(n);
if (Object.getOwnPropertySymbols) {
var a = Object.getOwnPropertySymbols(n);
e && (a = a.filter(function(e) {
return Object.getOwnPropertyDescriptor(n, e).enumerable;
})), t.push.apply(t, a);
}
return t;
}
function o(n) {
for (var e = 1; e < arguments.length; e++) {
var t = null != arguments[e] ? arguments[e] : {};
e % 2 ? i(Object(t), !0).forEach(function(e) {
r(n, e, t[e]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n, Object.getOwnPropertyDescriptors(t)) : i(Object(t)).forEach(function(e) {
Object.defineProperty(n, e, Object.getOwnPropertyDescriptor(t, e));
});
}
return n;
}
function r(n, e, t) {
return e in n ? Object.defineProperty(n, e, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : n[e] = t, n;
}
Object.defineProperty(e, "__esModule", {
value: !0
}), e.default = void 0;
var c = t("2f62"), s = a(t("80d6")), u = a(t("327a")), l = (a(t("d80f")), t("db49")), f = t("371c"), d = a(t("8e44")), p = {
mixins: [ u.default ],
components: {
Loading: function() {
t.e("components/views/loading").then(function() {
return resolve(t("7756"));
}.bind(null, t)).catch(t.oe);
},
Guest: function() {
Promise.all([ t.e("common/vendor"), t.e("pages/packageB/consultant_topic/_guest") ]).then(function() {
return resolve(t("affe"));
}.bind(null, t)).catch(t.oe);
}
},
data: function() {
return {
winner: [],
yesterdayWinner: [],
my_ranking: {
my_ranking: "",
my_ranking_desc: ""
},
type: "",
rankingBooth: [ {
name: "首页",
link: "/pages/index/main"
}, {
name: "资格查询",
link: "/pages/check_condition/main?verify_type=杭州购房资格查询"
}, {
name: "落户查询",
link: "/pages/check_condition/main?verify_type=杭州落户查询"
}, {
name: "购房指南",
link: "/pages/personal_package/material/main"
}, {
name: "房贷计算",
link: "/pages/loan_computer/main"
}, {
name: "税费计算",
link: "/pages/personal_package/taxation/main"
} ],
is_consultant: !1
};
},
computed: o(o({}, (0, c.mapState)([ "rankingTabs" ])), {}, {
show_winner: function() {
return this.rankingTabs.every(function(n) {
return "yesterday" !== n.key;
});
},
link: function() {
return "/pages/packageB/image_page/main?img=".concat(encodeURIComponent("https://cdn.vip-wifi.com/hzfangchan/version-img/1.14.25/consultants/topic_info.png"));
}
}),
onShareAppMessage: function() {
return this.getShareInfo({
title: "置业顾问活跃度排行",
path: "/pages/packageB/consultant_topic/main"
});
},
onLoad: function() {
var n = this;
d.default.getUserInfo().then(function(e) {
var t = e.is_consultant;
n.is_consultant = t, n.type = t ? "today" : "all", n.getData();
});
},
onPullDownRefresh: function() {
this.loading || (this.page = 1, this.items = [], this.getData());
},
methods: {
getData: function() {
var n = this;
this.loading = !0;
var e = {
today: "consultantTodayRankings",
yesterday: "consultantYesterdayRankings",
week: "consultantWeeklyRankings"
};
if ("all" === this.type) {
var t = this.page;
this.no_reach_bottom = !1, d.default.getConsultants({
page: t,
per: l.DEFAULT_PER
}).then(function(e) {
var a = e.items;
5 === t && (n.no_reach_bottom = !0), n.handleData({
items: a.map(function(n) {
return o({
consultant_headimgurl: n.weixin_headimgurl,
consultant_name: n.name,
consultant_level: n.level,
consultant_id: n.id,
consultant_weixin_name: n.weixin_name
}, n);
})
});
});
} else this.no_reach_bottom = !0, "today" === this.type && this.show_winner && d.default[e.yesterday]().then(function(e) {
var t = e.items;
n.yesterdayWinner = t.slice(0, 6);
}), d.default[e[this.type]]().then(function(e) {
var t = e.my_ranking, a = e.items, i = e.winner, o = void 0 === i ? [] : i;
n.my_ranking = t, n.items = a, n.winner = o, n.loading = !1, wx.stopPullDownRefresh();
});
},
changeCategory: function(n) {
this.type = n, this.page = 1, this.items = [], this.getData();
},
setClipboardData: function(n) {
var e = n.currentTarget.dataset, t = e.weixin, a = e.id;
s.default.setClipboardData(t, function() {
wx.showModal({
title: "复制成功",
content: "添加置业顾问时,请说明来自杭州购房通",
showCancel: !1
});
}), f.UserLog.copyConsultant(a);
},
goCst: function(n) {
var e = n.currentTarget.dataset.id;
wx.navigateTo({
url: "/pages/consultants/card/main?id=".concat(e)
});
}
}
};
e.default = p;
},
1367: function(n, e, t) {
var a = t("05e5");
t.n(a).a;
},
7516: function(n, e, t) {
(function(n) {
function e(n) {
return n && n.__esModule ? n : {
default: n
};
}
t("6cdc"), e(t("66fd")), n(e(t("7dbf")).default);
}).call(this, t("543d").createPage);
},
"7dbf": function(n, e, t) {
t.r(e);
var a = t("c31d"), i = t("9b86");
for (var o in i) [ "default" ].indexOf(o) < 0 && function(n) {
t.d(e, n, function() {
return i[n];
});
}(o);
t("1367");
var r = t("f0c5"), c = Object(r.a)(i.default, a.b, a.c, !1, null, "511053da", null, !1, a.a, void 0);
e.default = c.exports;
},
"9b86": function(n, e, t) {
t.r(e);
var a = t("0d7a"), i = t.n(a);
for (var o in a) [ "default" ].indexOf(o) < 0 && function(n) {
t.d(e, n, function() {
return a[n];
});
}(o);
e.default = i.a;
},
c31d: function(n, e, t) {
t.d(e, "b", function() {
return a;
}), t.d(e, "c", function() {
return i;
}), t.d(e, "a", function() {});
var a = function() {
var n = this;
n.$createElement;
n._self._c, n._isMounted || (n.e0 = function(n) {
n.stopPropagation();
});
}, i = [];
}
}, [ [ "7516", "common/runtime", "common/vendor" ] ] ]);
|
import Utils from 'udn-newmedia-utils'
export const handle_quizIndex = state => {
state.quizIndex ++
}
export const handle_dequizIndex = state => {
state.quizIndex --
}
export const handle_lookDemand = state => {
state.quizIndex = 9
}
export const detectDevice = state => {
state.platform = Utils.detectPlatform()
}
export const getWebTitle = state => {
state.webTitle = document.getElementsByTagName('title')[0].text
}
export const handle_headerBgc = state => {
state.headerBgc = '#fff'
}
export const handle_headerTrans = state => {
state.headerBgc = 'transparent'
}
export const handle_again = state => {
state.quizIndex = 0
}
|
(function () {
angular
.module('myApp')
.controller('TeacherGroupController', TeacherGroupController)
TeacherGroupController.$inject = ['$state', '$scope', '$rootScope', '$filter'];
function TeacherGroupController($state, $scope, $rootScope, $filter) {
$rootScope.setData('showMenubar', true);
$rootScope.setData('backUrl', "teacher");
$rootScope.setData('selectedMenu', 'group');
$rootScope.safeApply();
$scope.$on('$destroy', function () {
if ($scope.groupsRef) $scope.groupsRef.off('value')
if ($scope.shareRef) $scope.shareRef.off('value')
if ($scope.allGroupRef) $scope.allGroupRef.off('value')
for (ref in $scope.shareGroupRef) {
$scope.shareGroupRef[ref].off('value');
}
})
$scope.init = function () {
$rootScope.setData('loadingfinished', false);
$scope.shareGroupRef = {}
$scope.getgroups()
$scope.getSharedGroups();
// $scope.getSettings()
// $scope.getStudents()
}
$scope.getgroups = function () {
$scope.groupsRef = firebase.database().ref('Groups').orderByChild('teacherKey').equalTo($rootScope.settings.userId);
$scope.groupsRef.on('value', function (snapshot) {
$scope.myGroups = snapshot.val() || {}
$scope.ref_1 = true;
$scope.finalCalc();
});
}
$scope.getSharedGroups = function () {
$scope.shareRef = firebase.database().ref('SharedList/' + $rootScope.settings.userId);
$scope.shareRef.on('value', function (snapshot) {
// init
for (ref in $scope.shareGroupRef) {
$scope.shareGroupRef[ref].off('value');
}
$scope.shareGroupRef = {}
$scope.sharedGroups = {}
$scope.isGetSharedGroups = {}
// get teachers who shared to me
let shareLists = snapshot.val() || {}
for (var fromKey in shareLists) {
var fromTeacher = shareLists[fromKey];
for (var groupKey in fromTeacher) {
$scope.isGetSharedGroups[groupKey] = false;
}
}
$scope.checkFinishShared();
for (var fromKey in shareLists) {
var fromTeacher = shareLists[fromKey];
for (var groupKey in fromTeacher) {
$scope.getSharedGroup(groupKey)
}
}
});
}
$scope.getSharedGroup = function (groupKey) {
$scope.shareGroupRef[groupKey] = firebase.database().ref('Groups/' + groupKey);
$scope.shareGroupRef[groupKey].on('value', function (shareSnapshot) {
if (shareSnapshot.val()) {
$scope.sharedGroups[groupKey] = shareSnapshot.val();
$scope.isGetSharedGroups[groupKey] = true;
} else {
delete $scope.sharedGroups[groupKey];
delete $scope.isGetSharedGroups[groupKey];
}
$scope.checkFinishShared();
});
}
$scope.checkFinishShared = function () {
for (groupKey in $scope.isGetSharedGroups) {
if (!$scope.isGetSharedGroups[groupKey]) return;
}
$scope.ref_2 = true;
$scope.finalCalc();
}
$scope.finalCalc = function () {
if (!$scope.ref_1 || !$scope.ref_2) return;
$scope.groups = [];
for (key in $scope.myGroups) {
let group = $scope.myGroups[key];
$scope.groups.push({
groupName: group.groupname,
code: group.code,
key: key,
teacherId: group.teacherKey,
byMe: true,
});
}
for (key in $scope.sharedGroups) {
let group = $scope.sharedGroups[key];
$scope.groups.push({
groupName: group.groupname,
code: group.code,
key: key,
teacherId: group.teacherKey,
byMe: false,
});
}
$scope.groups = $filter('orderBy')($scope.groups, 'groupName');
$rootScope.setData('loadingfinished', true);
if ($scope.groups.length == 0) {
$rootScope.warning("There isn't any group!");
}
$rootScope.safeApply();
// snapshot.forEach(function (childSnapshot) {
// });
}
// ===================== show group detail functions==============================
$scope.gotoGroupDetails = function (obj) {
$rootScope.setData('groupKey', obj.key);
$rootScope.setData('teacherId', obj.teacherId);
$rootScope.setData('groupSetKey', undefined);
$rootScope.setData('subIndex', undefined);
$rootScope.setData('rootPageSetting', DEFAULT_PAGE_SETTING);
$state.go('groupRoot');
}
$scope.copyToClipboard = function (str) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(str).select();
document.execCommand("copy");
$temp.remove();
}
//delete group
$scope.deletegroup = function (group) {
if (!confirm("Are you sure want to delete this group?")) {
return;
}
$rootScope.setData('loadingfinished', false);
var key = group.key;
var updates = {};
updates['Groups/' + key] = {};
var loopCount = 3;
var groupAnswerRef = firebase.database().ref('GroupAnswers').orderByChild('studentgroupkey').equalTo(key);
groupAnswerRef.once('value', function (snapshot) {
var answers = snapshot.val();
if (answers) {
for (var ansKey in answers) {
updates['GroupAnswers/' + ansKey] = {};
}
}
loopCount--;
if (loopCount == 0) {
firebase.database().ref().update(updates).then(function () {
$rootScope.setData('loadingfinished', true);
$rootScope.success('Group delete finished successfully.');
});
}
});
var groupAnswerRef = firebase.database().ref('StudentGroups');
groupAnswerRef.once('value', function (snapshot) {
var students = snapshot.val();
if (students) {
for (var studentKey in students) {
var groups = students[studentKey];
for (var groupKey in groups) {
if (groups[groupKey] == key) {
updates['StudentGroups/' + studentKey + '/' + groupKey] = {};
}
}
}
}
loopCount--;
if (loopCount == 0) {
firebase.database().ref().update(updates).then(function () {
$rootScope.setData('loadingfinished', true);
$rootScope.success('Group delete finished successfully.');
});
}
});
var shareRef = firebase.database().ref('SharedList/');
shareRef.once('value', function (snapshot) {
var shareList = snapshot.val();
if (shareList) {
for (var toKey in shareList) {
for (var fromKey in shareList[toKey]) {
if (shareList[toKey][fromKey][key]) {
updates['SharedList/' + toKey + '/' + fromKey + '/' + key] = {};
}
}
}
}
loopCount--;
if (loopCount == 0) {
firebase.database().ref().update(updates).then(function () {
$rootScope.setData('loadingfinished', true);
$rootScope.success('Group delete finished successfully.');
});
}
});
}
$scope.setActive = function (obj) {
if (obj.key == $rootScope.settings.groupKey) {
return 'active';
}
return '';
}
}
})();
|
var authFunc = function() {
const sign_in_btn = document.querySelector("#sign-in-btn");
const sign_up_btn = document.querySelector("#sign-up-btn");
const container = document.querySelector(".authentication-container");
if(sign_up_btn){
sign_up_btn.addEventListener("click", () => {
container.classList.add("sign-up-mode");
})
}
if(sign_in_btn){
sign_in_btn.addEventListener("click", () => {
container.classList.remove("sign-up-mode");
})
}
}
document.addEventListener("turbolinks:load", function() {
authFunc();
})
|
const currentColor = document.querySelector('.current-color');
const bodyElem = document.querySelector('body');
const generateBtn = document.querySelector('.generate-btn');
// console.log('currentColor.innerText :>> ', currentColor);
// console.log('bodyElem :>> ', bodyElem);
// console.log('generateBtn :>> ', generateBtn);
bodyElem.style.backgroundColor = currentColor.innerText;
generateBtn.addEventListener('click', () => {
let randomColor = '';
let chaaracters = '0123456789abcdef';
for (let i=0; i < 6; i++) {
randomColor = randomColor + chaaracters[Math.floor(Math.random() * 16)];
}
currentColor.innerText = "#" + randomColor;
bodyElem.style.backgroundColor = "#" + randomColor;
})
|
import React from 'react';
import { connect } from 'react-redux';
import {ListView, StyleSheet, TouchableOpacity} from 'react-native';
import {Colors, Typography, View, Text, Modal} from 'react-native-ui-lib';//eslint-disable-line
import autobind from 'react-autobind';
import { selectChannel, fetchChannels } from '../../actions/channel_actions';
const mapStateToProps = (state) => {
var props = {
title: '',
channels: {},
current_channel_id: state.chatroom.channel.current_channel_id
};
if (state.chatroom.group.current_group_id) {
if (state.chatroom.group.groups) {
for (i in state.chatroom.group.groups) {
group = state.chatroom.group.groups[i]
if (group.id == state.chatroom.group.current_group_id) {
props.title = group.name;
break;
}
}
}
if (state.chatroom.channel.group_to_channels) {
props.channels = state.chatroom.channel.group_to_channels[state.chatroom.group.current_group_id];
}
}
console.log(state);
return props;
};
const mapDispatchToProps = dispatch => {
return {
dispatchSelectChannel: (channel_id) =>
dispatch(selectChannel(channel_id)),
dispatchFetchChannels: () =>
dispatch(fetchChannels()),
}
}
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
});
class ChannelList extends React.Component {
constructor(props) {
super(props);
autobind(this);
this.state = {
dataSource: ds,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.channels !== this.props.channels) {
this.setState({
dataSource: this.state.dataSource.cloneWithRowsAndSections(nextProps.channels)
});
}
}
onItemPressed(row) {
console.log(row); // eslint-disable-line
}
renderSectionHeader(sectionData, sectionID) {
return (
<View style={styles.sectionContainer}>
<Text style={styles.sectionText}>{sectionID}</Text>
</View>
);
}
renderSeparator(sId, id) {
return (<View style={styles.separator} key={`s${sId}_${id}`} />);
}
renderRow(row, index) {
return (
<TouchableOpacity
testID={index}
style={styles.row}
onPress={() => this.onItemPressed(row)}
>
<Text style={styles.rowText}>
{row.title}
</Text>
</TouchableOpacity>
);
}
render() {
return (
<View style={styles.container}>
<Modal.TopBar
title={this.props.title}
cancelButtonProps={{
disabled: true,
}}
doneButtonProps={{
disabled: true,
}}
/>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
renderSeparator={this.renderSeparator}
renderSectionHeader={this.renderSectionHeader}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'stretch',
backgroundColor: Colors.dark80
},
row: {
paddingVertical: 15,
paddingLeft: 12,
justifyContent: 'center',
},
rowText: {
...Typography.text70,
},
separator: {
// borderBottomWidth: 1,
// borderBottomColor: Colors.dark70,
},
sectionContainer: {
backgroundColor: Colors.purple30,
paddingVertical: 8,
paddingLeft: 4,
},
sectionText: {
...Typography.text70,
color: Colors.white,
},
});
export default connect(mapStateToProps, mapDispatchToProps)(ChannelList);
|
/**
* Created by Bartek on 09/11/2016.
*/
function PojazdProt(maxSpeed, name){
this.maxSpeed = maxSpeed;
this.name = name;
this.speed = 0;
}
PojazdProt.prototype.BiezacaPredkosc = function () {
return this.speed;
}
PojazdProt.prototype.Start = function (newSpeed) {
if(this.maxSpeed >= newSpeed){
this.speed = newSpeed;
}
}
PojazdProt.prototype.Stop = function () {
this.speed = 0;
}
|
module.exports=function(app)
{
var request = require('request');
app.get('/',function(req,res){
res.render('home.jade')
});
app.get('/test',function(req,res){
res.render('ajaxTest.jade');
});
app.get('/testAjax',function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
});
app.get('/getAllPopularEvents',function(req,res){
console.log('Retrieving events JSON');
var api_request = 'https://www.eventbriteapi.com/v3/events/search/?popular=true&token=ZH5SDZXHG4BR6EDDUSFI';
var venue = req.query.city;
var start_date = req.query.start_date;
if(venue!=null)
api_request = api_request + '&venue.city='+venue;
if(start_date!=null)
api_request = api_request + '&start_date.keyword='+start_date;
console.log(api_request);
request(api_request, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Done');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(body));
}
})
});
app.get('/getCategoryInfo',function(req,res){
console.log('Retrieving event categories');
var api_request = 'https://www.eventbriteapi.com/v3/categories/?token=ZH5SDZXHG4BR6EDDUSFI';
request(api_request, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Done');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(body));
}
})
});
}
|
import BagItem from "./bag-item";
export default BagItem;
|
require('dotenv/config');
const mongoose = require('mongoose');
db = getConnect();
async function getConnect(){
return await mongoose.connect(process.env.MONGO_URL,{
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = db;
|
module.exports = {
up: queryInterface =>
queryInterface.bulkInsert('Roles', [
{
title: 'admin',
description: 'Admin role has access to do everything',
createdAt: new Date(),
updatedAt: new Date()
},
{
title: 'regular',
description: 'Default user role',
createdAt: new Date(),
updatedAt: new Date()
}
], {}),
down: queryInterface => queryInterface.bulkDelete('Roles', null, {})
};
|
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
creator: DS.belongsTo('user', {async: true}),
applicants: DS.hasMany('user', {async: true}),
handler: DS.belongsTo('user', {async: true})
});
|
import { Container, window, Res, Sprite, Animation } from 'alpha'
import { adapter } from 'common/js'
const ProgressHight = adapter(30)
const ProgressProps = {
y: window.innerHeight - ProgressHight,
width: window.innerWidth,
height: window.innerHeight
}
// 进度条加载
export default class Progress extends Container {
constructor(props) {
super(ProgressProps)
this.initBox()
this.initProgress()
}
initBox() {
const box = new Sprite({
width: window.innerWidth,
height: ProgressHight
})
Res.loadImage({
url: '/image/common/loading-bar.png',
success: function (img) {
box.setDrawObject(img)
}
})
this.appendChild(box)
}
initProgress() {
const progress = new Sprite({
sx: 0,
sy: 0,
swidth: window.innerWidth,
sheight: 39,
height: ProgressHight,
visibility: false
})
Res.loadImage({
url: '/image/common/loading-bars.png',
success: function (img) {
progress.visibility = true
progress.setDrawObject(img)
}
})
this.progress = progress
this.appendChild(progress)
}
setProgress(n = 0) {
if (this.progress) {
const width = (n / 100) * window.innerWidth
Animation(this.progress, {
data: { width }
})
}
}
}
|
import { Avatar } from "@material-ui/core";
export default props => {
const {
member: { login, avatarUrl }
} = props;
return (
<div>
<a href={`https://github.com/${login}`}>
<div className="member-container">
<Avatar src={avatarUrl} />
<div className="member-login">{login}</div>
</div>
</a>
<style jsx>{`
a {
cursor: default;
text-decoration: none;
color: black;
}
.member-container {
display: flex;
flex-direction: row;
align-items: center;
}
.member-login {
margin-left: 15px;
}
.member-login:hover {
color: blue;
opacity: 0.6;
cursor: pointer;
}
`}</style>
</div>
);
};
|
import { excludePath } from './config';
import config from '../../package.json';
import { getCookie } from '@/utils/utils';
// locale 语言国际化标识
// authority 权限(__luo__jurisdiction__rule__);
// loginToken 只用于登入验证
// token token
// beforeLoginUrl 登入前进入的url
// routeMenuData 路由菜单
// routeData 路由(最终格式)
// pathRecords 路由浏览记录
// activePath 当前激活状态的菜单路由
// tagChangePaths 标签缓存
// ###################################
// vuexData vuex本地储存
// vueData vue组件缓存
// cachePathData 需要缓存的路由(fixedPaths和changePath)
function setLocalData (name, newData) { // 名称可配置或区分各个环境
if (!name) throw new Error('参数有误!');
if (!config.myConfig || !config.myConfig.localStorageName) new Error('请配置localStorageName');
const temData = window.localStorage.getItem(config.myConfig.localStorageName);
const data = temData ? JSON.parse(decodeURIComponent(temData)) : {};
data[name] = newData;
window.localStorage.setItem(config.myConfig.localStorageName, encodeURIComponent(JSON.stringify(data)));
}
function getLocalData (name) { // 名称可配置或区分各个环境
const temData = window.localStorage.getItem(config.myConfig.localStorageName);
const data = temData ? JSON.parse(decodeURIComponent(temData)) : {};
if (name) return data[name];
return data;
}
function getPatternConfig () { // 获取环境下路由模式
let obj = {mode: 'history', base: '/'};
if (process.env.NODE_ENV !== 'production') {
obj.mode = config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.mode ? config.buildConfig.dev.mode : 'hash';
const localPublicPath = config.buildConfig && config.buildConfig.base && config.buildConfig.base.localPublicPath ? config.buildConfig.base.localPublicPath :
config.buildConfig && config.buildConfig.dev && config.buildConfig.dev.localPublicPath ? config.buildConfig.dev.localPublicPath : '/';
obj.base = localPublicPath === '/' ? '/' : localPublicPath + '/';
} else {
obj.base = config.buildConfig && config.buildConfig.base && config.buildConfig.base.assetsPublicPath ? config.buildConfig.base.assetsPublicPath :
config.buildConfig && config.buildConfig.prod && config.buildConfig.prod.assetsPublicPath ? config.buildConfig.prod.assetsPublicPath : '/';
}
return obj;
}
// -------------------- 权限 -----------------------
function routingAuthority (to, from, next) {
// #####
if (excludePath.indexOf(to.path) >= 0) return next();
// #####
// -----------------
if (!getLocalData('token') && !getLocalData('beforeLoginUrl')) setLocalData('beforeLoginUrl', splicingPath(to.path, to.query));
// -----------------
if (to.query[config.myConfig.loginTokenPramasIf[0]] === 'true' && to.query[config.myConfig.loginTokenPramasIf[1]]) {
setLocalData('loginToken', to.query[config.myConfig.loginTokenPramasIf[1]]);
setLocalData('beforeLoginUrl', splicingPath(to.path, to.query));
}
// -----------------
let identity = getLocalData('authority');
if (to.matched.length >= 2 && (to.matched[to.matched.length - 2].path + '/') === to.matched[to.matched.length - 1].path && to.matched[to.matched.length - 2].meta.requiresAuth) {
let authority = to.matched[to.matched.length - 1].meta.requiresAuth ? to.matched[to.matched.length - 1].meta.authority : to.matched[to.matched.length - 2].meta.authority;
let redirectPath = to.matched[to.matched.length - 1].meta.requiresAuth ? to.matched[to.matched.length - 1].meta.redirectPath : to.matched[to.matched.length - 2].meta.redirectPath;
privilegeCheck(identity, authority, redirectPath, next, to);
} else if (to.matched.length >= 2 && to.matched[to.matched.length - 1].meta.requiresAuth) {
let authority = to.matched[to.matched.length - 1].meta.authority;
let redirectPath = to.matched[to.matched.length - 1].meta.redirectPath;
privilegeCheck(identity, authority, redirectPath, next);
} else if (to.matched.length >= 2) {
let matcheds = to.matched;
let authority, redirectPath;
for(let i = matcheds.length - 1;i >= 0;i--){
if (matcheds[i].meta.requiresAuth) {
authority = matcheds[i].meta.authority;
redirectPath = matcheds[i].meta.redirectPath;
break;
}
}
privilegeCheck(identity, authority, redirectPath, next);
} else {
let authority = to.matched[0].meta.authority;
let redirectPath = to.matched[0].meta.redirectPath;
privilegeCheck(identity, authority, redirectPath, next);
}
}
function privilegeCheck (identity, authority, redirectPath, next, to) {
if (!identity) {
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
}
// string 处理
if (typeof authority === 'string') {
// if (to.path === '/' && to.query.current_app_id && authority === identity) {delete to.query.current_app_id;return next('/');} // ######
if (authority === identity) return next();
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
}
// 数组处理
if (Array.isArray(authority)) {
// if (to.path === '/' && to.query.current_app_id && authority.indexOf(identity) >= 0) {delete to.query.current_app_id;return next('/');} // ######
if (authority.indexOf(identity) >= 0) return next();
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
}
// 对象处理
if (authority instanceof Object) {
for (let i in authority) {
if (typeof authority[i] !== 'string') throw new Error('authority如果是对象,里面的值一定要是字符串类型,并且是路模块路径!')
if (!(/^@\//g).test(authority[i])) throw new Error('authority如果是对象,里面的值(路径)一定要以@/开头!')
let fun = require(`@/${authority[i].replace('@/', '')}`)[i];
// Promise 处理
if (isPromise(fun)) {
fun.then(() => {
// if (to.path === '/' && to.query.current_app_id) {delete to.query.current_app_id;return next('/');} // ######
return next();
}).catch(() => {
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
});
return;
}
// Function 处理
if (typeof fun === 'function') {
try {
const bool = fun(identity);
if (isPromise(bool)) {
bool.then(() => {
// if (to.path === '/' && to.query.current_app_id) {delete to.query.current_app_id;return next('/');} // ######
return next();
}).catch(() => {
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
});
return;
}
if (bool) {
// if (to.path === '/' && to.query.current_app_id) {delete to.query.current_app_id;return next('/');} // ######
return next();
}
if (redirectPath) return next({path: redirectPath});
return next({path: '/login', query: {t: new Date().getTime()}});
} catch (error) {
throw error;
}
}
break;
}
}
throw new Error('unsupported parameters');
}
function isPromise(obj) { //
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function'
);
}
function splicingPath (path, query) { // 拼接参数为带参url
let newPath = path, j;
for (let i in query) {
newPath += j ? `&${i}=${query[i]}` : `?${i}=${query[i]}`;
if (!j) j = true;
}
return newPath;
}
function analysisPath (url, va) { // 解析url为对象
if (!url) return null;
if (!va) {
let rega = new RegExp("(\\?|&)" + config.myConfig.loginTokenPramasIf[1] + "=[^&]*", "g");
let regb = new RegExp("(\\?|&)" + config.myConfig.loginTokenPramasIf[0] + "=[^&]*", "g");
url = url.replace(rega, '');
url = url.replace(regb, '');
}
let temUrl = url.split('?');
let obj = {path: temUrl[0]};
if (temUrl[1]) {
obj.query = {};
let query = temUrl[1].split('&');
for (let i = 0;i < query.length;i++) {
let params = query[i].split('=');
obj.query[params[0]] = params[1];
}
}
return obj;
}
function useFilters (Vue, filters) {
for (let i in filters) {
Vue.filter(i, filters[i]);
}
}
function useDirectives (Vue, directives) {
for (let i in directives) {
Vue.directive(i, directives[i]);
}
}
function isCachePath (path, vb) {
let pathData = getLocalData('pathRecords');
if (!pathData) {setLocalData('pathRecords', []);return undefined;}
if (pathData.indexOf(path) > -1) return true;
if (!vb) return;
pathData.push(path);
setLocalData('pathRecords', pathData);
}
function isTemPath (path) {
let temPath = getLocalData('cachePathData');
if (!temPath || !temPath.changePath) return undefined;
if (temPath.changePath.indexOf(path) > -1) return true;
}
function monitorCookie (obj) { // 监听cookie
let token = getCookie(config.myConfig.cookieMonitorIdent);
if (Boolean(obj.auto) !== Boolean(token) && !token) {
// -----------------
setLocalData('locale', 'zh');
setLocalData('token', undefined);
setLocalData('authority', undefined);
setLocalData('loginToken', undefined);
setLocalData('beforeLoginUrl', undefined);
setLocalData('routeMenuData', undefined);
setLocalData('routeData', undefined);
setLocalData('vuexData', undefined);
setLocalData('vueData', undefined);
setLocalData('cachePathData', undefined);
setLocalData('pathRecords', undefined);
setLocalData('activePath', undefined);
setLocalData('tagChangePaths', undefined);
// -----------------
try {window.$cookies.remove('eln_session_id');} catch (e) {}
// -----------------
obj.auto = '';
vm.$router.push({path: '/', query: {t: new Date().getTime()}});
} else {
obj.auto = token;
}
requestAnimationFrame(() => monitorCookie(obj));
}
export {
setLocalData, getLocalData, monitorCookie, routingAuthority, getPatternConfig, analysisPath, useFilters,
useDirectives, isCachePath, isTemPath,
}
|
import {HtmlView} from "gml-html";
import template from './template.html';
import * as style from './style.scss';
export default async function ({ locale }) {
const view = HtmlView(template, style, locale.get());
return view;
}
|
$(function(){
$("#admin_cancel").click(function(){
$.ajax({
url:"/admincancel",
data:{},
success:function(rs){
if(rs.code==0){
setTimeout(function(){
location.href = "../admin"
},500)
}
}
})
})
$("#img_upload").click(function(){
var files = $('#avatar').prop('files');
var data = new FormData();
for(var i=0;i<files.length;i++){
data.append(files[i].name,files[i]);
}
$.ajax({
url: '/imgupload',
type: 'post',
data:data,
cache: false,
processData: false,
contentType: false,
success:function(rs){
console.log(rs)
}
});
});
})
|
(function () {
'use strict';
angular.module('app').controller('TeamController', Controller);
Controller.$inject = ['MasterDataService','TeamService', 'UserService', '$scope', '$filter', '$ngConfirm', 'toastr','$localStorage'];
function Controller(mds, ts, us, $scope, $filter, confirm, toastr,storage) {
//variables
//scope variables
$scope.teams = [];
$scope.users = [];
$scope.teamname = '';
$scope.teamid = 0;
$scope.employees = [];
$scope.employee = {};
//scope functions
$scope.get = get;
$scope.add = add;
$scope.update = update;
$scope.remove = remove;
$scope.getUsers = getUsers;
$scope.addUser = addUser;
$scope.removeUser = removeUser;
$scope.showNewModal = showNewModal;
$scope.showEditModal = showEditModal;
$scope.showUsersModal = showUsersModal;
$scope.resetEmployee = resetEmployee;
//functions
init();
function init() {
get();
getEmployees();
}
function resetEmployee($item, $model, $label) {
addUser($scope.teamid,$model);
$scope.searchUser = '';
}
function showNewModal() {
$scope.teamname = '';
angular.element("#modal-new").modal('show');
}
function showEditModal(teamid) {
$scope.teamid = teamid;
$scope.teamname = $scope.teams.find(x => x.TeamId == teamid).TeamName;
angular.element("#modal-edit").modal('show');
}
function showUsersModal(teamid) {
$scope.filterUsers = '';
angular.element("#modal-users").modal('show');
getUsers(teamid);
}
function getEmployees() {
mds.employees(function(response) {
$scope.employees = response.data;
});
}
function get() {
ts.get(function(response) {
if(response.success) {
$scope.teams = response.data;
}
});
}
function add(teamname) {
ts.add(teamname, function(response) {
if(response.success) {
ts.get(function(response) {
if(response.success) {
$scope.teams = response.data;
toastr.success('New team added succcessfully.');
angular.element("#modal-new").modal('hide');
showUsersModal($scope.teams[$scope.teams.length-1].TeamId);
}
});
}
});
}
function update(teamid, teamname) {
ts.update(teamid, teamname, function(response) {
if(response.success) {
angular.element("#modal-edit").modal('hide');
get();
}
});
}
function remove(teamid) {
confirm({
theme: 'material',
icon: 'fa fa-question-circle',
closeIcon: true,
title: 'Confirmation',
content: 'Remove this team?',
escapeKey: 'close',
buttons: {
confirm: {
keys: ['enter'],
btnClass: 'btn-red',
action: function() {
ts.remove(teamid, function(response) {
if(response.success) {
get();
toastr.success('Team removed successfully.');
}
});
}
},
close: function() {}
}
});
}
function getUsers(teamid) {
$scope.teamid = teamid;
$scope.teamname = $scope.teams.find(x => x.TeamId == teamid).TeamName;
us.get(teamid, function(response) {
if(response.success) $scope.users = response.data;
})
}
function addUser(teamid, empcode) {
us.add(teamid, empcode, function(response) {
if(response.success) {
getUsers(teamid);
get();
}
})
}
function removeUser(teamid, empcode) {
us.remove(teamid, empcode, function(response) {
if(response.success) {
getUsers(teamid);
get();
}
})
}
}
})();
|
import "typeface-montserrat"
import "typeface-merriweather"
import "./src/normalize.css"
import "./src/style.css"
import "prismjs/themes/prism.css"
|
/**
* 填写注册资料
*/
import React, { Component, PureComponent } from "react";
import {
StyleSheet,
Dimensions,
View,
Text,
Image,
TouchableOpacity,
ScrollView,
Keyboard,
RefreshControl,
Platform,
BackHandler
} from "react-native";
import { connect } from "rn-dva";
import SplashScreen from "react-native-splash-screen";
import Header from "../../../components/Header";
import CommonStyles from "../../../common/Styles";
import CommonButton from '../../../components/CommonButton';
import * as requestApi from "../../../config/requestApi";
import * as regular from "../../../config/regular";
import Content from "../../../components/ContentItem";
const { width, height } = Dimensions.get("window");
import ActionSheet from "../../../components/Actionsheet";
import PickerOld from "react-native-picker-xk";
import * as taskRequest from "../../../config/taskCenterRequest"
import ShowBigPicModal from '../../../components/ShowBigPicModal';
import { NavigationComponent } from "../../../common/NavigationComponent";
import ListItem from './ListItem.js';
import * as constUser from '../../../const/user'
import {sortLists} from '../../../config/utils';
const nochooseIcon = require('../../../images/user/nochooseIcon.png')
const chooseIcon = require('../../../images/user/chooseIcon.png')
const needGetSourceKeys=['firstIndustry','workType','specialIndustry']
class MyApplyFormScreen extends NavigationComponent {
static navigationOptions = {
header: null,
gesturesEnabled: false, // 禁用ios左滑返回
};
constructor(props) {
super(props);
const { userInfo: user,navigation } = props
const params = navigation.state.params || {}
let isEditorble = false
const auditStatus = params.auditStatus || 'unSubmit'
if (params.page!='task' && (auditStatus == 'unSubmit' || auditStatus == 'audit_fail' || params.updateAuditStatus == 'un_pass' || !user.auditStatus)) {
isEditorble = true
}
this.state = {
discount: '', // 折扣上限
name: params.name,
page: params.page,
visible: false,
largeImage: '',
updateAuditStatus: params.updateAuditStatus,
familyUp: params.familyUp || 0,
merchantType: params.familyUp?'familyL1':params.merchantType,
selectOptions: ['取消'],
isEditorble: isEditorble, //是否能编辑
auditStatus,
remark: '',//审核失败原因
route: params.route,
lists: [],//重组列表
oldLists: [],//服务器获取下来的列表
loadData: false,//0还未获取数据列表或获取失败,1获取成功
callback: params.callback || (() => { }),
showBigPicArr: [],
showIndex: 0,
showBigModal: false,
hasDidTask: params.hasDidTask || true,
agress: false,//是否同意协议,
refreshing:false,//刷新
};
}
blurState = {
showBigModal: false,
visible: false,
}
screenDidFocus = (payload) => {
super.screenDidFocus(payload)
const params = this.props.navigation.state.params || {}
if (params.page == 'login' || params.page == 'register') {
BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid)
}
}
screenWillBlur = (payload) => {
super.screenWillBlur(payload)
this.removeEventListener()
}
removeEventListener = () => {
BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid)
}
//触发返回键执行方法
onBackAndroid = () => {
this.goBack()
return true;
};
componentWillUnmount() {
super.componentWillUnmount()
PickerOld.hide();
clearTimeout(this.timer)
this.removeEventListener()
}
upgrade = () => {
this.getDataDetail(requestApi.upFamilyFieldTemplateList, (res) => {
this.setState({
isEditorble: true,
name: '公会'
}, () => { this.oprateData(res.fieldInfos || res.identity || res) })
})
}
regularItem = (item2) => { //字段验证
if(item2.component != "input"){
return item2
}
if (item2.name.indexOf('注册资本') != -1) {
item2.regular = regular.price
item2.warningMessage = '请填写正确格式的注册资本,金额格式'
}
if (item2.name.indexOf('邮箱') != -1) {
item2.regular = regular.email
item2.warningMessage = '请输入正确格式的邮箱'
item2.keyboardType = 'email-address'
}
if (item2.key == 'cardNumber') {
item2.regular = regular.card
item2.warningMessage = '请输入正确格式的银行卡账号'
item2.keyboardType = 'numeric'
}
if (item2.name.indexOf('手机号') != -1) {
item2.regular = regular.phone
item2.warningMessage = '请输入正确格式的手机号,11位数字'
item2.keyboardType = 'numeric'
}
if (item2.name.indexOf('身份证号') != -1 || item2.key == 'legalPersonIdCard') {
item2.regular = regular.ID
item2.warningMessage = '请输入正确格式的身份证号,18位'
}
if (item2.key == 'bankInstNo' || item2.name.indexOf('安全码') != -1) {
item2.regular = regular.number
item2.warningMessage = '只能填写数字'
}
return item2
}
addItemCondition=(item,i)=>{
const { userInfo: user } = this.props
const { auditStatus, isEditorble, page,familyUp } = this.state
item.canChange = true
item.indexGroup = i
if (item.key == 'phone' && page !== 'task') {
item.value=global.loginInfo && global.loginInfo.phone || null
item.canChange = false
}
if (item.key == 'verifyCode' && (auditStatus == 'audit_fail')) {
item.value = null
}
if((auditStatus=='active' || familyUp) && ['accountCreationType' ,'nickname','account'].includes(item.key)){
item.canChange = false
}
if ((item.key == 'familySecurityCode' || item.key == 'verifyCode')&& item.value) {
item.canChange = false
}
else {
if (item.group == 'base' && item.value && isEditorble && user.auditStatus != 'audit_fail') {//入驻成功后或审核中基本资料不能修改 //入驻成功后修改资料后查看
item.canChange = false
} else {
// item.value=null //继续入驻数据要回显
}
}
if(constUser[item.key]){
this.setState({[item.key+'Source']:constUser[item.key]})
}
return this.regularItem(item)
}
oprateData = (res) => {//处理返回的数据列表
const { merchantType } = this.state
if (!res) {
return
}
let lists = [
{ name: '基本资料', key: 'base', column: [] },
{ name: merchantType == 'anchor' || merchantType == 'familyL1' || merchantType == 'personal' ? '个人资料' : '公司资料', key: 'company', column: [] },
{ name: '自定义资料', key: 'custom', column: [] },
]
res=sortLists(res)
for (let i = 0; i < lists.length; i++) {
let item1 = lists[i]
for (let j = 0; j < res.length; j++) {
let item2 = res[j]
if(needGetSourceKeys.includes(item2.key) && item2.value){
this.getSource(item2)
}
if (item2.group == item1.key) {
item2 = this.addItemCondition(item2,i),
item1.column.push(item2)
item1.column[item1.column.length - 1] ?item1.column[item1.column.length - 1] .index = item1.column.length - 1:null
if(item2.options && item2.showBy){ //如果有子集
let arr=sortLists(item2.key=='industrySelect'?item2.showBy.select || [] : [])
if(item2.options && item2.showBy && item2.key!='industrySelect'){
item2.options.map(itemOption=>{
let secondArrs=sortLists(item2.showBy[itemOption] || [])
secondArrs.map(item=>item.showByKey=itemOption)
arr=arr.concat(secondArrs)
})
}
for(let item3 of arr){
item3 = this.addItemCondition(item3,i)
if(item2.key=='industrySelect'){
item2.component="input"
item2.value='select'
item3.key=='specialIndustry'?item3.parentkey='firstIndustry':null
}else{
item3.parentkey=item2.key
}
if(needGetSourceKeys.includes(item3.key) && item3.value){
this.getSource(item3,item2.value)
}
item1.column.push(item3)
item1.column[item1.column.length - 1].index = item1.column.length - 1
}
}
}
}
}
this.setState({
lists, loadData: 1, oldLists: res
})
}
getSource = async (data,parentCode,callback=()=>{}) => { //获取行业分类
try{
callback?Loading.show():null
let func=data.key=='workType'?requestApi.getWorkType:requestApi.getIndustry
const res=await func({parentCode,page:1,limit:100})
if(res && res.data){
let source={}
res.data.map(item=>source[item.code]=item.name)
this.setState({
[data.key+'Source']:source
},callback)
return
}
Toast.show('分类查询数据为空')
this.setState({
[data.key+'Source']:''
})
}catch(error){
console.log('error',error)
}
}
getDataDetail = (propsFunc, callback = () => { }) => {
const { userInfo: user, navigation, merchant } = this.props
const { page, joinMerchantId, updateAuditStatus, familyUp } = navigation.state.params
let func;
let params = {}
const { auditStatus,merchantType } = this.state
if (page === 'task') {
func = taskRequest.fetchjobMerchantDetail
params.joinMerchantId = joinMerchantId
params.joinMerchantType = merchantType
func(params).then((res) => {
this.oprateData(res.fieldInfos || res.identity || res)
}).catch(err => {
console.log(err)
});
} else {
if (propsFunc) { //
func = propsFunc
}
else if (!user.createdMerchant) {//首次入驻
func = requestApi.fieldTemplateList
params = { merchantType }
}
else if (['un_audit','audit_fail'].includes(user.auditStatus)) {//首次入驻没走完,继续入驻 或首次入驻审核失败
func = requestApi.keepEnterMerchantDetail
}
else if (familyUp == 1) { //继续升级
func = requestApi.merchantKeepEnterUpFamilyMerchantDetail
}
else if (auditStatus == 'unSubmit') {//扩展身份
func = requestApi.merchantExtendDetail
params = { merchantType }
}
else {//审核中查看
func = requestApi.merchantIdentityDetailForUpdate
params = { merchantType }
}
func(params).then((res) => {
if (propsFunc) {
callback(res)
} else {
this.oprateData(res.fieldInfos || res.identity || res)
const currentMerchantType = merchantType || res.merchantType
let currentMerchant = merchant.filter(item => item.merchantType == currentMerchantType)[0]
if (auditStatus === 'audit_fail' || updateAuditStatus == 'un_pass') {
requestApi.auditFailReason({ merchantType: currentMerchantType }).then((error) => {//查询失败原因
this.setState({ remark: error.auditFailReason })
}).catch(err => {
console.log(err)
});
}
this.setState({
name: currentMerchant && currentMerchant.name || '',
merchantType: currentMerchantType,
refreshing:false
})
}
}).catch((error)=>{
console.log('error',error)
this.setState({refreshing:false})
})
}
}
componentDidMount() {
this.timer = setTimeout(() => {
SplashScreen.hide();
}, 100)
Loading.show()
this._onRefresh(false)
}
_onRefresh=(refreshing)=>{
this.setState({refreshing})
this.getDataDetail();
this.getMerchantHome();
}
gobackOprate = () => {
const { userInfo: user, navigation, resetPage, navPage } = this.props
this.removeEventListener()
if (user.auditStatus == 'audit_fail' && this.state.page == 'login') {
resetPage("Index")
} else {
if (this.state.page == 'login') {
resetPage("Login")
} else {
navigation.goBack()
}
}
}
goBack = () => {
let auditStatus = this.getAuditStatus()
let page = this.props.navigation.getParam("page", '');
if ((page == 'login' || page == 'register') && this.state.oldLists.length > 0) {
if (auditStatus == 'unSubmit' || auditStatus == 'audit_fail' || (auditStatus == 'active' && this.state.isEditorble)) {
CustomAlert.onShow(
"confirm",
"确定后需要重新填写资料?",
"是否放弃编辑",
() => this.gobackOprate()
)
} else {
this.gobackOprate()
}
} else {
this.props.navigation.goBack()
}
};
changeFormData = (item, value, wrong = 0) => {
let lists = this.state.lists;
// const isWrong=wrong?wrong:((item.regular && !item.regular(item.value)) || 0)
console.log('value',item.key,value)
lists[item.indexGroup].column[item.index] = {
...item,
value,
wrong
}
console.log(lists[item.indexGroup].column[item.index].value)
this.setState({ lists: [...lists] })
}
scrollToItem = (item1, wrong = 1) => {
wrong && this.changeFormData(item1, item1.value, 1)
const itemLayout = (this[item1.key + 'layout'+item1.index] || 0) + (this[this.state.lists[item1.indexGroup].name + 'layout'] || 0)
this.myScrollView.scrollTo({ x: 0, y: itemLayout, animated: true })
}
getMerchantHome = () => {
this.props.userInfo.createdMerchant == 1 ? this.props.getMerchantHome({
successCallback:()=>this.getAuditStatus()
}) : null
}
getAuditStatus = () => {
const { userInfo: user, navigation ,merchantData} = this.props;
const {merchantType,familyUp}=this.state
let { identityStatuses = [] } = merchantData.merchant || {};
let auditStatus
let updateAuditStatus=null
if (user.createdMerchant === 1) {
let findItem = identityStatuses.find(item => familyUp? item.merchantType ==='familyL2':item.merchantType== merchantType);
if (findItem && findItem.auditStatus) {
auditStatus = findItem.auditStatus;
updateAuditStatus=findItem.updateAuditStatus
}
}
this.setState({auditStatus:auditStatus || 'unSubmit',updateAuditStatus,isEditorble:this.state.page!='task' && (auditStatus == 'audit_fail' || updateAuditStatus == 'un_pass')?true:this.state.isEditorble})
return auditStatus || 'unSubmit';
}
submitNextFunc = (navigation, navigateParam) => {
this.removeEventListener()
Toast.show('提交审核成功')
navigation.replace('ApplyFormDone', navigateParam);
}
judgeFun = (func, params, navigateParam, navigation = this.props.navigation) => {
const auditStatus = this.getAuditStatus();
Loading.show()
func(params).then((res) => {
this.state.callback()
const { userInfo: user, userSave, getMerchantHome, navPage } = this.props;
if ((res && res.token) || user.auditStatus == "audit_fail") {
global.loginInfo = {
...global.loginInfo,
token: (res && res.token) || user.token,
createdMerchant: 1,
merchantId: (res && res.merchantId) || user.merchantId,
auditStatus: 'un_audit',
isAdmin: 1
}
userSave({ user: loginInfo })
}
if (auditStatus == 'active') {
if (this.state.merchantType == 'familyL1' && (this.state.name == '公会' || this.state.familyUp)) { //家族长升级
this.submitNextFunc(navigation, navigateParam)
} else {
Toast.show('修改成功,请等待审核')
getMerchantHome();
navPage(this.state.route || 'RegisterList')
}
}
else {
this.submitNextFunc(navigation, navigateParam)
}
}).catch((error) => {
console.log('error', error)
if (error) {
let errorKey = ''
switch (error.message) {
case '邮箱已被使用!': errorKey = 'companyEmail'; break;
case '邀请码不存在': errorKey = 'esCode'; break;
// case '短信验证码不存在': errorKey = 'verifyCode'; break;
case '家族邀请码不存在': errorKey = 'familySecurityCode'; break;
}
const { lists } = this.state
let errorItem;
for (let item of lists) {
errorItem = item.column.find(item2 => item2.key == errorKey);
if (errorItem) break;
}
console.log('errorItem', errorItem)
errorItem && this.scrollToItem(errorItem)
}
})
}
submit = oprate => {
Keyboard.dismiss();
const { name, lists, merchantType, auditStatus, page, route, familyUp, updateAuditStatus, isEditorble ,oldLists} = this.state;
let merchant = {}
let verifyCodeItem={}
for (let j = 0; j < lists.length; j++) {
let item = lists[j]
if (item.column) {
for (let i = 0; i < item.column.length; i++) {
let item1 = item.column[i]
if (isEditorble) { //如果编辑了资料需验证
if(item1.wrong){
this.scrollToItem(item1)
return
}
if (item1.display && item1.canChange) {
let length = item1.maxLength || item1.length
if (length && item1.value && item1.value.length > length && item1.component == "input") {
Toast.show(item1.name + '最多' + length + '位字符')
this.scrollToItem(item1)
return
}
if (item1.value && item1.regular && !item1.regular(item1.value)) {
Toast.show(item1.warningMessage || ('请输入正确格式的' + item1.name))
this.scrollToItem(item1)
return
}
}
if (item1.required == 1 && item1.display == 1 && item1.canChange) {
if (!item1.value || item1.value.length === 0) {
Toast.show(item1.name ? '请完善' + item1.name : '请上传作品');
this.scrollToItem(item1)
return;
}
if ((item1.key == 'bankNo' || item1.key == 'openBank') && !this.state[item1.key + 'Name']) { //兼容旧版本
Toast.show('请选择开户行及行号')
this.scrollToItem(item1)
return;
}
}
}
let itemSubmit=1
if(item1.showByKey){
const parentItem=lists[item1.indexGroup].column.find(itemF=>itemF.key==item1.parentkey) || {}
parentItem.value!=item1.showByKey?itemSubmit=0:null
}
if(item1.key=='verifyCode' && itemSubmit){
verifyCodeItem=item1
}
itemSubmit?
merchant[item1.key] = {
name: item1.name,
media: item1.media,
value: item1.value,
group: item1.group,
length: item1.length
}:null
}
}
}
const { userInfo: user, getMerchantHome } = this.props;
let params = {
merchantType,
merchant
}
let navigateParam = {
name,
route: route,
merchantType,
auditStatus: this.getAuditStatus(),
familyUp,
page,
callback: () => {
getMerchantHome();
}
}
let func;
if (!user.createdMerchant) {
func = requestApi.merchantEnter //首次入驻
} else if (familyUp) { //家族长继续升级
func = requestApi.merchantKeepEnterUpFamilyUpdateMerchant
}
else if (auditStatus == 'active') { //商户入驻成功,修改资料
if (merchantType == 'familyL1' && name == '公会') {
func = requestApi.upFamilySave //家族长升级
}
else {
func = requestApi.merchantIdentityUpdate //修改入驻资料
}
}
else if (user.auditStatus == 'audit_fail') {//首次入驻没走完,继续入驻
func = requestApi.merchantUpdateEnter //修改入驻资料
} else if (auditStatus == 'audit_fail') {//扩展身份,继续入驻
func = requestApi.merchantUpdateReExtend //修改入驻资料
} else if (user.auditStatus == 'active' && auditStatus === 'unSubmit') {//扩展身份,首次入驻
func = requestApi.merchantExtend //扩展身份,首次入驻
}
else { //审核中,不需要做处理
Toast.show('资料审核中')
}
const nextStype=()=>{
if (navigateParam.auditStatus == 'audit_fail' || navigateParam.auditStatus == 'active' || updateAuditStatus == 'un_pass') { //判断是否是修改资料,修改资料需要验证手机号
this.removeEventListener()
this.props.navigation.navigate('VerifyPhone', {
phone: global.loginInfo && global.loginInfo.phone,
editable: false,
bizType: 'VALIDATE',
onConfirm: (phone, code, navigation) => {
Loading.show()
requestApi.smsCodeValidate({ phone, code }).then(() => {
this.judgeFun(func, params, navigateParam, navigation)
}).catch(err => {
console.log(err)
});
}
})
} else {
this.judgeFun(func, params, navigateParam)
}
}
if(verifyCodeItem.canChange && isEditorble){ //验证验证码
requestApi.smsCodeValidateUserAccount({
phone:merchant['account'].value,
code:merchant['verifyCode'].value,
smsAuthBizType:merchant['accountCreationType'].value=='create'?'CREATE_XK_USER':'BIND_XK_USER'
}).then(() => {
nextStype()
}).catch(()=>{
this.scrollToItem(verifyCodeItem)
})
return
}
nextStype()
}
merchantJoinTaskAudit = () => {
const { navigation } = this.props
const { taskId, callback, listcallBack } = navigation.state.params
taskRequest.fetchMerchantJoinTaskAudit({ jobId: taskId }).then(() => {
Toast.show('审核通过')
if (callback) {
callback(1)
}
if (listcallBack) {
listcallBack(1)
}
navigation.goBack()
}).catch(err => {
console.log(err)
});
}
auditTask = (isPass) => {
const { navigation } = this.props
const { taskId, callback, merchantTaskNode, listcallBack, cantAudit } = navigation.state.params
if (isPass) {
if (cantAudit) {
CustomAlert.onShow(
"confirm",
cantAudit,
"提示",
() => { },
() => { navigation.goBack() },
botton1Text = "确定",
botton2Text = "取消",
)
} else {
CustomAlert.onShow(
"confirm",
"确定通过审核?",
"提示",
() => { },
() => { this.merchantJoinTaskAudit() },
botton1Text = "通过",
botton2Text = "取消",
)
}
} else {
this.props.navigation.navigate('CancelTaskAudit', {
listcallBack: listcallBack,
merchantTaskNode: merchantTaskNode,
taskcore: 'auditcore',
taskId: taskId,
callback: callback
})
}
}
actionOperate = (index) => {
let { oprateData, oprateCallback = () => { },selectOptions } = this.state
if(index== selectOptions.length - 1){
return
}
if (oprateData.component == "file") {
oprateCallback(index === 0 ? 'take' : 'pick')
return
}
let selectedCode;
for(let key in this.state[oprateData.key + 'Source']){
this.state[oprateData.key + 'Source'][key]==selectOptions[index]?selectedCode=key:null
}
console.log('selectedCode && oprateData.value',selectedCode , oprateData.value)
if (selectedCode && oprateData.value != selectedCode) {
this.changeFormData(this.state.oprateData, selectedCode)
if (oprateData.key=='firstIndustry') {
const secondList = this.state.lists[oprateData.indexGroup].column.find((itemF) => itemF.parentkey === oprateData.key)
secondList && this.changeFormData(secondList, '')
}
}
}
renderRightView = (headerWidth) => {
const { oldLists, page, isEditorble, auditStatus, lists, updateAuditStatus } = this.state;
let headerRightValue = ''
let onPress = (() => { })
if ((auditStatus == 'active' || auditStatus == 'audit_fail') && page != 'task') {
if (isEditorble) {
if (auditStatus == 'audit_fail' || updateAuditStatus == 'un_pass') {
headerRightValue = '重新提交'
} else {
headerRightValue = '保存'
}
} else {
auditStatus == 'active' && updateAuditStatus!='un_audit'? headerRightValue = '修改':null
}
onPress = (() => {
if (isEditorble) {
this.submit()
} else { //修改资料
this.setState({
isEditorble: true
},
() => {
lists[1] && lists[1].column && lists[1].column[0] && this.scrollToItem(lists[1].column[0], 0)
this.oprateData(oldLists, 0)
})
}
})
}
return (
headerRightValue ?
<TouchableOpacity style={[styles.headerRightView, { width: headerWidth }]} onPress={() => onPress()} >
<Text style={styles.headerRightView_text}> {headerRightValue} </Text>
</TouchableOpacity> :
<TouchableOpacity style={[styles.headerRightView, { width: headerWidth }]} />
)
}
renderNextButtonSubmit = () => { //下一步
const { navigation } = this.props;
const { auditStatus, loadData, agress ,merchantType, name,page} = this.state
return loadData && auditStatus == 'unSubmit' && page!='task'? (
<View>
<TouchableOpacity
onPress={() => {
this.setState({
agress: !agress
})
}}
style={{ marginTop: 15, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}
>
<Image source={agress ? chooseIcon : nochooseIcon} style={{ marginRight: 8 }} />
<Text style={styles.c9f12}>我已阅读并同意</Text>
<TouchableOpacity
onPress={() => {
navigation.navigate('Contract', { merchantType, name })
}}
><Text style={styles.cbf14}>《联盟商加盟合同》</Text></TouchableOpacity>
<Text style={styles.c9f12}>及</Text>
<TouchableOpacity
onPress={() => {
navigation.navigate('Appoint', { merchantType, name })
}}
><Text style={styles.cbf14}>《特别约定》</Text></TouchableOpacity>
</TouchableOpacity>
<CommonButton
style={{ marginBottom: 20 + CommonStyles.footerPadding }}
title='下一步'
onPress={() => {
if (!agress) {
Toast.show('请先阅读联盟商加盟合同和特别约定')
return
}
CustomAlert.onShow(
"confirm",
"请确认提交的资料填写无误,资料提交后必须完成系统审核才能修改",
"提示",
() => { console.log('取消') },
() => { this.submit() },
botton1Text = "确定",
botton2Text = "取消"
)
}}
/>
</View>
) : null
}
render() {
const { navigation, userInfo: user,canUpgrade } = this.props;
const { refreshing,merchantType, selectOptions, isEditorble, auditStatus, remark, lists, updateAuditStatus, showBigPicArr, showIndex, showBigModal } = this.state;
const { hasBtn, page } = navigation.state.params
console.log(this.state.route)
let headerName = '入驻资料'
let headerWidth = 100
if (auditStatus == 'unSubmit' && page != 'task') {
headerName = '入驻资料(' + '未提交' + ')'
headerWidth = 50
}
console.log('lists',lists)
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack={false}
title={headerName}
leftView={
<TouchableOpacity
style={[styles.headerLeftView, { width: headerWidth }]}
onPress={() => { this.goBack(); }}
>
<Image source={require("../../../images/mall/goback.png")} />
</TouchableOpacity>
}
rightView={this.renderRightView(headerWidth)}
/>
{
page!='task' && (auditStatus == 'audit_fail' || updateAuditStatus == 'un_pass') ?
<View style={styles.autfailView}>
<View style={styles.failicon}><Text style={{ fontSize: 17, color: '#FFC125' }}>!</Text></View>
<Text style={styles.autfailViewText}>审核不通过原因:{remark}</Text>
</View>
: null
}
<ScrollView
style={{ flex: 1, paddingBottom: 20 }}
ref={(view) => { this.myScrollView = view; }}
refreshControl={(
<RefreshControl
refreshing={refreshing}
onRefresh={()=>this._onRefresh(true)}
/>
)}
>
<View style={{ alignItems: 'center', paddingBottom: CommonStyles.footerPadding + 20 }}>
{
lists.map((item1, index0) => {
return (item1.column && item1.column.length != 0 && item1.column.filter((item) => item.display === 1).length > 0 ?
<View key={index0} onLayout={event => { this[item1.name + 'layout'] = event.nativeEvent.layout.y }}>
{
canUpgrade && merchantType == 'familyL1' && item1.key == 'base' && !isEditorble ? (
<View style={styles.familyUp}>
<Text style={styles.title_text}>{item1.name}</Text>
<TouchableOpacity
onPress={this.upgrade}
>
<Text style={[styles.title_text, { color: CommonStyles.globalRedColor }]}>升级为公会 >></Text>
</TouchableOpacity>
</View>
) : (
<Text style={styles.title_text}>{item1.name}</Text>
)
}
<Content style={styles.itemsBlock}>
{
item1.column && item1.column.map((item, index1) => {
return (
<View key={index1} onLayout={event => { this[item.key + 'layout'+index1] = event.nativeEvent.layout.y }} key={item.key + item.index}>
<ListItem
state={this.state}
showActionSheet={() => this.ActionSheet.show()}
setState={(data, callback = () => { }) => this.setState(data, () => callback())}
item={item}
scrollToItem={this.scrollToItem}
changeFormData={this.changeFormData}
getSource={this.getSource}
/>
</View>
)
})
}
</Content>
</View> : null
)
})
}
{this.renderNextButtonSubmit()}
</View>
</ScrollView>
<ActionSheet
ref={o => (this.ActionSheet = o)}
options={selectOptions}
cancelButtonIndex={selectOptions.length - 1}
onPress={index => this.actionOperate(index)}
/>
<ShowBigPicModal
ImageList={showBigPicArr}
visible={showBigModal}
showImgIndex={showIndex}
onClose={() => {
this.setState({
showBigModal: false
})
}}
/>
{
hasBtn && (
<View>
<CommonButton
title='审核通过'
style={[styles.botton, { marginBottom: 0 }]}
onPress={() => this.auditTask(true)}
/>
<CommonButton
onPress={() => this.auditTask(false)}
title='审核不通过'
style={[styles.botton, styles.botton2]}
textStyle={{ color: CommonStyles.globalHeaderColor }}
/>
</View>
)
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding
},
headerLeftView: {
width: width / 3,
alignItems: 'flex-start',
paddingLeft: 18,
},
headerRightView: {
paddingRight: 18,
width: width / 3,
alignItems: 'flex-end'
},
headerRightView_text: {
fontSize: 17,
color: "#fff",
},
autfailView: {
backgroundColor: '#FFEBCD',
paddingHorizontal: 15,
paddingVertical: 10,
flexDirection: 'row',
alignItems: 'center'
},
autfailViewText: {
fontSize: 14,
color: CommonStyles.globalRedColor
},
c9f12: {
color: '#999999',
fontSize: 12
},
cbf14: {
color: '#4A90FA',
fontSize: 12
},
itemsBlock: {
width: width - 20,
overflow: 'hidden',
marginTop: 15
},
title_text: {
fontSize: 14,
color: "#777",
marginLeft: 15,
marginTop: 15
},
botton: {
marginLeft: 10,
},
botton2: {
backgroundColor: '#fff',
marginBottom: 20 + CommonStyles.footerPadding
},
failicon: {
borderColor: '#FFC125',
borderWidth: 2,
borderRadius: 20,
alignItems: 'center',
justifyContent: 'center',
width: 24,
height: 24,
marginRight: 10
},
familyUp: {
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'space-between',
paddingRight: 8
}
});
export default connect(
state => ({
userInfo: state.user.user || {},
canUpgrade:state.user.canUpgrade,
merchantData:state.user.merchantData || {},
shop: state.shop || {},
merchant: state.user.merchant || []
}), {
resetPage: (routeName) => ({ type: 'system/resetPage', payload: { routeName } }),
navPage: (routeName, params = {}) => ({ type: 'system/navPage', payload: { routeName, params } }),
replacePage: (routeName, params = {}) => ({ type: 'system/replacePage', payload: { routeName, params } }),
backPage: (routeName, params = {}) => ({ type: 'system/back', payload: { routeName, params } }),
getMerchantHome: (payload = {}) => ({ type: 'user/getMerchantHome', payload }),
userSave: (payload = {}) => ({ type: 'user/save', payload }),
updateUser: (payload = {}) => ({ type: 'user/updateUser', payload }),
}
)(MyApplyFormScreen);
|
import React from 'react';
import { View, Text, TouchableOpacity, TextInput, Alert, StatusBar, ToastAndroid, StyleSheet, AsyncStorage } from 'react-native';
import { Container, Content, Header, Body, Right, Icon, Form, Item, Picker } from 'native-base';
import PropTypes from 'prop-types';
import moment from 'moment';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import PopupMenu from '../components/PopupMenu';
import ModalContent from '../components/ModalContent';
export default class ViewNote extends React.Component {
static propTypes = {
navigator: PropTypes.object.isRequired,
screen: PropTypes.string,
item: PropTypes.shape({
createdAt: PropTypes.number.isRequired,
updatedAt: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
priority: PropTypes.string.isRequired,
note: PropTypes.string.isRequired,
}),
onTest: PropTypes.func,
}
static navigatorStyle = {
navBarHidden: true,
statusBarColor: '#B93221',
}
constructor(props) {
super(props);
this.state = {
modalContentVisible: false,
height: 60,
title: '',
priority: '',
note: '',
createdAt: '',
updatedAt: '',
isSelected: '',
list: '',
};
}
componentWillMount() {
const { createdAt, updatedAt, title, priority, note, isSelected } = this.props.item; // eslint-disable-line
this.setState({
createdAt,
updatedAt,
title,
priority,
note,
isSelected,
});
AsyncStorage.getItem('savednote').then((items) => {
this.setState({ list: JSON.parse(items) });
});
}
updateNote = () => {
const { createdAt, title, priority, note, isSelected } = this.state; // eslint-disable-line
let counter = 0;
if (title.trim() !== this.props.item.title) counter += 1;
if (priority !== this.props.item.priority) counter += 1;
if (note.trim() !== this.props.item.note) counter += 1;
if (counter === 0) ToastAndroid.showWithGravityAndOffset('Tidak Ada Perubahan', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 100);
else {
const result = this.state.list.filter(items => items.createdAt !== this.state.createdAt);
const updatedAt = moment().unix();
const storeItem = { createdAt, updatedAt, title, priority, note, isSelected }; // eslint-disable-line
const finalResult = result.concat([storeItem]);
AsyncStorage.setItem('savednote', JSON.stringify(finalResult)).then(() => {
ToastAndroid.showWithGravityAndOffset('Berhasil Merubah Catatan', ToastAndroid.SHORT, ToastAndroid.BOTTOM, 0, 100);
setTimeout(() => {
this.pop();
}, 1000);
});
}
}
showPopup = (eventName, index) => {
if (eventName !== 'itemSelected') return;
if (index === 0) this.toggleModal(true);
else this.beriBintang();
}
beriBintang = () => {
Alert.alert(
'Give a Star',
'If you have any trouble while using this application, feel free to get in touch with me on email',
[
{ text: 'OK' },
],
{ cancelable: false },
);
}
toggleModal = (visibility) => {
this.setState({
modalContentVisible: visibility,
});
}
updateSize = (height) => {
this.setState({
height,
});
}
pop = () => {
this.props.navigator.pop({
animated: true,
animationType: 'fade',
});
if (this.props.screen !== 'favorit') this.props.onTest();
}
createdAtHuman = (createdAt) => {
const createdAtHuman = moment.unix(createdAt).format('dddd, DD MMMM YYYY');
return createdAtHuman;
}
updatedAtHuman = (updatedAt) => {
const updatedAtHuman = moment.unix(updatedAt).format('DD/MM/YY HH:mm');
return updatedAtHuman;
}
renderHeader = () => (
<Header style={styles.headerColor}>
<StatusBar backgroundColor="#B93221" />
<TouchableOpacity
style={styles.backIconParent}
onPress={this.pop}>
<FontAwesome
name="caret-left"
style={[styles.backIcon, styles.white]} />
</TouchableOpacity>
<Body>
<Text style={[styles.white, styles.title]}>Simple Notes</Text>
<Text style={styles.white}>Edit Catatan</Text>
</Body>
<Right>
<TouchableOpacity
style={styles.iconContainer}>
<FontAwesome
name="save"
style={{ color: '#fff', fontSize: 25 }}
onPress={this.updateNote} />
</TouchableOpacity>
<PopupMenu
actions={['Tentang aplikasi', 'Beri bintang 5']}
onPress={this.showPopup} />
</Right>
<ModalContent
modalContentVisible={this.state.modalContentVisible}
closeModal={this.toggleModal} />
</Header>
);
render() {
const { height, createdAt, updatedAt, title, priority, note, isSelected } = this.state; // eslint-disable-line
const newStyle = { height };
return (
<Container>
{this.renderHeader()}
<Content
keyboardShouldPersistTaps="always">
<View style={styles.dateContainer}>
<Text style={{ flex: 1 }}>{this.createdAtHuman(createdAt)}</Text>
<Text style={{ flex: 1, textAlign: 'right' }}>
<Icon
name="md-time"
style={{ fontSize: 16, color: '#555' }} /> {this.updatedAtHuman(this.state.updatedAt)}
</Text>
</View>
<Form>
<TextInput
underlineColorAndroid="transparent"
value={title}
onChangeText={value => this.setState({ title: value })}
style={styles.textInput} />
<Text style={{ alignSelf: 'flex-end', fontSize: 12, marginRight: 15 }}>- Note Title -</Text>
<View style={styles.pickerContainer}>
<Text style={{ flex: 1 }}>Note Priority</Text>
<Picker
mode="dropdown"
selectedValue={priority}
style={{ flex: 1 }}
onValueChange={val => this.setState({ priority: val })} >
<Item label="High" value="high" />
<Item label="Medium" value="medium" />
<Item label="Low" value="low" />
</Picker>
</View>
<TextInput
underlineColorAndroid="transparent"
editable
multiline
value={note}
style={[newStyle, styles.textInput2]}
onChangeText={value => this.setState({ note: value })}
onContentSizeChange={e => this.updateSize(e.nativeEvent.contentSize.height)} />
<Text style={{ alignSelf: 'flex-end', fontSize: 12, marginRight: 15 }}>- Note Content -</Text>
</Form>
</Content>
</Container >
);
}
}
const styles = StyleSheet.create({
white: {
color: '#fff',
},
headerColor: {
backgroundColor: '#DB4437',
},
backIconParent: {
alignSelf: 'center',
width: 40,
},
backIcon: {
fontSize: 45,
},
title: {
fontSize: 16,
},
dateContainer: {
flexDirection: 'row',
paddingLeft: 10,
paddingRight: 10,
marginBottom: 15,
},
textInput: {
backgroundColor: '#eee',
marginLeft: 10,
marginRight: 10,
borderRadius: 5,
fontSize: 17,
},
textInput2: {
backgroundColor: '#eee',
marginLeft: 10,
marginRight: 10,
borderRadius: 5,
},
pickerContainer: {
flex: 1,
flexDirection: 'row',
padding: 15,
alignItems: 'center',
},
iconContainer: {
width: 50,
height: 50,
justifyContent: 'center',
alignItems: 'center',
},
});
|
export const rootPath='http://localhost:3000'
|
// Require dependencies
const Grid = require('grid');
const tmpl = require('riot-tmpl');
const Model = require('model');
const config = require('config');
const Controller = require('controller');
const escapeRegex = require('escape-string-regexp');
// Require models
const Notification = model('notification');
const Block = model('block');
const Acl = model('acl');
// require helpers
const formHelper = helper('form');
const fieldHelper = helper('form/field');
const blockHelper = helper('cms/block');
/**
* Build notification controller
*
* @acl admin
* @fail next
* @mount /admin/config/notification
*/
class NotificationAdminController extends Controller {
/**
* Construct notification Admin Controller
*/
constructor() {
// run super
super();
// bind build methods
this.build = this.build.bind(this);
// bind methods
this.gridAction = this.gridAction.bind(this);
this.indexAction = this.indexAction.bind(this);
this.createAction = this.createAction.bind(this);
this.updateAction = this.updateAction.bind(this);
this.removeAction = this.removeAction.bind(this);
this.createSubmitAction = this.createSubmitAction.bind(this);
this.updateSubmitAction = this.updateSubmitAction.bind(this);
this.removeSubmitAction = this.removeSubmitAction.bind(this);
this.flowSetupHook = this.flowSetupHook.bind(this);
// bind private methods
this._grid = this._grid.bind(this);
// set building
this.building = this.build();
}
// ////////////////////////////////////////////////////////////////////////////
//
// BUILD METHODS
//
// ////////////////////////////////////////////////////////////////////////////
/**
* build notification admin controller
*/
build() {
//
// REGISTER BLOCKS
//
// register simple block
blockHelper.block('admin.notification.grid', {
acl : ['admin.notification'],
for : ['admin'],
title : 'Notification Grid',
description : 'Notification Grid block',
}, async (req, block) => {
// get notes block from db
const blockModel = await Block.findOne({
uuid : block.uuid,
}) || new Block({
uuid : block.uuid,
type : block.type,
});
// create new req
const fauxReq = {
query : blockModel.get('state') || {},
};
// return
return {
tag : 'grid',
name : 'Notification',
grid : await (await this._grid(req)).render(fauxReq),
class : blockModel.get('class') || null,
title : blockModel.get('title') || '',
};
}, async (req, block) => {
// get notes block from db
const blockModel = await Block.findOne({
uuid : block.uuid,
}) || new Block({
uuid : block.uuid,
type : block.type,
});
// set data
blockModel.set('class', req.body.data.class);
blockModel.set('state', req.body.data.state);
blockModel.set('title', req.body.data.title);
// save block
await blockModel.save(req.user);
});
//
// REGISTER FIELDS
//
// register simple field
fieldHelper.field('admin.notification', {
for : ['admin'],
title : 'Notification',
description : 'Notification Field',
}, async (req, field, value) => {
// set tag
field.tag = 'notification';
field.value = value ? (Array.isArray(value) ? await Promise.all(value.map(item => item.sanitise())) : await value.sanitise()) : null;
// return
return field;
}, async (req, field) => {
// save field
}, async (req, field, value, old) => {
// set value
try {
// set value
value = JSON.parse(value);
} catch (e) {}
// check value
if (!Array.isArray(value)) value = [value];
// return value map
return await Promise.all((value || []).filter(val => val).map(async (val, i) => {
// run try catch
try {
// buffer notification
const notification = await Notification.findById(val);
// check notification
if (notification) return notification;
// return null
return null;
} catch (e) {
// return old
return old[i];
}
}));
});
}
/**
* setup flow hook
*
* @pre flow.build
*/
async flowSetupHook(flow) {
// do initial actions
flow.action('notification.trigger', {
tag : 'notification',
icon : 'fa fa-bell',
title : 'Trigger Notification',
}, (action, render) => {
}, async (opts, element, data) => {
let done = await this.eden.lock ('flowSetupHook.notification', (1 * 1000));
try {
// set config
element.config = element.config || {};
// query for data
const User = model('user');
// clone data
const newData = Object.assign({}, data);
let content = {
body : '',
title : '',
url : '',
nofity: true
};
// set values
content.body = tmpl.tmpl(element.config.body || '', newData);
content.title = tmpl.tmpl(element.config.title || '', newData);
content.url = tmpl.tmpl(element.config.url || '', newData);
const isadmin = tmpl.tmpl(element.config.isadmin || '', newData);
const from_ = tmpl.tmpl(element.config.from || '', newData);
const in_ = tmpl.tmpl(element.config.in || '', newData);
const once = tmpl.tmpl(element.config.sendonce || '', newData);
const role = tmpl.tmpl(element.config.role || '', newData);
let addusers = '';
if (isadmin && isadmin === 'yes') {
const adminacl = await Acl.where({name : 'Admin'}).findOne();
addusers = await User.where({'acl.id' : adminacl.get('_id')}).find();
}
if (role) {
const acl = await Acl.where({name : role}).findOne();
addusers = await User.where({'acl.id' : acl.get('_id')}).find();
}
if (from_ && in_) {
const frommodel = (await newData.model.get(from_) || {});
if (!frommodel || Object.keys(frommodel).length === 0) return;
const user = await frommodel.get(in_);
if (!user || Object.keys(user).length === 0) return;
addusers = addusers.concat([user]);
}
// send model
if (newData.model instanceof Model) {
// sanitise model
newData.model = await newData.model.sanitise();
content.body = tmpl.tmpl(element.config.body || '', newData.model);
content.title = tmpl.tmpl(element.config.title || '', newData.model);
}
await this.eden.hook(`notification.${data.model.constructor.name}`, newData.model, content);
if (!content.nofity) {
return;
}
if (once === 'yes') {
const found = await Notification.where({ body : content.body }).findOne();
const result = await found;
if (found) return;
}
// create query
let query = User;
// loop queries
(element.config.queries || []).forEach((q) => {
// get values
const { method, type } = q;
let { key, value } = q;
// data
key = tmpl.tmpl(key, newData);
value = tmpl.tmpl(value, newData);
// check type
if (type === 'number') {
// parse
value = parseFloat(value);
} else if (type === 'boolean') {
// set value
value = value.toLowerCase() === 'true';
}
// add to query
if (method === 'eq' || !method) {
// query
query = query.where({
[key] : value,
});
} else if (['gt', 'lt'].includes(method)) {
// set gt/lt
query = query[method](key, value);
} else if (method === 'ne') {
// not equal
query = query.ne(key, value);
}
});
// get alerted users
let alertedUsers = (from_ && in_) ? [] : Array.isArray(element.config.queries) && element.config.queries.length > 0 ? await query.find() : [];
if (addusers && Array.isArray(addusers) && addusers.length > 0) alertedUsers = alertedUsers.concat(addusers);
// create notifications
(await Promise.all(await alertedUsers.map(async (alertedUser) => {
// create notification
const notification = new Notification({
url : content.url,
body : content.body,
title : content.title,
user : alertedUser,
image : newData.model && newData.model.image ? newData.model.image : null,
});
// save
await notification.save();
}))).filter(t=>t);
done();
// return true
return true;
} catch (e) {
done ();
}
});
}
// ////////////////////////////////////////////////////////////////////////////
//
// CRUD METHODS
//
// ////////////////////////////////////////////////////////////////////////////
/**
* Index action
*
* @param {Request} req
* @param {Response} res
*
* @icon fa fa-bell
* @menu {ADMIN} Notifications
* @title Notification Administration
* @parent /admin/config
* @route {get} /
* @layout admin
* @priority 10
*/
async indexAction(req, res) {
// Render grid
res.render('notification/admin', {
grid : await (await this._grid(req)).render(req),
});
}
/**
* Add/edit action
*
* @param {Request} req
* @param {Response} res
*
* @route {get} /create
* @layout admin
* @return {*}
* @priority 12
*/
createAction(req, res) {
// Return update action
return this.updateAction(req, res);
}
/**
* Update action
*
* @param {Request} req
* @param {Response} res
*
* @route {get} /:id/update
* @layout admin
*/
async updateAction(req, res) {
// Set website variable
let notification = new Notification();
let create = true;
// Check for website model
if (req.params.id) {
// Load by id
notification = await Notification.findById(req.params.id);
create = false;
}
// get form
const form = await formHelper.get('edenjs.notification');
// digest into form
const sanitised = await formHelper.render(req, form, await Promise.all(form.get('fields').map(async (field) => {
// return fields map
return {
uuid : field.uuid,
value : await notification.get(field.name || field.uuid),
};
})));
// get form
if (!form.get('_id')) res.form('edenjs.notification');
// Render page
res.render('notification/admin/update', {
item : await notification.sanitise(),
form : sanitised,
title : create ? 'Create notification' : `Update ${notification.get('_id').toString()}`,
fields : config.get('notification.fields'),
});
}
/**
* Create submit action
*
* @param {Request} req
* @param {Response} res
*
* @route {post} /create
* @return {*}
* @layout admin
* @upload {single} image
*/
createSubmitAction(req, res) {
// Return update action
return this.updateSubmitAction(req, res);
}
/**
* Add/edit action
*
* @param {Request} req
* @param {Response} res
* @param {Function} next
*
* @route {post} /:id/update
* @layout admin
*/
async updateSubmitAction(req, res, next) {
// Set website variable
let create = true;
let notification = new Notification();
// Check for website model
if (req.params.id) {
// Load by id
notification = await Notification.findById(req.params.id);
create = false;
}
// get form
const form = await formHelper.get('edenjs.notification');
// digest into form
const fields = await formHelper.submit(req, form, await Promise.all(form.get('fields').map(async (field) => {
// return fields map
return {
uuid : field.uuid,
value : await notification.get(field.name || field.uuid),
};
})));
// loop fields
for (const field of fields) {
// set value
notification.set(field.name || field.uuid, field.value);
}
// Save notification
await notification.save(req.user);
// set id
req.params.id = notification.get('_id').toString();
// return update action
return this.updateAction(req, res, next);
}
/**
* Delete action
*
* @param {Request} req
* @param {Response} res
*
* @route {get} /:id/remove
* @layout admin
*/
async removeAction(req, res) {
// Set website variable
let notification = false;
// Check for website model
if (req.params.id) {
// Load user
notification = await Notification.findById(req.params.id);
}
// Render page
res.render('notification/admin/remove', {
item : await notification.sanitise(),
title : `Remove ${notification.get('_id').toString()}`,
});
}
/**
* Delete action
*
* @param {Request} req
* @param {Response} res
*
* @route {post} /:id/remove
* @title Remove Notification
* @layout admin
*/
async removeSubmitAction(req, res) {
// Set website variable
let notification = false;
// Check for website model
if (req.params.id) {
// Load user
notification = await Notification.findById(req.params.id);
}
// Alert Removed
req.alert('success', `Successfully removed ${notification.get('_id').toString()}`);
// Delete website
await notification.remove(req.user);
// Render index
return this.indexAction(req, res);
}
// ////////////////////////////////////////////////////////////////////////////
//
// QUERY METHODS
//
// ////////////////////////////////////////////////////////////////////////////
/**
* index action
*
* @param req
* @param res
*
* @acl admin
* @fail next
* @route {GET} /query
*/
async queryAction(req, res) {
// find children
let notifications = await Notification;
// set query
if (req.query.q) {
notifications = notifications.where({
name : new RegExp(escapeRegex(req.query.q || ''), 'i'),
});
}
// add roles
notifications = await notifications.skip(((parseInt(req.query.page, 10) || 1) - 1) * 20).limit(20).sort('name', 1)
.find();
// get children
res.json((await Promise.all(notifications.map(notification => notification.sanitise()))).map((sanitised) => {
// return object
return {
text : sanitised.name,
data : sanitised,
value : sanitised.id,
};
}));
}
// ////////////////////////////////////////////////////////////////////////////
//
// GRID METHODS
//
// ////////////////////////////////////////////////////////////////////////////
/**
* User grid action
*
* @param {Request} req
* @param {Response} res
*
* @route {post} /grid
* @return {*}
*/
async gridAction(req, res) {
// Return post grid request
return (await this._grid(req)).post(req, res);
}
/**
* Renders grid
*
* @param {Request} req
*
* @return {grid}
*/
async _grid(req) {
// Create new grid
const notificationGrid = new Grid();
// Set route
notificationGrid.route('/admin/config/notification/grid');
// get form
const form = await formHelper.get('edenjs.notification');
// Set grid model
notificationGrid.id('edenjs.notification');
notificationGrid.model(Notification);
notificationGrid.models(true);
// Add grid columns
notificationGrid.column('_id', {
sort : true,
title : 'Id',
priority : 100,
});
// branch fields
await Promise.all((form.get('_id') ? form.get('fields') : config.get('notification.fields').slice(0)).map(async (field, i) => {
// set found
const found = config.get('notification.fields').find(f => f.name === field.name);
// add config field
await formHelper.column(req, form, notificationGrid, field, {
hidden : !(found && found.grid),
priority : 100 - i,
});
}));
// add extra columns
notificationGrid.column('read', {
tag : 'grid-date',
sort : true,
title : 'Read',
priority : 4,
}).column('updated_at', {
tag : 'grid-date',
sort : true,
title : 'Updated',
priority : 3,
}).column('created_at', {
tag : 'grid-date',
sort : true,
title : 'Created',
priority : 2,
}).column('actions', {
tag : 'notification-actions',
type : false,
width : '1%',
title : 'Actions',
priority : 1,
});
// branch filters
config.get('notification.fields').slice(0).filter(field => field.grid).forEach((field) => {
// add config field
notificationGrid.filter(field.name, {
type : 'text',
title : field.label,
query : (param) => {
// Another where
notificationGrid.match(field.name, new RegExp(escapeRegex(param.toString().toLowerCase()), 'i'));
},
});
});
// Set default sort order
notificationGrid.sort('created_at', -1);
// Return grid
return notificationGrid;
}
}
/**
* Export notification controller
*
* @type {NotificationAdminController}
*/
module.exports = NotificationAdminController;
|
const Promise = require('bluebird');
const webdriver = require('selenium-webdriver');
const By = webdriver.By;
function getPageLinksAndAssets(url, domain) {
// connect to selenium.
// NOTE: hard coded for this project, ideally this would live in a config file
// and/or potentially be injected into the method
const driver = new webdriver.Builder().
forBrowser('chrome').
usingServer('http://selenium:4444/wd/hub').build();
// load the page via selenium
driver.get(url);
//debugging statement
console.log(`scanning ${url} ...`);
const getLinks = getPageLinks(driver, domain);
const getAssets = getPageAssets(driver, domain);
return Promise.all([getLinks, getAssets]).then(result => {
// we've finished with the page, so exit the driver
driver.quit();
return result;
});
}
function getPageLinks(driver, domain) {
// I consider both http or https links within the domain to be fair game
// NOTE: selenium is making this easier by converting all relative paths
// to absolute paths before we get them
const internalLinkRegexp = new RegExp("^https?://" + domain);
const getStandardLinks = attrValueFinder(driver,
//all 'anchor' tags that aren't set to "no follow"
'a[href]:not([rel="no-follow"])',
[], //no element filters
'href', //extract the href attributes
//then filter it by the domain
[x => internalLinkRegexp.test(x)]);
const getIframePages = attrValueFinder(driver,
'iframe[src]', //any iframe with a src
[],
'src', //extract the src attributes
//and filter it by the domain
[x => internalLinkRegexp.test(x)]);
return Promise.join(getStandardLinks, getIframePages,
(standardLinks, iframePages) =>
standardLinks.concat(iframePages));
}
function getPageAssets(driver, domain) {
const getStandardAssets = attrValueFinder(driver,
'[src]', //any element with a src attribute
// filter out elements with a tag of 'iframe'.
// I'm considering those to be page links (see above)
[(e) => e.getTagName().then(tn => tn !== 'iframe')],
'src', //extract the src attributes
[]);
const getLinkAssets = attrValueFinder(driver,
//all link tags of rel types: icon or stylesheet
'link[href][rel="icon"], link[href][rel="stylesheet"]',
[],
'href', //extract the href attributes
[]);
return Promise.join(getStandardAssets, getLinkAssets,
(standardAssets, linkAssets) =>
standardAssets.concat(linkAssets));
}
/**
* Returns a promise, that will find all the matching attribute
* values in a page.
* This is where all the selenium goodness lives
* @param {object} driver - the selenium web driver setup for the current page
* @param {string} elementCssSelector - css selector to select the elements we want
* @param {array} elementFilters - array of element filters, each which takes the
* element and returns a Promise to a bool
* @param {string} attributeName - attribute on the elements we are looking for
* @param {array} attributeFilters - filters out attributes values we're not interseted
* in. Takes a string and returns a bool. No promises for this one
*/
function attrValueFinder(driver, elementCssSelector, elementFilters, attributeName, attributeFilters) {
return driver.findElements(webdriver.By.css(elementCssSelector)
).then(elements => {
// run a filter on the elements
// NOTE: this is a bit of a pain, becuase our filters are promises,
// as are their results. Thank goodness for bluebird
return Promise.filter((elements || []), e => {
return Promise.reduce((elementFilters || []),
(acc, filter) => acc && filter(e),
true);
});
}).then(elements => {
return Promise.all(elements.map(e => e.getAttribute(attributeName)));
}).then(attrValues => {
//apply all the attribute filters we have, if any
const vals = (attributeFilters || [])
.reduce((vals, filter) => vals.filter(filter), attrValues)
return vals;
});
}
module.exports = getPageLinksAndAssets;
|
const connection = require('./connection');
const coll = 'sales';
const createOrder = async (id, totalPrice, streetInput, houseNumberInput) => {
const date = new Date();
const status = 'Pendente';
const [result] = await connection.execute(
`INSERT INTO Trybeer.${coll}
(user_id, total_price, delivery_address, delivery_number, sale_date, status)
VALUES (?, ?, ?, ?, ?, ?)`,
[id, totalPrice, streetInput, houseNumberInput, date, status],
);
return result;
};
const updateSalesProduct = async (insertId, checkoutProducts) => {
checkoutProducts.forEach((product) => {
const { id: productId, productQuantity } = product;
connection.execute(
`INSERT INTO Trybeer.sales_products (sale_id, product_id, quantity)
VALUES (?, ?, ?)`, [insertId, productId, productQuantity],
);
});
};
const getOrdersByUser = async (id) => {
const [orders] = await connection.execute('SELECT * FROM Trybeer.sales WHERE user_id = ?', [id]);
return orders;
};
const getOrderDetailsById = async (id) => {
const [orderDetails] = await connection.execute(
`SELECT
sales.id, sales.total_price, sales.sale_date, sales.status, sp.quantity, prod.name, prod.price
FROM Trybeer.sales
INNER JOIN Trybeer.sales_products as sp
on sales.id = sp.sale_id
INNER JOIN Trybeer.products as prod
on sp.product_id = prod.id
WHERE sales.id = ?;`, [id],
);
return orderDetails;
};
module.exports = {
createOrder,
updateSalesProduct,
getOrdersByUser,
getOrderDetailsById,
};
|
var assign = require('object-assign')
var jsonPatch = require('fast-json-patch')
module.exports = {
add: add,
replace: replace,
remove: remove,
merge: merge,
context: context,
getIn: getIn,
applyPatches: applyPatches,
parentPathMatch: parentPathMatch,
flatten: flatten,
fullyNormalizeArray: fullyNormalizeArray,
normalizeArray: normalizeArray,
isPromise: isPromise,
isFn: isFn,
forEachNew: forEachNew,
forEachNewPrimitive: forEachNewPrimitive,
isJsonPatch: isJsonPatch,
isContextPatch: isContextPatch,
isPatch: isPatch,
isError: isError,
isMutation: isMutation,
}
function applyPatches(obj, patches) {
patches = normalizeArray(patches).concat()
for (var i = 0, len = patches.length; i < len; i++) {
var p = patches[i]
var newPatch = Object.create(p)
if(newPatch.path)
newPatch.path = normalizeJSONPath(newPatch.path)
if(newPatch.op === 'merge') {
var valPatch = _get(newPatch.path)
jsonPatch.apply(obj, [valPatch])
assign(valPatch.value, newPatch.value)
patches[i] = undefined
continue
}
patches[i] = newPatch
}
jsonPatch.apply(obj, cleanArray(patches))
return obj
}
function normalizeJSONPath(path) {
if(Array.isArray(path)) {
if(path.length < 1)
return ''
return '/' + path.map(function (item) {
item = item+''
return item.replace(/~/g, '~0').replace(/\//g, '~1')
}).join('/')
}
return path
}
// JSON-Patch, wrappers
function add(path, value) {
return {op: 'add', path: path, value: value}
}
function _get(path) {
return {op: '_get', path: path}
}
function replace(path, value) {
return {op: 'replace', path: path, value: value}
}
function remove(path, value) {
return {op: 'remove', path: path}
}
// Custom wrappers
function merge(path, value) {
return {type: 'mutation', op: 'merge', path: path, value: value}
}
function context(path, value) {
return {type: 'context', path: path, value: value}
}
// Iterators
function forEachNew(mutations, fn) {
try {
return forEachNewPatch(mutations, forEach, fn)
} catch(e) {
return e
}
}
function forEachNewPrimitive(mutations, fn) {
try {
return forEachNewPatch(mutations, forEachPrimitive, fn)
} catch(e) {
return e
}
}
function forEachNewPatch(mutations, fn, callback) {
var res = mutations.filter(isAdditiveMutation).map(function (mutation) {
return fn(mutation.value, callback, mutation.path)
}) || []
var flat = flatten(res)
var clean = cleanArray(flat)
return clean
}
function forEachPrimitive(obj, fn, basePath) {
basePath = basePath || []
if(Array.isArray(obj)) {
return obj.map(function (val, key) {
return forEachPrimitive(val, fn, basePath.concat(key))
})
}
if(isObject(obj)) {
return Object.keys(obj).map(function (key) {
var val = obj[key]
return forEachPrimitive(val, fn, basePath.concat(key))
})
}
return fn(obj, basePath[basePath.length - 1], basePath)
}
function forEach(obj, fn, basePath) {
basePath = basePath || []
var results = []
if(basePath.length > 0) {
var newResults = fn(obj, basePath[basePath.length - 1], basePath)
if(newResults)
results = results.concat(newResults)
}
if(Array.isArray(obj)) {
var arrayResults = obj.map(function (val, key) {
return forEach(val, fn, basePath.concat(key))
})
if(arrayResults)
results = results.concat(arrayResults)
} else if(isObject(obj)) {
var moreResults = Object.keys(obj).map(function (key) {
var val = obj[key]
return forEach(val, fn, basePath.concat(key))
})
if(moreResults)
results = results.concat(moreResults)
}
results = flatten(results)
return results
}
function getIn(obj, path) {
return path.reduce(function (val, token) {
if(typeof token !== 'undefined' && val) {
return val[token]
}
return val
}, obj)
}
function isObject(val) {
return val && typeof val === 'object'
}
function isPromise(val) {
return isObject(val) && (typeof val.then === 'function')
}
function isFn(val) {
return val && typeof val === 'function'
}
// Patch Matchers...
function isJsonPatch(patch) {
if(isPatch(patch)) {
var op = patch.op
return op === 'add' || op === 'remove' || op === 'replace'
}
return false
}
function isMutation(patch) {
return isJsonPatch(patch) || (isPatch(patch) && patch.type === 'mutation')
}
function isAdditiveMutation(patch) {
return isMutation(patch) && (patch.op === 'add' || patch.op === 'replace' || patch.op === 'merge')
}
function isContextPatch(patch) {
return isPatch(patch) && patch.type == 'context'
}
function isPatch(patch) {
return (patch && typeof(patch) === 'object')
}
function isError(patch) {
return patch instanceof Error
}
function isCollection(obj) {
return obj && (Array.isArray(obj) || typeof obj === 'object')
}
// Path matchers
function parentPathMatch(path, arr) {
if(!Array.isArray(arr))
return false
for (var i = 0, len = arr.length; i < len; i++) {
if(arr[i] !== path[i])
return false
}
return true
}
function getParent(obj, path) {
if(path.length < 1) {
return null
}
if(path.length < 2) {
return obj
}
return path.slice(0,-1).reduce(function (val, token) {
if(!isCollection(val)) {
throw new TypeError('Lib getParent, invalid path to get')
}
return val[token]
},obj)
}
// Array helpers..
function fullyNormalizeArray(arr) {
return cleanArray(flatten(normalizeArray(arr)))
}
function normalizeArray(sub) {
if(!Array.isArray(sub)) {
sub = [sub]
}
return sub
}
function flatten(arr) {
return [].concat.apply([], arr.map(function (val) {
if(Array.isArray(val)) {
return flatten(val)
}
return val
}))
}
function cleanArray(arr) {
return arr.filter(function (item) { return notUndefined(item) })
}
function notUndefined(thing) {
return typeof(thing) !== 'undefined'
}
|
// jscs:disable jsDoc
module.exports = function () {
return function deleteAll (Model, callback) {
this.getDelegateMethod(Model, 'deleteAll')(Model, callback)
}
}
|
/* eslint-disable no-undef */
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const { faunaFetch } = require("./utils/fauna");
exports.handler = async (event, context) => {
const { body } = event;
const { priceId } = JSON.parse(body);
const {
identity = { url: "https://example.com" },
user,
} = context.clientContext;
try {
const result = await faunaFetch({
query: `
query ($netlifyID: ID!) {
getUserByNetlifyID(netlifyID: $netlifyID) {
stripeID
}
}
`,
variables: {
netlifyID: user.sub,
},
});
const { stripeID } = result.data.getUserByNetlifyID;
const session = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: `${identity.url}/thanks?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${identity.url}/canceled.html`,
customer: stripeID,
});
return {
statusCode: 200,
body: JSON.stringify({ sessionId: session.id }),
};
} catch (e) {
console.error(JSON.stringify(e.message, null, 2));
return {
statusCode: 400,
body: "Not found",
};
}
};
|
import React, { Component } from 'react';
import * as api from '../api';
import ArticleSummary from '../components/ArticleSummary';
import ajaxLoader from '../img/ajax-loader.gif';
class Articles extends Component {
constructor(props) {
super(props);
this.state = {
articles: [],
isLoading: true,
sort_by: "votes",
sort_ascending_value: "descending",
sort_ascending: false,
dirty: false
}
this.handleSortOrder = this.handleSortOrder.bind(this);
this.handleSortBy = this.handleSortBy.bind(this);
}
render() {
if (this.state.isLoading || !this.state.articles.length) {
return (
<React.Fragment key="article">
<img id="loading" src={ajaxLoader} alt="ajax loader circle" height="100" width="100" />
</React.Fragment>
)
} else {
return (
<div className="articles" >
<h2 id="article-title">Articles</h2>
<select value={this.state.sort_ascending_value} onChange={this.handleSortOrder}>
<option value="ascending">Sort Ascending</option>
<option value="descending">Sort Descending</option>
</select>
<select value={this.state.sort_by} onChange={this.handleSortBy}>
<option value="author">Author</option>
<option value="votes">Votes</option>
<option value="created_at">Date</option>
</select>
<ul className="article-scroll">{[].concat(this.state.articles).sort((a, b) => b.votes - a.votes).map((article, index) => {
return (
<React.Fragment key={index}>
<ArticleSummary article={article} user={this.props.user} />
<hr />
</React.Fragment>
);
})}
</ul>
</div>
);
}
}
componentDidMount() {
this.setState({ isLoading: true })
api.getArticles(`?sort_by=${this.state.sort_by}&sort_ascending=${this.state.sort_ascending}`).then(articles => {
this.setState({ articles, isLoading: false });
});
}
componentDidUpdate(prevProps, prevState) {
if (this.state.dirty) {
api.getArticles(`?sort_by=${this.state.sort_by}&sort_ascending=${this.state.sort_ascending}`).then(articles => {
this.setState({ articles: articles, isLoading: false });
});
this.setState({ isLoading: true, dirty: false });
}
}
handleSortOrder(event) {
if (event.target.value === "ascending") {
this.setState({ sort_ascending: true, sort_ascending_value: "ascending", dirty: true })
} else {
this.setState({ sort_ascending: false, sort_ascending_value: "descending", dirty: true })
}
}
handleSortBy(event) {
this.setState({ sort_by: event.target.value, dirty: true })
}
}
export default Articles;
|
var app = app || {};
app.table_filter = (function($){
function init() {
$('.js-table-filter').each(function(){
var $container = $(this);
var $submit = $container.find('[type="submit"]');
var $reset = $container.find('.btn-reset');
console.log($submit);
$submit.click(function(){
window.location = window.location.pathname + '?' + $.param(get_values($container))
});
$reset.click(function(){
window.location = window.location.pathname;
});
});
}
function get_values($container) {
var values = {};
var $inputs = $container.find('[name]');
$inputs.each(function() {
values[$(this).attr('name')] = $(this).val();
});
return values;
}
return {
init: init
}
})(jQuery);
app.table_filter.init();
|
var express = require('express');
var http = require('http');
var request = require('request');
var bodyParser = require('body-parser');
var bunyan = require('bunyan');
var fs = require('fs');
var app = express();
var log = bunyan.createLogger({
name: 'honeytest',
streams: [
{
level: 'info',
path: __dirname + '/log/bunyan.log'
}
]
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
//function definition at bottom of file
readLines(parseAndAdd);
var activities = (function(){
var all = {};
all.user_set = [];
all.getUserByID = function(id){
for(var i = 0; i<all.user_set.length; i++){
if(all.user_set[i].user_id === id){
return all.user_set[i];
}
}
return false;
};
return all;
}());
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log("TEST APP LISTENING AT http://%s%s", host, port);
});
app.get('/', function(req, res){
res.sendFile('/index.html', { root: 'public' });
});
app.post('/activity', bodyParser.json(), function (req, res){
if(req.body.user_id !== undefined){
var user = activities.getUserByID(parseInt(req.body.user_id));
if(user !== false){
if(req.body.session_id !== undefined){
user.session_id = parseInt(req.body.session_id);
}
else{
user.session_id ++;
}
log.info(user);
}
else{
var newuser = {};
newuser.user_id = parseInt(req.body.user_id);
if(req.body.session_id !== undefined){
newuser.session_id = parseInt(req.body.session_id);
}
else{
newuser.session_id = 1;
}
activities.user_set.push(newuser);
log.info(newuser);
}
}
});
app.get('/stats', function (req, res){
if (res.statusCode === 200){
var filter = {};
if(req.query.start_date !== undefined){
filter.start_date = req.query.start_date;
}
if(req.query.end_date !== undefined){
filter.end_date = req.query.end_date;
}
if(req.query.user_id !== undefined){
filter.user_id = parseInt(req.query.user_id);
}
readLinesWithFilter(filter, res);
}
});
function readLinesWithFilter(filter, res){
var remaining = '';
var sesdata = {};
sesdata.total_sessions = 0;
sesdata.total_sessions_per_day = {};
sesdata.total_users = [];
var newin = fs.createReadStream(__dirname + '/log/bunyan.log');
newin.on('data', function(data){
remaining += data;
var index = remaining.indexOf('\n');
while(index > -1){
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
parseAndCompose(line, filter, sesdata);
index = remaining.indexOf('\n');
}
});
newin.on('end', function(){
if(remaining.length > 0){
parseAndCompose(remaining);
}
var finaldata = {};
finaldata.total_sessions = sesdata.total_sessions;
finaldata.total_sessions_per_day = sesdata.total_sessions_per_day;
finaldata.total_users = sesdata.total_users.length;
finaldata.avg_sessions_per_user = sesdata.total_sessions/sesdata.total_users.length;
res.end(JSON.stringify(finaldata));
});
}
function parseAndCompose(data, filter, reqsesdata){
if(data !== ''){
var datainjson = JSON.parse(data);
if(filter.start_date !== undefined){
var datetimestamp = datainjson.time.split("T")[0];
var datear = datetimestamp.split("-");
var filterar = filter.start_date.split("-");
for(var i = 0; i<filterar.length; i++){
if(filterar[i] === datear[i]){}
else if(filterar[i] < datear[i]){
break;
}
else{
return false;
}
}
}
if(filter.end_date !== undefined){
var datetimestamp = datainjson.time.split("T")[0];
var datear = datetimestamp.split("-");
var filterar = filter.end_date.split("-");
for(var i = 0; i<filterar.length; i++){
if(filterar[i] === datear[i]){
}
else if(filterar[i] > datear[i]){
break;
}
else{
return false;
}
}
}
if(filter.user_id !== undefined){
if(filter.user_id !== datainjson.user_id){
return false;
}
}
reqsesdata.total_sessions ++;
if(reqsesdata.total_sessions_per_day[datainjson.time.split("T")[0]] === undefined){
reqsesdata.total_sessions_per_day[datainjson.time.split("T")[0]] = 1;
}
else{
reqsesdata.total_sessions_per_day[datainjson.time.split("T")[0]] ++;
}
if(reqsesdata.total_users.length > 0){
var exists = false;
for(var i = 0; i<reqsesdata.total_users.length; i++){
if(reqsesdata.total_users[i] === datainjson.user_id){
exists = true;
break;
}
}
if(exists === false){
reqsesdata.total_users.push(datainjson.user_id);
}
}
else{
reqsesdata.total_users.push(datainjson.user_id);
}
}
}
function readLines(func){
var remaining = '';
var input = fs.createReadStream(__dirname + '/log/bunyan.log');
input.on('data', function(data){
remaining += data;
var index = remaining.indexOf('\n');
while(index > -1){
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function(){
if(remaining.length > 0){
func(remaining);
}
});
}
function parseAndAdd(data){
if(data !== ''){
var datainjson = JSON.parse(data);
if(!activities.getUserByID(datainjson.user_id)){
var new_user = {}
new_user.user_id = datainjson.user_id;
new_user.session_id = datainjson.session_id;
activities.user_set.push(new_user);
}
else{
var user = activities.getUserByID(datainjson.user_id);
if(datainjson.session_id > user.session_id){
user.session_id = datainjson.session_id;
}
}
}
}
|
import { fakeSubmitForm, getStepForm, getUserStore } from './service';
const Model = {
namespace: 'formStepForm',
state: {
current: 'info',
stepList: [],
myStore:[],
},
effects: {
*fetch({ payload }, { call, put }) {
const res = yield call(getStepForm, payload);
yield put({
type: 'saveStepFormData',
payload:res,
});
const msg = yield call(getUserStore,payload);
yield put({
type: 'saveMyStore',
payload:msg,
});
yield put({
type: 'saveCurrentStep',
payload: 'info',
});
},
},
reducers: {
saveCurrentStep(state, { payload }) {
return { ...state, current: payload };
},
saveStepFormData(state, { payload }) {
return { ...state, stepList:payload};
},
saveMyStore(state, { payload }) {
return { ...state, myStore:payload};
},
},
};
export default Model;
|
tippy('#affective-states-diffuse', {
theme: 'light-border',
arrow: false,
allowHTML: true,
placement: 'right',
touch: false,
maxWidth: 550,
interactive: true,
interactiveBorder: 1,
content: '<div class="article-component"><h1>Affective states diffuse across time and across people</h1><p>Affective states have a way of diffusing into the past and future. You don’t just enjoy a donut. You also enjoy the anticipation of the donut, and the memory of it.</p><p>Affective states also diffuse into the people you interact with. When you enjoy a donut, the people around you get to enjoy the it too, through your good mood—even if you don’t share!</p></div>'
});
|
import React, { Component } from "react";
class Messagelist extends Component {
render() {
const { messagelist } = this.props;
var list = null;
if (messagelist != null) {
list = messagelist.map((mess, ind) => {
return <div key={ind}>{mess}</div>;
});
}
return <div>{list}</div>;
}
}
export default Messagelist;
|
'use strict';
let img1=document.getElementById('image1')
let img2=document.getElementById('image2')
let img3=document.getElementById('image3')
let buttonElement=document.getElementById('button')
let resultList = document.getElementById('result')
let maxAttempts=10;
let attempt=0;
let imgIndex1;
let imgIndex2;
let imgIndex3;
let products=[];
// let namesArr=[];
// let votesArr=[];
// let shownArr=[];
function Items(name,src)
{
this.name=name;
this.path=src;
this.vote=0;
this.shown=0;
products.push(this)
// namesArr.push(this)
}
new Items('Bags','img/bag.jpg')
new Items('Banana','img/banana.jpg')
new Items('Bathroom','img/bathroom.jpg')
new Items('Boots','img/boots.jpg')
new Items('Breakfast','img/breakfast.jpg')
new Items('Bubblegum','img/bubblegum.jpg')
new Items('Chair','img/chair.jpg')
new Items('cthulhu','img/cthulhu.jpg')
new Items('Dog duck','img/dog-duck.jpg')
new Items('Dragon','img/dragon.jpg')
new Items('Pen','img/pen.jpg')
new Items('Pet sweep','img/pet-sweep.jpg')
new Items('Scissors','img/scissors.jpg')
new Items('Shark','img/shark.jpg')
new Items('Sweep','img/sweep.png')
new Items('Tauntaun','img/tauntaun.jpg')
new Items('Unicorn','img/unicorn.jpg')
new Items('Water can','img/water-can.jpg')
new Items('Wine glass','img/wine-glass.jpg')
function getnumbers()
{
return Math.floor(Math.random()*products.length)
}
let shownPic=[];
function render()
{
imgIndex1=getnumbers()
imgIndex2=getnumbers()
imgIndex3=getnumbers()
while(imgIndex1 === imgIndex3 || imgIndex1 === imgIndex2 || imgIndex3 === imgIndex2 || shownPic.includes(imgIndex1) || shownPic.includes(imgIndex2) || shownPic.includes(imgIndex3))
{
imgIndex1=getnumbers()
imgIndex2=getnumbers()
imgIndex3=getnumbers()
}
img1.src=products[imgIndex1].path
img2.src=products[imgIndex2].path
img3.src=products[imgIndex3].path
products[imgIndex1].shown++;
products[imgIndex2].shown++;
products[imgIndex3].shown++;
shownPic=[imgIndex1,imgIndex2,imgIndex3]
}
img1.addEventListener('click' ,userClick)
img2.addEventListener('click' ,userClick)
img3.addEventListener('click' ,userClick)
function userClick(event)
{
attempt++;
if(attempt<maxAttempts)
{
if(event.target.id==='image1')
{
products[imgIndex1].vote++
}
else if(event.target.id==='image2')
{
products[imgIndex2].vote++
}
else if(event.target.id==='image3')
{
products[imgIndex3].vote++
}
render()
}
else
{
saveStorage()
buttonElement.hidden=false;
buttonElement.addEventListener('click',showList)
function showList()
{
let list = document.getElementById('result')
for(let i=0;i<products.length;i++)
{
let listItem=document.createElement('li')
list.appendChild(listItem)
listItem.textContent=`${products[i].name} has been voted ${products[i].vote} and has been shown ${products[i].shown} times`
}
buttonElement.removeEventListener('click' ,showList)
}
img1.removeEventListener('click',userClick)
img2.removeEventListener('click',userClick)
img3.removeEventListener('click',userClick)
}
}
render()
function saveStorage()
{
let stringArr=JSON.stringify(products)
localStorage.setItem('Products',stringArr)
}
function loadStorage()
{
let data=localStorage.getItem('Products')
let parsedArr=JSON.parse(data)
if(parsedArr !== null)
{
parsedArr = products
}
}
loadStorage()
|
var thumb149="TkSWZ9/CYkrrc5VP0dMeP2SepWcz3FM9jnH7+7ZWhToPsDPYfRBi14Gao1WdIZUsXwbw6JdzaJZnoclM/hlli5OWuN/lrFVhA3Bh4BtBY3uDc3LmD25UPqqVdKqRYIQtR5jTqgJbIaD72pyLQkfdZ7wmseMlFdDvrkd526MHIjcvcCDF+/tf9StNJlvhxncsFGuJ1HRQZU7742S+KwjaVXhh5FTXzkdFVJ2uXNybsFbzqmvc8LY+T0pmNT7b1zAHPCBUw4WtUq05aZR1Xq+K3943gHjKBe7R+P3Nqdz65BkPJLJQS5dvQ2NExbdi6QMyxiZ5cn3QOkbz+dmgSb0Sq/PScrvEBHIT0G6Vq30R2zxAXxmPPwMwxDkXQk66as9T0LvQ04isTQ74iznPcBnNVS8u6km5MWyVclgSVw2BK8V4wyPaUA+fTWtOasAPDEmwlV9nJIXK/U18pVsVe4i5VoKR2CFBqdKtCDE7h1/A7ChujiiX4I2InO0fxIQ4P5/+k6/pEk8vFjWMuPs0tz8UTZwS3mg4zqnf53vDu7Lp+9bZMH6vg1b31x7TcrO6XJ5vsLNudTAK9nRncATGgMQbMkRULkf2AW6uIDDCOfYxj7Z6SMiVsPtpXOFYZKEWQYL+j4j8hbSgsOWBLUP72Kb6tN+zMaUxWHNo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E4tTc70lSJ8t3f+Zi8/ujNDkhD6qL6dz0Kc5bl1TBUfTYk2HKykrAaFo1KTwYJx6BXW08LOhinXuE5Y/U6agkDKPsiMnNu3GL/uUunkps7wDU/9dsck507TQ/lFp+6l2e7p+svLBnEfwyLwG5vRampd5Wlt0GgU0Wt9dtGrenKlJbwZCZrEEY1b2jhs2o0YaI89n6X59zNoLEXfZVvi1M1iBQbVuvE55CtKxVooV+Y3DykuFQNz0WQCrK8NKH4ycixW+ZQYaUKnuhKFh2v7w0+HUZK7nmCGY3j4AD99TX7CJWz7Xi0lD4FgQ/2dYJcgH3aDKQ5EcuE2SAdKp+mCmudSg3UFW1SNv+PUpJThxQeMipuqZQ/7diBUsjSbw74TMfGN2/oyw3Oam0CV+ujzhmyUERvPQ6pDAcekxuvNSsg";
|
'use strict';
var app = require('./all').app;
module.exports = {
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + app.name
};
|
import React, { Component, PropTypes } from 'react';
import { View, Text, StyleSheet, Navigator, TouchableHighlight, Button, AsyncStorage, Modal } from 'react-native';
import Character from '../Character';
const _ = require('underscore');
const CHARACTER_STORAGE_BASE = '@AsyncStorageCharactersSheets:';
function charStorageKey(key) {
return CHARACTER_STORAGE_BASE + key;
}
export default class CharacterSheet extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
backgroundModal: false,
raceModal: false
}
}
componentWillMount() {
const that = this;
AsyncStorage.getItem(charStorageKey(this.props.name)).then(function (encodedCharacter) {
const character = new Character(Character.fromSaveState(encodedCharacter));
that.setState({
isLoading: false,
character: character
});
});
}
flipModalState(modalKey) {
switch(modalKey) {
case 'background':
this.setState({backgroundModal: !this.state.backgroundModal});
break;
case 'race':
this.setState({raceModal: !this.state.raceModal});
break;
}
}
displayStat(statKey) {
const base = this.state.character[statKey];
const mod = this.state.character.race.statMods[statKey];
return base + mod;
}
render () {
if (this.state.isLoading) {
return (
<View><Text>Loading...</Text></View>
);
}
const racialOptionsTemplate = this.state.character.race.isIncomplete ? this.state.character.race.optionsTemplate : null;
const racialOptions = racialOptionsTemplate ?
_.map(racialOptionsTemplate, (template, index) => {
return <template.component key={index} options={template.options} onSave={template.onSave} />
}) : null;
return (
<View style={styles.characterSheet}>
<View style={styles.headerRow}>
<TouchableHighlight
style={styles.backButton}
underlayColor="#f0f0f0"
onPress={this.props.toCharacterSelect}>
<Text style={styles.backButtonText}><</Text>
</TouchableHighlight>
<Text style={styles.characterName}>{this.state.character.name}</Text>
<TouchableHighlight
style={styles.deleteButton}
underlayColor="#b44444"
onPress={this.props.deleteCharacter.bind(null, this.props.name)}>
<Text style={styles.deleteButtonText}>×</Text>
</TouchableHighlight>
</View>
<View style={styles.raceRow}>
<TouchableHighlight
style={styles.raceButton}
underlayColor="#f0f0f0"
onPress={() => {
this.flipModalState('race');
}}>
<Text style={styles.raceButtonText}>{this.state.character.raceKey}</Text>
</TouchableHighlight>
</View>
<View style={styles.bgRow}>
<TouchableHighlight
style={styles.bgButton}
underlayColor="#f0f0f0"
onPress={() => {
this.flipModalState('background');
}}>
<Text style={styles.bgButtonText}>Background: {this.state.character.background.label}</Text>
</TouchableHighlight>
</View>
<View style={styles.statRow}>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Strength:</Text>
<Text style={styles.statValue}>{this.displayStat('strength')}</Text>
</View>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Dexterity:</Text>
<Text style={styles.statValue}>{this.displayStat('dexterity')}</Text>
</View>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Constitution:</Text>
<Text style={styles.statValue}>{this.displayStat('constitution')}</Text>
</View>
</View>
<View style={styles.statRow}>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Intelligence:</Text>
<Text style={styles.statValue}>{this.displayStat('intelligence')}</Text>
</View>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Wisdom:</Text>
<Text style={styles.statValue}>{this.displayStat('wisdom')}</Text>
</View>
<View style={styles.statBin}>
<Text style={styles.statLabel}>Charisma:</Text>
<Text style={styles.statValue}>{this.displayStat('charisma')}</Text>
</View>
</View>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.backgroundModal}
onRequestClose={() => {}}>
<TouchableHighlight
style={styles.bgButton}
underlayColor="#f0f0f0"
onPress={() => {
this.flipModalState('background');
}}>
<Text style={styles.bgButtonText}>Close Modal</Text>
</TouchableHighlight>
</Modal>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.raceModal}
onRequestClose={() => {}}>
{racialOptions}
<TouchableHighlight
style={styles.bgButton}
underlayColor="#f0f0f0"
onPress={() => {
this.flipModalState('race');
}}>
<Text style={styles.bgButtonText}>Close Modal</Text>
</TouchableHighlight>
</Modal>
</View>
)
}
}
CharacterSheet.propTypes = {
name: PropTypes.string.isRequired,
toCharacterSelect: PropTypes.func.isRequired,
deleteCharacter: PropTypes.func.isRequired
};
/*
* === STYLES ===
*/
const styles = StyleSheet.create({
characterSheet: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffffff',
},
headerRow: {
flex:1,
flexDirection: 'row'
},
backButton: {
flex: 1
},
backButtonText: {
fontSize: 32,
textAlign: 'center',
},
deleteButton: {
flex: 1
},
deleteButtonText: {
fontSize: 32,
textAlign: 'center'
},
characterName: {
flex: 6,
fontSize: 28,
textAlign: 'center'
},
statRow: {
flex: 5,
flexDirection: 'row'
},
statBin: {
flex: 1
},
statLabel: {
flex: 1
},
statValue: {
flex: 2,
fontSize: 24
},
bgRow: {
flex: 1,
flexDirection: 'row'
},
bgButton: {
flex: 1,
justifyContent: 'center'
},
bgButtonText: {
fontSize: 18
},
raceRow: {
flex: 1,
flexDirection: 'row'
},
raceButton: {
flex: 1,
justifyContent: 'center'
},
raceButtonText: {
fontSize: 18
}
});
|
import React from 'react';
import Item from './Item';
import { Text, Box, Flex } from 'rebass';
import personal1 from '../img/personal1.png'
import personal2 from '../img/personal2.png'
import haendlr1 from '../img/haendlr1.png'
import haendlr2 from '../img/haendlr2.png'
import haendlr3 from '../img/haendlr3.png'
import guse1 from '../img/screen1.PNG'
import guse2 from '../img/screen2.PNG'
import guse3 from '../img/screen4.PNG'
const ImageFeed = function (props) {
return (
<div>
<Flex justifyContent='center' flexWrap='nowrap'>
<Box p={4} pt={5} bg='white' color='#373543' width={[0.9, 0.8, 0.5]}>
<Text fontSize={4} fontWeight='bold'>
web shop: händlr.
</Text>
</Box>
</Flex>
<Item imagePath={haendlr1} text="this is a screenshot of a webshop i built. i used Typescript and React for the frontend.
further customizations were made using CSS and html." />
<Item imagePath={haendlr3} text="the design is responsive, i.e. it adjusts to various screen sizes. the page itself is in german, for
a german audience. however, the shown articles come from a database in english and therefore have english properties." />
<Item imagePath={haendlr2} text="the entire application follows the same color and font scheme. furthermore, all text containers
look the same, creating unity within the web application." />
<Flex justifyContent='center' flexWrap='nowrap'>
<Box p={4} pt={5} bg='white' color='#373543' width={[0.9, 0.8, 0.5]}>
<Text fontSize={4} fontWeight='bold'>
personal website.
</Text>
</Box>
</Flex>
<Item imagePath={personal1} text="this is a screenshot of my personal website. the main site
shows miniature views of my projects. i built it using Javascript and React.
i also customized the site further using html and CSS." />
<Item imagePath={personal2} text="this is another screenshot from my personal website.
it was taken from the detailed post view, which is shown as the user selects one of the posts. throughout the entire
website, i used the material design principles." />
<Flex justifyContent='center' flexWrap='nowrap'>
<Box p={4} pt={5} bg='white' color='#373543' width={[0.9, 0.8, 0.5]}>
<Text fontSize={4} fontWeight='bold'>
web app: guse.
</Text>
</Box>
</Flex>
<Item imagePath={guse3} text="this is a screenshot of a web app i built using React and Javascript. again, the site follows a unified
design concept, in colors, fonts and structural elements." />
<Item imagePath={guse2} text="the web app takes in user input to assemble a personalized investment portfolio.
the purpose of the platform is to help non-finance experts make sound personal finance decisions." />
<Item imagePath={guse1} text="me and my team built this as a part of a hackathon project at Calhacks, the world's largest collegiate
hackathon. with the app, we won the IBM challenge, against over 2,000 competitors." />
</div>
);
};
export default ImageFeed;
|
var OBJLoader = function ()
{
this.ready = false;
this.initialized = false;
this.data = {
'indices' : [],
'positions' : [],
'textureCoords' : [],
'normals' : [],
'vertexColors' : [],
}
this.loader = null;
this.rawModel = null;
}
OBJLoader.prototype.loadOBJModel = function ( filepath, loader )
{
this.loader = loader;
// Because it might take a while to prepare...
// this.createPlaceholder();
this.readFile( filepath );
}
OBJLoader.prototype.createPlaceholder = function ()
{
this.rawModel = this.loader.loadToVAO(
OBJLoader.placeholderData.positions,
OBJLoader.placeholderData.textureCoords,
OBJLoader.placeholderData.normals,
OBJLoader.placeholderData.indices
);
}
OBJLoader.prototype.onLoad = function ( rawText )
{
this.parseFile( rawText );
this.rawModel = this.loader.loadToVAO( this.data, false );
this.ready = true;
console.log( 'OBJ model is ready!' );
}
OBJLoader.prototype.readFile = function ( filepath )
{
// save 'this'; https://stackoverflow.com/a/6985358
var instance = this;
var request = new XMLHttpRequest();
request.open( 'GET', filepath, true );
request.onreadystatechange = function ()
{
if ( request.readyState === 4 )
{
if ( request.status === 200 || request.status === 0 )
{
instance.onLoad( request.responseText );
}
}
}
request.send( null );
}
OBJLoader.prototype.parseFile = function ( rawText )
{
var lines = rawText.split( '\n' );
var positions = [];
var textureCoords = [];
var normals = [];
var vertexColors = [];
var vertData = [];
for ( var i = 0; i < lines.length; i += 1 )
{
line = lines[ i ].split( ' ' );
// console.log( line );
// vertex coordinates
if ( line[ 0 ] == 'v' )
{
var coordRaw = line.slice( 1 );
var coord = [];
for ( var j = 0; j < 3; j += 1 )
{
coord.push( parseFloat( coordRaw[ j ] ) );
}
// console.log( 'v', coord );
positions.push( coord );
// vertex colors
if ( coordRaw.length > 3 )
{
var color = [];
for ( var j = 3; j < 6; j += 1 )
{
color.push( parseFloat( coordRaw[ j ] ) );
}
color.push( 1.0 ); // will ignore object alpha...
// console.log( 'vc', color );
vertexColors.push( color );
}
}
// texture coordinates
else if ( line[ 0 ] == 'vt' )
{
var coordRaw = line.slice( 1 );
var coord = [];
for ( var j = 0; j < 2; j += 1 )
{
coord.push( parseFloat( coordRaw[ j ] ) );
}
coord[ 1 ] = 1 - coord[ 1 ]; // something about Blender vs OpenGL yAxis
// console.log( 'vt', coord );
textureCoords.push( coord );
}
// normal coordinates
else if ( line[ 0 ] == 'vn' )
{
var coordRaw = line.slice( 1 );
var coord = [];
for ( var j = 0; j < 3; j += 1 )
{
coord.push( parseFloat( coordRaw[ j ] ) );
}
// console.log( 'vn', coord );
normals.push( coord );
}
// face
else if ( line[ 0 ] == 'f' )
{
var coordRaw = line.slice( 1 );
var coord = [];
for ( var j = 0; j < coordRaw.length; j += 1 )
{
var face = coordRaw[ j ];
var indicesRaw = face.split( '/' );
var indices = [];
for ( var k = 0; k < indicesRaw.length; k += 1 )
{
indices.push( parseInt( indicesRaw[ k ] ) );
}
vertData.push( {
'key' : face,
'indices' : indices
})
// coord.push( indices );
}
// console.log( 'f', coord );
// faces.push( coord );
}
}
// console.log( vertData );
// Create index...
var keys = [];
var iIdx = 0;
for ( var i = 0; i < vertData.length; i += 1 )
{
var vData = vertData[ i ];
var key = vData[ 'key' ];
var vIdx = vData[ 'indices' ][ 0 ] - 1; // OBJ one vs zero-indexed
var tIdx = vData[ 'indices' ][ 1 ] - 1;
var nIdx = vData[ 'indices' ][ 2 ] - 1;
if ( keys.indexOf( key ) >= 0 )
{
// Not unique combination so reference existing
this.data[ 'indices' ].push( keys.indexOf( key ) );
}
else
{
// Unique combinantion so create new entries
this.data[ 'indices' ].push( iIdx );
Array.prototype.push.apply( this.data[ 'positions' ], positions[ vIdx ] );
if ( vertexColors.length != 0 )
{
Array.prototype.push.apply( this.data[ 'vertexColors' ], vertexColors[ vIdx ] );
}
if ( textureCoords.length != 0 )
{
Array.prototype.push.apply( this.data[ 'textureCoords' ], textureCoords[ tIdx ] );
}
if ( normals.length != 0 )
{
Array.prototype.push.apply( this.data[ 'normals' ], normals[ nIdx ] );
}
iIdx += 1;
keys.push( key );
}
}
// console.log( this.data );
}
OBJLoader.placeholderData = {
// Cube
'positions' :
[
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
],
'textureCoords' :
[
// Front
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Back
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Top
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Bottom
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Right
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
// Left
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
],
'normals' :
[
// Front
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
// Back
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
// Top
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
// Bottom
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
// Right
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
// Left
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0
],
'indices' :
[
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
],
}
OBJLoader.placeholderData_rectangle = {
'positions' : [
-0.5, 0.5, 0, // v0
-0.5, -0.5, 0, // v1
0.5, -0.5, 0, // v2
0.5, 0.5, 0, // v3
],
'textureCoords' : [
0, 0, // v0
0, 1, // v1
1, 1, // v2
1, 0 // v3
],
'normals' : [],
'indices' : [
0, 1, 3, // top left triangle (v0, v1, v3)
3, 1, 2 // bottom right triangle (v3, v1, v2)
],
}
OBJLoader.placeholderData_cubeTut = {
'positions' : [
-0.5, 0.5,-0.5,
-0.5,-0.5,-0.5,
0.5,-0.5,-0.5,
0.5, 0.5,-0.5,
-0.5, 0.5, 0.5,
-0.5,-0.5, 0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
0.5, 0.5,-0.5,
0.5,-0.5,-0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
-0.5,-0.5,-0.5,
-0.5,-0.5, 0.5,
-0.5, 0.5, 0.5,
-0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
0.5, 0.5,-0.5,
0.5, 0.5, 0.5,
-0.5,-0.5, 0.5,
-0.5,-0.5,-0.5,
0.5,-0.5,-0.5,
0.5,-0.5, 0.5
],
'textureCoords' : [
0,0,
0,1,
1,1,
1,0,
0,0,
0,1,
1,1,
1,0,
0,0,
0,1,
1,1,
1,0,
0,0,
0,1,
1,1,
1,0,
0,0,
0,1,
1,1,
1,0,
0,0,
0,1,
1,1,
1,0
],
'normals' : [],
'indices' : [
0, 1, 3,
3, 1, 2,
4, 5, 7,
7, 5, 6,
8, 9,11,
11, 9,10,
12,13,15,
15,13,14,
16,17,19,
19,17,18,
20,21,23,
23,21,22
],
}
|
export { default } from './ContactList';
export * from './ContactList';
|
function navMiniDropdown() {
let menu_icon = document.querySelector(".menu__icon"),
menu_mini = document.querySelector(".menu__nav");
menu_icon.addEventListener("click", (e) => {
menu_mini.classList.toggle("show-lg");
});
let all = document.querySelectorAll(".dropdown"),
home = document.querySelector(".menu__item--home"),
home_dropdown = document.querySelector(".dropdown--home"),
products = document.querySelector(".menu__item--products"),
products_dropdown = document.querySelector(".dropdown--products"),
wordpress = document.querySelector(".menu__item--wordpress"),
wordpress_dropdown = document.querySelector(".dropdown--wordpress"),
pages = document.querySelector(".menu__item--pages"),
pages_dropdown = document.querySelector(".dropdown--pages");
home.addEventListener("click", () => {
all.forEach(element => {
if (!(element.classList.contains("dropdown--home")))
element.classList.remove("show");
});
home_dropdown.classList.toggle("show");
});
products.addEventListener("click", () => {
all.forEach(element => {
if (!(element.classList.contains("dropdown--products")))
element.classList.remove("show");
});
products_dropdown.classList.toggle("show");
});
wordpress.addEventListener("click", () => {
all.forEach(element => {
if (!(element.classList.contains("dropdown--wordpress")))
element.classList.remove("show");
});
wordpress_dropdown.classList.toggle("show");
});
pages.addEventListener("click", () => {
all.forEach(element => {
if (!(element.classList.contains("dropdown--pages")))
element.classList.remove("show");
});
pages_dropdown.classList.toggle("show");
});
}
export default navMiniDropdown;
|
import React, {useContext, useState} from "react";
import {AlertContext} from "../context/alert/alertContext";
export const Form = () => {
const [value, setValue] = useState('')
const alert = useContext(AlertContext)
const handleChange = e => setValue(e.target.value)
const handleSubmit = e => {
e.preventDefault()
if(value.trim()) {
// ...
alert.show('Note been created', 'success')
setValue('')
} else {
alert.show('Enter name note')
}
}
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input type="text" className="form-control" placeholder="Enter name note" value={value} onChange={handleChange}/>
</div>
</form>
)
}
|
import React from 'react';
import { BrowserRouter, Route, Switch, Link, NavLink } from 'react-router-dom';
import Menu from '../components/Menu';
import Golden from '../components/Golden';
import NotFound from '../components/NotFound';
import Contact from '../components/Contact';
import ProjectOne from '../components/projects/ProjectOne';
import ProjectTwo from '../components/projects/ProjectTwo';
import ProjectThree from '../components/projects/ProjectThree';
import ProjectFour from '../components/projects/ProjectFour';
const NordicRouter = () => (
<BrowserRouter>
<div>
<Menu />
<Switch>
<Route path="/" component ={ Golden } exact={ true } />
<Route path="/contact" component = { Contact } />
<Route path="/project/1" component = { ProjectOne } />
<Route path="/project/2" component = { ProjectTwo } />
<Route path="/project/3" component = { ProjectThree } />
<Route path="/project/4" component = { ProjectFour } />
<Route path="/golden" component = { Golden } />
<Route component ={ NotFound } />
</Switch>
</div>
</BrowserRouter>
);
export default NordicRouter;
|
var searchData=
[
['rect_2eh',['rect.h',['../rect_8h.html',1,'']]]
];
|
../../../../../shared/src/App/FindVideos/index.js
|
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var currentEffectNode = null;
var audioInput = null;
var wetGain = null;
var outputMix = null;
var wetGainVal = 0;
// --------- Delay ---------------------------------------------------------------------------
var delayActive = false;
var delayController = null;
var delayNode = null;
var delayGainNode = null;
var delayTime = 0.1;
var delayFeedback = 0.1;
function createDelay() {
delayNode = audioContext.createDelay();
delayNode.delayTime.value = delayTime;
delayGainNode = audioContext.createGain();
delayGainNode.gain.value = delayFeedback;
delayGainNode.connect( delayNode );
delayNode.connect( delayGainNode );
delayNode.connect( wetGain );
delayActive = true;
return delayNode;
}
function updateDelay(x, val) {
if (delayActive)
{
switch (x)
{
case "t":
delayTime = val/360;
delayNode.delayTime.value = delayTime;
break;
case "v":
wetGainVal = val/360;
wetGain.gain.value = wetGainVal;
if (wetGain.gain.value > 1) { wetGain.gain.value = 1; }
break;
case "f":
delayFeedback = val/360;
delayGainNode.gain.value = delayFeedback;
if (delayGainNode.gain.value > 1) { delayGainNode.gain.value = 1; }
break;
}
}
// removeEffect("delay");
// addEffect("delay");
}
function restartDelay() {
if (delayActive) {
removeEffect("delay");
addEffect("delay");
}
}
// --------- Drive ---------------------------------------------------------------------------
var driveActive = false;
var driveController = null;
var driveNode = null;
var driveAmount = 1.0;
function createDrive() {
driveNode = new WaveShaper( audioContext );
driveNode.output.connect ( wetGain )
driveNode.output.connect ( outputMix )
driveNode.setDrive(driveAmount);
driveActive = true;
return driveNode.input;
}
function updateDrive(x, val) {
if (driveActive)
{
switch (x)
{
case "d":
driveAmount = (val/360)*50;
driveNode.setDrive(driveAmount);
restartDelay();
break;
}
}
}
function restartDrive() {
if (driveActive) {
removeEffect("drive");
addEffect("drive");
}
}
// --------- MAIN ---------------------------------------------------------------------------
function audioStream(stream) {
// Create an AudioNode from the stream.
audioInput = audioContext.createMediaStreamSource( stream );
// Connect it to the destination to hear yourself (or any other node for processing!)
outputMix = audioContext.createGain();
wetGain = audioContext.createGain();
audioInput.connect(outputMix);
wetGain.connect(outputMix);
outputMix.connect( audioContext.destination );
}
function addEffect(type) {
switch (type)
{
case "delay":
delayController = createDelay();
audioInput.connect( delayController );
if (driveActive) { delayController.connect( driveController ) }
break;
case "drive":
driveController = createDrive();
audioInput.connect( driveController );
// wetGain.connect( driveController );
// outputMix.connect( driveController );
if (delayActive) { driveController.connect( delayController ); restartDelay(); }
}
}
function removeEffect(type) {
switch (type)
{
case "delay":
delayController.disconnect(0);
delayController = null;
delayNode = null;
delayGainNode = null;
delayActive = false;
break;
case "drive":
driveController.disconnect(0);
driveController = null;
driveNode = null;
driveActive = false;
break;
}
}
function setUp() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
navigator.getUserMedia( {audio:true}, audioStream );
}
$( document ).ready(function() {
setUp();
});
|
import React from 'react'
import { StyleSheet } from 'react-native'
import PropTypes from 'prop-types'
import {
Container,
Content,
Card,
CardItem,
Text,
Thumbnail
} from 'native-base'
import moment from 'moment'
import LabelList from './LabelList'
const IssueDetails = ({ issue }) => {
const fromNow = moment(issue.created_at).fromNow()
const cratedAt = moment.utc(issue.created_at).format('YYYY-MM-DD HH:mm:ss')
return (
<Container>
<Content>
<Card>
<CardItem header style={styles.cardItem}>
<Text>
{issue.title} ({issue.state})
</Text>
</CardItem>
<CardItem style={styles.cardItem}>
<Thumbnail small square source={{ uri: issue.user.avatar_url }} />
<Text style={styles.userName}> {issue.user.login} </Text>
<Text> opened this issue {fromNow}</Text>
</CardItem>
<LabelList labels={issue.labels} />
<CardItem style={styles.cardItem}>
<Text>Opened: {cratedAt} (UTC)</Text>
</CardItem>
<CardItem style={styles.cardItem}>
<Text>{issue.body}</Text>
</CardItem>
</Card>
</Content>
</Container>
)
}
const styles = StyleSheet.create({
cardItem: {
borderBottomWidth: 1,
borderColor: 'rgba(0,0,0,0.2)'
},
userName: {
fontWeight: 'bold'
}
})
IssueDetails.propTypes = {
issue: PropTypes.object.isRequired
}
export default IssueDetails
|
import domUpdates from './domUpdates';
class Hotel {
constructor(users, roomServices, bookings, rooms, today) {
this.users = users;
this.roomServices = roomServices;
this.bookings = bookings;
this.rooms = rooms;
this.today = today;
this.availableRooms = this.returnRoomsUnoccupiedByDate(this.today);
}
filterItemsBySpecificDate(date, property) {
return this[property].filter(item => item.date === date);
}
returnPercentRoomsOccupiedByDate(date) {
return Math.round(this.filterItemsBySpecificDate(date, 'bookings').length / this.rooms.length * 100);
}
returnTotalNumberOfUnoccupiedRoomsByDate(date) {
return this.rooms.length - this.filterItemsBySpecificDate(date, 'bookings').length;
}
returnRoomsUnoccupiedByDate(date) {
let filteredBookings = this.filterItemsBySpecificDate(date, 'bookings');
return this.rooms.filter(room => !filteredBookings.some(booking => booking.roomNumber === room.number));
}
calculateTotalRevenueByDate(date) {
let roomServicesTotal = this.filterItemsBySpecificDate(date, 'roomServices').reduce((acc, item) => {
return acc += item.totalCost;
}, 0);
let totalRevenue = this.filterItemsBySpecificDate(date, 'bookings').reduce((acc, booking) => {
this.rooms.forEach(room => {
if (booking.roomNumber === room.number) {
acc += room.costPerNight;
}
})
return acc;
}, 0) + roomServicesTotal;
return Number(totalRevenue.toFixed(2));
}
findMostAndLeastPopularBookingDate(popularity) {
let bookingObj = this.bookings.reduce((acc, booking) => {
if (!acc[booking.date]) {
acc[booking.date] = 1
} else {
acc[booking.date]++;
}
return acc;
}, {});
return Object.keys(bookingObj).reduce((acc, key) => {
if (popularity === 'high') {
return bookingObj[acc] > bookingObj[key] ? acc : key
} else if (popularity === 'low') {
return bookingObj[acc] < bookingObj[key] ? acc : key
}
})
}
returnAllRoomServiceOrdersByDate(date) {
let targetRoomServiceObjects = this.filterItemsBySpecificDate(date, 'roomServices');
let result = targetRoomServiceObjects.map(obj => {
return { food: obj.food, cost: obj.totalCost }
})
domUpdates.appendAllFoodItemsAndCostByDate(result);
}
}
export default Hotel;
|
import { useStoreContext } from '../lib/globalstore'
import { useState, useEffect } from 'react'
import { GrTrophy } from 'react-icons/gr'
import './gameover.css'
function GameOver(){
const [{ end, countdown, score }, dispatch] = useStoreContext()
const [counter, setCounter] = useState(35)
useEffect(()=>{
setCounter(35)
if(countdown) counter > 0 && setTimeout(() => setCounter(counter - 1), 100)
if (counter < 1) {
dispatch({type:'GAME_START'})
setCounter(35)
}
}, [countdown, counter])
function closeStart(){
dispatch({type:"GAME_BOARD"})
}
const highscore = localStorage.getItem("SnakeGameHighScore")
return (
<>
<div className="gameoverContainer" style={{display: end ? 'block' : 'none'}}>
<div className="dropGameover">
<div className="highscore"><GrTrophy/> : {highscore}</div>
<div className="lastscorebox"><div className="lastscore"></div>: {score}</div>
<button className="startBtn" onClick={closeStart}>Start</button>
</div>
</div>
</>
)
}
export default GameOver
|
_.each(UNITS, unit => {
var hooksObject = {
onSubmit: function(insertDoc) {
console.log('onSubmit');
var hook = this
var price = {
unit: insertDoc.unit,
productId: insertDoc.productId,
}
var existingPrice = Mart.Prices.findOne(price)
var pricing = {priceInCents: parseInt(insertDoc.priceInDollars * 100)}
console.log(insertDoc.depositInDollars);
if(insertDoc.depositInDollars)
_.extend(pricing, {depositInCents: parseInt(insertDoc.depositInDollars * 100)})
console.log(pricing);
if(existingPrice) {
console.log('existingPrice');
Mart.Prices.update(existingPrice._id, {$set: pricing}, function(error, priceId) {
console.log('tried to update');
if(error) {
console.log('error');
hook.done(error)
} else {
console.log('success');
sAlert.success("Price added")
hook.done()
}
})
} else {
_.extend(price, pricing)
Mart.Prices.insert(price, function(error, priceId) {
if(error) {
hook.done(error)
} else {
sAlert.success("Price added")
hook.done()
}
})
}
return false
},
};
AutoForm.addHooks(spaceManagePriceId(unit), hooksObject, true);
AutoForm.addHooks(spaceManagePriceId(unit), MeteorErrorHook, true);
})
Template.manageSpace.onCreated(function() {
MANAGE_SPACE_UPLOADERS = new ReactiveVar({})
var template = this
Tracker.autorun(function() {
var spaceId = FlowRouter.getParam('spaceId')
template.subscribe("mart/product", spaceId);
});
})
Template.manageSpaceForbid.onCreated(function() {
var propertyId = FlowRouter.getParam('propertyId')
console.log(propertyId);
var property = Mart.Storefronts.findOne(propertyId);
var permitted = canManageProperty(property)
if(!permitted)
forbid()
})
|
var global = {};
$(function() {
$( window ).on('beforeunload', function() {
var valid= true;
$('.panel input[type="text"]').each(function(){
if($(this).val() != '') valid = false;
});
if(!valid){
return "سوف تفقد الوارد إذا لم تقم بالضغط أولا على زر إضافة الوارد، هل تريد حقا ترك الصفحة؟";
}
});
global.baseUrl = $('#baseUrl').val();
global.categories = [];
$("#importDate").datetimepicker({
pickTime: false,
language: 'ar'
});
$("#addcategory").on("click", function () {
var row = $('.new-row tbody').html();
$('.last-row').before(row);
$.each($('td.row-id'), function(index){
$(this).html(index+1);
});
if($('#billPercentage:checked').length){
$('.col-buy-price').hide();
$('input[name="buyPrice"]').prop('disabled', true);
}else{
$('.col-buy-price').show();
$('input[name="buyPrice"]').prop('disabled', false);
}
});
$("#addnewcategory").on("click", function(){
$('#addNewCategoryModal').modal();
});
$('#addNewCategoryModal').on('hidden.bs.modal', function () {
$('#success-msg').addClass('hidden');
$('#categoryName').val('');
$('#categoryForm .errors').remove();
});
$("#addNewCategoryModal #categoryForm").on("submit", function (e) {
e.preventDefault();
var categoryName = $('#categoryName').val();
$('#success-msg').addClass('hidden');
$('#categoryForm .errors').remove();
$('#submit').button('loading');
$.ajax({
async: false,
dataType: 'json',
url: global.baseUrl + '/category/ajax',
type: "post",
data: { categoryName: categoryName },
success: function(json){
if(json.errors){
$('#success-msg').addClass('hidden');
$.each(json.errors, function(field, msg){
$('#'+field).after('<ul class="errors"><li>'+msg.isEmpty+'</li></ul>');
});
} else {
$('#success-msg').html(json.success).removeClass('hidden');
$('#categoryName').val('');
}
}
}).always(function () {
$('#submit').button('reset');
});
});
$('#categoryName').autocomplete({
serviceUrl: global.baseUrl + '/category/query',
minChars:1,
delimiter: /(,|;)\s*/, // regex or character
maxHeight:400,
zIndex: 9999,
deferRequestBy: 0, //miliseconds
triggerSelectOnValidInput: false,
noCache: true, //default is false, set to true to disable caching
});
$('.table-category').on('click', 'input[name="category"]', function(){
$(this).autocomplete({
serviceUrl: global.baseUrl + '/category/query',
minChars:1,
delimiter: /(,|;)\s*/, // regex or character
maxHeight:400,
//width:300,
zIndex: 9999,
deferRequestBy: 0, //miliseconds
triggerSelectOnValidInput: false,
params: { import:true }, //aditional parameters
noCache: true, //default is false, set to true to disable caching
onSelect: function(category){
var decoded = $("<div/>").html(category.value).text();
$(this).val(decoded);
$(this).attr('data-id',category.data)
.prop('disabled',true)
.addClass('text-center input-tagged')
.next().removeClass('hidden');
$(this).parent().next().find('input').focus();
}
})
}).on('click' , '.remove-category', function(){
if($('.table-category .category-row').length > 1)
$(this).closest('.category-row').remove();
$.each($('td.row-id'), function(index){
$(this).html(index+1);
});
}).on('click' , '.edit-category' , function(){
$(this).prev().prop('disabled',false)
.removeClass('text-center input-tagged')
.focus()
.next().addClass('hidden');
});
$('#importForm').submit(function(e){
e.preventDefault();
var valid = true;
$('ul.errors').remove();
$('.table-category .category-row').each(function(index, row){
var category = {};
category['categoryId'] = $(row).find('input[name="category"]').attr('data-id');
category['categoryQuantity'] = $(row).find('input[name="quantity"]').val();
category['categoryBuyPrice'] = $(row).find('input[name="buyPrice"]:enabled').val();
category['categorySellPrice'] = $(row).find('input[name="sellPrice"]').val();
if($('#billPercentage').prop('checked')){
if( !isInteger(category['categoryId'])
|| !isInteger(category['categoryQuantity'])
|| !isFloat(category['categorySellPrice'])
) { valid = false; }
category['categoryBuyPrice'] = 0;
} else {
if( !isInteger(category['categoryId'])
|| !isInteger(category['categoryQuantity'])
|| !isFloat(category['categoryBuyPrice'])
|| !isFloat(category['categorySellPrice'])
) { valid = false; }
}
console.log(category);
console.log(valid);
if(!valid) return valid;
global.categories[index] = category;
});
if(valid){
$('#importCategories').val(JSON.stringify(global.categories));
var importCategories = $('#importCategories').val(),
importDiscount = ($('#billPercentage').prop('checked')) ? $('#importDiscount').val() : 0,
importSupplier = $('#importSupplier').val(),
importOrder = $('#importOrder').val(),
importDate = $('#importDate').val(),
formAction = global.baseUrl + $(this).attr('action');
$.ajax({
type: 'POST',
dataType: 'json',
url: formAction,
async: false,
data: { importCategories: importCategories,
importDiscount: importDiscount,
importSupplier: importSupplier,
importOrder: importOrder,
importDate: importDate },
success: function(json) {
if(json.errors){
$.each(json.errors, function(field, msg){
$('#'+field).after('<ul class="errors"><li>'+msg.isEmpty+'</li></ul>');
});
} else {
$(window).unbind('beforeunload');
window.location.replace(json.redirectUrl);
}
}
});
} else {
$('.table-category').after('<ul class="errors"><li>يجب ملئ كل الحقول </li></ul>');
}
});
$('#importDiscount-label, #importDiscount-element').hide();
$('#importDiscount').prop('disabled', true);
$('#billPercentage').click(function () {
if(this.checked){
$('.col-buy-price').hide();
$('#importDiscount-label, #importDiscount-element').show();
$('input[name="buyPrice"]').prop('disabled', true);
$('#importDiscount').prop('disabled', false);
}else{
$('.col-buy-price').show();
$('#importDiscount-label, #importDiscount-element').hide();
$('input[name="buyPrice"]').prop('disabled', false);
$('#importDiscount').prop('disabled', true);
}
});
$('.number').attr('type', 'number')
.on('keyup', function(){
$(this).removeClass('errors');
var value = $(this).val();
if( $(this).hasClass('float') )
if( !isFloat(value) ) $(this).addClass('errors');
else
if( !isInteger(value) ) $(this).addClass('errors');
});
function isInteger(value) { return /^\d+$/.test(value); }
function isFloat(value) { return /^\d+(\.\d*){0,1}$/.test(value); }
function isPositive(value){ return (value >= 0); }
});
|
import { createLocalVue, shallowMount } from "@vue/test-utils";
import LoginForm from "@/components/LoginForm";
import Vuex from "vuex";
import { createStore } from "../../helpers";
const localVue = createLocalVue();
localVue.use(Vuex);
describe("LoginForm component", () => {
const defaultStoreOptions = {
state: {
loginErrors: []
},
actions: {
login: jest.fn()
}
};
it("Should render correctly", () => {
const wrapper = shallowMount(LoginForm, {
localVue,
store: createStore(defaultStoreOptions),
stubs: ["router-link"]
});
expect(wrapper.html()).toMatchSnapshot();
});
it("Should render any login errors", () => {
const wrapper = shallowMount(LoginForm, {
localVue,
store: createStore(defaultStoreOptions, {
state: {
loginErrors: ["Invalid password"]
}
}),
stubs: ["router-link"]
});
expect(wrapper.html()).toMatchSnapshot();
});
it("Should log user in", async () => {
const expectedEmail = "test@user.com";
const expectedPassword = "myPassword123";
const $router = {
push: jest.fn()
};
defaultStoreOptions.actions.login.mockImplementation(async () => true);
const wrapper = shallowMount(LoginForm, {
localVue,
store: createStore(defaultStoreOptions),
mocks: {
$router
},
stubs: ["router-link"]
});
const inputs = wrapper.findAll("input[type=text]");
inputs.at(0).setValue(expectedEmail);
inputs.at(1).setValue(expectedPassword);
wrapper.find("form").trigger("submit");
await wrapper.vm.$nextTick();
expect(defaultStoreOptions.actions.login).toHaveBeenCalledWith(
expect.anything(),
{
email: expectedEmail,
password: expectedPassword
}
);
expect($router.push).toHaveBeenCalledWith("/");
});
});
|
module.exports = function() {
'use strict';
var People = {
names: [
'Justin',
'Matt',
'Ashur'
],
titles: [
'Graphic Designer',
'Web Developer',
'Photographer and Video'
],
bios: [
'Makes Pretty Graphics',
'Not sure what he is doing',
'Does everything '
]
};
return People;
};
|
/**
* 应付月账单首页
*/
import { connect } from 'react-redux';
import OrderPage from '../../../components/OrderPage';
import helper, {fetchJson, getObject, postOption, showError, swapItems} from '../../../common/common';
import {toFormValue,hasSign} from '../../../common/check';
import {Action} from '../../../action-reducer/action';
import {getPathValue} from '../../../action-reducer/helper';
import {search2} from '../../../common/search';
import showModeDialog from '../../../components/ModeOutput/showModeOutputDialog';
import showFilterSortDialog from "../../../common/filtersSort";
const TAB_KEY = 'index';
const STATE_PATH = ['payMonthlyBill'];
const URL_LIST = '/api/bill/pay_monthly_bill/list';//查询列表
const URL_ONE = '/api/bill/pay_monthly_bill/one';//根据ID获取单条数据
const URL_DELETE = '/api/bill/pay_monthly_bill/delete';
const URL_SEND = '/api/bill/pay_monthly_bill/send';
const URL_CHECK = '/api/bill/pay_monthly_bill/check';
const URL_REVOKE = '/api/bill/pay_monthly_bill/cancel';
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH)[TAB_KEY];
};
// 页面的初始状态
const buildPageState = (tabs, tabKey, title, look=false,value={}) => {
return {
activeKey: tabKey,
tabs: tabs.concat({key: tabKey, title: title}),
[tabKey]: {look,tabKey,value,updateTable},
};
};
//刷新表格
const updateTable = async (dispatch, getState) => {
const {currentPage, pageSize, searchDataBak={},tabKey} = getSelfState(getState());
return search2(dispatch, action, URL_LIST, currentPage, pageSize, toFormValue(searchDataBak),{},tabKey);
};
//新增
const addActionCreator = (dispatch,getState) => {
const {tabs} = getPathValue(getState(), STATE_PATH);
const tabKey = 'add';
const title = '新增';
if(helper.isTabExist(tabs,tabKey)){
dispatch(action.assign({activeKey:tabKey}));
return
}
dispatch(action.assign(buildPageState (tabs, tabKey,title,false,{})));
};
//编辑
const editActionCreator = async(dispatch,getState) => {
const state = getSelfState(getState());
const {tabs} = getPathValue(getState(), STATE_PATH);
const items = state.tableItems.filter(item => item.checked);
if (items.length !== 1) {
helper.showError('请勾选一条记录');
}else {
const tabKey = 'edit_'+items[0].billNumber;
const id = items[0].id;
if(helper.isTabExist(tabs,tabKey)){
dispatch(action.assign({activeKey:tabKey}));
return
}
const json = await helper.fetchJson(`${URL_ONE}/${id}`);
if(json.returnCode !==0 ){
helper.showError(json.returnMsg);
return
}
dispatch(action.assign(buildPageState (tabs, tabKey,items[0].billNumber,false,json.result)));
}
};
//输出
const outputActionCreator = (dispatch,getState) => {
showModeDialog('receivable_month_bill',[])
};
const resetActionCreator = (dispatch,getState) =>{
const {tabKey} = getSelfState(getState());
dispatch( action.assign({searchData: {}},tabKey) );
};
const searchClickActionCreator = async (dispatch, getState) => {
const {pageSize, searchData,tabKey} = getSelfState(getState());
const newState = {searchDataBak: searchData, currentPage: 1};
return search2(dispatch, action, URL_LIST, 1, pageSize, toFormValue(searchData), newState,tabKey);
};
const sortActionCreator = async (dispatch, getState) => {
const {filters} = getSelfState(getState());
const newFilters = await showFilterSortDialog(filters, 'pay_month_bill_sort');
newFilters && dispatch(action.assign({filters: newFilters}, TAB_KEY));
};
const deleteActionCreator = async (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const idList = tableItems.reduce((result, item) => {
item.checked && item.statusType === 'status_draft' && result.push(item.id);
return result;
}, []);
if (idList.length === tableItems.filter(item => item.checked).length) {
const {returnCode, returnMsg} = await fetchJson(URL_DELETE, postOption(idList));
return returnCode === 0 ? updateTable(dispatch, getState) : showError(returnMsg);
}else {
return showError('请选择草稿状态的记录!');
}
};
const sendActionCreator = async (dispatch, getState) =>{
const {tableItems} = getSelfState(getState());
const idList = tableItems.reduce((result, item) => {
item.checked && (item.statusType === 'status_draft' || item.statusType === 'status_fall_back_completed') && result.push(item.id);
return result;
}, []);
if (idList.length === tableItems.filter(item => item.checked).length) {
const {returnCode, returnMsg} = await fetchJson(URL_SEND, postOption(idList));
return returnCode === 0 ? updateTable(dispatch, getState) : showError(returnMsg);
}else {
return showError('请选择草稿或已回退状态的记录!');
}
};
const reconciliationActionCreator = async (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const idList = tableItems.reduce((result, item) => {
item.checked && item.statusType !== 'status_completed' && result.push(item.id);
return result;
}, []);
if (idList.length === tableItems.filter(item => item.checked).length) {
const {returnCode, returnMsg} = await fetchJson(URL_CHECK, postOption(idList));
return returnCode === 0 ? updateTable(dispatch, getState) : showError(returnMsg);
}else {
return showError('包含已完成状态的记录!');
}
};
const cancelActionCreator = async (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const idList = tableItems.reduce((result, item) => {
item.checked && item.statusType === 'status_completed' && result.push(item.id);
return result;
}, []);
if (idList.length === tableItems.filter(item => item.checked).length) {
const {returnCode, returnMsg} = await fetchJson(URL_REVOKE, postOption(idList));
return returnCode === 0 ? updateTable(dispatch, getState) : showError(returnMsg);
}else {
return showError('请选择已完成状态的记录!');
}
};
const toolbarActions = {
sort: sortActionCreator,
search: searchClickActionCreator,
reset: resetActionCreator,
add:addActionCreator,
edit:editActionCreator,
output:outputActionCreator,
del: deleteActionCreator,
send: sendActionCreator,
check: reconciliationActionCreator,
revoke: cancelActionCreator
};
const clickActionCreator = (key) => {
if (toolbarActions.hasOwnProperty(key)) {
return toolbarActions[key];
} else {
console.log('unknown key:', key);
return {type: 'unknown'};
}
};
const onLinkActionCreator = (key, rowIndex, item) => async (dispatch,getState) => {
const {tabs} = getPathValue(getState(), STATE_PATH);
const tabKey = 'edit_'+item.billNumber;
const id = item.id;
if(helper.isTabExist(tabs,tabKey)){
dispatch(action.assign({activeKey:tabKey}));
return
}
const json = await helper.fetchJson(`${URL_ONE}/${id}`);
if(json.returnCode !==0 ){
helper.showError(json.returnMsg);
return
}
dispatch(action.assign(buildPageState (tabs, tabKey,item.billNumber,true,json.result)));
};
const changeActionCreator = (key, value) => (dispatch,getState) =>{
const {tabKey} = getSelfState(getState());
dispatch(action.assign({[key]: value}, [tabKey,'searchData']));
};
const formSearchActionCreator = (key, title,keyControl) => async (dispatch, getState) => {
const {filters,tabKey} = getSelfState(getState());
const json = await helper.fuzzySearchEx(title,keyControl);
if (!json.returnCode) {
const index = filters.findIndex(item => item.key == key);
dispatch(action.update({options:json.result}, [tabKey,'filters'], index));
}else {
helper.showError(json.returnMsg)
}
};
const checkActionCreator = (isAll, checked, rowIndex) => (dispatch, getState) =>{
const {tabKey} = getSelfState(getState());
isAll && (rowIndex = -1);
dispatch(action.update({checked}, [tabKey,'tableItems'], rowIndex));
};
const swapActionCreator = (key1, key2) => (dispatch,getState) => {
const {tableCols} = getSelfState(getState());
dispatch(action.assign({tableCols: swapItems(tableCols, key1, key2)}));
};
const pageNumberActionCreator = (currentPage) => (dispatch, getState) => {
const {pageSize, searchDataBak={},tabKey} = getSelfState(getState());
const newState = {currentPage};
return search2(dispatch, action, URL_LIST, currentPage, pageSize, toFormValue(searchDataBak), newState,tabKey);
};
const pageSizeActionCreator = (pageSize, currentPage) => async (dispatch, getState) => {
const {searchDataBak={},tabKey} = getSelfState(getState());
const newState = {pageSize, currentPage};
return search2(dispatch, action, URL_LIST, currentPage, pageSize, toFormValue(searchDataBak), newState,tabKey);
};
const doubleClickActionCreator = (rowIndex) => async(dispatch, getState) => {
const state = getSelfState(getState());
const {tabs} = getPathValue(getState(), STATE_PATH);
if (!hasSign('pay_monthly_bill', 'edit')) return;
const items = state.tableItems[rowIndex];
const tabKey = 'edit_'+items.billNumber;
const id = items.id;
if(helper.isTabExist(tabs,tabKey)){
dispatch(action.assign({activeKey:tabKey}));
return
}
const json = await helper.fetchJson(`${URL_ONE}/${id}`);
if(json.returnCode !==0 ){
helper.showError(json.returnMsg);
return
}
dispatch(action.assign(buildPageState (tabs, tabKey,items.billNumber,false,json.result)));
};
const mapStateToProps = (state) => {
return getObject(getSelfState(state), OrderPage.PROPS);
};
const actionCreators = {
onClick: clickActionCreator,
onChange: changeActionCreator,
onCheck: checkActionCreator,
onSwapCol: swapActionCreator,
onPageNumberChange: pageNumberActionCreator,
onPageSizeChange: pageSizeActionCreator,
onSearch: formSearchActionCreator,
onLink: onLinkActionCreator,
onDoubleClick: doubleClickActionCreator,
};
const Container = connect(mapStateToProps, actionCreators)(OrderPage);
export default Container;
export {updateTable,buildPageState};
|
/**
* Meetings access and update.
*/
var db = require('./database'); // database connection and collection cursors
var utilityDao = require('./utility.js');
var config = db.config;
var log = config.log;
var util = config.utility;
var hash = require(util+'hash.js');
var ObjectID = require('mongodb').ObjectID; // MongoDB System Generated Object ID
var thisModule = 'dao/meetings.js';
log.debug('initializing',thisModule);
var readFields = {date:1, description:1, voteList:1, voteId: 1} ;
var updateFields = [
{header: 'Date (required)', name: 'date', type: 'date', editable: true, listClass:'txt-center', headerClass:'txt-center', required: true},
{header: 'Description (required)', name: 'description', type: 'text', editable: true, listClass:'txt-left', headerClass:'txt-left', required: true}
];
// Get meeting for a given user and meeting id
exports.getMeeting = function(userId,meetingId, callback){
log.debug('getting meeting',thisModule);
userId = utilityDao.parseObjectId(userId);
meetingId = utilityDao.parseObjectId(meetingId);
var query = {_id: meetingId, userId: userId};
var options = {fields : readFields};
db.meetings.findOne(query,options,callback);
};
// Add a new meeting
exports.addMeeting = function(userId,data,callback){
log.debug('add meeting',thisModule);
// default fields for a new document
var newDocument = {
createDate: new Date(),
userId: utilityDao.parseObjectId(userId),
voteList: []
};
var errorMessage = utilityDao.buildDocument(newDocument,data,updateFields);
if (errorMessage) return callback(null,errorMessage,null);
// Generate the semi-unique meeting number - voteId
utilityDao.getMeetingNumber(newDocument.date, 10, undefined, function(err,voteId){
if (err) return callback(null,err,null);
newDocument.voteId = voteId;
// insert the meeting
db.meetings.insert(newDocument,function(err){
callback(err,null,data);
});
})
};
exports.updateMeeting = function(userId,meetingId,data,callback){
// todo: if date changes, verify that the code is still unique within a 60 day window
var result = utilityDao.buildUpdateParams(data,updateFields);
if (result.errors.length > 0) return callback(null, result.errors[0],0);
if (!result.dataUpdated) return callback(null, 'no data updated', 0);
var query = {
_id: utilityDao.parseObjectId(meetingId),
userId: utilityDao.parseObjectId(userId)
};
var date = result.updateParams['$set'].date;
// if date changes, set the the voteId to either the existing or a new number
if (date){
utilityDao.getMeetingNumber(date, 10, query._id, function(err,voteId){
if (err) return callback(null,err,null);
result.updateParams['$set'].voteId = voteId;
// update the meeting
db.meetings.update(query,result.updateParams, function(err, count){
callback(err, null, count);
})
})
}
else {
db.meetings.update(query,result.updateParams, function(err, count){
callback(err, null, count);
})
}
};
// Read a list of meetings
exports.getMeetingPage = function(userId,meetingType,callback){
log.debug('get meeting page type '+meetingType,thisModule);
var query = {userId: utilityDao.parseObjectId(userId)};
var options = {limit: 30, sort: ['date','_id']};
// past = more than two days in past
var pastDate = new Date();
pastDate.setDate(pastDate.getDate()-2);
// future = more than one day in future
var futureDate = new Date();
futureDate.setDate(futureDate.getDate()+1);
if (meetingType === 'future'){
options.limit = 60;
query.date = {'$gte':futureDate};
}
else if (meetingType === 'past'){
options.sort = [['date','desc'],['_id','desc']];
query.date = {'$lte':pastDate};
}
else {
query['$and'] = [{date: {'$gte':pastDate}},{date: {'$lte': futureDate}}]
}
db.meetings.find(query,readFields,options).toArray( function(err, data) {
callback(err,data);
});
};
exports.removeMeeting = function(userId,meetingId,callback){
log.debug('remove meeting',thisModule);
var query = {
_id: utilityDao.parseObjectId(meetingId),
userId: utilityDao.parseObjectId(userId)
};
db.meetings.remove(query,{w:1},callback);
};
// Download all meetings, ordered by Date
exports.getDownload = function(userId,callback){
log.debug('getting user downloads',thisModule);
var query = {userId: utilityDao.parseObjectId(userId)};
var options = {sort: ['date','_id'], limit: 60};
db.meetings.find(query,readFields,options).toArray( function(err, data) {
callback(err,data);
});
};
// Get meeting vote item id
exports.getMeetingByVoteId = function(voteId, callback){
log.debug('getting meeting for voteId '+voteId,thisModule);
var query = {voteId: utilityDao.parseInteger(voteId)};
var options = {fields : {date: 1, description: 1, voteId: 1}};
// make sure meeting date is within a certain range
buildDateQuery(new Date(),query);
db.meetings.findOne(query,options,callback);
};
// Add a vote to a meeting
exports.addMeetingVote = function(voteId,vote,callback){
log.debug('add vote to meeting',thisModule);
var query = {voteId: utilityDao.parseInteger(voteId)};
// make sure meeting date is within a certain range
buildDateQuery(new Date(),query);
// build update parms
var itemId = new ObjectID();
var voteItem = {
value: utilityDao.parseInteger(vote),
itemId: itemId};
var updateParams = {'$push': {voteList:voteItem}}
// update meeting
db.meetings.update(query,updateParams, function(err, count){
callback(err, null, count, voteItem);
})
};
var buildDateQuery = function(date,dateQuery){
// past = more than two days in past
var pastDate = new Date(date.getTime());
pastDate.setDate(pastDate.getDate()-2);
// future = more than one day in future
var futureDate = new Date(date.getTime());
futureDate.setDate(futureDate.getDate()+1);
dateQuery['$and'] = [{date: {'$gte':pastDate}},{date: {'$lte': futureDate}}]
};
|
const Users = require('../models/Users');
const getAll = async () => Users.getAll();
const newUser = async (name, email, password) => {
const userList = await Users.getAll();
const isUnique = userList.find(result => result.user.email === email);
if (isUnique) {
return { 'message': 'Email already registered' };
};
const addUser = await Users.newUser(name, email, password);
return addUser;
};
const findById = async (email) => Users.findById(id);
const login = async (email, password) => {
const login = await Users.login(email, password);
if (!login) return { message: 'Incorrect username or password' };
return login;
};
module.exports = {
getAll,
newUser,
findById,
login,
};
|
export default {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || ''
}
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: ['~/assets/css/tailwind.css', '~/assets/css/page-transitions.css'],
/*
** Plugins to load before mounting the App
*/
// CUSTOM: I create an env variable so that I can make a baseURL for my axios calls, see more: https://nuxtjs.org/api/configuration-env/
env: {
apiBaseUrl:
process.env.BASE_URL || 'https://intelistyle-task-api.herokuapp.com/api/'
},
plugins: [],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
'@nuxtjs/pwa'
],
/*
** Build configuration
*/
buildDir: 'nuxt',
build: {
postcss: {
plugins: {
tailwindcss: './tailwind.config.js'
}
},
// publicPath: '/assets/',
extractCSS: true,
babel: {
presets: ({ isServer }) => [
[
'@nuxt/babel-preset-app',
{
targets: isServer ? { node: '8.11.1' } : { browsers: ['defaults'] }
}
]
]
},
extend(config, ctx) {
if (ctx.isDev && ctx.isClient) {
}
}
}
}
|
import React, { PureComponent } from 'react';
import { View, StyleSheet, Text, Platform } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
import colors from '@config/colors';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { FONT_FAMILY } from '@config/typography';
const ios = Platform.OS == 'ios' ? true : false;
class PickerCustom extends PureComponent {
state = {
value: this.props.defaultValue ? this.props.defaultValue : '',
error: '',
};
componentDidMount() {
if (this.props.onRef) this.props.onRef(this);
}
componentWillUnmount() {
if (this.props.onRef) this.props.onRef(undefined);
}
render() {
let { containerStyle, header, required, data } = this.props;
return (
<View style={[styles.resTr, containerStyle]}>
{header ? (
<Text style={styles.headerStyle}>
{header}
{required && <Text style={styles.required}> *</Text>}
</Text>
) : null}
<View style={styles.containerInput}>
<RNPickerSelect
style={pickerSelectStyles}
onValueChange={value => this.setState({ value: value })}
items={data}
// placeholder={data[0]}
value={this.state.value}
Icon={() => (
<AntDesign
name="caretdown"
color={colors.TextLink}
size={10}
style={{ marginTop: 14, marginRight: 10 }}
/>
)}
/>
</View>
</View>
);
}
setValue = value => {
try {
if (!value) {
this.showError('');
}
this.setState({ value });
} catch (error) {}
};
getValue = () => this.state.value.trim();
}
const pickerSelectStyles = StyleSheet.create({
inputIOS: {
paddingVertical: 12,
paddingHorizontal: 10,
color: colors.ColorBody,
fontFamily: FONT_FAMILY.REGULAR,
fontSize: 15,
height: 40,
paddingRight: 30, // to ensure the text is never behind the icon
},
inputAndroid: {
paddingVertical: 8,
color: colors.ColorBody,
fontFamily: FONT_FAMILY.REGULAR,
fontSize: 15,
height: 40,
paddingRight: 30, // to ensure the text is never behind the icon
},
});
const styles = StyleSheet.create({
headerStyle: {
fontSize: 11,
fontFamily: ios ? FONT_FAMILY.LIGHT : FONT_FAMILY.REGULAR,
color: colors.ColorBody,
fontStyle: 'normal',
fontWeight: 'normal',
marginBottom: 4,
},
resTr: {},
containerInput: {
flex: 1,
height: 40,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 4,
borderWidth: 0.5,
borderColor: colors.border,
},
required: {
color: colors.red,
fontSize: 11,
fontFamily: FONT_FAMILY.REGULAR,
},
});
export default PickerCustom;
|
import React from 'react'
import { useDrag } from 'react-dnd'
/**
* Render draggable box
*
* @param {Object} data
*
* @return {*}
* @constructor
*/
export const Box = ({ data }) => {
const [, drag] = useDrag({ item: data })
return (
<div ref={drag} className="box">
{data.title}
</div>
)
}
|
module.exports =
{
"topic": "主题",
"topic_id": "主题 ID",
"topic_id_placeholder": "输入主题 ID",
"no_topics_found": "没有找到主题!",
"no_posts_found": "没有找到帖子!",
"post_is_deleted": "此回复已被删除!",
"topic_is_deleted": "此主题已被删除!",
"profile": "资料",
"posted_by": "%1 发布",
"posted_by_guest": "游客发布",
"chat": "聊天",
"notify_me": "此主题有新回复时通知我",
"quote": "引用",
"reply": "回复",
"replies_to_this_post": "回复 %1",
"last_reply_time": "最后回复",
"reply-as-topic": "在新帖中回复",
"guest-login-reply": "登录后回复",
"edit": "编辑",
"delete": "删除",
"purge": "清除",
"restore": "恢复",
"move": "移动",
"fork": "分割",
"link": "链接",
"share": "分享",
"tools": "工具",
"locked": "已锁定",
"pinned": "已固定",
"moved": "已移动",
"bookmark_instructions": "点击阅读本主题帖中的最新回复",
"flag_title": "举报此帖",
"deleted_message": "此主题已被删除。只有拥有主题管理权限的用户可以查看。",
"following_topic.message": "当有人回复此主题时,您会收到通知。",
"not_following_topic.message": "您将在未读主题列表中看到这个主题,但您不会在帖子被回复时收到通知。",
"ignoring_topic.message": "您将不会在未读主题列表里看到这个主题,但在被提到以及帖子被顶时仍将收到通知。",
"login_to_subscribe": "请注册或登录后,再订阅此主题。",
"markAsUnreadForAll.success": "将全部主题标为未读。",
"mark_unread": "标记为未读",
"mark_unread.success": "主题已被标记为未读。",
"watch": "关注",
"unwatch": "取消关注",
"watch.title": "当此主题有新回复时,通知我",
"unwatch.title": "取消关注此主题",
"share_this_post": "分享",
"watching": "关注中",
"not-watching": "未关注",
"ignoring": "忽略中",
"watching.description": "有新回复时通知我。<br/>在未读主题中显示。",
"not-watching.description": "不要在有新回复时通知我。<br/>如果这个版块未被忽略则在未读主题中显示。",
"ignoring.description": "不要在有新回复时通知我。<br/>不要在未读主题中显示该主题。",
"thread_tools.title": "主题工具",
"thread_tools.markAsUnreadForAll": "标记全部未读",
"thread_tools.pin": "置顶主题",
"thread_tools.unpin": "取消置顶主题",
"thread_tools.lock": "锁定主题",
"thread_tools.unlock": "解锁主题",
"thread_tools.move": "移动主题",
"thread_tools.move_all": "移动全部",
"thread_tools.fork": "分割主题",
"thread_tools.delete": "删除主题",
"thread_tools.delete-posts": "删除这些帖子",
"thread_tools.delete_confirm": "确定要删除此主题吗?",
"thread_tools.restore": "恢复主题",
"thread_tools.restore_confirm": "确定要恢复此主题吗?",
"thread_tools.purge": "清除主题",
"thread_tools.purge_confirm": "确认清除此主题吗?",
"topic_move_success": "此主题已成功移到 %1",
"post_delete_confirm": "确定删除此帖吗?",
"post_restore_confirm": "确定恢复此帖吗?",
"post_purge_confirm": "确认清除此回帖吗?",
"load_categories": "正在载入版块",
"disabled_categories_note": "停用的版块为灰色",
"confirm_move": "移动",
"confirm_fork": "分割",
"bookmark": "书签",
"bookmarks": "书签",
"bookmarks.has_no_bookmarks": "您还没有添加任何书签",
"loading_more_posts": "正在加载更多帖子",
"move_topic": "移动主题",
"move_topics": "移动主题",
"move_post": "移动帖子",
"post_moved": "帖子已移走!",
"fork_topic": "分割主题",
"topic_will_be_moved_to": "此主题将被移动到版块",
"fork_topic_instruction": "点击将分割的帖子",
"fork_no_pids": "未选中帖子!",
"fork_pid_count": "选择了 %1 个帖子",
"fork_success": "成功分割主题! 点这里跳转到分割后的主题。",
"delete_posts_instruction": "点击想要删除/永久删除的帖子",
"composer.title_placeholder": "在此输入您主题的标题...",
"composer.handle_placeholder": "姓名",
"composer.discard": "撤销",
"composer.submit": "提交",
"composer.replying_to": "正在回复 %1",
"composer.new_topic": "新主题",
"composer.uploading": "正在上传...",
"composer.thumb_url_label": "粘贴主题缩略图网址",
"composer.thumb_title": "给此主题添加缩略图",
"composer.thumb_url_placeholder": "http://example.com/thumb.png",
"composer.thumb_file_label": "或上传文件",
"composer.thumb_remove": "清除字段",
"composer.drag_and_drop_images": "拖拽图片到此处",
"more_users_and_guests": "%1 名会员和 %2 名游客",
"more_users": "%1 名会员",
"more_guests": "%1 名游客",
"users_and_others": "%1 和 %2 其他人",
"sort_by": "排序",
"oldest_to_newest": "从旧到新",
"newest_to_oldest": "从新到旧",
"most_votes": "最多投票",
"most_posts": "最多回复",
"stale.title": "接受建议,创建新主题?",
"stale.warning": "您回复的主题已经非常老了。开个新帖,然后在新帖中引用这个老帖的内容,可以吗?",
"stale.create": "创建新主题",
"stale.reply_anyway": "仍然回复此帖",
"link_back": "回复: [%1](%2)"
}
|
const { authenticate } = require('../utils/authentification')
const articles = require('./articles')
const auth = require('./auth')
const users = require('./users')
const comments = require('./comments')
module.exports = {
Comment: {
author: ({ authorId }) => users.get({ id: authorId }),
article: ({ articleId }) => articles.get({ id: articleId }),
},
Article: {
author: ({ authorId }) => users.get({ id: authorId }),
comments: ({ id }) => comments.list({ articleId: id }),
},
User: {
articles: ({ id }) => articles.list({ authorId: id }),
comments: ({ id }) => comments.list({ authorId: id }),
},
Query: {
user: (_, args) => users.get(args),
articles: () => articles.list(),
article: (_, args) => articles.get(args),
comments: () => comments.list(),
comment: (_, args) => comments.get(args),
},
Mutation: {
login: (_, { loginInput }) => auth.login(loginInput),
register: (_, { registerInput }) => users.create(registerInput),
createArticle: (_, { createArticleInput }, context) => authenticate(context, () => articles.create({ authorId: context.user.id, ...createArticleInput })),
}
}
|
import h from '@kuba/h'
import Input, { Label, Supporting } from '@kuba/input'
function component () {
return (
<Input id='newPassword' type='password' name='newPassword'>
<Label>New password</Label>
<Supporting>Your new password must be more than 8 characters</Supporting>
</Input>
)
}
export default component
|
import React from "react";
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
const Live = () => {
return (
<div>
{/* <div class="fh5co-loader"></div> */}
<div id="page">
<Navbar />
<header id="fh5co-header" class="fh5co-cover fh5co-cover-sm" role="banner" style={{backgroundImage:`url(assets/images/img_bg_1.jpg)`}}>
<div class="overlay"></div>
<div class="fh5co-container">
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center">
<div class="display-t">
<div class="display-tc animate-box" data-animate-effect="fadeIn">
<h1>Live</h1>
<h2>belumpi jadi bosku</h2>
</div>
</div>
</div>
</div>
</div>
</header>
<div id="fh5co-couple" class="fh5co-section-gray">
<div class="container">
<div class="row">
<div class="col-md-6 col-md-push-6 animate-box">
<h3>Live Video</h3>
<div class="fh5co-video fh5co-bg" style={{backgroundImage:`url(assets/images/img_bg_3.jpg)`}}>
<a href="https://vimeo.com/channels/staffpicks/93951774" class="popup-vimeo"><i class="icon-video2"></i></a>
<div class="overlay"></div>
</div>
</div>
<div class="col-md-5 col-md-pull-5 animate-box">
<div class="fh5co-contact-info">
<h3>Live Chat</h3>
<form action="#">
<div class="row form-group">
<div class="col-md-12">
<label for="message">Message</label>
<textarea name="message" id="message" cols="30" rows="10" class="form-control" placeholder="Write us something"></textarea>
</div>
</div>
<div class="form-group">
<input type="submit" value="Send Message" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{/* <div id="map" class="fh5co-map"></div>
<!-- END map --> */}
<Footer />
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up"></i></a>
</div>
</div>
);
};
export default Live;
|
export default {
contentPadding: {
minHeight: '100%',
padding: 20
}
}
|
import React from 'react'
import {plainText, ulList, images} from '../store/db'
function About() {
const List = () => {
return (
<> {
ulList[0].listOne.map((list,key)=>{
return(
<li key={key}><i className="ion-android-checkmark-circle"></i>
{list}</li>
)
})
} </>
);
}
return (
<section id="about" className="section-bg">
<div className="container-fluid">
<div className="section-header">
<h3 className="section-title">About Us</h3>
<span className="section-divider"></span>
<p className="section-description">
{plainText[0]}<br/>{plainText[1]}
</p>
</div>
<div className="row">
<div className="col-lg-6 about-img wow fadeInLeft">
<img src={images[0]} alt="" />
</div>
<div className="col-lg-6 content wow fadeInRight">
<h2>{plainText[3]}</h2>
<h3>{plainText[4]}</h3>
<p> {plainText[5]} </p>
<ul>
<List />
</ul>
<p>{plainText[6]} </p>
</div>
</div>
</div>
</section>
)
}
export default About
|
var defaultMatch = 5;
var player1 = document.querySelector("#p1");
var player2 = document.querySelector("#p2");
var reset = document.querySelector("#reset");
var p1display = document.querySelector("#p1score")
var p2display = document.querySelector("#p2score")
var winscore = document.querySelector("#winscore")
var p1score = 0;
var p2score = 0;
var game = document.querySelector("input")
game.valueAsNumber = defaultMatch
winscore.textContent = defaultMatch
player1.addEventListener("click", function() {
if (p1display.textContent < game.valueAsNumber && p2display.textContent < game.valueAsNumber) {
p1score++;
p1display.textContent = p1score;
if (p1display.textContent == game.valueAsNumber) {
p1display.style.color = "green"
} else {
p1display.style.color = "black"
}
}})
player2.addEventListener("click", function() {
if (p2display.textContent < game.valueAsNumber && p1display.textContent < game.valueAsNumber) {
p2score++;
p2display.textContent = p2score;
if (p2display.textContent == game.valueAsNumber) {
p2display.style.color = "green";
} else {
p2display.style.color = "black"
}
}})
reset.addEventListener("click", function() {
p1display.textContent = 0;
p1score = 0;
p2display.textContent = 0;
p2score = 0;
})
game.addEventListener("change", function() {
winscore.textContent = game.valueAsNumber;
})
|
const config = require('../config.json')
module.exports = function (bot, guild) {
console.log(`Guild "${guild.name}" (Users: ${guild.members.size}) has been added.`)
if (!config.logging.discordChannelLog) return
const logChannelId = config.logging.discordChannelLog
const logChannel = bot.channels.get(logChannelId)
if (typeof logChannelId !== 'string' || !logChannel) {
if (bot.shard) {
bot.shard.broadcastEval(`
const channel = this.channels.get('${logChannelId}');
if (channel) {
channel.send('Guild Info: "${guild.name}" has been added.\\nUsers: ${guild.members.size}').catch(err => console.log('Could not log guild addition to Discord, ', err.message || err));
true;
}
`).then(results => {
for (var x in results) if (results[x]) return
console.log(`Error: Could not log guild addition to Discord, invalid channel ID.`)
}).catch(err => console.log(`Guild Info: Error: Could not broadcast eval log channel send for guildCreate. `, err.message || err))
} else console.log(`Error: Could not log guild addition to Discord, invalid channel ID.`)
} else logChannel.send(`Guild Info: "${guild.name}" has been added.\nUsers: ${guild.members.size}`).catch(err => console.log(`Could not log guild addition to Discord. `, err.message || err))
}
|
const { Item } = require("../models");
const ItemRepository = {
save: (item) => {
return Item.create(item);
},
findAll: (filters) => {
return Item.find(filters).lean();
},
update: (id, values) => {
return Item.updateOne({ _id: id }, values);
},
delete: (id) => {
return Item.findByIdAndDelete(id);
},
findById: (id) => {
return Item.findById(id).lean();
},
}
module.exports = ItemRepository;
|
import React, {Component} from 'react';
import {
StyleSheet,
TouchableOpacity,
Image
} from 'react-native';
import PropTypes from 'prop-types';
import { scale } from '../styles/variables';
export default class BackBtn extends Component {
render() {
const { onPress, green = false } = this.props;
return (
<TouchableOpacity
activeOpacity={0.8}
style={styles.back}
onPress={()=> onPress()}
>
<Image
style={{width: scale(25), height: scale(25)} }
resizeMode='contain'
fadeDuration={0}
source={require('../../assets/img/arrow_white.png')}
/>
</TouchableOpacity>
);
}
}
BackBtn.propTypes = {
onPress: PropTypes.func.isRequired,
green: PropTypes.bool
}
const styles = StyleSheet.create({
back: {
width: scale(25),
height: scale(25)
}
});
|
import {
GET_USER,
GET_CURRENT_USER,
ADD_ITEM_TO_CART,
REMOVE_ITEM_FROM_CART
} from "../actions/types";
const initialState = {
currentUser: null,
user: null,
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_USER:
return {
...state,
user: action.payload,
loading: false
};
case GET_CURRENT_USER:
return {
...state,
currentUser: action.payload,
loading: false
};
case ADD_ITEM_TO_CART:
return {
...state,
cart: [action.payload, ...state.user.currentUser.cart]
};
case REMOVE_ITEM_FROM_CART:
return {
...state,
cart: state.user.currentUser.cart.filter(
item => item._id !== action.payload
)
};
default:
return state;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.