text
stringlengths
7
3.69M
const TacoModel = require('../models/TacoModel'); const tacoModel = new TacoModel(); function validateTacos(req, res, next) { const { body } = req; const invalidTacosIds = []; const tacoIds = Object.keys(body); if (!tacoIds.length) { return next(); } tacoIds.forEach((tacoId) => { const taco = tacoModel.getById(tacoId); if (!taco) { // taco id doesn't exist invalidTacosIds.push(tacoId); } }); if (invalidTacosIds.length > 0) { const invalidTacosList = invalidTacosIds.join(', '); return res.status(400).send({ message: `Invalid tacoIds: [ ${invalidTacosList} ]`, }); } // tacos list is valid return next(); } module.exports = validateTacos;
const name = document.getElementById("name"); const lastName1 = document.getElementById("lastName1"); const lastName2 = document.getElementById("lastName2"); const birthday = document.getElementById("birthday"); const newRFC = document.getElementById("newRFC"); // Arreglos // 0 1 2 const x = ["México", "El Salvador", "Costa Rica"]; console.log(x[0]); function getRFC() { // Gerardo Medina Romero // MERG950719 console.log(name.value); console.log(lastName1.value); console.log(lastName2.value); console.log(birthday.value); let RFC = lastName1.value[0] + lastName1.value[1]; RFC = RFC + lastName2.value[0]; RFC += name.value[0]; // "1995-07-19" RFC += birthday.value[2] + birthday.value[3] + birthday.value[5] + birthday.value[6] + birthday.value[8] + birthday.value[9]; // let RFC = lastName1.value[0] + lastName1.value[1] + lastName2.value[0] + name.value[0] + birthday.value[2] + birthday.value[3] + birthday.value[5] + birthday.value[6] + birthday.value[8] + birthday.value[9]; RFC = RFC.toUpperCase(); console.log(RFC); newRFC.innerHTML = "Tu RFC es: " + RFC; }
import React from 'react' import { AppRegistry } from 'react-native' import ReactNativeTodo from './components/ReactNativeTodo' AppRegistry.registerComponent('ReactNativeTodo', () => ReactNativeTodo)
'use strict'; function main() { const claimInner = document.getElementsByClassName('claim-inner'); const topBanner = document.getElementById('top-banner'); window.setTimeout(() => { claimInner[0].classList.add('s2') topBanner.classList.add('bgPink'); }, 2000); window.setTimeout(() => { claimInner[0].classList.add('s3') }, 4000); window.setTimeout(() => { claimInner[0].classList.add('s4') }, 6000); const button = document.getElementById('button'); button.addEventListener('click', () => { scroll(0, 1000) }); } window.addEventListener('load', main);
import { renderComponent , expect } from '../test_helper'; import App from '../../src/components/app'; describe('App' , () => { let component; beforeEach(() => { component = renderComponent(App); }); it('shows a header', () => { expect(component.find('.navbar')).to.exist; }); describe('signing in and clicking resources', () => { beforeEach(() => { component.find('.auth-button').simulate('click', null); component.find('.resources-link').simulate('click', null); }); it('shows a list of resources to users who are signed in', () => { expect(component.find('.resources-link')).to.exist; expect(component).to.contain('Home'); expect(component).to.contain('Sign Out'); ///////////////////////////////////////////////// // the expect statements below are both failing// ///////////////////////////////////////////////// expect(component).to.contain('Super Special Recipe'); expect(component.find('.recipe-list')).to.exist; }); }); // ends describe signing in and clicking resources }); // ends describe app
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("file:src/resources/Features/search.feature"); formatter.feature({ "name": "This feature file contains search verification", "description": "", "keyword": "Feature" }); formatter.scenario({ "name": "User should see This field is required message", "description": "", "keyword": "Scenario", "tags": [ { "name": "@run" } ] }); formatter.step({ "name": "User is on Google page", "keyword": "Given " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "User search for \"Ducks\"", "keyword": "When " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "User gets a proper result for required result", "keyword": "Then " }); formatter.match({}); formatter.result({ "status": "undefined" }); });
// Provide resolver functions for your schema fields const resolvers = { Query: { getAllUsers: (root, args, { db }, info) => db.users.findMany(), getUser: (root, args, { db }, info) => db.findByPk(args.id), }, Mutation: { createUser: (root, { firstname, lastname }, { db }, info) => db.create({ firstname: firstname, lastname: lastname, }), updateUser: (root, args, { db }, info) => db.update({ firstname: args.firstname, lastname: args.lastname }, { where: { id: args.id } }), deleteUser: (root, args, { db }, info) => db.destroy({ where: { id: args.id } }) } }; module.exports = resolvers;
import { expect } from 'chai'; import { shallowMount } from '@vue/test-utils'; import HomePage from '@/views/Home.vue'; describe('Home.vue', () => { it('renders Home page text', () => { const wrapper = shallowMount(HomePage, {/* propsData: { msg }, */}); expect(wrapper.text()).to.include('PheGET'); }); });
(function () { 'use strict'; angular.module('MyApp').controller('DashboardController', DashboardController).constant('PromotionSchema', { type: 'object', properties: { id: { type: 'string', title: 'Promotion Id' }, product_id: { type: 'string', title: 'Product Id' }, catid: { type: 'string', title: 'Category' }, brandId: { type: 'string', title: 'Brand' }, discount: { type: 'string', title: 'Discount' }, originalPrice: { type: 'string', title: 'Original Price' }, discountText: { type: 'string', title: 'Discount Text' }, locationId: { type: 'string', title: 'Location' }, description: { type: 'string', title: 'Description' } } }); DashboardController.$inject = ['UserService', '$rootScope','$scope','$location','FlashService','$uibModal', '$log','$localStorage','uiGridConstants']; function DashboardController(UserService, $rootScope,$scope,$location,FlashService,$uibModal, $log,$localStorage,uiGridConstants) { var vm = this; /*vm.allPromotions = [];*/ vm.merchantPromotions= []; vm.allCategories = []; vm.allBrands = []; vm.brands = []; vm.merchantProducts = []; vm.merchantLocations= []; vm.merchantBeacons = []; vm.beaconPromotionList = []; vm.mainBeaconPromotion = []; vm.bpid = []; vm.merchantPromotion = merchantPromotion; vm.showBeaconActionForm = showBeaconActionForm; vm.updateP = vm.updateP; /* vm.activeClass='promotions'; vm.getActiveClass =getActiveClass; vm.isActive = isActive; function getActiveClass(activeClass) { return vm.activeClass = activeClass; } function isActive(activeClass) { return vm.activeClass === activeClass; }*/ /* vm.allUsers = []; vm.deleteUser = deleteUser;*/ initController(); function initController() { loadCurrentUser(); loadMerchantPromotions(); loadMerchantProducts(); loadMerchantLocations(); loadAllBrands(); loadAllCategories(); /*loadAllUsers();*/ } /* function loadCurrentUser() { UserService.GetByUsername($rootScope.globals.currentUser.username) .then(function (merchant) { vm.merchant = merchant; console.log($rootScope.globals.currentUser.username); }); }*/ function loadCurrentUser() { /*console.log($rootScope.globals.currentUser.id);*/ /* UserService.GetMerchantInfo() .then(function (res) { vm.merchant = res; console.log(vm.merchant ); });*/ } function loadMerchantPromotions() { vm.merchatid={ "id":$rootScope.globals.currentUser.id }; console.log(vm.merchatid); UserService.GetMerchantPromotions(vm.merchatid) .then(function (promotions) { vm.gridPromotions.data = promotions.data; console.log(vm.gridPromotions.data); /*UserService.GetMerchantBeacons(vm.merchatid) .then(function (beacons) { vm.merchantBeacons= beacons.data; vm.beaconPromotionlistObject = []; for (var i=0; i < vm.merchantBeacons.length; i++){ vm.beaconObject= { "beaconUID":vm.merchantBeacons[i].beaconUid, "beaconMinorValue":vm.merchantBeacons[i].beaconMinorValue, "beaconMajorValue":vm.merchantBeacons[i].beaconMajorValue } vm.beaconPromotionlistObject.push(vm.beaconObject); } console.log("out"); console.log(vm.beaconPromotionlistObject); UserService.GetMerchantBeaconsPromotions(vm.beaconPromotionlistObject) .then(function (beaconPromotion) { vm.beaconPromotionList = beaconPromotion.data; console.log(vm.beaconPromotionList); console.log("Beacon Pro"); for(var i=0; i<vm.beaconPromotionList.length;i++){ console.log(vm.beaconPromotionList[i].promotionDtos); console.log("pushing"); vm.mainBeaconPromotion.push(vm.beaconPromotionList[i].promotionDtos); } console.log('After pushed'); console.log(vm.mainBeaconPromotion); for(var i=0; i<vm.mainBeaconPromotion.length;i++){ for(var j=0; j<vm.mainBeaconPromotion[i].length;j++){ for(var k=0;k < vm.merchantPromotions.length;k++){ if(vm.mainBeaconPromotion[i][j].id == vm.merchantPromotions[k].id){ console.log(vm.mainBeaconPromotion[i][j].id); console.log(vm.merchantPromotions[k].id); vm.bpid.push(vm.mainBeaconPromotion[i][j].id); } } } } console.log(' b ids') console.log(vm.bpid); }); });*/ }); }/*end loadMerchantPromotions*/ vm.gridPromotions = { enableFiltering: false, enableSorting: true, /*showGridFooter: true,*/ enableGridMenu: true, paginationPageSizes: [10, 20], paginationPageSize: 10, onRegisterApi: function(gridApi){ vm.gridApi = gridApi; vm.gridApi.grid.registerRowsProcessor( vm.singleFilter, 200 ); }, columnDefs: [ /*{ field: 'id', sort: { direction: uiGridConstants.ASC, priority: 2 } },*/ { field: 'brandName', suppressRemoveSort: true,cellTooltip: function( row, col ) { return 'Double click to edit: ' + row.entity.brandName; }, headerTooltip: function( col ) { return col.displayName; } }, { field: 'categoryName',cellTooltip: function( row, col ) { return 'Double click to edit: ' + row.entity.categoryName; }, headerTooltip: function( col ) { return col.displayName; }, sort: { direction: uiGridConstants.DESC, priority: 1 } }, { field: 'discount',type: 'number'}, { field: 'discountText', enableSorting: false }, { field: 'locationName' }, { field: 'originalPrice',type: 'number' }, { field: 'startdate',type: 'date' }, { field: 'enddate',type: 'date' }, { name:'Actions', cellTemplate :'views/partials/edit-promotion-button.html' } ] }; vm.filter = function() { vm.gridApi.grid.refresh(); }; vm.singleFilter = function( renderableRows ){ var matcher = new RegExp(vm.filterValue); renderableRows.forEach( function( row ) { var match = false; [ 'brandName', 'categoryName', 'discount','discountText','locationName','originalPrice' ].forEach(function( field ){ if ( row.entity[field].match(matcher) ){ match = true; } }); if ( !match ){ row.visible = false; } }); return renderableRows; }; function loadMerchantProducts() { vm.merchatid={ "merchantId":$rootScope.globals.currentUser.id }; console.log(vm.merchatid); UserService.GetMerchantProducts(vm.merchatid) .then(function (products) { console.log(products.data); vm.merchantProducts = products.data[0].merchantProducts; console.log(vm.merchantProducts); }); } vm.showMe = function(grid,row){ console.log(grid); console.log(row.entity); var modalInstance = $uibModal.open({ templateUrl: 'views/partials/edit-merchant-promotion.html', controller: 'EditMerchantPromotionCtrl', controllerAs: 'vm', resolve: { grid: function () { return grid; }, row: function () { return row; } } }); modalInstance.result.then(function (selectedItem) { vm.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; vm.deletePromotion = function(grid,row){ console.log(grid); console.log(row.entity); vm.promotionId=row.entity.id; UserService.DeletePromotion(vm.promotionId).then(function (response) { if (response.success) { /*FlashService.Success('Promotion Posted successful', true);*/ /*row.entity = angular.extend(row.entity);*/ loadMerchantPromotions(); console.log(response); $uibModalInstance.close('closed'); } else { FlashService.Error(response.message); console.log('errorrrr') $uibModalInstance.close('closed'); vm.dataLoading = false; } }); } function loadMerchantLocations() { UserService.GetLocations() .then(function (locations) { vm.merchantLocations = locations.data; /*console.log(locations.data);*/ }); }/*end loadMerchantLocations method*/ function loadAllCategories() { UserService.GetCategories() .then(function (categories) { vm.allCategories = categories.data; console.log(vm.allCategories); }); } function loadAllBrands() { UserService.GetBrands() .then(function (res) { vm.allBrands = res.data; console.log(vm.allBrands); /*for (var i = 0; i < vm.allBrands.length; i++) { console.log(vm.allBrands[i].brands[i]); }*/ }); } vm.populateDemands = function(catid){ vm.brands = vm.allBrands[catid-1].brands; }; function merchantPromotion(){ vm.dataLoading = true; console.log(vm.promotion); console.log($rootScope.globals.currentUser.id); var headers = { 'Content-Type':'application/json', 'Access-Control-Allow-Origin':'*' }; vm.addPromotion = { "merchatid":$rootScope.globals.currentUser.id, "product_id":vm.promotion.product_id, "description":vm.promotion.description, "product_image":vm.promotion.product_image, "originalPrice":vm.promotion.originalPrice, "discount":vm.promotion.discount, "locationId":vm.promotion.location_id, "catid":vm.promotion.catid, "brandId":vm.promotion.brandId, "discountText":vm.promotion.discountText }; console.log('after add merchant promotion'); console.log(vm.addPromotion); UserService.CreatePromotion(vm.addPromotion).then(function (response) { if (response.success) { /*FlashService.Success('Promotion Posted successful', true);*/ loadMerchantPromotions(); vm.resetPromotionForm(); $location.path('dashboard/promotions'); } else { FlashService.Error(response.message); console.log('errorrrr') vm.dataLoading = false; } }); } vm.resetPromotionForm = function(){ vm.promotion.product_id=''; vm.promotion.description=''; vm.promotion.product_image=''; vm.promotion.originalPrice=''; vm.promotion.discount=''; vm.promotion.location=''; vm.promotion.catid=''; vm.promotion.brandId=''; } function showBeaconActionForm(promotionid,e){ vm.message = "Show beacon Form Button Clicked"; console.log(vm.message); console.log(promotionid); var elem = e.target; console.log("Elemtnt promotion"); console.log(elem); var modalInstance = $uibModal.open({ templateUrl: 'views/partials/addBeacons-to-promotion.html', controller: 'AddBeaconToPromotionCtrl', controllerAs: 'vm', resolve: { promotion_id: promotionid, elem:elem } }); modalInstance.result.then(function (selectedItem) { vm.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); } } })();
// @ts-nocheck import React, { Component } from "react"; import { ContainerWrapper } from "./Components/styles"; import { Form, Field } from "./Components"; class Container extends Component { render() { return ( <ContainerWrapper> <Form /> <Field /> </ContainerWrapper> ); } } export default Container;
import { map } from "../map/map" import { reduce } from "../reduce/reduce" import { type } from "../type/type" /** * Creates a new instance of the object with same properties than original. * Will not inherit prototype, only own enumerable properties. * * @param {Any} source Source input value * * @returns {Any} New instance of source * * @name clone * @tag Core * @signature (source: Any): Any * * @see {@link deepEqual} * * @example * let x = {a: [1]} * * clone(x) * // => {a: [1]} * * close(x) === x * // => false */ export const clone = source => { const sourceType = type(source) if (sourceType === "Array") { return map(clone, source) } if (sourceType === "Object") { return reduce( (acc, [key, elm]) => { acc[key] = clone(elm) return acc }, {}, Object.entries(source) ) } if (sourceType === "Date") { return new Date(source.getTime()) } if (sourceType === "RegExp") { return new RegExp(sourceType.toString()) } return source }
import React from 'react' import './Options.css' import { Dropdown } from 'react-bootstrap' import { NavLink, Link } from 'react-router-dom' const Options = () => { const active = { color: 'blue' } return ( <div> <NavLink className='link' activeStyle={active} to='/create' > Add Account </NavLink> <NavLink className='link' activeStyle={active} to='/balance' > Search Balances </NavLink> <NavLink className='link' activeStyle={active} to='/transaction' > Make a Transaction </NavLink> </div> ) } export default Options
import React from 'react'; import {connect} from 'react-redux'; import * as ACTIONS from '../actions'; class Header extends React.Component { render() { return ( <div className="jumbotron"> <h1 className="display-4">The hero initial</h1> <p className="lead">Select hero from right menu, to see the initial!</p> <hr className="my-1"/> <button onClick={this.props.loadData} key="o">Load</button> <button onClick={this.props.editPerson} key="e">Edit</button> <button onClick={this.props.listPerson} key="l">List</button> </div> ); } } const mapActionToProps = (dispatch) => { return { loadData: () => { dispatch({type: ACTIONS.ACTIONS_FETCH_PEOPLE}) }, editPerson: () => { dispatch({type: "PAGE_SET", page: 'edit_person'}); }, listPerson: () => { dispatch({type: "PAGE_SET", page: 'list_person'}); } } } const mapStateToProps = () => { return {} } export default connect(mapStateToProps, mapActionToProps)(Header);
const {StyledDialogActions} = require("./DialogAction.style"); const DialogActions = function (props) { return <StyledDialogActions {...props}>{props.children}</StyledDialogActions>; }; export default DialogActions;
//注意:如果修改 penName 和 title,记得前往 docs/index 里第 4 行修改,尽量统一 // 首页左上角 | 文章右上角的名字 const penName = "不器"; // 首页左上角的描述,衔接 penName const title = "小窝"; // 文章右上角点击名字的跳转链接 const link = "https://xingcxb.github.io/"; // 底部的 | 后的描述 const footerTitle = "小窝"; // 头像图片 const avatar = "https://cdn.staticaly.com/gh/xingcxb/blog_img@blog1/blog/basic/Avatar.png"; // 头像下的昵称 const name = "不器"; // 头像下的签名 const slogan = "知行合一"; module.exports = { penName, title, link, footerTitle, avatar, name, slogan, };
import React, { Component, Fragment } from 'react' import Input from '../components/input' import Axios from 'axios' import { ToastContainer, toast } from 'react-toastify' import { browserHistory } from 'react-router' import 'react-toastify/dist/ReactToastify.css' import BlockUi from 'react-block-ui'; import 'react-block-ui/style.css'; const initialState = { email: "", senha: "", blocking: false } class Login extends Component { constructor(props) { super(props); this.toggleBlocking = this.toggleBlocking.bind(this); this.state = initialState; } toggleBlocking() { this.setState({ blocking: !this.state.blocking }); } toastMessage(mensagem, type) { toast[type](mensagem, { position: toast.POSITION.BOTTOM_RIGHT }) } envia(e) { e.preventDefault(); this.toggleBlocking() Axios.post('https://minhas-series-api.herokuapp.com/auth', { username: this.state.email, password: this.state.senha }).then(ress => { console.log('ress', ress) if (ress.data.success) { const token = ress.data.token; localStorage.setItem('token', token) browserHistory.push('/dashboard') this.toggleBlocking() } else { this.toastMessage('Login ou senha incorretos!', 'error') this.toggleBlocking() } }).catch(error => console.log(error)) console.log(this.state) } handleChange(e) { const form = { ...this.state } const { name, value } = e.target; form[name] = value; this.setState(form) } render() { return ( <BlockUi tag="div" blocking={this.state.blocking}> <div className="page-holder d-flex align-items-center"> <div className="container"> <div className="row align-items-center py-5"> <div className="col-5 col-lg-7 mx-auto mb-5 mb-lg-0"> <div className="pr-lg-5"><img src="img/series-muito-longas.jpg" alt="" className="img-fluid shadow-img" /></div> {/* illustration.svg */} </div> <div className="col-lg-5 px-lg-4"> <h1 className="text-base text-primary text-uppercase mb-4">Minas Séries Dashboard</h1> <h2 className="mb-4">Bem-Vindo!</h2> <p className="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore.</p> <form id="loginForm" action="index.html" className="mt-4"> <Input type="text" name="email" onChange={e => this.handleChange(e)} label="Username or Email address" placeholder="Username or Email address" value={this.state.email} /> <Input type="password" name="senha" onChange={e => this.handleChange(e)} label="Password" placeholder="Password" value={this.state.senha} /> <button type="button" disabled={this.state.blocking} onClick={e => this.envia(e)} className="btn btn-primary shadow px-5">Log in</button> </form> </div> </div> <p className="mt-5 mb-0 text-gray-400 text-center">Design by <a href="https://bootstrapious.com/admin-templates" className="external text-gray-400">Bootstrapious</a> & Your company</p> </div> </div> <ToastContainer /> </BlockUi> ); } } export default Login;
var main = function () { var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // 垂直視野角, 縦横比, var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var geometry = new THREE.CubeGeometry(1, 1, 1); var material = new THREE.MeshBasicMaterial({color: 0x00ff00}); var material02 = new THREE.MeshBasicMaterial({color: 0x00ffff}); var cube = new THREE.Mesh(geometry, material); var cube02 = new THREE.Mesh(geometry, material02); cube.position.set(1, 1, 6); cube02.position.set(-1, -1, 1); scene.add(cube); scene.add(cube02); camera.position.z = 5; // helper var axis = new THREE.AxisHelper(1000); axis.position.set(0, 0, 0); scene.add(axis); // control var controls = new THREE.OrbitControls(camera, renderer.domElement); var render = function () { requestAnimationFrame(render); cube.rotation.x += 0.1; cube.rotation.y += 0.1; cube.rotation.z += 0.1; cube02.rotation.x += 0.1; cube02.rotation.y += 0.1; renderer.render(scene, camera); controls.update(); }; render(); }; window.addEventListener('DOMContentLoaded', main, false);
var vt = vt || {}; function unicodeToUtf8(str) { var out, i, len, c; out = ""; len = str.length; for (i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0) && (c <= 0x7F)) { out += str.charAt(i); } else if ((c >= 0x80) && (c <= 0x7FF)) { out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1F)); out += String.fromCharCode(0x80 | (c & 0x3F)); } else if ((c >= 0x800) && (c <= 0xFFFF)) { out += String.fromCharCode(0xe0 | ((c >> 12) & 0xF)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | (c & 0x3F)); } else if ((c >= 0x10000) && (c <= 0x1FFFFF)) { out += String.fromCharCode(0xF0 | ((c >> 18) & 0x7)); out += String.fromCharCode(0x80 | ((c >> 12) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | (c & 0x3F)); } else if ((c >= 0x200000) && (c <= 0x3FFFFFF)) { out += String.fromCharCode(0xF8 | ((c >> 24) & 0x3)); out += String.fromCharCode(0x80 | ((c >> 18) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 12) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | (c & 0x3F)); } else if ((c >= 0x4000000) && (c <= 0x7FFFFFFF)) { out += String.fromCharCode(0xFC | ((c >> 30) & 0x1)); out += String.fromCharCode(0x80 | ((c >> 24) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 18) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 12) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | (c & 0x3F)); } } return out; } function unicodeToUtf8ForJsb(str) { var out, i, len, c; var pos = 0; len = str.length; out = new Uint8Array(len * 6); for (i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0) && (c <= 0x7F)) { out[pos++] = str.charCodeAt(i); } else if ((c >= 0x80) && (c <= 0x7FF)) { out[pos++] = (0xc0 | ((c >> 6) & 0x1F)); out[pos++] = (0x80 | (c & 0x3F)); } else if ((c >= 0x800) && (c <= 0xFFFF)) { out[pos++] = (0xe0 | ((c >> 12) & 0xF)); out[pos++] = (0x80 | ((c >> 6) & 0x3F)); out[pos++] = (0x80 | (c & 0x3F)); } else if ((c >= 0x10000) && (c <= 0x1FFFFF)) { out[pos++] = (0xF0 | ((c >> 18) & 0x7)); out[pos++] = (0x80 | ((c >> 12) & 0x3F)); out[pos++] = (0x80 | ((c >> 6) & 0x3F)); out[pos++] = (0x80 | (c & 0x3F)); } else if ((c >= 0x200000) && (c <= 0x3FFFFFF)) { out[pos++] = (0xF8 | ((c >> 24) & 0x3)); out[pos++] = (0x80 | ((c >> 18) & 0x3F)); out[pos++] = (0x80 | ((c >> 12) & 0x3F)); out[pos++] = (0x80 | ((c >> 6) & 0x3F)); out[pos++] = (0x80 | (c & 0x3F)); } else if ((c >= 0x4000000) && (c <= 0x7FFFFFFF)) { out[pos++] = (0xFC | ((c >> 30) & 0x1)); out[pos++] = (0x80 | ((c >> 24) & 0x3F)); out[pos++] = (0x80 | ((c >> 18) & 0x3F)); out[pos++] = (0x80 | ((c >> 12) & 0x3F)); out[pos++] = (0x80 | ((c >> 6) & 0x3F)); out[pos++] = (0x80 | (c & 0x3F)); } } var rtn = new Uint8Array(pos); for (i = 0; i < pos ; i++) { rtn[i] = out[i]; } return rtn; } var isType = function (obj, type) { return (type === "Null" && obj === null) || (type === "Undefined" && obj === void 0) || (type === "Number" && isFinite(obj)) || Object.prototype.toString.call(obj).slice(8, -1) === type; }; function filterFunc(o) { var d = null; if (isType(o, "Object")) { d = {}; } else if (isType(o, "Array")) { d = []; } else { return; } var k; for (k in o) { if (isType(o[k], "Object")/* && !o[k].isFiltered*/) { //o[k].isFiltered = true; d[k] = filterFunc(o[k]); } else if (o[k] == null || typeof (o[k]) == 'undefined') { continue; } else if (isType(o[k], 'Function')) { continue; } else if (isType(o[k], "Array")) { d[k] = filterFunc(o[k]); } else { d[k] = o[k]; } } return d; } /** * 消息管理器,负责跟服务器收发消息包 * @class * @extends vt.Class */ vt.SyncNetManager = cc.Class.extend(/** @lends vt.SyncNetManager# */{ m_netMsgDispatcher: null, m_xhr: null, ctor: function () { this.m_syncManager = vt.SyncManager.getInstance(); this.m_netMsgDispatcher = vt.NetMsgDispatcher.getInstance(); }, connect: function (addr, port) { }, onOpen: function (event) { }, /** * 获取HttpRequest对象 */ getXMLHttpRequest: function () { return XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); }, /** * 发送消息回调函数 */ onMessage: function () { var _this = vt.s_pNetManager; try { if(m_xhr.readyState == 4) { if(m_xhr.status == 200) { var packet = JSON.parse(m_xhr.response); if(packet){ var _index = packet.msgList.shift(); _this.m_netMsgDispatcher.handleMessage(_index, packet); } // 收到最终逻辑处理包, 超时转圈可以消失,设置的回调也可以调用了 var uuid = vt.NetManager.getInstance().getCurrentMsgId(); _this.m_syncManager.stopWaitAndDoCallback(uuid, packet); } else { _this.onError("Net Status Error, Status = " + m_xhr.status); } } }catch (e){ cc.log("SyncNetManager onMessage Error:" + e.toString()); } }, /** * 网络错误 */ onError: function (err) { vt.Log("SyncNetManager onError:" + err); }, /** * 发送消息到服务器 * @param msgType [大消息Id] * @param msgId [小消息Id] * @param data [消息体] */ sendMsg: function (msgList, data) { var that = this; m_xhr = that.getXMLHttpRequest(); m_xhr.open("POST", "http://" + SERVERIP + ":" + SERVERPORT+"/ClientMsg", true); if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { // IE-specific logic here m_xhr.setRequestHeader("Accept-Charset", "utf-8"); m_xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded'); } else { if (m_xhr.overrideMimeType) { m_xhr.overrideMimeType("text\/plain; charset=utf-8"); } m_xhr.setRequestHeader("Content-Type", 'application/x-www-form-urlencoded'); } var request = { "msgList": msgList, "uuid": data.uuid, "result":data.result }; m_xhr.onreadystatechange = that.onMessage; m_xhr.send("request="+JSON.stringify(request)); }, onOpen: function (event) { //vt.Log("<<<<<--------------<<<< 链接服务器成功! >>>>>>>>>---------->>>>>>>>>"); }, onError: function (event) { //cc.Assert(0, "<<<<<<<<<<<<<<<<< Net Error --- 连接服务器出错! >>>>>>>>>>>>>>>>>>"); }, onClose: function (event) { //vt.Log("<<<<<--------------<<<< Net Close 服务器关闭或未开启>>>>>>>>>---------->>>>>>>>>"); }, connectServer: function () { } }); vt.SyncNetManager.getInstance = function () { if (!vt.s_pSyncNetManager) { vt.s_pSyncNetManager = new vt.SyncNetManager(); } return vt.s_pSyncNetManager; };
import React from 'react' //Styling and Animation import styled from 'styled-components'; import {motion} from 'framer-motion'; //REDUX import {useDispatch, useSelector} from 'react-redux'; import {loadDetail} from '../actions/detailAction'; import {Link} from 'react-router-dom'; function Topscorer({name, image, age, team, goals, assist}) { const {isLoading} = useSelector((state) => state.detail) return ( <> {isLoading && (<StyledTop> <div className="card"> <h4>{name == "L. Messi" ? name = name + " (Scamssi)" : name }</h4> <img src={image} alt={name}/> <p>Age: {age}</p> <p>Team: {team}</p> <p>Goals: {goals}</p> <p>Assists: {assist}</p> </div> </StyledTop>)} </> ) }; const StyledTop = styled(motion.div)` color: white; .card{ transition: all .8s; height: 100%; box-shadow: 0px 5px 20px rgba(0,0,0,0.2); text-align: center; border-radius: 1rem; margin-right: 1rem; padding: 2rem 1rem; background: white; /* position: absolute; */ top: 0; left: 0; width: 30rem; backface-visibility: hidden; transition: all .8s ease; display: flex; flex-direction: column; align-items: center; color: black; h4 { font-size: 1.5rem; font-weight: 700; } p { padding-top: .7rem; } img{ width: 70%; height: 80%; object-fit: contain; border: solid 3px #25203a; border-radius: 1000000px; transition: transform 450ms; } } ` export default Topscorer
var mongoose = require('mongoose'); //schema to our book details var bookSchema = mongoose.Schema({ vegetableId: {type: String}, qty: {type: String}, name: {type: String}, email: {type: String}, address: {type: String}, phoneNumber: {type: Number}, }); module.exports = mongoose.model('book', bookSchema);
import React from 'react'; import {connect} from 'react-redux'; import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import TopBar from './TopBar/TopBar' import LeaseTable from '../LeaseTable' import TenantsList from '../TenantsList' import LeaseInfo from '../LeaseInfo' class AppContainer extends React.Component { render() { return <Container id="main-content" fluid="true"> <TopBar/> <Row> <Col lg="4"> <Row><Col lg="12"><h3>Tenants</h3></Col></Row> <Row><Col lg="12"><TenantsList tenantsList={this.props.tenantsList}/></Col></Row> <Row><Col lg="12"><LeaseInfo leaseInfo={this.props.leaseInfo} /></Col></Row> </Col> <Col lg="8"><LeaseTable leaseList={this.props.leaseList} /></Col> </Row> </Container> } } function mapStateToProps(state) { return { leaseList: state.leaseData, tenantsList :state.tenants, leaseInfo :state.leaseInfo }; } export default connect(mapStateToProps)(AppContainer);
/** * @fileoverview Helpers related to the contacts plugin * @author Gabriel Womble */ import { contacts } from 'e2e/constants'; /** @typedef ContactE2EParam @type {Object} @property {string} name - contact's name @property {string} address - contact's address @property {string} desc - optional contact description */ /** * Function that creates a given contact * @param {Class} page - the puppeteer page class * @param {ContactE2EParam} contact - the contact to be created */ const createContact = (async (page, contact) => { const { name, address, desc = '' } = contact; // Open sidepanel await page.click(contacts.selectors.addBtn.attr); await page.waitForSelector(contacts.selectors.sidepanel.attr); await page.type(contacts.selectors.nameInput.attr, name); await page.type(contacts.selectors.addressInput.attr, address); if (desc) { await page.type(contacts.selectors.descInput.attr, desc); } await page.click(contacts.selectors.sidepanelBtn.attr); }); export { createContact };
//Open mobile nav if ($(window).width() <= 760) { $(function() { $('.header-menu-part-opener, .header-menu-part-closer, .main-menu a').on('click', function(){ $('.header-menu-part').toggleClass('header-menu-part-active'); $('body').toggleClass('no-scroll-nav'); }); }); } // Open prices modal $(function() { $('.home-prices-list-two .home-prices-list-header, .home-prices-modal-closer').on('click', function(){ $('.home-prices-modal-2').toggleClass('home-prices-modal-2-show'); $('.home-prices-lists-top').toggleClass('home-prices-lists-top-noline'); $(this).toggleClass('home-prices-list-header-active'); if ($(window).width() <= 1024) { $('body').toggleClass('no-scroll'); } }); }); // Form var form; form = function() { return $('.input-wrapper input').focus(function() { return $(this).closest('.input-wrapper').addClass('focused has-value'); }).focusout(function() { return $(this).closest('.input-wrapper').removeClass('focused'); }).blur(function() { if (!this.value) { $(this).closest('.input-wrapper').removeClass('has-value'); } return $(this).closest('.input-wrapper').removeClass('focused'); }); }; $(function() { return form(); }); // Interested $(function() { $('.js-intrested').each(function() { var $accordion = $(this); $(".js-intrested-top", $accordion).click(function(e) { e.preventDefault(); $div = $(".js-intrested-list", $accordion); $div.slideToggle(200); $(".js-intrested-list").not($div).slideUp(200); $div.parent(".js-intrested").toggleClass('js-intrested-active').siblings().removeClass('js-intrested-active'); return false; }); }); }); // Smooth scroll $(document).on('click', 'a.smooth-scroll[href^="#"]', function(e) { var id = $(this).attr('href'); var $id = $(id); if ($id.length === 0) { return; } e.preventDefault(); var pos = $(id).offset().top - 72; $('body, html').animate({scrollTop: pos}); }); // Nav on scroll var fixTop = $('header').offset().top + 1; $(window).scroll(function() { var currentScroll = $(window).scrollTop(); if (currentScroll >= fixTop) { $('header').addClass('current-scroll'); } else { $('header').removeClass('current-scroll'); } }); // Active nav item $(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $(this).removeClass('current-menu-item'); }) $(this).addClass('current-menu-item'); var target = this.hash, menu = target; $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top - 72 }, 500, 'swing', function () { window.location.hash = target; $(document).on("scroll", onScroll); }); }); }); // Add active class on scroll function onScroll(event){ var scrollPos = $(document).scrollTop(); $('.main-menu a').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top - 200 <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { $('.main-menu a').removeClass("current-menu-item"); currLink.addClass("current-menu-item"); } else{ currLink.removeClass("current-menu-item"); } }); }
import React, { useState, useEffect } from "react"; import { toast } from "react-toastify"; import { db } from "../firebase"; const LinkForm = (props) => { const initialStateValues = { url: '', name: '', description: '' } const [values, setValues] = useState(initialStateValues); const handleInputChange = e => { const {name, value} = e.target; setValues({...values, [name]:value}) } const handleSubmit = e => { e.preventDefault(); props.addOrEditLink(values); //limpiando los campos del formulario una vez se envían (también se debe poner el Value a los inputs porque o si no, no se limpiaran) setValues({...initialStateValues}); } //Actualizando datos const getLinkById = async(id) =>{ const doc = await db.collection('links').doc(id).get(); //llenando el formulario con los datos que trae el registro del ID correspondiente setValues({...doc.data()}); } useEffect(()=>{ if(props.currentId === ''){ setValues({...initialStateValues}); }else{ getLinkById(props.currentId); } },[props.currentId]); return ( <form className="card car-body" onSubmit={handleSubmit}> <div className="form-group input-group"> <div className="input-group-text bg-light"><i className="material-icons">insert_link</i></div> <input type="text" name="url" className="form-control" placeholder="https://someurl.com" onChange={handleInputChange} value={values.url} //importante para resetear los campos del form /> </div> <div className="form-group input-group"> <div className="input-group-text bg-light"><i className="material-icons">create</i></div> <input type="text" name="name" className="form-control" placeholder="Website name" onChange={handleInputChange} value={values.name} /> </div> <div className="form-group"> <textarea name="description" rows="10" className="form-control" placeholder="Descripción" onChange = {handleInputChange} value={values.description} ></textarea> </div> <button className="btn btn-primary btn-block"> {props.currentId === '' ? 'Guardar' : 'Actualizar' } </button> </form> ); } export default LinkForm;
Webcam.set({ width:350, height:350, image_format:'jpg', jpg_quality:100 }); camera=document.getElementById("camera"); Webcam.attach('#camera'); function click(){ Webcam.snap(function(img){ document.getElementById("result").innerHTML='<img id="captured" src="'+img+'">'; }); } console.log(ml5.version); classifier=ml5.imageClassifier("https://teachablemachine.withgoogle.com/models/zjMARzZNz/model.json",modelLoaded); function modelLoaded(){ console.log("Model is Loaded") } function identify(){ img=document.getElementById("captured"); classifier.classify(img,gotResult) } function gotResult(error,results){ if(error){ console.log(error); } else{ console.log(results); document.getElementById("object").innerHTML=results[0].label document.getElementById("objectAccuracy").innerHTML=results[0].confidence.toFixed(3); } }
import React, { Component } from 'react'; import { Tabs, Tab, Grid, Cell, Card, CardTitle, CardText, CardActions, Button, CardMenu, IconButton } from 'react-mdl'; class Projects extends Component { constructor(props) { super(props); this.state = { activeTab: 0 }; } toggleCategories() { if(this.state.activeTab === 0){ return( <div className="projects-grid"> {/* Projects */} <Card shadow={5} style={{minWidth: '450', margin: 'auto'}}> <CardTitle style={{color: 'white', height: '350px', background: 'url(https://i.postimg.cc/mZnq1VWr/ladda-ned.png) center / cover'}} ></CardTitle> <CardText> Quire is an easy to use lightweight notekeeping app. </CardText> <CardActions border> <Button colored>GitHub</Button> <Button colored>Try it</Button> </CardActions> <CardMenu style={{color: '#fff'}}> </CardMenu> </Card> </div> ) } } render() { return( <div> <Grid> <Cell col={12}> <div className="content">{this.toggleCategories()}</div> </Cell> </Grid> </div> ) } } export default Projects;
const model = require('../models/ferramenta'); module.exports = { create(req, res){ const id = req.headers.authorization; const { descricao, valor_dia } = req.body; model.create(id, descricao, valor_dia, (error)=>{ if(error)return res.json({error}); return res.send('Ferramenta criada'); }); }, list(req, res){ model.list( (error, result)=>{ if(error)return res.json({error}); return res.json(result); }); }, count(req, res){ /*Buscar quantas vezes uma ferramenta já foi alugada*/ const id = req.params.id; model.count(id, (error, result)=>{ if(error)return res.json(error).send(); // return res.json(result[0]); return res.json({ id:result[0].id, descrição: result[0].descricao, "Quantidade de vezes alugada": result[0].count}); }); }, alter(req, res){ const { fields, values } = req.body; const ferramenta_id = req.query.id; const usuario_id = req.headers.authorization; model.findID(ferramenta_id, (error, result)=>{ if(error)return res.json({error}); if(result.length<1)return res.status(404).send('Ferramenta não encontrada');/*Verificar se há resultados*/ if(result[0].id_usuario != usuario_id)return res.status(403).send("Você não tem autorização para alterar essa ferramenta");/*Validar id do usuário*/ model.alter(ferramenta_id, fields, values, (error)=>{ if(error)return res.json({error}); return res.send('Dados alterados'); }); }); }, delete(req, res){ const ferramenta_id = req.query.id; const usuario_id = req.headers.authorization; model.findID(ferramenta_id, (error, result)=>{/*Busca pelo ID da ferramenta*/ if(error)return res.json({error}); /*Verificar se há resultados*/ if(result.length<1)return res.status(404).send('Ferramenta não encontrada'); /*Validar id do usuário*/ if(result[0].id_usuario != usuario_id)return res.status(403).send("Você não tem autorização para deletar essa ferramenta"); /*Deletar ferramenta*/ model.delete(ferramenta_id, (error)=>{ if(error)return res.json({error}); return res.send(`Ferramenta com id = ${usuario_id} deletada`); }); }); } }
export const listData = data => ({ type: "USERLIST", data })
import React from "react"; import { NavLink } from "react-router-dom"; import styled from "styled-components"; import { Colors } from "../Global/Color"; import { slideDown } from "../Global/keyframesAnimation"; export const NavBar = () => { return ( <Wrapper> <Li> <Link to="/homepage">Home</Link> </Li> <Li> <Link to="/projects">Projects</Link> </Li> <Li> <Link to="/skillset">Skillset</Link> </Li> <Li> <Link to="/resume">Resume</Link> </Li> </Wrapper> ); }; const Wrapper = styled.ul` z-index: 2000; position: absolute; top: -5%; right: 3%; list-style: none; display: flex; transform: translate(0%, -50%); animation: ${slideDown} 0.5s forwards; animation-delay: 2s; @media (max-width: 500px) { left: 44%; transform: translate(-50%, -50%); } `; const Li = styled.div` margin-right: 3vw; position: relative; padding: 10px; width: 8vw; height: 3vw; display: flex; justify-content: center; align-items: center; @media (max-width: 500px) { margin-right: 13px; width: 70px; height: 30px; } &:after, &:before { color: ${Colors.blue}; content: ""; display: block; position: absolute; width: 20%; height: 20%; border: 2px solid; transition: all 0.6s ease; border-radius: 2px; } &:after { bottom: 0; right: 0; border-top-color: transparent; border-left-color: transparent; border-bottom-color: ${Colors.blue}; border-right-color: ${Colors.blue}; } &:before { top: 0; left: 0; border-bottom-color: transparent; border-right-color: transparent; border-top-color: ${Colors.blue}; border-left-color: ${Colors.blue}; } &:hover:after, &:hover:before { width: 100%; height: 100%; } `; const Link = styled(NavLink)` position: relative; z-index: 2; font-weight: bolder; font-size: 1.7vw; text-decoration: none; color: ${Colors.blue}; font-family: "Indie Flower", cursive; @media (max-width: 500px) { font-size: 0.9rem; } `;
import React from 'react' import greenCheckmarkIcon from "../images/icon-checkmark.svg" import invalidIcon from "../images/icon-invalid.svg" const InputStatus = (props) => { const {isValid, isLast} = props return ( <div className={`form-group__input-status${isLast ? " form-group__input-status--last" : ""}`}> <img src={isValid ? greenCheckmarkIcon : invalidIcon} alt={isValid ? "valid" : "invalid"}/> </div> ) } export default InputStatus
(function(){ var http = require('http'); var send = require('send'); var fs = require("fs"); var server = http.createServer(); server.on('request', function(req, res){ send(req, req.url, {root: '/drunken-bear/'}) .on('error', function(err){ serveErrorFile(res, err.status, err.status + '.html'); }) .pipe(res); }); server.listen(30000); console.log('server started on port 30000'); function serveErrorFile(response, statusCode, file) { response.statusCode = statusCode; fs.readFile(file, function(err, data) { if (err) throw err; response.end(data); }); } })();
const axios = require('axios') const apiUrlBase = require('../config.json').apiUrlBase export default { async getOtherStats (officeId) { let response = await axios.get(`${apiUrlBase}/api/otherstats?officeId=${officeId}`) return response.data }, async getRatingStats (officeId) { let response = await axios.get(`${apiUrlBase}/api/ratingstats?officeId=${officeId}`) return response.data }, async getOffices () { let response = await axios.get(`${apiUrlBase}/api/offices`) return response.data }, async addOffice (officeName, officePassword, passwordHint, slackBotUrl) { let response = await axios.post(`${apiUrlBase}/api/offices`, { officeName: officeName, officePassword: officePassword, passwordHint: passwordHint, slackBotUrl: slackBotUrl }) return response.data }, async updateOffice (officeId, newOfficeName, currentPassword, newPassword, passwordHint, newSlackBotUrl) { let response = await axios.post(`${apiUrlBase}/api/offices/${officeId}`, { officeName: newOfficeName, currentPassword: currentPassword, newPassword: newPassword, passwordHint: passwordHint, slackBotUrl: newSlackBotUrl }) return response.data }, async login (officeId, password) { let response = await axios.post(`${apiUrlBase}/login`, { officeId: officeId, password: password }) return response.data }, async getRatingSystems () { let response = await axios.get(`${apiUrlBase}/api/testratingsystem/systems`) return response.data }, async getSampleOutcomes () { let response = await axios.get(`${apiUrlBase}/api/testratingsystem/samples`) return response.data }, async simulateRatingSystem (ratingSystemName, officeId) { let response = await axios.get(`${apiUrlBase}/api/testratingsystem/${ratingSystemName}?officeId=${officeId}`) return response.data } }
import React, { useState, useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { useHistory } from 'react-router-dom'; import LoadingOverlay from 'react-loading-overlay'; import { isEmpty } from 'underscore'; // import Tooltip from '@material-ui/core/Tooltip'; // import DeleteIcon from '@material-ui/icons/DeleteOutlineOutlined'; import { Parser } from 'json2csv'; import { loadActivitiesData} from 'redux/ActivityLogs/operations'; import { useActivitiesSummaryData } from 'redux/ActivityLogs/selectors'; import CustomMaterialTable from '../Table/CustomMaterialTable'; import { formatDateString } from 'utils/dateTime'; // css import 'assets/css/location-registry.css'; // horizontal loader import HorizontalLoader from 'views/components/HorizontalLoader/HorizontalLoader'; const BLANK_SPACE_HOLDER = '-'; const renderCell = (field) => (rowData) => <span>{rowData[field] || BLANK_SPACE_HOLDER}</span>; const ActivitiesTable = () => { const history = useHistory(); const dispatch = useDispatch(); const site_activities = useActivitiesSummaryData(); // for horizontal loader const [loading, setLoading] = useState(false); const [isLoading, setIsLoading] = useState(false); const [delState, setDelState] = useState({ open: false, name: '', id: '' }); const activeNetwork = JSON.parse(localStorage.getItem('activeNetwork')); useEffect(() => { //code to retrieve all site_activities data if (isEmpty(site_activities)) { setIsLoading(true); if (!isEmpty(activeNetwork)) { dispatch(loadActivitiesData(activeNetwork.net_name)); } setIsLoading(false); } }, []); return ( <> {/* custome Horizontal loader indicator */} <HorizontalLoader loading={loading} /> <LoadingOverlay active={isLoading} spinner text="Loading Locations..."> <CustomMaterialTable pointerCursor userPreferencePaginationKey={'site_activities'} title="Site Activities" columns={[ { title: 'Device Name', field: 'device', render: renderCell('device') }, { title: 'Tags', field: 'tags', render: renderCell('tags'), cellStyle: { fontFamily: 'Open Sans' } }, { title: 'Description', field: 'description', render: renderCell('description'), cellStyle: { fontFamily: 'Open Sans' } }, { title: 'Activity Type', field: 'activityType', render: renderCell('activityType'), cellStyle: { fontFamily: 'Open Sans' } }, { title: 'Date', field: 'date', render: renderCell('date'), cellStyle: { fontFamily: 'Open Sans' } } ]} data={site_activities} options={{ search: true, exportButton: true, searchFieldAlignment: 'left', showTitle: false, searchFieldStyle: { fontFamily: 'Open Sans' }, headerStyle: { fontFamily: 'Open Sans', fontSize: 16, fontWeight: 600 }, exportCsv: (columns, data) => { const fields = [ 'device', 'description', 'date', 'activityType', 'site_id', 'nextMaintenance', 'createdAt', 'updatedAt', 'tags' ]; const json2csvParser = new Parser({ fields }); const csv = json2csvParser.parse(data); let filename = `site-activities.csv`; const link = document.createElement('a'); link.setAttribute( 'href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv) ); link.setAttribute('download', filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }} /> </LoadingOverlay> </> ); }; export default ActivitiesTable;
import React from 'react'; import * as _ from 'lodash'; import sh from 'sh-core'; import Validator from './validator'; class ShForm extends React.Component { constructor() { super(); this.state = { status: 'unknown' }; this.validator = new Validator(this); this.onSubmit = this.onSubmit.bind(this); } onSubmit(event) { event.preventDefault(); let valid = this.validator.validate(true); if (valid && this.props.onSubmit) { this.props.onSubmit(); } } generateChildren(children) { return React.Children.map(children, (child) => { if (!child) { return; } if (_.isFunction(child.type)) { if (!_.isUndefined(child.props.validator)) { return React.cloneElement(child, {validator: this.validator}); } else { return child; } } else { if (child.props && !_.isEmpty(child.props.children)) { return React.cloneElement(child, {}, this.generateChildren(child.props.children)); } else { return child; } } }); } render() { let children = this.generateChildren(this.props.children); let classes = { shForm: true, shStatus: this.state.status }; return ( <form className={sh.getClassNames(classes)} onSubmit={this.onSubmit}> {children} </form> ); } } export default ShForm;
ctx.clearRect(0,0,width, height); ctx.save(); ctx.translate(Math.sin(Date.now()*0.001)*100 - 25, 0); ctx.beginPath(); // begin custom shape ctx.moveTo(170, 80); ctx.bezierCurveTo(130, 100, 130, 150, 230, 150); ctx.bezierCurveTo(250, 180, 320, 180, 340, 150); ctx.bezierCurveTo(420, 150, 420, 120, 390, 100); ctx.bezierCurveTo(430, 40, 370, 30, 340, 50); ctx.bezierCurveTo(320, 5, 250, 20, 250, 50); ctx.bezierCurveTo(200, 5, 150, 20, 170, 80); ctx.closePath(); // complete custom shape // create radial gradient var grd = ctx.createRadialGradient(238, 50, 10, 238, 50, 200); grd.addColorStop(0, "#8ED6FF"); // light blue grd.addColorStop(1, "#004CB3"); // dark blue ctx.fillStyle = grd; ctx.fill(); // add stroke ctx.lineWidth = 5; ctx.strokeStyle = "#0000ff"; ctx.stroke(); ctx.restore();
import React, {Component} from 'react'; class EducationOutput extends Component{ render() { return ( <div id="education-output"> <h3 class="text-center border-bottom pb-2e">Education</h3> <h5 class="ml-3 d-inline">{this.props.school}</h5> <div class="ml-5 pt-3 pb-3"> <p class="d-inline">{this.props.degree}</p> <p class="d-inline float-right mr-5">{this.props.gpa}</p> </div> <p class="ml-3">{this.props.achievements.map(items => <li>{items}</li>)}</p> </div> ) } } export default EducationOutput;
import Main from "./Main.js" import Ajax from "./Ajax.js" export default class Cart{ ul constructor(){ Main.instance.checkLogin(); this.init() } init(){ Ajax.ajax("http://10.20.159.170:4002/getShoppingList"); // this.allchecked = document.querySelector("#all") document.addEventListener("getShoppingList",e=>this.renderDom(e)) document.addEventListener("changNums",e=>this.renderDom(e)) document.addEventListener("delShopping",e=>this.renderDom(e)) document.addEventListener("changeChecked",e=>this.renderDom(e)) document.addEventListener("allcheck",e=>this.renderDom(e)) this.ul = document.querySelector(".cart ul") } renderDom(e){ this.ul.innerHTML = `<li> <ul> <li> <input type="checkbox" id="all"><label for="all">全选</label> </li> <li> 商品 </li> <li> 规格 </li> <li> 单价 </li> <li> 数量 </li> <li> 小计 </li> <li> 操作 </li> </ul> </li>` let data = e.data; data.forEach((item,index)=>{ this.ul.innerHTML+=`<li> <ul> <li><input type="checkbox" ${item.checked? "checked":""}> <img src="${item.img}" ></li> <li> ${item.title} </li> <li>${item.size}</li> <li>¥${item.price}</li> <li><span>-</span><input type="text" value="${item.nums}"><span>+</span></li> <li>¥${item.total}</li> <li><span>删除</span></li> </ul> </li>` }); let flag =true data.forEach((item,index)=>{ let input = document.querySelectorAll("input[type='text']")[index] let now = document.querySelectorAll(".cart>ul>li")[index+1] let reduce = now.querySelectorAll("span")[0]; let add = now.querySelectorAll("span")[1]; let del = now.querySelectorAll("span")[2]; reduce.addEventListener("click",e=>this.changeNum(e,input,item)) add.addEventListener("click",e=>this.changeNum(e,input,item)) input.addEventListener("input",e=>this.inputHandler(e,item)); del.addEventListener("click",e=>this.delHandler(e,item)) let check = now.querySelector("input[type='checkbox']"); check.addEventListener("click",e=>this.changeChecked(e,item)) console.log(item.checked) if(!item.checked) flag = false }); // 全选 this.allchecked = document.querySelector("#all"); this.allchecked.addEventListener("click",e=>this.allcheck(e)) if(flag) this.allchecked.setAttribute("checked","checked") } changeNum(e,input,data){ if(e.target.innerText ==="-"){ input.value<2? input.value =1 : input.value-- }else if(e.target.innerText === "+"){ input.value>98? input.value =99 : input.value++ } var o = { id:data.id, size : data.size, nums : parseInt(input.value) } Ajax.ajax("http://10.20.159.170:4002/changNums",o) } inputHandler(e,data){ if(isNaN(e.target.value)) e.target.value = parseInt(e.target.value) e.target.value<1? e.target.value =1 : e.target.value; e.target.value>98? e.target.value =99 : e.target.value; var o = { id:data.id, size : data.size, nums : parseInt(e.target.value) } Ajax.ajax("http://10.20.159.170:4002/changNums",o) } delHandler(e,data){ Ajax.ajax("http://10.20.159.170:4002/delShopping",{id : data.id,size : data.size}) } changeChecked(e,data){ var o = { id:data.id, size : data.size, } Ajax.ajax("http://10.20.159.170:4002/changeChecked",o) } allcheck(e){ Ajax.ajax("http://10.20.159.170:4002/allcheck") } }
import request from '@/utils/request'; /** * 查询所有记录 */ export function queryAllDept() { return request({ url: '/sample/user/queryAllDept' }); };
function functionSubmit() { const question1 = document.quiz.question1.value; const question2 = document.quiz.question2.value; const question3 = document.quiz.question3.value; let correct = 0; if (question1 === "Antwerpen") { correct++; } if (question2 === "Mediterranean Sea") { correct ++; } if (question3 === "90%") { correct++; } document.getElementById("submitted").style.visibility = "visible"; document.getElementById("correctNumber").innerHTML = "You have " + correct + " correct answers. "; }
QUnit.module("Special attribute names",{ beforeEach: function() { /** * clears all mock calls before each test */ $.mockjax.clear(); } }); QUnit.test("should get embedded item resource", function(assert) { var done = assert.async(); $.mockjax({ url: "/", type: "GET", responseText: { "links": { "self": "/" }, "embedded": { "testing": { "links": { "self": "/testing" }, "id": "one!" } } } }); $.hal.$get("/", { linksAttribute: "links", embeddedAttribute: "embedded" }).then(function (resource) { assert.propEqual(resource, {}); resource.$get("testing").then(function (r) { assert.propEqual(r, { "id": "one!" }, "embedded resource should have id property"); done(); }); }); }); QUnit.test("should get linked item resource", function(assert) { var done = assert.async(); $.mockjax({ url: "/", type: "GET", responseText: { "links": { "self": "/", "testing": "/testing" } } }); $.mockjax({ url: "/testing", type: "GET", responseText: { "links": { "self": "/testing" }, "id": "one!" } }); $.hal.$get("/", { linksAttribute: "links", embeddedAttribute: "embedded" }).then(function (resource) { assert.propEqual(resource, {}); resource.$get("testing").then(function (r) { assert.propEqual(r, { "id": "one!" }); done(); }); }); });
import $ from 'jquery'; import digitTemplate from './index.html'; import Mustache from 'mustache'; export default class Digit { constructor(value) { if( !value ) this._value = 0; else if(typeof(value) == "number") this._value = value else throw new Error("Digit cannot be initialized with a number " + value) } set value(val) { this._value = val; } get value() { return this._value; } // Render Digit render() { return Mustache.render(digitTemplate, { number: this.value }) } }
function setup() { // create a place to draw createCanvas(640, 360); } function draw() { // clear the background background(0, 0, 0); // set a fill color fill(255, 255, 255); // set a stroke color stroke(255, 0, 0); // draw a circle ellipse(320, 180, 100, 100); }
import React from "react"; class Article extends React.Component{ render(){ return ( <a href={this.props.article.route} className="link"> <article> <h2>{this.props.article.name}</h2> <p>{this.props.article.description}</p> <p>Publicado por {this.props.article.author} el dia {this.props.article.date}</p> </article> </a> ) } } class ArticlesList extends React.Component{ render(){ return ( <div> { this.props.articles.map((article, key) => { return <Article key={key} article={article}/> }) } </div> ) } } function HomeView({renderService}) { function render({articles}){ renderService.reactRender({component: <ArticlesList articles={articles}/>}); } return { render: render } } module.exports = HomeView;
import React, { Component } from 'react' import { Route, Link } from 'react-router-dom' import ProdutosHome from './produtosHome' import Categoria from './categoria' export default class Produtos extends Component { constructor(props) { super(props) this.state = { categorias: [] } this.handleNewCategoria = this.handleNewCategoria.bind(this) this.renderCategoria = this.renderCategoria.bind(this) } componentDidMount() { // buscar as categorias this.props.loadCategorias() } renderCategoria(cat) { return ( <li key={cat.id}> <button className='btns btns-sm' onClick={()=> this.props.removeCategoria(cat)}> <span className='glyphicon glyphicon-remove'></span> </button> <Link to={`/produtos/categoria/${cat.id}`}>{cat.categoria}</Link> </li> ) } handleNewCategoria(key) { if(key.keyCode === 13 ) { this.props.createCategoria({ categoria: this.refs.categoria.value }) this.refs.categoria.value = '' } } render() { const { match, categorias } = this.props return ( <div className='row'> <div className='col-md-2'> <h3>Categorias</h3> <ul> {categorias.map(this.renderCategoria)} </ul> <div className='well well-sm'> <input className='form-control' onKeyUp={this.handleNewCategoria} type="text" ref='categoria' placeholder='Nova categoria'/> </div> </div> <div className='col-md-10'> <h1>Produtos</h1> <Route exact path={match.url} component={ProdutosHome}/> <Route path={match.url+'/categoria/:catId'} component={Categoria}/> </div> </div> ) } }
var insert = require('../lib/insert') var Assert = require('assert') var Type = require('is') /*eslint-env mocha */ describe('#insert()', function () { it('should be curried', function () { Assert.ok(Type.fn(insert(1, 'el'))) Assert.deepEqual(insert(1, 'el')([1, 2]), [1, 'el', 2]) }) it('should insert an element at given index', function () { Assert.deepEqual(insert(1, 'el', [1, 2, 3]), [1, 'el', 2, 3]) }) })
console.clear(); //callback const callMe = name => { console.log(`Time for dinner, ${name}!!!`); } setTimeout(name => { console.log("Done like dinner"); callMe(name); }, 2000, 'Mitchell Haak'); // promises new Promise((resolve, reject) => { setTimeout(() => { console.log("Done like dinner"); resolve(); }, 2000); }) .then(() => callMe("Mitch")); // async const asyncFunc = async () => { await new Promise((resolve, reject) => { setTimeout(() => { console.log("done like dinner"); return resolve(); }); }); await callMe(name); };
import reducer from '../../src/redux/cars/reducers' import * as action from '../../src/redux/cars/actions' import MockData from '../../MockData' const initialState = { carList: [], pageInfo: {}, carListFailed: '' }; describe('cars reducer', () => { it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual(initialState) }) it('should handle Car List Success', () => { const payloadObject = { carList: MockData.CAR_LIST.data.vehicles.edges, pageInfo: { hasNextPage: MockData.CAR_LIST.data.vehicles.pageInfo.hasNextPage, totalCount: MockData.CAR_LIST.data.vehicles.totalCount }, resetPage: false } expect(reducer({}, { type: action.CAR_LIST_SUCCESS, payload: payloadObject })).toEqual({carList: payloadObject.carList, pageInfo: payloadObject.pageInfo}) }) it('should handle Car List Failed', () => { const payloadObject = "No Data Found" expect(reducer({}, { type: action.CAR_LIST_FAILED, payload: payloadObject })).toEqual({carListFailed: payloadObject}) }) })
import React from "react" import ReactMarkdown from "react-markdown" export default ({ data }) => ( <div className="relative"> <figure className="flex items-center"> <div className="w-1/2" style={{ marginRight: '-7%' }} > <img className="block w-full" src={data.headshot.url} alt="Testimonial" /> </div> <div className="relative z-10" style={{ width: '57%' }} > <div className="dynamic-padding text-center bg-blue-100 py-24 xl:pl-24 px-8 relative"> <ReactMarkdown source={data.content} /> {data.signature && <img className="inline-block mb-4" src={data.signature.url} alt={data.name} /> } <div className="font-bold"> – {data.name} </div> </div> </div> </figure> </div> )
$(document).on('click','.subcontratado_check,.compartido_check', function (){ if($('.compartido_check').is(':checked')){ $('.container_select_compartido').show(); }else{ $('.container_select_compartido').hide(); } if($('.subcontratado_check').is(':checked')){ $('.container_select_subcontratado').show(); }else{ $('.container_select_subcontratado').hide(); } }); function load_swal_return_movimientos(){ }
"use strict" const bankApp = new BankApp() bankApp.register("Jhake", "password1") bankApp.register("Rommel", "password2") bankApp.logout()
module.exports = function(User) { var getUserById = function(userId, callback) { User.findById(userId, callback); }; var getUser = function(flags, callback) { User.find(flags, callback); } var saveUser = function(user, callback){ user.save(callback); }; return { getUserById, saveUser, getUser }; }
import React from 'react' import './Order.css'; import moment from "moment"; import Checkout__Product from '../Checkout/Checkout__Product.jsx' import CurrencyFormat from 'react-currency-format'; function Order({order}) { return ( <div className='order'> <h2>Order</h2> <p>{moment.unix(order.data.created).format("MMMM Do YYYY,h:mma")}</p> <p className="order__id"> <small>{order.id}</small> </p> {order.data.basket?.map(element=>( <Checkout__Product image_slider={element.Image_Slider} id={element.ID} title={element.description} image={element.Image} price={element.Price} rating={element.rating} button_disable={true} ></Checkout__Product> ))} <CurrencyFormat renderText={(value)=>( <> <p> Subtotal ({basket.length} items): <strong>{` ${ value}`}</strong> </p> <small className="subtotal__gift"> <input type="checkbox"></input> This order contains a gift </small> </> )} decimalScale={2} value={order.data.amount} displayType={"text"} thousandSeparator={true} prefix={"₹"} /> </div> ) } export default Order;
import React, {useEffect, useState, useRef} from "react"; import { useSelector } from 'react-redux' import { useParams, Redirect } from 'react-router-dom' import Cookies from 'universal-cookie' import Card from "@mui/material/Card"; import { Container, Grid, Paper, TextareaAutosize } from "@mui/material"; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' import { faChevronUp, faChevronDown } from '@fortawesome/fontawesome-free-solid' import CardContent from "@mui/material/CardContent"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; import './Post.css' import './SingleQuestion.css' const SingleQuestion = (props) => { const { AuthorEmail, content, name, tags, questionData } = props.location.state; const user = useSelector(state => state.user) const { id } = useParams() const [isAuth, setAuth] = useState(true) const [answers, setAnswers] = useState([]) const [initRequest, setRequestStatus] = useState(false) const [upvotedAns, setUpvotedAns] = useState([]) const [downvotedAns, setDownvotedAns] = useState([]) const [originallyUpvoted, setOriginallyUpvoted] = useState([]) const [originallyDownvoted, setOriginallyDownvoted] = useState([]) const textInput = useRef(null) const requestAnswers = async () => { const idToken = (new Cookies()).get('idToken') const questionId = id const res = await fetch('https://xha59eviig.execute-api.ap-south-1.amazonaws.com/prod/question_answers?id='+questionId, { method: 'GET', headers: { 'Authorization': 'Bearer '+idToken, 'Content-type': 'application/json', 'Accept': 'application/json' } }) const data = await res.json() // Handle errors if(!data.error) { const newAnswers = [] data.answers.forEach(answer => { const ans = { author: answer.author.email, content: answer.content, id: answer._id, upvotes: answer.upvotes, downvotes: answer.downvotes } newAnswers.push(ans) }); setAnswers(newAnswers) setUpvotedAns(data.answersUpvoted) setOriginallyUpvoted(data.answersUpvoted) setOriginallyDownvoted(data.answersDownvoted) setDownvotedAns(data.answersDownvoted) setRequestStatus(true) } else { if(data.error === 'Please authenticate!') setAuth(false) } } const submitVotes = async (upvoteId, downvoteId) => { const idToken = (new Cookies()).get('idToken') if(upvoteId !== "") { const res = await fetch('https://xha59eviig.execute-api.ap-south-1.amazonaws.com/prod/upvote', { method: 'PATCH', headers: { 'Authorization': 'Bearer '+idToken, 'Content-type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ email: user.email, answers: [upvoteId] }) }) const data = await res.json() if(data.error === 'Please authenticate!') setAuth(false) } if(downvoteId !== "") { const res = await fetch('https://xha59eviig.execute-api.ap-south-1.amazonaws.com/prod/downvote', { method: 'PATCH', headers: { 'Authorization': 'Bearer '+idToken, 'Content-type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ email: user.email, answers: [downvoteId] }) }) const data = await res.json() if(data.error === 'Please authenticate!') setAuth(false) } // Handle errors } useEffect(() => { if(initRequest === false) { requestAnswers() } }, [initRequest]) const submitAnswer = async content => { const idToken = (new Cookies()).get('idToken') const res = await fetch('https://xha59eviig.execute-api.ap-south-1.amazonaws.com/prod/answer', { method: 'POST', headers: { 'Authorization': 'Bearer '+idToken, 'Content-type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ email: user.email, question: id, answer: content }) }) const data = await res.json() if(!data.error) { const newAnswers = [...answers] newAnswers.push({ author: user.email, content, id: data.answer._id, upvotes: [], downvotes: [] }) setAnswers(newAnswers) } else { if(data.error === 'Please authenticate!') setAuth(false) } // Handle error } const handleSubmit = () => { const content = textInput.current.value if(content === "") return submitAnswer(content) } const newUpvote = async answerId => { await submitVotes(answerId, "") const upvoteArr = [...upvotedAns] const downvoteArr = [...downvotedAns] const idIndex = upvoteArr.indexOf(answerId) if(idIndex === -1) upvoteArr.push(answerId) const downvoteIndex = downvoteArr.indexOf(answerId) if(downvoteIndex !== -1) downvoteArr.splice(downvoteIndex, 1) setUpvotedAns(upvoteArr) setDownvotedAns(downvoteArr) } const newDownvote = async answerId => { await submitVotes("", answerId) const upvoteArr = [...upvotedAns] const downvoteArr = [...downvotedAns] const idIndex = upvoteArr.indexOf(answerId) if(idIndex !== -1) upvoteArr.splice(idIndex, 1) const downvoteIndex = downvoteArr.indexOf(answerId) if(downvoteIndex === -1) downvoteArr.push(answerId) setUpvotedAns(upvoteArr) setDownvotedAns(downvoteArr) } return ( isAuth===false?<Redirect to="/"/>: <Container> <Grid> <Grid item> <Card sx={{ minWidth: 650 }}> <CardContent> <Typography sx={{ fontSize: 15 }} color="text.primary" > <b>{name}</b> </Typography> <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom > <b>{AuthorEmail}</b> </Typography> <Typography variant="h5">{content}</Typography> <br /> <Typography variant="body2">{}</Typography> <div className="post__tags"> { tags.map((tag, index) => ( <div className="tag-ele" key={index}> {tag} </div> )) } </div> </CardContent> </Card> </Grid> <Grid xs={12} sx={{ minWidth: 635, marginTop: 5 }}> {answers.map((ans) => { const upvoteStatus = upvotedAns.indexOf(ans.id)===-1?0:1 const downvoteStatus = downvotedAns.indexOf(ans.id)===-1?0:1 const originallyUpvotedStatus = originallyUpvoted.indexOf(ans.id)===-1?0:1 const originallyDownvotedStatus = originallyDownvoted.indexOf(ans.id)===-1?0:1 const originalScore = ans.upvotes.length - ans.downvotes.length const scoreWithoutUser = originalScore - (originallyUpvotedStatus-originallyDownvotedStatus) const score = scoreWithoutUser + upvoteStatus - downvoteStatus return <Card style={{ marginBottom: 15 }}> <div className="answer-container"> <div className="vote-container"> <FontAwesomeIcon className="vote-icon" icon={faChevronUp} size="2x" onClick={()=>{newUpvote(ans.id)}} cursor="pointer" color={upvoteStatus === 0?"black":"orange"} /> <div className="vote-count-container">{score}</div> <FontAwesomeIcon className="vote-icon" icon={faChevronDown} size="2x" onClick={()=>{newDownvote(ans.id)}} cursor="pointer" color={downvoteStatus === 0?"black":"orange"} /> </div> <CardContent sx={{ minHeight: 50 }}> <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom > <b>{ans.author}</b> </Typography> <Typography sx={{ fontSize: 18, display: "inline-block", }} color="text.primary" > {ans.content} </Typography> </CardContent> </div> </Card> })} </Grid> <Grid item> <Typography variant="h5" style={{ marginBottom: 5 }}> Want to answer? </Typography> <Card style={{ marginBottom: 15 }} sx={{ minWidth: 650 }}> <CardContent sx={{ minHeight: 50 }}> <Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom > </Typography> <TextareaAutosize ref={textInput} style={{ maxWidth: 600, minWidth: 600, maxHeight: 300, minHeight: 300, overflow: "auto", }} /> </CardContent> <div style={{ marginBottom: 4 }}> <Button style={{ textDecoration: "none", marginLeft: 5, marginRight: 5, }} variant="contained" color="primary" onClick={handleSubmit} > Submit </Button> </div> </Card> </Grid> </Grid> </Container> ); }; export default SingleQuestion;
import Route from 'ember-route'; export function initialize() { Route.reopen({ setupController(controller, ...args) { this._super(...arguments); if (controller.setup) { controller.setup(...args); } }, resetController(controller, ...args) { this._super(...arguments); if (controller.reset) { controller.reset(...args); } } }); } export default { name: 'controller-lifecycle', initialize };
import getSounds from './soundUtils'; describe('getSounds()', () => { it('should return audio object with correct path when give type', () => { expect(getSounds('hint')[0].src).toMatch(/hint.ogg/); }); it('should return same number of audio objects more than one type is given', () => { expect(getSounds('hint', 'no-hint')).toHaveLength(2); }); });
const url = 'https://happy-stars.herokuapp.com/api/universe'; const fetchUniverse = () => { fetch(url) .then(response => { if(!response.ok) { throw Error('ERROR'); } return response.json(); }) .then(data => { const html = data.universes .map(universe => { // Map table values for Universes.js return ` <tr> <td>${universe.id}</td> <td></td> <td>${universe.name}</td> <td></td> <td>${universe.maxSize}</td> </tr>` }) .join(""); // Add cleaned html to <table> element in Universes.js document.querySelector("#universeTable").insertAdjacentHTML("beforeend", html); }) .catch(err => { console.log(err); }) } export { fetchUniverse } ;
'use strict'; const path = require('path'); const NODE_ENV = process.env.NODE_ENV || 'development'; const projectDir = process.cwd(); const staticDir = path.resolve(projectDir, 'public'); const clientDir = path.resolve(projectDir, 'client'); const customStylusUtils = path.join(clientDir, 'css/utils/**/*.styl'); const autoprefixer = require('autoprefixer')({ browsers: ['last 100 versions', 'ie > 7'], flexbox: true }); const locals = require('../locals'); module.exports = { // 端口 port: +process.env.port || +process.env.PORT || 5100, // 网页模板路径 viewsDir: path.resolve(projectDir, 'server', 'views'), // client存放目录 clientDir: clientDir, // 日志文件存放目录 logsDir: path.resolve(projectDir, 'logs'), // 配置文件路径 logsCfg: path.join(projectDir, 'conf/log4js.json'), // 静态文件目录 staticDir: staticDir, // 静态资源前缀 // staticPath: staticPath, // 静态文件的映射 staticMappings: {}, // 静态目录配置参数 staticOpts: {}, // 自定义favicon favicon: undefined, // 是否开启模板缓存 viewsCache: NODE_ENV === 'production', // stylus 配置 stylus: { // 是否开启stylus插件 disabled: NODE_ENV !== 'development', define: { '$CDN_PATH': locals.CDN_PATH }, use: [ require('nib')(), // require('poststylus')(['autoprefixer', 'rucksack-css']) require('poststylus')([autoprefixer, 'rucksack-css']) ], import: [ '~nib/lib/nib/index.styl', customStylusUtils ], url: { name: 'inline-url', limit: 50000, paths: [staticDir] }, src: clientDir, dest: staticDir }, // http请求相关配置 req: { // 默认走nginx,需要解压缩 gzip: true }, // 路由配置 router: { path: path.resolve(projectDir, 'server', 'routes'), exclude: [] }, // 控制器 controller: { path: path.resolve(projectDir, 'server', 'controllers'), }, // 构建打包 build: {} };
var btnRegistrar = document.getElementById("btnRegistrar"); btnRegistrar.addEventListener("click",()=>{ axios.post("http://localhost:4567/registro", { nombre:document.getElementById("nombre").value, user: document.getElementById("user").value, password: document.getElementById("password").value }) .then(function (res) { alert("Nombre:" + res.data.status + " user:" + res.data.user+" password: "+res.data.password); }) .catch(function (error) { console.log(error) }) });
/** * Progress */ import React from 'react'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import CircularProgress from '@material-ui/core/CircularProgress'; import { green, red } from '@material-ui/core/colors'; import Button from '@material-ui/core/Button'; import CheckIcon from '@material-ui/icons/Check'; import SaveIcon from '@material-ui/icons/Save'; //Component import LinearBuffer from './components/LinearBuffer'; import LinearQuery from './components/LinearQuery'; import LinearDeterminate from './components/LinearDeterminate'; import LinearIndeterminate from './components/LinearIndeterminate'; // page title bar import PageTitleBar from 'Components/PageTitleBar/PageTitleBar'; // intl messages import IntlMessages from 'Util/IntlMessages'; // rct card box import RctCollapsibleCard from 'Components/RctCollapsibleCard/RctCollapsibleCard'; const styles = theme => ({ root: { display: 'flex', alignItems: 'center', }, wrapper: { margin: theme.spacing.unit, position: 'relative', }, buttonSuccess: { backgroundColor: green[500], '&:hover': { backgroundColor: green[700], }, }, fabProgress: { color: green[500], position: 'absolute', top: -6, left: -6, zIndex: 1, }, buttonProgress: { color: green[500], position: 'absolute', top: '50%', left: '50%', marginTop: -12, marginLeft: -12, }, }); class ProgressBar extends React.Component { state = { loading: false, success: false, }; componentWillUnmount() { clearTimeout(this.timer); } handleButtonClick = () => { if (!this.state.loading) { this.setState( { success: false, loading: true, }, () => { this.timer = setTimeout(() => { this.setState({ loading: false, success: true, }); }, 2000); }, ); } }; timer = undefined; render() { const { loading, success } = this.state; const { classes } = this.props; const buttonClassname = classNames({ [classes.buttonSuccess]: success, }); return ( <div className="progress-wrapper"> <PageTitleBar title={<IntlMessages id="sidebar.progress" />} match={this.props.match} /> <div className="row"> <RctCollapsibleCard colClasses="col-sm-12 col-md-12 col-xl-4 d-sm-full" heading={<IntlMessages id="widgets.circularProgressBottomStart" />} > <CircularProgress className="w-10 mr-30 mb-10 progress-primary" thickness={2} /> <CircularProgress className="mr-30 mb-10 progress-success" size={70} /> <CircularProgress className="w-10 mr-30 mb-10 text-pink" thickness={5} /> <CircularProgress className="w-10 mr-30 mb-10" style={{ color: red[600] }} thickness={7} /> </RctCollapsibleCard> <RctCollapsibleCard colClasses="col-sm-12 col-md-12 col-xl-4 d-sm-full" heading={<IntlMessages id="widgets.interactiveIntegration" />} > <div className={classes.root}> <div className={classes.wrapper}> <Button variant="fab" color="secondary" className={buttonClassname} onClick={this.handleButtonClick}> {success ? <CheckIcon /> : <SaveIcon />} </Button> {loading && <CircularProgress size={68} className={classes.fabProgress} />} </div> <div className={classes.wrapper}> <Button variant="raised" color="secondary" className={buttonClassname} disabled={loading} onClick={this.handleButtonClick} > Accept terms </Button> {loading && <CircularProgress size={24} className={classes.buttonProgress} />} </div> </div> </RctCollapsibleCard> <RctCollapsibleCard colClasses="col-sm-12 col-md-12 col-xl-4 d-sm-full" heading={<IntlMessages id="widgets.determinate" />} > <CircularProgress className="progress-primary mr-30 mb-10" size={60} mode="determinate" value={75} /> <CircularProgress className="progress-danger mr-30 mb-10" size={70} mode="determinate" value={35} min={0} max={50} /> <CircularProgress className="progress-success mr-30 mb-10" size={60} mode="determinate" value={75} /> <CircularProgress className="progress-warning mr-30 mb-10" size={70} mode="determinate" value={40} min={0} max={50} /> </RctCollapsibleCard> </div> <div className="sub-title"> <h4><IntlMessages id="widgets.linearProgressLineBar" /> </h4> </div> <div className="row"> <RctCollapsibleCard colClasses="col-xs-12 col-sm-12 col-md-6" heading={<IntlMessages id="widgets.indeterminate" />} > <LinearIndeterminate /> </RctCollapsibleCard> <RctCollapsibleCard colClasses="col-xs-12 col-sm-12 col-md-6" heading={<IntlMessages id="widgets.determinate" />} > <LinearDeterminate /> </RctCollapsibleCard> <RctCollapsibleCard colClasses="col-xs-12 col-sm-12 col-md-6" heading={<IntlMessages id="widgets.buffer" />} > <LinearBuffer /> </RctCollapsibleCard> <RctCollapsibleCard colClasses="col-xs-12 col-sm-12 col-md-6" heading={<IntlMessages id="widgets.query" />} > <LinearQuery /> </RctCollapsibleCard> </div> </div> ); } } export default withStyles(styles)(ProgressBar);
import React from "react"; import { useHistory } from "react-router-dom"; import PropTypes from "prop-types"; import { Map as LeafletMap, TileLayer, Popup, Marker } from "react-leaflet"; import FullscreenControl from "react-leaflet-fullscreen"; import L from "leaflet"; import { MapKey } from "./MapKey"; // css import "assets/scss/device-management-map.sass"; import "react-leaflet-fullscreen/dist/styles.css"; const Map = ({ className, devices, ...rest }) => { const history = useHistory(); let CategoryColorClass = (isOnline) => { return isOnline === true ? "deviceOnline" : isOnline === false ? "deviceOffline" : "UnCategorise"; }; let CategoryColorClass2 = (maintenanceStatus) => { return maintenanceStatus === "overdue" ? "red" : maintenanceStatus === "due" ? "orange" : maintenanceStatus === -1 ? "grey" : "b-success"; }; const handleDetailsClick = (device) => (event) => { event.preventDefault(); history.push(`/device/${device.name}/overview`); }; return ( <LeafletMap animate attributionControl center={[0.3341424, 32.5600613]} doubleClickZoom dragging easeLinearity={0.35} scrollWheelZoom zoom={7} zoomControl > <TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" /> {devices.map( (device, index) => device.latitude && device.longitude && ( <Marker position={[device.latitude, device.longitude]} fill="true" key={`device-maintenance-${device.channelId}-${index}`} clickable="true" icon={L.divIcon({ //html:`${contact.isOnline}`, iconSize: 38, className: `leafletMarkerIcon ${CategoryColorClass2( device.maintenance_status )}`, })} /> ) )} {devices.map( (device, index) => device.latitude && device.longitude && ( <Marker position={[device.latitude, device.longitude]} fill="false" key={`device-status-${device.channelId}-${index}`} clickable="true" icon={L.divIcon({ //html:`${contact.isOnline}`, iconSize: 30, className: `leafletMarkerIcon ${CategoryColorClass( device.isOnline )}`, })} > <Popup> <div className={"popup-container"}> <span> <b>Device Name</b>: {device.name} </span> <span> <b>Status</b>:{" "} {device.isOnline ? ( <span className={"popup-success"}>online</span> ) : ( <span className={"popup-danger"}>offline</span> )} </span> <span> <b>Maintenance Status</b>:{" "} {device.maintenance_status === "overdue" ? ( <span className={"popup-danger"}> {device.maintenance_status} </span> ) : device.maintenance_status === -1 ? ( <span className={"popup-grey"}>not set</span> ) : ( <span className={"popup-success"}> {device.maintenance_status} </span> )} </span> <a className={"popup-more-details"} onClick={handleDetailsClick(device)} > Device details </a> </div> </Popup> </Marker> ) )} <FullscreenControl position="topleft" /> <MapKey /> </LeafletMap> ); }; Map.propTypes = { className: PropTypes.string, }; export default Map;
'use strict'; var utils = { // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript validateEmail: function (email) { let regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return regex.test(email); }, mergeArrays: function (array1, array2) { let aux = array1.concat(array2); let result = aux.filter(function (item, pos) { return aux.indexOf(item) == pos; }); return result; }, dbErrorResponse: function (err) { if (err.errmsg && err.errmsg.indexOf('nombre_1 dup key') > -1) { return 'Username already exists.'; } else if (err.errmsg && err.errmsg.indexOf('email_1 dup key') > -1) { return 'Email already in use.'; } return 'Service currently unavailable.'; } }; module.exports = utils;
// create the controller and inject Angular's $scope app.controller('mainController', function($scope) { // create a message to display in our view $scope.message = 'Everyone come and see how good I look!'; }); app.controller('aboutController', function($scope) { $scope.message = 'Look! I am an about page.'; }); app.controller('contactController', function($scope) { $scope.message = 'Contact us! JK. This is just a demo.'; }); app.controller("formController", function($scope, $location, formService){ $scope.form = { name: formService.name, email: formService.email }; $scope.changeView = function(view){ formService.name = $scope.form.name; formService.email = $scope.form.email; console.log(formService); $location.path(view); } });
var requirejs = require('requirejs'); var controllerMap = require('../../../app/server/controller_map')(); var get_dashboard_and_render = require('../../../app/server/mixins/get_dashboard_and_render'); var StagecraftApiClient = requirejs('stagecraft_api_client'); describe('get_dashboard_and_render', function () { var fakeRenderContent, fake_request, fake_response, fakeStatusCall, api_client_initialize_spy; beforeEach(function (){ api_client_initialize_spy = spyOn(StagecraftApiClient.prototype, 'initialize').andCallThrough(); fakeRenderContent = jasmine.createSpy('fakiefakefakefake'); var request_attrs = { 'port': 8989, 'stagecraftUrl': 'urlURL' }; fake_request = { get: function(key) { return { 'Request-Id':'Xb35Gt', 'GOVUK-Request-Id': '1231234123' }[key]; }, 'app': { 'get': function(key) { return request_attrs[key]; } }, originalUrl: '' }; fakeStatusCall = jasmine.createSpy('status'); fake_response = {status: fakeStatusCall}; }); it('should set up the correct client_instance', function(){ var client_instance = get_dashboard_and_render(fake_request, fake_response, fakeRenderContent); expect(StagecraftApiClient.prototype.initialize).toHaveBeenCalledWith( { params: {} }, { ControllerMap: controllerMap, requestId: 'Xb35Gt', govukRequestId: '1231234123' }); expect(client_instance.stagecraftUrlRoot).toEqual('urlURL/public/dashboards'); }); it('should escape XSS attempts in queries', function(){ fake_request.originalUrl = 'http://localhost:3057/performance/central-government-websites?sortby=percentOfTotal(count:sum)%22%27--!%3E%3C/Title/%3C/Style/%3C/script/%3C/Textarea/%3C/Noscr%20ipt/%3C/Pre/%3C/Xmp%3E%3CSvg/Onload=confirm`OPENBUGBOUNTY`%3E&sortorder=descending'; var client_instance = get_dashboard_and_render(fake_request, fake_response, fakeRenderContent); expect(StagecraftApiClient.prototype.initialize).toHaveBeenCalledWith( { params: { sortby: 'percentOfTotal(count:sum)&#34;\'--!&gt;&lt;/Title/&lt;/Style/&lt;/script/&lt;/Textarea/&lt;/Noscr ipt/&lt;/Pre/&lt;/Xmp&gt;&lt;Svg/Onload=confirm`OPENBUGBOUNTY`&gt;', sortorder: 'descending' } }, { ControllerMap: controllerMap, requestId: 'Xb35Gt', govukRequestId: '1231234123' }); expect(client_instance.stagecraftUrlRoot).toEqual('urlURL/public/dashboards'); }); describe('on sync of client_instance', function() { it('should set up the correct client_instance', function(){ var client_instance = get_dashboard_and_render(fake_request, fake_response, fakeRenderContent); var offSpy = spyOn(StagecraftApiClient.prototype, 'off').andCallThrough(); client_instance.set({'status': 200}); client_instance.trigger('sync'); expect(offSpy).toHaveBeenCalled(); expect(fakeStatusCall).toHaveBeenCalledWith(200); expect(fakeRenderContent).toHaveBeenCalledWith(fake_request, fake_response, client_instance); }); }); describe('on error of client_instance', function() { it('it should return an error', function(){ var client_instance = get_dashboard_and_render(fake_request, fake_response, fakeRenderContent); var offSpy = spyOn(StagecraftApiClient.prototype, 'off').andCallThrough(); client_instance.set({'status': 404}); client_instance.trigger('error'); client_instance.trigger('error'); expect(offSpy).toHaveBeenCalled(); expect(fakeStatusCall).toHaveBeenCalledWith(404); expect(fakeRenderContent).toHaveBeenCalledWith(fake_request, fake_response, client_instance); }); }); });
Ext.define('Assessmentapp.assessmentapp.com.model.assessmentcontext.survey.AssessmentQuestionsExtDTOModel', { "extend": "Ext.data.Model", "fields": [{ "name": "questionNumber" }, { "name": "question" }, { "name": "yesLinkedQuestion" }, { "name": "noLinkedQuestion" }, { "name": "keywordForInference" }] });
function solve(rows, cols) { let matrix=[] let maxEl=rows*cols; let minEl=0; let minRow=0; let minCol=0; let maxRow=rows-1; let maxCol=cols-1; for (let i = 0; i < rows; i++) matrix[i]=[]; while(minEl<maxEl) { for (let i = minCol; i <= maxCol; i++) { matrix[minRow][i]=++minEl; } minRow++; for (let i = minRow; i <= maxRow; i++){ matrix[i][maxCol]=++minEl; } maxCol--; for (let i = maxCol; i >= minCol; i--) { matrix[maxRow][i]=++minEl } maxRow--; for (let i = maxRow; i >= minRow; i--) { matrix[i][minCol]=++minEl; } minCol++; } matrix.forEach(r=>console.log(r.join(' '))); } solve(5, 5)
/* * eCommerceViewComponent.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Product -> eCommerce View page component. * * @author vn70516 * @since 2.0.14 */ (function () { angular.module('productMaintenanceUiApp').component('eCommerceView', { bindings: { productMaster: '<', isLastProduct: '&' }, // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/product/eCommerceView/eCommerceView.html', // The controller that handles our component logic controller: ECommerceViewController }); ECommerceViewController.$inject = ['ECommerceViewApi', '$scope', '$timeout', '$filter', '$sce', '$rootScope', 'VocabularyService', 'ProductGroupService', '$state', 'appConstants', 'ProductSearchService', 'taskService', '$location', 'PermissionsService', 'customHierarchyService']; function ECommerceViewController(eCommerceViewApi, $scope, $timeout, $filter, $sce, $rootScope, vocabularyService, productGroupService, $state, appConstants, productSearchService, taskService, $location, permissionsService, customHierarchyService) { var self = this; self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING = 'There are no changes on this page to be saved. Please make any changes to update.'; self.SELECT_DATE_SUBSCRIPTION_ELIGIBLE = 'Please select the date for the Subscription Eligible.'; /** * Reload eCommerce view key. * @type {string} */ self.RELOAD_ECOMMERCE_VIEW = 'reloadECommerceView'; /** * Reset eCommerce view. * @type {string} */ self.RESET_ECOMMERCE_VIEW = 'resetECommerceView'; /** * Reload after save popup. * @type {string} */ self.RELOAD_AFTER_SAVE_POPUP = 'reloadAfterSavePopup'; /** * Validate warning eCommerce view key. * @type {string} */ self.VALIDATE_WARNING = 'validateWarning'; /** * Clear message key. * @type {string} */ self.CLEAR_MESSAGE = 'clearMessage'; /** * The (select for heb com) button is disable or not. * @type {boolean} */ self.isDisableHebComButton = false; /** * The key for showing next product * @type {string} */ const NEXT_PRODUCT = 'nextProduct'; /** * The id of favor tab * @type {string} */ const FAVOR_TAB_ID = 'Favor'; /** * sale channel of heb.com. * @type {string} */ const SAL_CHANNEL_HEB_COM = '01'; /** * Check edit text mode * @type {boolean} */ self.isEditText = false; /** * Romance copy logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_ROMANCE_COPY = 1666; /** * Ingredient editable phycical attribute id. * * @type {number} */ self.PHY_ATTR_ID_INGREDIENT = 1643; /** * Ingredient logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_INGREDIENT = 1674; /** * Brand attribute logical attribute id. * @type {number} */ self.LOG_ATTR_ID_BRAND = 1672; /** * Display name logical attribute id. * @type {number} */ self.LOG_ATTR_ID_DISPLAY_NAME = 1664; /** * Size logical attribute id. * @type {number} */ self.LOG_ATTR_ID_SIZE = 1667; /** * The direction logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_DIRECTION= 1676; /** * The warning logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_WARNING = 1677; /** * The tag logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_TAG = 1729; /** * Nutrient logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_NUTRIENT = 1679; /** * Specification logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_SPEC = 1728; /** * Favor item description logical attribute id. * * @type {number} */ self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION = 3989; /** * The current error message. * @type {String} */ self.error = null; /** * Keeps track of whether front end is waiting for back end response. * * @type {boolean} */ self.isWaitingForResponse = false; /** * The current tab information * @type {{}} */ self.currentTab = {}; /** * The list of sale channel * @type {Array} */ self.saleChannels = []; /** * The domain tab bar data provider. */ self.domainTabBarDataProvider = []; /** * eCommerce View details information. * @type {{}} */ self.eCommerceViewDetails = {}; /** * Holds the status to request publish action after save success. * @type {boolean} */ self.isRequestPublishAfterSave = false; /** * The current error message. * @type {String} */ self.errorPopup = null; /** * The data source title basing on attribute id. * @type {string} */ self.dataSourceTitle = ''; /** * Keeps track of whether front end is waiting for back end response. * * @type {boolean} */ self.isWaitingForResponsePopup = false; /** * Keeps track of whether front end is waiting for check spelling response. * * @type {boolean} */ self.isWaitingForCheckSpellingResponse = false; /** * The list of data source provider information. * @type {Array} */ self.eCommerceViewAttributePriority = {}; /** * The list of data source provider information back up * @type {Array} */ self.eCommerceViewAttributePriorityOrg = {}; /** * Holds the new subscription info. * * @type {{subscriptionStartDate: null, subscriptionEndDate: null, subscription: boolean}} */ self.newSubscription=null; /** * The attribute mapping data provider. */ self.attributeMappingDataProvider = []; /** * The current attribute id. when set open edit source */ self.currentAttributeId; /** * identify if user click on Aa or Reset button */ self.clickOnAaOrResetButton = false; /** * Keeps track of whether front end is waiting for back end response for attribute mapping pop up. * * @type {boolean} */ self.isWaitingForResponsePopupAttr = false; /** * Min length for value of source * * @type {number} */ self.MIN_LENGTH_READ = 200; /** * From page navigated to ecommerce view page * @type {String} */ const FROM_PAGE_DETAIL_PRODUCT = 'associatedProductDetail'; /** * From page navigated to ecommerce view page * @type {String} */ const FROM_PAGE_ECOMMERCE_TASK_DETAIL = 'ecommerceTaskDetail'; /** * enable or disable return to list button * * @type {Boolean} */ self.disableReturnToList = true; /** * Keeps track of whether front end is waiting for back end response for attribute mapping popup. * * @type {boolean} */ self.errorPopupAttr = false; self.vocabularyService = vocabularyService; /** * Task Detail base url. * @type {string} */ const TASK_DETAIL_URL = "/task/ecommerceTask/taskInfo/"; /** * Constant when start date invalid. * * @type {String} */ const START_DATE_MANDATORY = 'Start Date is mandatory.'; /** * Constant when start date invalid. * * @type {String} */ const START_GREATER_OR_EQUAL_CUR = 'Start Date must be greater than or equal to Current Date.'; /** * Constant when start date invalid. * * @type {String} */ const START_LESS_END = 'Start Date must be less than End Date.'; /** * Constant when end date invalid. * * @type {String} */ const END_DATE_MANDATORY = 'End Date is mandatory.'; /** * Constant when end date invalid. * * @type {String} */ const END_GREATER_CUR_AND_LESS_MAX = 'End Date must be greater than Current Date and less than 12/31/9999.'; /** * Constant when end date invalid. * * @type {String} */ const END_GREATER_START_AND_LESS_MAX = 'End Date must be greater than Start Date and less than 12/31/9999.'; /** * Constant for empty string. * @type {String} */ const EMPTY = ''; /** * Constant for RED. * @type {String} */ const RED = 'red'; /** * Initialize values for heb guarantee type code */ const HEB_GUARANTEE_TYPE_CODE_02 = '00002'; const HEB_GUARANTEE_TYPE_CODE_04 = '00004'; const HEB_GUARANTEE_TYPE_CODE_05 = '00005'; const HEB_GUARANTEE_TYPE_CODE_06 = '00006'; const HEB_GUARANTEE_TYPE_CODE_07 = '00007'; /** * Constant type of file of image */ self.GUARANTEE_IMAGE_PATH_002 = 'images/guarantee-00002.png'; self.GUARANTEE_IMAGE_PATH_004 = 'images/guarantee-00004.png'; self.GUARANTEE_IMAGE_PATH_005 = 'images/guarantee-00005.png'; self.GUARANTEE_IMAGE_PATH_006 = 'images/guarantee-00006.png'; self.GUARANTEE_IMAGE_PATH_007 = 'images/guarantee-00007.png'; self.isEBM = false; /** * Holds the save or publish function to do after spell check. * @type {null} */ self.callbackfunctionAfterSpellCheck = null; /** * Flag to show type of html. * @type {boolean} */ self.htmlMode = false; /** * HTML Tab Pressing flag. * @type {boolean} */ self.htmlTabPressing = false; /** * Keeps track of whether $onInit is run or not. */ self.hasLoadInit = false; /** * Initialize the controller. */ this.$onInit = function () { //Check to enable or disable the return to list button self.disableReturnToList = productSearchService.getDisableReturnToList(); self.countRequest = 0; self.hasLoadInit = true; self.loadDataInit(); self.error = ''; self.success = ''; }; /** * Component will reload the kits data whenever the item is changed in casepack. */ this.$onChanges = function () { self.error = ''; self.success = ''; self.getECommerceViewInformation(); if(self.hasLoadInit){ self.getHebGuaranteeTypeCode(); } }; /** * Load data init */ self.loadDataInit = function () { self.isWaitingForResponse = true; eCommerceViewApi.findAllSaleChanel( //success function (results) { angular.forEach(results, function (value) { value.id = value.id + " "; }); self.saleChannels = angular.copy(results); self.buildECommerceViewTabBySaleChanel(self.saleChannels); self.getECommerceViewInformation(); } , self.fetchError ); self.getHebGuaranteeTypeCode(); }; /** * Build eCommerce View Tab by the list of sale channel. Ignore sale channel element with index=1(Store) * @param saleChannels */ self.buildECommerceViewTabBySaleChanel = function (saleChannels) { self.domainTabBarDataProvider = [ { displayName: "Heb.com", id: "HebCom", logo: "images/logo_hebcom.png", saleChannel: saleChannels[0], hierCntxtCd: "CUST" }, { displayName: "Hebtoyou", id: "Hebtoyou", logo: "images/logo_hebtoyou.png", saleChannel: saleChannels[2], hierCntxtCd: "HEBTO" }, { displayName: "Blooms", id: "Blooms", logo: "images/logo_blooms.jpg", saleChannel: saleChannels[3], hierCntxtCd: "BLOOM" }, { displayName: "Google", id: "Google", logo: "images/logo_google_shopping.jpg", saleChannel: saleChannels[4], hierCntxtCd: "GOOGL" }, { displayName: "Central Market", id: "Central_M", logo: "images/logo_central_market.jpg", saleChannel: saleChannels[5], hierCntxtCd: "CM" }, { displayName: "Favor", id: FAVOR_TAB_ID, logo: "images/logo_favor.png", saleChannel: saleChannels[7], hierCntxtCd: "FAVOR" } ]; }; /** * Get eCommerce View information by product id, sale channel,...ect */ self.getECommerceViewInformation = function () { eCommerceViewApi.getECommerceViewInformation( { productId: self.productMaster.prodId, upc: self.productMaster.productPrimaryScanCodeId }, //success case function (results) { self.buildDataForSubscriptionDatePicker(results); //store data eCommerce view details self.eCommerceViewDetails.publishedDate = results.publishedDate; self.eCommerceViewDetails.publishedBy = results.publishedBy; self.eCommerceViewDetails.snipes = results.snipes; self.eCommerceViewDetails.pdpTemplateId = results.pdpTemplateId; self.eCommerceViewDetails.pdpTemplateIdOrg = angular.copy(self.eCommerceViewDetails.pdpTemplateId); self.eCommerceViewDetails.storeCount = results.storeCount; self.eCommerceViewDetails.publishedDateString = results.publishedDateString; //validation self.validateWarning(); } //error case , self.fetchError ); }; /** * Build data time picker for show on site information. * @param productFullfilmentChanels */ self.buildDataForSubscriptionDatePicker = function (eCommerceViewDetails) { self.eCommerceViewDetails["subscription"] = self.productMaster.subscription; self.eCommerceViewDetails["subscriptionStartDateOpen"] = false; self.eCommerceViewDetails["subscriptionEndDateOpen"] = false; self.eCommerceViewDetails["subscriptionStartDate"] = null; self.eCommerceViewDetails["subscriptionEndDate"] = null; self.eCommerceViewDetails["subscriptionStartDateOrg"] = null; self.eCommerceViewDetails["subscriptionEndDateOrg"] = null; if (self.productMaster.subscriptionStartDate != undefined && self.productMaster.subscriptionStartDate != null) { self.eCommerceViewDetails["subscriptionStartDate"] = new Date(self.productMaster.subscriptionStartDate.replace(/-/g, '\/')); self.eCommerceViewDetails["subscriptionStartDateOrg"] = angular.copy(self.eCommerceViewDetails["subscriptionStartDate"]); } if (self.productMaster.subscriptionEndDate != undefined && self.productMaster.subscriptionEndDate != null) { self.eCommerceViewDetails["subscriptionEndDate"] = new Date(self.productMaster.subscriptionEndDate.replace(/-/g, '\/')); self.eCommerceViewDetails["subscriptionEndDateOrg"] = angular.copy(self.eCommerceViewDetails["subscriptionEndDate"]); } self.eCommerceViewDetails["subscriptionOrg"] = angular.copy(self.eCommerceViewDetails["subscription"]); }; /** * Callback for when the backend returns an error. * * @param error The error from the backend. */ self.fetchError = function (error) { $rootScope.contentChangedFlag = true; self.isWaitingForResponse = false; self.nextTab = null; if (error && error.data) { if (error.data.message) { self.error = (error.data.message); } else if (error.data.error) { self.error = (error.data.error); } else { self.error = error; } } else { self.error = "An unknown error occurred."; } $rootScope.$broadcast(self.RELOAD_AFTER_SAVE_POPUP, self.currentAttributeId, true); }; /** * Get heb guarantee type code */ self.getHebGuaranteeTypeCode = function(){ self.hebGuaranteeTypeDescription = ''; self.hebGuaranteeImage = null; self.hebGuaranteeTypeCode = null; eCommerceViewApi.findHebGuaranteeTypeCode({productId:self.productMaster.prodId}, //success function (results) { if(results != null ){ self.hebGuaranteeTypeDescription = results.hebGuaranteeTypeDescription; self.hebGuaranteeTypeCode = results.hebGuaranteeTypeCode; if(results.hebGuaranteeTypeCode != undefined && $.trim(results.hebGuaranteeTypeCode) != ""){ self.hebGuaranteeImage = self.findGuaranteeImagePath(results.hebGuaranteeTypeCode); } } } , self.fetchError ); }; /** * Find guarantee image path base on guarantee image type code * @param hebGuaranteeTypeCode * @returns {*} */ self.findGuaranteeImagePath = function(hebGuaranteeTypeCode){ switch (hebGuaranteeTypeCode){ case HEB_GUARANTEE_TYPE_CODE_02: return self.GUARANTEE_IMAGE_PATH_002; case HEB_GUARANTEE_TYPE_CODE_04: return self.GUARANTEE_IMAGE_PATH_004; case HEB_GUARANTEE_TYPE_CODE_05: return self.GUARANTEE_IMAGE_PATH_005; case HEB_GUARANTEE_TYPE_CODE_06: return self.GUARANTEE_IMAGE_PATH_006; case HEB_GUARANTEE_TYPE_CODE_07: return self.GUARANTEE_IMAGE_PATH_007; } return null; } /** * validate when user change on end date */ self.changeEndDate = function () { if (self.eCommerceViewDetails.showOnSiteEndDate === null || self.eCommerceViewDetails.showOnSiteEndDate == EMPTY) { self.eCommerceViewDetails.endDateErrorMgs = END_DATE_MANDATORY; self.eCommerceViewDetails.isEndDateErrorMgs = true; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, new Date())) { self.eCommerceViewDetails.endDateErrorMgs = END_GREATER_CUR_AND_LESS_MAX; self.eCommerceViewDetails.isEndDateErrorMgs = true; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, self.eCommerceViewDetails.showOnSiteStartDate)) { self.eCommerceViewDetails.endDateErrorMgs = END_GREATER_START_AND_LESS_MAX; self.eCommerceViewDetails.isEndDateErrorMgs = true; } else{ self.eCommerceViewDetails.endDateErrorMgs = EMPTY; self.eCommerceViewDetails.isEndDateErrorMgs = false; } }; /** * validate when user change on end date */ self.changeStartDate = function () { if (self.eCommerceViewDetails.showOnSiteStartDate === null || self.eCommerceViewDetails.showOnSiteStartDate == EMPTY) { self.eCommerceViewDetails.startDateErrorMgs = START_DATE_MANDATORY; self.eCommerceViewDetails.isStartDateErrorMgs = true; } else if (!self.isDate1GreaterThanOrEqualToDate2(self.eCommerceViewDetails.showOnSiteStartDate, new Date())) { self.eCommerceViewDetails.startDateErrorMgs = START_GREATER_OR_EQUAL_CUR; self.eCommerceViewDetails.isStartDateErrorMgs = true; // self.eCommerceViewDetails.endDateErrorMgs = END_GREATER_START_AND_LESS_MAX; // self.eCommerceViewDetails.isEndDateErrorMgs = true; } else if(!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, self.eCommerceViewDetails.showOnSiteStartDate)) { if(self.eCommerceViewDetails.showOnSiteEndDate !== null){ self.eCommerceViewDetails.startDateErrorMgs = START_LESS_END; self.eCommerceViewDetails.isStartDateErrorMgs = true; }else{ self.eCommerceViewDetails.startDateErrorMgs = EMPTY; self.eCommerceViewDetails.isStartDateErrorMgs = false; } } else{ self.eCommerceViewDetails.startDateErrorMgs = EMPTY; self.eCommerceViewDetails.isStartDateErrorMgs = false; } }; /** * Save the data. */ self.save = function () { self.callbackfunctionAfterSpellCheck = null; self.error = ''; self.success = ''; self.errorMessages = []; self.isRequestPublishAfterSave = false; self.newSubscription = null; if (self.eCommerceViewDetails.showOnSite != self.eCommerceViewDetails.showOnSiteOrg) { self.changeEndDate(); self.changeStartDate(); } if (self.isDataChanged()) { if (self.validateDataChanged()) { // save data. self.updateECommerceViewInformation(); } } else { // Show message. if(self.eCommerceViewDetails.subscription && self.eCommerceViewDetails.subscriptionStartDate == null && self.eCommerceViewDetails.subscriptionEndDate == null) { self.error = self.SELECT_DATE_SUBSCRIPTION_ELIGIBLE; } else { self.error = self.THERE_ARE_NO_DATA_CHANGES_MESSAGE_STRING; } } }; /** * Save data for heb. */ self.updateECommerceViewInformation = function () { self.isWaitingForResponse = true; eCommerceViewApi.updateECommerceViewInformation(self.eCommerceViewDetailsParams, //success function (results) { $rootScope.contentChangedFlag = false; if(self.newSubscription != null){ /* update new subscription into product to avoid reloading the product.*/ self.productMaster.subscription = self.newSubscription.subscription; self.productMaster.subscriptionStartDate = self.newSubscription.subscriptionStartDate; self.productMaster.subscriptionEndDate = self.newSubscription.subscriptionEndDate; } if (self.isRequestPublishAfterSave) { // Execute publish after save success. self.doPublish(); } else { self.error = ''; self.success = results.message; self.isWaitingForResponse = false; if(self.nextTab !== null){//move to next tab $scope.active = self.nextTab; }else{ self.updateNewDataToOriginalObject(); } } }, self.fetchError ); }; /** * Validate data. * * @returns {boolean} */ self.validateDataChanged = function () { self.errorMessages = []; /* validate show on site.*/ var checkDateShowOnSite = false; //if(self.isShowOnSiteChanged){ var showOnSiteTitle = 'Show On Site'; if(self.eCommerceViewDetails.showOnSite){ if (self.isStartDateShowOnSiteChanged()) { if (self.eCommerceViewDetails.showOnSiteStartDate === null) { self.errorMessages.push(showOnSiteTitle + '<li>Start Date is mandatory.</li>'); showOnSiteTitle = ''; } else if (!self.isDate1GreaterThanOrEqualToDate2(self.eCommerceViewDetails.showOnSiteStartDate, new Date())) { self.errorMessages.push(showOnSiteTitle + '<li>Start Date must be greater than or equal to Current Date.</li>'); showOnSiteTitle = ''; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, self.eCommerceViewDetails.showOnSiteStartDate)) { if(self.eCommerceViewDetails.showOnSiteEndDate !== null && self.eCommerceViewDetails.showOnSiteStartDate !== null) self.errorMessages.push(showOnSiteTitle + '<li>Start Date must be less than End Date.</li>'); } checkDateShowOnSite = true; } if (self.isEndDateShowOnSiteChanged() || checkDateShowOnSite) { if (self.eCommerceViewDetails.showOnSiteEndDate === null) { self.errorMessages.push(showOnSiteTitle + '<li>End Date is mandatory.</li>'); showOnSiteTitle = ''; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, new Date())) { self.errorMessages.push(showOnSiteTitle + '<li>End Date must be greater than Current Date and less than 12/31/9999.</li>'); showOnSiteTitle = ''; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.showOnSiteEndDate, self.eCommerceViewDetails.showOnSiteStartDate)) { if(self.eCommerceViewDetails.showOnSiteEndDate !== null && self.eCommerceViewDetails.showOnSiteStartDate !== null) self.errorMessages.push(showOnSiteTitle + '<li>End Date must be greater than Start Date and less than 12/31/9999.</li>'); } } } var subcription = 'Subscription Eligible'; var checkDateSubscription = false; //if (self.isSubscriptionChanged()) { if (self.eCommerceViewDetails.subscription && self.isStartDateSubscriptionChanged()) { if (self.eCommerceViewDetails.subscriptionStartDate === null) { self.errorMessages.push(subcription+'<li>Start Date is mandatory.</li>'); subcription = ''; }else if (!self.isDate1GreaterThanOrEqualToDate2(self.eCommerceViewDetails.subscriptionStartDate, new Date())) { self.errorMessages.push(subcription+'<li>Start Date must be greater than or equal to Current Date.</li>'); subcription = ''; } var checkDateSubscription = true; } if (self.eCommerceViewDetails.subscription && self.isEndDateSubscriptionChanged()) { if (self.eCommerceViewDetails.subscriptionEndDate === null) { self.errorMessages.push(subcription+'<li>End Date is mandatory.</li>'); subcription = ''; }else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.subscriptionEndDate, new Date())) { self.errorMessages.push(subcription+'<li>End Date must be greater than Current Date.</li>'); subcription = ''; } var checkDateSubscription = true; } if(checkDateSubscription){ if (self.eCommerceViewDetails.subscriptionStartDate !== null && self.eCommerceViewDetails.subscriptionEndDate !== null) { if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.subscriptionEndDate, self.eCommerceViewDetails.subscriptionStartDate)) { self.errorMessages.push(subcription+'<li>Start Date must be less than End Date.</li>'); } } } // } /* Validate Product Fullfilment Chanel. */ if (self.isProductFullfilmentChanelsChanged()) { self.validateFullfilmentChanelHeb(); } if (self.errorMessages.length > 0) { var errorMessagesAsString = ''; angular.forEach(self.errorMessages, function (errorMessage) { errorMessagesAsString += errorMessage; }); self.error = $sce.trustAsHtml('<ul style="text-align: left;">' + errorMessagesAsString + '</ul>'); return false; } return true; }; /** * Check start date is changed for show on site. * * @returns {boolean} true start date is changed or not. */ self.isStartDateShowOnSiteChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.showOnSiteStartDateOrg == null) { if (self.eCommerceViewDetails.showOnSiteStartDate != self.eCommerceViewDetails.showOnSiteStartDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteStartDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteStartDateOrg); if (oldDate !== newDate) { isChanged = true; }else{ if (self.eCommerceViewDetails.showOnSiteOrg != self.eCommerceViewDetails.showOnSite) { isChanged = true; } } } return isChanged; }; /** * Check end date is changed for show on site. * * @returns {boolean} true show on site is changed or not. */ self.isEndDateShowOnSiteChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.showOnSiteEndDateOrg == null) { if (self.eCommerceViewDetails.showOnSiteEndDate != self.eCommerceViewDetails.showOnSiteEndDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteEndDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteEndDateOrg); if (oldDate !== newDate) { isChanged = true; } else if (self.eCommerceViewDetails.showOnSiteOrg != self.eCommerceViewDetails.showOnSite) { isChanged = true; } } return isChanged; }; /** * Validate fullfilment chanel data for Heb. */ self.validateFullfilmentChanelHeb = function () { var errors = []; var displayOnlyItem = null; for (var i = 0; i < self.eCommerceViewDetails.productFullfilmentChanels.length; i++) { var check = false; if(self.checkEffectDateChanged(self.eCommerceViewDetails.productFullfilmentChanels[i])){ self.eCommerceViewDetails.productFullfilmentChanels[i].effectDateErrorCss = ''; self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDateErrorCss = ''; if (self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate == null) { if (errors.indexOf('<li>Effective Date is mandatory.</li>') == -1) { errors.push('<li>Effective Date is mandatory.</li>'); } self.eCommerceViewDetails.productFullfilmentChanels[i].effectDateErrorCss = RED; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate, new Date())) { if (errors.indexOf('<li>Effective Date must be greater than Current Date.</li>') == -1) { errors.push('<li>Effective Date must be greater than Current Date.</li>'); } self.eCommerceViewDetails.productFullfilmentChanels[i].effectDateErrorCss = RED; } check = true; } if(self.checkExpirationDateChanged(self.eCommerceViewDetails.productFullfilmentChanels[i])){ if (self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate == null) { if (errors.indexOf('<li>End Date is mandatory.</li>') === -1) { errors.push('<li>End Date is mandatory.</li>'); } self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDateErrorCss = RED; } else if (!self.isDate1GreaterThanDate2(self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate, new Date())) { if (errors.indexOf('<li>End Date must be greater than Current Date.</li>') == -1) { errors.push('<li>End Date must be greater than Current Date.</li>'); } self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDateErrorCss = RED; } check = true; } if(check){ if (self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate != null && self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate != null) { if (!self.isDate1GreaterThanOrEqualToDate2(self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate, self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate)) { if (errors.indexOf('<li>Effective Date must be less than or equal to End Date.</li>') == -1) { errors.push('<li>Effective Date must be less than or equal to End Date.</li>'); } self.eCommerceViewDetails.productFullfilmentChanels[i].effectDateErrorCss = RED; self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDateErrorCss = RED; } } } if(self.eCommerceViewDetails.productFullfilmentChanels[i].key !== null && self.eCommerceViewDetails.productFullfilmentChanels[i].key.fullfillmentChanelCode !== null && self.eCommerceViewDetails.productFullfilmentChanels[i].key.fullfillmentChanelCode.trim() === '03'){ displayOnlyItem = angular.copy(self.eCommerceViewDetails.productFullfilmentChanels[i]); } } if (errors.length == 0 && displayOnlyItem !== null) {//check display only rule angular.forEach(self.eCommerceViewDetails.productFullfilmentChanels, function(productFullfilmentChanel){ if(productFullfilmentChanel.key !== null && productFullfilmentChanel.key.fullfillmentChanelCode !== null && productFullfilmentChanel.key.fullfillmentChanelCode.trim() !== '03'){ var a = self.convertDateToStringWithYYYYMMDD(productFullfilmentChanel.effectDate); var b = self.convertDateToStringWithYYYYMMDD(displayOnlyItem.effectDate); var c = self.convertDateToStringWithYYYYMMDD(productFullfilmentChanel.expirationDate); var d = self.convertDateToStringWithYYYYMMDD(displayOnlyItem.expirationDate); if(a === b && c === d){ if (errors.indexOf('<li>Cannot set sellable and non-sellable with overlapping dates.</li>') === -1) { errors.push('<li>Cannot set sellable and non-sellable with overlapping dates.</li>'); } } } }); } if (errors.length > 0) { self.errorMessages.push('Fulfillment Program'); self.errorMessages = self.errorMessages.concat(errors); } }; /** * Check the data change for ProductFullfilmentChanels. * * @returns {boolean} true subscription is changed or not. */ self.checkEffectDateChanged = function (checkItem) { var isChanged = false; if (self.eCommerceViewDetails.productFullfilmentChanelsOrg == null) { isChanged = true; } else { var oldItem = self.getProductFullfilmentChanelOrg(checkItem); if (oldItem == null) { isChanged = true; }else{ if (checkItem.effectDate != null && oldItem.effectDate != null) { if (!self.isDate1EqualToDate2(checkItem.effectDate, oldItem.effectDate)) { isChanged = true; } } else { if (checkItem.effectDate != oldItem.effectDate) { isChanged = true; } } } } return isChanged; }; /** * Check the data change for ProductFullfilmentChanels. * * @returns {boolean} true subscription is changed or not. */ self.checkExpirationDateChanged = function (checkItem) { var isChanged = false; if (self.eCommerceViewDetails.productFullfilmentChanelsOrg == null) { isChanged = true; } else { var oldItem = self.getProductFullfilmentChanelOrg(checkItem); if (oldItem == null) { isChanged = true; }else{ if (checkItem.expirationDate != null && oldItem.expirationDate != null) { if (!self.isDate1EqualToDate2(checkItem.expirationDate, oldItem.expirationDate)) { isChanged = true; } } else { if (checkItem.expirationDate != oldItem.expirationDate) { isChanged = true; } } } } return isChanged; }; /** * Change the data change. * * @returns {boolean} */ self.isDataChanged = function () { var isChanged = false; self.eCommerceViewDetailsParams = {}; self.eCommerceViewDetailsParams.scanCodeId = self.productMaster.productPrimaryScanCodeId; self.eCommerceViewDetailsParams.productId = self.productMaster.prodId; // Romance Copy. self.eCommerceViewDetailsParams.attributeListChange = []; if (self.isNotEqualRomanceCopy(self.eCommerceViewDetails.romanceCopy, self.eCommerceViewDetails.romanceCopyOrg)) { //set data change self.eCommerceViewDetailsParams.romanceCopy = angular.copy(self.eCommerceViewDetails.romanceCopy); self.eCommerceViewDetailsParams.romanceCopy.logicAttributeId = self.LOG_ATTR_ID_ROMANCE_COPY; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_ROMANCE_COPY); isChanged = true; if (self.eCommerceViewDetailsParams.romanceCopy.htmlSave) { self.eCommerceViewDetailsParams.romanceCopy.content = angular.copy(self.eCommerceViewDetails.romanceCopy.htmlContent); } else { //format data changed with html tag (br, bullet) var contentHtml = $('#romanceCopyDiv').html(); contentHtml = contentHtml.split("<br>").join("<div>"); contentHtml = contentHtml.split("</p>").join("<div>"); var contentHtmlArray = contentHtml.split("<div>"); var contentNoneHtml = ''; if (contentHtmlArray.length > 1) { for (var i = 0; i < contentHtmlArray.length; i++) { if (contentHtmlArray[i] != null && contentHtmlArray[i] != '') { contentNoneHtml = contentNoneHtml.concat(self.htmlToPlaintext(contentHtmlArray[i])); if (i < (contentHtmlArray.length - 1)) { contentNoneHtml = contentNoneHtml.concat(" <br> "); } } } contentNoneHtml = contentNoneHtml.split("&nbsp;").join(" "); var escapeArray = contentNoneHtml.split(" "); var content = ''; for (var i = 0; i < escapeArray.length; i++) { if (escapeArray[i] != " " && escapeArray[i] != "<br>") { content = content.concat(self.encodeHTMLEntity(escapeArray[i])).concat(" "); } else { content = content.concat(escapeArray[i]).concat(" "); } } self.eCommerceViewDetailsParams.romanceCopy.content = self.removeBreakTag(content); } else if (contentHtmlArray.length == 1) { self.eCommerceViewDetailsParams.romanceCopy.content = self.removeBreakTag(self.encodeHTMLEntity(self.htmlToPlaintext(contentHtml))); } } } //Favor item description if(self.currentTab.id === FAVOR_TAB_ID) { if (self.isNotEqualRomanceCopy(self.eCommerceViewDetails.favorItemDescription, self.eCommerceViewDetails.favorItemDescriptionOrg)) { //set data change self.eCommerceViewDetailsParams.favorItemDescription = angular.copy(self.eCommerceViewDetails.favorItemDescription); self.eCommerceViewDetailsParams.favorItemDescription.logicAttributeId = self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION); isChanged = true; if (self.eCommerceViewDetailsParams.favorItemDescription.htmlSave) { self.eCommerceViewDetailsParams.favorItemDescription.content = angular.copy(self.eCommerceViewDetails.favorItemDescription.htmlContent); } else { //format data changed with html tag (br, bullet) var contentHtml = $('#favorItemDescriptionDiv').html(); contentHtml = contentHtml.split("<br>").join("<div>"); contentHtml = contentHtml.split("</p>").join("<div>"); var contentHtmlArray = contentHtml.split("<div>"); var contentNoneHtml = ''; if (contentHtmlArray.length > 1) { for (var i = 0; i < contentHtmlArray.length; i++) { if (contentHtmlArray[i] != null && contentHtmlArray[i] != '') { contentNoneHtml = contentNoneHtml.concat(self.htmlToPlaintext(contentHtmlArray[i])); if (i < (contentHtmlArray.length - 1)) { contentNoneHtml = contentNoneHtml.concat(" <br> "); } } } contentNoneHtml = contentNoneHtml.split("&nbsp;").join(" "); var escapeArray = contentNoneHtml.split(" "); var content = ''; for (var i = 0; i < escapeArray.length; i++) { if (escapeArray[i] != " " && escapeArray[i] != "<br>") { content = content.concat(self.encodeHTMLEntity(escapeArray[i])).concat(" "); } else { content = content.concat(escapeArray[i]).concat(" "); } } self.eCommerceViewDetailsParams.favorItemDescription.content = self.removeBreakTag(content); } else if (contentHtmlArray.length == 1) { self.eCommerceViewDetailsParams.favorItemDescription.content = self.removeBreakTag(self.encodeHTMLEntity(self.htmlToPlaintext(contentHtml))); } } } } // Brand if (self.isNotEqualBrandDisplayName(self.eCommerceViewDetails.brand, self.eCommerceViewDetails.brandOrg)) { self.eCommerceViewDetailsParams.brand = self.eCommerceViewDetails.brand; self.eCommerceViewDetailsParams.brand.logicAttributeId = self.LOG_ATTR_ID_BRAND; if (self.eCommerceViewDetails.brand.htmlSave) { self.eCommerceViewDetailsParams.brand.content = angular.copy(self.eCommerceViewDetails.brand.htmlContent); } self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_BRAND); isChanged = true; } if (self.isNotEqualBrandDisplayName(self.eCommerceViewDetails.displayName, self.eCommerceViewDetails.displayNameOrg)) { self.eCommerceViewDetailsParams.displayName = self.eCommerceViewDetails.displayName; self.eCommerceViewDetailsParams.displayName.content = self.encodeHTMLEntity(self.eCommerceViewDetailsParams.displayName.content); self.eCommerceViewDetailsParams.displayName.logicAttributeId = self.LOG_ATTR_ID_DISPLAY_NAME; if (self.eCommerceViewDetails.displayName.htmlSave) { self.eCommerceViewDetailsParams.displayName.content = angular.copy(self.eCommerceViewDetails.displayName.htmlContent); } self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_DISPLAY_NAME); isChanged = true; } if (self.isNotEqual(self.eCommerceViewDetails.size, self.eCommerceViewDetails.sizeOrg)) { self.eCommerceViewDetailsParams.size = self.eCommerceViewDetails.size; self.eCommerceViewDetailsParams.size.logicAttributeId = self.LOG_ATTR_ID_SIZE; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_SIZE); isChanged = true; } if (self.isNotEqual(self.eCommerceViewDetails.warnings, self.eCommerceViewDetails.warningsOrg)) { self.eCommerceViewDetailsParams.warnings = self.eCommerceViewDetails.warnings; self.eCommerceViewDetailsParams.warnings.logicAttributeId = self.LOG_ATTR_ID_WARNING; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_WARNING); isChanged = true; } if (self.isNotEqual(self.eCommerceViewDetails.directions, self.eCommerceViewDetails.directionsOrg)) { self.eCommerceViewDetailsParams.directions = self.eCommerceViewDetails.directions; self.eCommerceViewDetailsParams.directions.logicAttributeId = self.LOG_ATTR_ID_DIRECTION; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_DIRECTION); isChanged = true; } if (self.isEditingIngredient === true) { if (self.isNotEqual(self.eCommerceViewDetails.ingredients, self.eCommerceViewDetails.ingredientsOrg)) { self.eCommerceViewDetailsParams.ingredients = self.eCommerceViewDetails.ingredients; self.eCommerceViewDetailsParams.ingredients.logicAttributeId = self.LOG_ATTR_ID_INGREDIENT; self.eCommerceViewDetailsParams.ingredients.physicalAttributeId = self.PHY_ATTR_ID_INGREDIENT; self.eCommerceViewDetailsParams.attributeListChange.push(self.LOG_ATTR_ID_INGREDIENT); isChanged = true; } } var orgDescription = ''; var selectedDescription = ''; if (self.eCommerceViewDetails.pdpTemplateIdOrg != null && self.eCommerceViewDetails.pdpTemplateIdOrg !== undefined) { orgDescription = self.eCommerceViewDetails.pdpTemplateIdOrg; } if (self.eCommerceViewDetails.pdpTemplateId != null && self.eCommerceViewDetails.pdpTemplateId !== undefined) { selectedDescription = self.eCommerceViewDetails.pdpTemplateId; } if (orgDescription !== selectedDescription) { self.eCommerceViewDetailsParams.pdpTemplate = {content: selectedDescription}; isChanged = true; } if (self.isShowOnSiteChanged()) { self.eCommerceViewDetailsParams.showOnSite = self.eCommerceViewDetails.showOnSite; self.currentDate = self.convertDateToStringWithYYYYMMDD(new Date()); self.eCommerceViewDetailsParams.showOnSiteStartDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteStartDate); if (self.eCommerceViewDetailsParams.showOnSiteStartDate <= self.currentDate && !self.eCommerceViewDetailsParams.showOnSite) { self.eCommerceViewDetailsParams.showOnSiteEndDate = self.currentDate; } else { self.eCommerceViewDetailsParams.showOnSiteEndDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteEndDate); } self.eCommerceViewDetailsParams.salsChnlCd = self.getSalsChnlCd(); isChanged = true; } if (self.isSubscriptionChanged()) { self.eCommerceViewDetailsParams.subscription = self.eCommerceViewDetails.subscription; self.eCommerceViewDetailsParams.subscriptionStartDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionStartDate) self.eCommerceViewDetailsParams.subscriptionEndDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionEndDate); self.eCommerceViewDetailsParams.subscriptionChanged = true; /* Catch new subscription*/ self.newSubscription = { subscriptionStartDate: self.eCommerceViewDetailsParams.subscriptionStartDate, subscriptionEndDate: self.eCommerceViewDetailsParams.subscriptionEndDate, subscription: self.eCommerceViewDetailsParams.subscription } isChanged = true; } // Fullfilment if (self.isProductFullfilmentChanelsChanged()) { self.eCommerceViewDetailsParams.productFullfilmentChanels = []; var oldItem = null; var newItem = null; angular.forEach(self.eCommerceViewDetails.productFullfilmentChanels, function (item) { oldItem = self.getProductFullfilmentChanelOrg(item); newItem = angular.copy(item); if (oldItem === null) { // Add new item. newItem.actionCode = 'A'; newItem.effectDate = self.convertDateToStringWithYYYYMMDD(newItem.effectDate); newItem.expirationDate = self.convertDateToStringWithYYYYMMDD(newItem.expirationDate); delete newItem['lastUpdateTime']; self.eCommerceViewDetailsParams.productFullfilmentChanels.push(newItem); } else { if (!self.isDate1EqualToDate2(newItem.effectDate, oldItem.effectDate) || !self.isDate1EqualToDate2(newItem.expirationDate, oldItem.expirationDate)) { // Update item newItem.effectDate = self.convertDateToStringWithYYYYMMDD(newItem.effectDate); newItem.expirationDate = self.convertDateToStringWithYYYYMMDD(newItem.expirationDate); if (newItem.actionCode === null) { newItem.actionCode = ''; } delete newItem['lastUpdateTime']; self.eCommerceViewDetailsParams.productFullfilmentChanels.push(newItem); } } }); // Add Remove list of item. if (self.eCommerceViewDetails.productFullfilmentChanelsRemoveList !== null && (self.eCommerceViewDetails.productFullfilmentChanelsRemoveList instanceof Array) && self.eCommerceViewDetails.productFullfilmentChanelsRemoveList.length > 0) { angular.forEach(self.eCommerceViewDetails.productFullfilmentChanelsRemoveList, function (item) { item.effectDate = self.convertDateToStringWithYYYYMMDD(item.effectDate); item.expirationDate = self.convertDateToStringWithYYYYMMDD(item.expirationDate); delete item['lastUpdateTime']; self.eCommerceViewDetailsParams.productFullfilmentChanels.push(item); }); } isChanged = true; } else { self.eCommerceViewDetailsParams.productFullfilmentChanels = []; } // PanelType if (self.isPanelTypeChanged()) { self.eCommerceViewDetailsParams.nutriPanelTypCd = self.eCommerceViewDetails.panelType.panelTypeCode; isChanged = true; } return isChanged; }; /** * Get sale channel code. */ self.getSalsChnlCd = function () { var salsChnlCd = null; if (self.currentTab.saleChannel != null && self.currentTab.saleChannel !== undefined) { salsChnlCd = self.currentTab.saleChannel.id.trim(); } else { salsChnlCd = SAL_CHANNEL_HEB_COM; } return salsChnlCd; }; /** * Compare the content property of two objects. * * @param newObject the new object. * @param oldObject the old object. * @returns {boolean} true the content of two objects are not the same or the same. */ self.isNotEqual = function (newObject, oldObject) { if (newObject !== null && newObject !== undefined) { if (oldObject === null || oldObject === undefined) { return true; } if(newObject.content === undefined || oldObject.content === undefined){ return false; } if (newObject.content === oldObject.content) { // there is no data change. return false; } else { return true; } } return false; }; /** * Compare the content property of two objects. * * @param newObject the new object. * @param oldObject the old object. * @returns {boolean} true the content of two objects are not the same or the same. */ self.isNotEqualHasHTMLTab = function (newObject, oldObject) { if (newObject !== null && newObject !== undefined) { if (oldObject === null || oldObject === undefined) { return true; } if(newObject.content === undefined || oldObject.content === undefined){ return false; } if(newObject.htmlSave){ if (newObject.htmlContent === oldObject.htmlContent) { // there is no data change. return false; } else { return true; } }else{ if (newObject.content === oldObject.content) { // there is no data change. return false; } else { return true; } } } return false; }; /** * Compare the content property of two objects. * * @param newObject the new object. * @param oldObject the old object. * @returns {boolean} true the content of two objects are not the same or the same. */ self.isNotEqualRomanceCopy = function (newObject, oldObject) { if (newObject !== null && newObject !== undefined) { if (oldObject === null || oldObject === undefined) { return true; } if(newObject.content === undefined || oldObject.content === undefined){ return false; } if(newObject.htmlSave){ if (newObject.htmlContent === oldObject.htmlContent) { // there is no data change. return false; } else { return true; } }else{ var newText = $("<div/>").html(newObject.content).text(); var oldText = $("<div/>").html(oldObject.content).text(); newText = newText.split(/\s+/).join(" "); oldText = oldText.split(/\s+/).join(" "); if (newText === oldText) { // there is no data change. return false; } else { return true; } } } return false; }; /** * Compare the content property of two objects. * * @param newObject the new object. * @param oldObject the old object. * @returns {boolean} true the content of two objects are not the same or the same. */ self.isNotEqualBrandDisplayName = function (newObject, oldObject) { if (newObject !== null && newObject !== undefined) { if (oldObject === null || oldObject === undefined) { return true; } if(newObject.content === undefined || oldObject.content === undefined){ return false; } if(newObject.htmlSave){ if (newObject.htmlContent === oldObject.htmlContent) { return false; } else { return true; } }else{ if (newObject.content === oldObject.content) { return false; } else { var newText = $("<div/>").html(newObject.content).text(); var oldText = $("<div/>").html(oldObject.content).text(); newText = newText.split(/\s+/).join(" "); oldText = oldText.split(/\s+/).join(" "); if (newText === oldText) { return false; } else { return true; } } } } return false; }; /** * Compare the dat1 and date2 are the same or not. * * @param date1 the date. * @param date2 the date. * @returns {boolean} true if the date equal to date 2 or false. */ self.isDate1EqualToDate2 = function (date1, date2) { if ((new Date(self.convertDateToStringWithYYYYMMDD(date1)).getTime() == new Date(self.convertDateToStringWithYYYYMMDD(date2)).getTime())) { return true; } return false; }; /** * Compare the date is greater than date 2 or not. * * @param date1 the date. * @param date2 the date. * @returns {boolean} true if the date1 is greater than date 2 or false. */ self.isDate1GreaterThanDate2 = function (date1, date2) { if ((new Date(self.convertDateToStringWithYYYYMMDD(date1)).getTime() > new Date(self.convertDateToStringWithYYYYMMDD(date2)).getTime())) { return true; } return false; }; /** * Compare date1 greate than or equal to date2. * * @param date1 the date. * @param date2 the date. * @returns {boolean} true if the date is greater than or equal to the date 2. */ self.isDate1GreaterThanOrEqualToDate2 = function (date1, date2) { if ((new Date(self.convertDateToStringWithYYYYMMDD(date1)).getTime() >= new Date(self.convertDateToStringWithYYYYMMDD(date2)).getTime())) { return true; } return false; }; /** * Check the data change for subscription. * * @returns {boolean} true subscription is changed or not. */ self.isSubscriptionChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.subscriptionStartDate == null || self.eCommerceViewDetails.subscriptionEndDate == null) { if (self.eCommerceViewDetails.subscriptionStartDate != self.eCommerceViewDetails.subscriptionStartDateOrg) { isChanged = true; } else if (self.eCommerceViewDetails.subscriptionEndDate != self.eCommerceViewDetails.subscriptionEndDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionStartDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionStartDateOrg); if (oldDate !== newDate) { isChanged = true; } else { newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionEndDate); oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionEndDateOrg); if (oldDate !== newDate) { isChanged = true; } else if (self.eCommerceViewDetails.subscription != self.eCommerceViewDetails.subscriptionOrg) { isChanged = true; } } } return isChanged; }; /** * Check the data change for subscription. * * @returns {boolean} true subscription is changed or not. */ self.isStartDateSubscriptionChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.subscriptionStartDate == null) { if (self.eCommerceViewDetails.subscriptionStartDate != self.eCommerceViewDetails.subscriptionStartDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionStartDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionStartDateOrg); if (oldDate !== newDate) { isChanged = true; } else { if (self.eCommerceViewDetails.subscription != self.eCommerceViewDetails.subscriptionOrg) { isChanged = true; } } } return isChanged; }; /** * Check the data change for subscription. * * @returns {boolean} true subscription is changed or not. */ self.isEndDateSubscriptionChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.subscriptionEndDate == null) { if (self.eCommerceViewDetails.subscriptionEndDate != self.eCommerceViewDetails.subscriptionEndDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionEndDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.subscriptionEndDateOrg); if (oldDate !== newDate) { isChanged = true; } else if (self.eCommerceViewDetails.subscription != self.eCommerceViewDetails.subscriptionOrg) { isChanged = true; } } return isChanged; }; /** * Check the data change for show on site. * * @returns {boolean} true show on site is changed or not. */ self.isShowOnSiteChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.showOnSiteStartDateOrg == null || self.eCommerceViewDetails.showOnSiteEndDateOrg == null) { if (self.eCommerceViewDetails.showOnSiteStartDate != self.eCommerceViewDetails.showOnSiteStartDateOrg) { isChanged = true; } else if (self.eCommerceViewDetails.showOnSiteEndDate != self.eCommerceViewDetails.showOnSiteEndDateOrg) { isChanged = true; } } else { var newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteStartDate); var oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteStartDateOrg); if (oldDate !== newDate) { isChanged = true; } else { newDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteEndDate); oldDate = self.convertDateToStringWithYYYYMMDD(self.eCommerceViewDetails.showOnSiteEndDateOrg); if (oldDate !== newDate) { isChanged = true; } else if (self.eCommerceViewDetails.showOnSiteOrg != self.eCommerceViewDetails.showOnSite) { isChanged = true; } } } return isChanged; }; /** * Check the data change for ProductFullfilmentChanels. * * @returns {boolean} true subscription is changed or not. */ self.isProductFullfilmentChanelsChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.productFullfilmentChanelsOrg == null) { if (self.eCommerceViewDetails.productFullfilmentChanels != null) { isChanged = true; } } else { if (self.eCommerceViewDetails.productFullfilmentChanelsOrg.length != self.eCommerceViewDetails.productFullfilmentChanels.length) { isChanged = true; } else { var oldItem = null; for (var i = 0; i < self.eCommerceViewDetails.productFullfilmentChanels.length; i++) { oldItem = self.getProductFullfilmentChanelOrg(self.eCommerceViewDetails.productFullfilmentChanels[i]); if (oldItem == null) { isChanged = true; break; } if (self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate != null && oldItem.effectDate != null) { if (!self.isDate1EqualToDate2(self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate, oldItem.effectDate)) { isChanged = true; break; } } else { if (self.eCommerceViewDetails.productFullfilmentChanels[i].effectDate != oldItem.effectDate) { isChanged = true; break; } } if (self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate != null && oldItem.expirationDate != null) { if (!self.isDate1EqualToDate2(self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate, oldItem.expirationDate)) { isChanged = true; break; } } else { if (self.eCommerceViewDetails.productFullfilmentChanels[i].expirationDate != oldItem.expirationDate) { isChanged = true; break; } } } } } return isChanged; }; /** * Get ProductFullfilmentChanel from ProductFullfilmentChanel Orginal. * * @param newProductFullfilmentChanel the new ProductFullfilmentChanel. * @returns {*} */ self.getProductFullfilmentChanelOrg = function (newProductFullfilmentChanel) { if (newProductFullfilmentChanel.key != null) { if (newProductFullfilmentChanel.key.fullfillmentChanelCode != null && newProductFullfilmentChanel.key.fullfillmentChanelCode.trim().length > 0) { var item = null; for (var i = 0; i < self.eCommerceViewDetails.productFullfilmentChanelsOrg.length; i++) { item = self.eCommerceViewDetails.productFullfilmentChanelsOrg[i]; if (item.key != null && item.key.fullfillmentChanelCode != null && item.key.fullfillmentChanelCode.trim() === newProductFullfilmentChanel.key.fullfillmentChanelCode.trim()) { return item; } } } } return null; }; /** * Check the panel type is changed or not. * * @returns {boolean} */ self.isPanelTypeChanged = function () { var isChanged = false; if (self.eCommerceViewDetails.panelTypeOrg != null) { if (self.eCommerceViewDetails.panelType == null || self.eCommerceViewDetails.panelType === undefined) { isChanged = true; } else if (self.eCommerceViewDetails.panelType.panelTypeCode != self.eCommerceViewDetails.panelTypeOrg.panelTypeCode) { isChanged = true; } } return isChanged; } self.stopWaitingLoading = function (status) { self.isWaitingForResponse = status; }; /** * Convert the date to string with format: yyyy-MM-dd. * @param date the date object. * @returns {*} string */ self.convertDateToStringWithYYYYMMDD = function (date) { return $filter('date')(date, 'yyyy-MM-dd'); }; /** * Reset data. It will be called when click on reset button. */ self.reset = function () { $rootScope.contentChangedFlag = false; self.htmlMode = false; self.error = ''; self.success = ''; self.eCommerceViewDetails.endDateErrorMgs = ''; self.eCommerceViewDetails.isEndDateErrorMgs = false; self.eCommerceViewDetails.startDateErrorMgs = ''; self.eCommerceViewDetails.isStartDateErrorMgs = false; self.eCommerceViewDetails.romanceCopy = angular.copy(self.eCommerceViewDetails.romanceCopyOrg); self.eCommerceViewDetails.favorItemDescription = angular.copy(self.eCommerceViewDetails.favorItemDescriptionOrg); self.eCommerceViewDetails.pdpTemplateId = angular.copy(self.eCommerceViewDetails.pdpTemplateIdOrg); self.eCommerceViewDetails.subscriptionStartDate = angular.copy(self.eCommerceViewDetails.subscriptionStartDateOrg); self.eCommerceViewDetails.subscriptionEndDate = angular.copy(self.eCommerceViewDetails.subscriptionEndDateOrg); self.eCommerceViewDetails.subscription = angular.copy(self.eCommerceViewDetails.subscriptionOrg); self.eCommerceViewDetails.brand = angular.copy(self.eCommerceViewDetails.brandOrg); self.eCommerceViewDetails.displayName = angular.copy(self.eCommerceViewDetails.displayNameOrg); self.eCommerceViewDetails.size = angular.copy(self.eCommerceViewDetails.sizeOrg); self.eCommerceViewDetails.warnings = angular.copy(self.eCommerceViewDetails.warningsOrg); self.eCommerceViewDetails.directions = angular.copy(self.eCommerceViewDetails.directionsOrg); self.eCommerceViewDetails.ingredients = angular.copy(self.eCommerceViewDetails.ingredientsOrg); self.eCommerceViewDetails.showOnSite = angular.copy(self.eCommerceViewDetails.showOnSiteOrg); self.resetShowOnsite(); self.eCommerceViewDetails.fulfillmentChannels = angular.copy(self.eCommerceViewDetails.fulfillmentChannelsOrg); self.eCommerceViewDetails.productFullfilmentChanels = angular.copy(self.eCommerceViewDetails.productFullfilmentChanelsOrg); self.eCommerceViewDetails.panelType = angular.copy(self.eCommerceViewDetails.panelTypeOrg); self.eCommerceViewDetails.productFullfilmentChanelsRemoveList = []; self.eCommerceViewDetails.currentProductFulfillment = null; self.validateWarning(); self.resetEcommerceView(); }; /** * Reset start date and end date. */ self.resetShowOnsite = function () { if (self.eCommerceViewDetails.showOnSiteEndDateOrg !== undefined && self.eCommerceViewDetails.showOnSiteEndDateOrg !== null) { self.eCommerceViewDetails.showOnSiteEndDate = new Date(self.eCommerceViewDetails.showOnSiteEndDateOrg.replace(/-/g, '\/')); } else { self.eCommerceViewDetails.showOnSiteEndDate = null; } if (self.eCommerceViewDetails.showOnSiteStartDateOrg !== undefined && self.eCommerceViewDetails.showOnSiteStartDateOrg !== null) { self.eCommerceViewDetails.showOnSiteStartDate = new Date(self.eCommerceViewDetails.showOnSiteStartDateOrg.replace(/-/g, '\/')); } else { self.eCommerceViewDetails.showOnSiteStartDate = null; } } /** * Reset status of ecommerce view components. It will be called when click on reset button. */ self.resetEcommerceView = function () { $rootScope.$broadcast(self.RESET_ECOMMERCE_VIEW); }; /** * Update new date to original object. It will be called after save success to reload the data for eCommerce View. */ self.updateNewDataToOriginalObject = function () { self.eCommerceViewDetails={}; self.resetEcommerceView(); $rootScope.$broadcast(self.RELOAD_ECOMMERCE_VIEW); }; /** * Reload ECommerceView. Listen reload ECommerce View event. */ $scope.$on(self.RELOAD_ECOMMERCE_VIEW, function () { self.loadDataInit(); }); /** * This method will be called when the publish button clicked. * It will show publish confirmation, if the data is valid or show the invalid data. */ self.publish = function () { self.callbackfunctionAfterSpellCheck = null; self.error = ''; self.success = ''; var countPrimaryPath = 0; if (self.eCommerceViewDetails.customerHierarchyPrimaryPaths != null) { countPrimaryPath = self.eCommerceViewDetails.customerHierarchyPrimaryPaths.length; } if (self.isValidatePublishData() && countPrimaryPath == 1) { self.confirmTitle = 'Publish Confirmation'; self.confirmMessage = 'Are you sure you want to publish the selected Product?'; $('#confirmPublishModal').modal({backdrop: 'static', keyboard: true}); } else if(!self.isValidatePublishData()){ self.error = 'Product can not be published as mandatory field(s) are not entered.'; } else if(countPrimaryPath > 1){ self.error = 'Only one Hierarchy can be Primary.'; } self.validateWarning(); }; /** * This method will be called when click on yes button of publish confirmation modal to call the method to publish. */ self.agreePublish = function () { $('#confirmPublishModal').modal("hide"); self.publishForHeb(); }; /** * This method is used to publish data for heb. */ self.publishForHeb = function () { self.isRequestPublishAfterSave = false; // Check the data change. if (self.isDataChanged()) { /* validate data change to save. */ if (self.validateDataChanged()) { self.isRequestPublishAfterSave = true; /* Save data. */ self.updateECommerceViewInformation(); } } else { // check fulfillment. self.checkFulfillment(); } }; /** * Request to the server to publish. */ self.doPublish = function () { var eCommerceViewDetailsParams = { productId: self.productMaster.prodId, scanCodeId: self.productMaster.productPrimaryScanCodeId, alertId: taskService.getAlertId() }; if (self.currentTab.saleChannel != null && self.currentTab.saleChannel !== undefined) { // Set channel code for another tab. eCommerceViewDetailsParams.salsChnlCd = self.currentTab.saleChannel.id.trim(); } else { eCommerceViewDetailsParams.salsChnlCd = SAL_CHANNEL_HEB_COM; } /* Call the service to publish. */ eCommerceViewApi.publishECommerceViewDataToHebCom(eCommerceViewDetailsParams, function (results) { /* Publish success. */ self.error = ''; self.success = results.message; self.isWaitingForResponse = false; if (productSearchService.getFromPage() == appConstants.HOME) {//navigate to next productId if (self.isLastProduct()) { self.updateNewDataToOriginalObject(); } else { $rootScope.$broadcast(NEXT_PRODUCT); } } else { $rootScope.$broadcast(self.RELOAD_ECOMMERCE_VIEW); setTimeout(function () { if(self.isLastProduct()){ $rootScope.$broadcast("reloadPreviousPageAfterPublish"); }else { $rootScope.$broadcast("reloadCurrentPageAfterPublish"); } }, 2000); } } , self.fetchError ); }; /** * Check fulfillment. */ self.checkFulfillment = function () { self.isWaitingForResponse = true; eCommerceViewApi.checkFulfillment({productId: self.productMaster.prodId}, function (results) { if (results.data == true && self.isValidatePublishData()) { // publish after check fulfillment success. self.doPublish(); } else { self.isWaitingForResponse = false; if (results.data == false && !self.isValidatePublishData()) { self.error = 'Product can not be published as mandatory fields are not entered, fulfillment channel is not set.'; } else if (results.data == false) { self.error = 'Product can not be published as fulfillment channel is not set.'; } else { self.error = 'Product can not be published as mandatory field(s) are not entered.'; } } self.validateWarning(); } , self.fetchError ); }; /** * Validate the data for publish. * @returns {boolean} */ self.isValidatePublishData = function () { if (self.eCommerceViewDetails.size == null || self.eCommerceViewDetails.size == undefined) { return false; } else if (self.eCommerceViewDetails.size.mandatory !== undefined && self.eCommerceViewDetails.size.mandatory !== null && self.eCommerceViewDetails.size.mandatory) { return false; } if (self.eCommerceViewDetails.brand == null || self.eCommerceViewDetails.brand == undefined ) { return false; } else if (self.eCommerceViewDetails.brand.mandatory !== undefined && self.eCommerceViewDetails.brand.mandatory !== null && self.eCommerceViewDetails.brand.mandatory) { return false; } if (self.eCommerceViewDetails.displayName == null || self.eCommerceViewDetails.displayName == undefined) { return false; } else if (self.eCommerceViewDetails.displayName.mandatory !== undefined && self.eCommerceViewDetails.displayName.mandatory !== null && self.eCommerceViewDetails.displayName.mandatory) { return false; } if (self.isEmpty(self.eCommerceViewDetails.customerHierarchyPrimaryPath)) { return false; } // Ignore check image mandatory if (self.currentTab.id != FAVOR_TAB_ID) { if (self.isEmpty(self.eCommerceViewDetails.imagePrimary)) { return false; } if (self.eCommerceViewDetails.romanceCopy === null || self.eCommerceViewDetails.romanceCopy === undefined) { return false; } else if (self.eCommerceViewDetails.romanceCopy.mandatory !== undefined && self.eCommerceViewDetails.romanceCopy.mandatory !== null && self.eCommerceViewDetails.romanceCopy.mandatory) { return false; } } return true; }; /** * Check empty value. * * @param val * @returns {boolean} */ self.isEmpty = function(val){ if (val == null || val == undefined || val.trim().length == 0) { return true; } return false; }; /** * Validate and show warning message. */ self.validateWarning = function(){ $rootScope.$broadcast(self.VALIDATE_WARNING); }; /** * Clear message. */ self.clearMessage = function(){ self.error = ''; self.success=''; }; /** * Clear message listener. */ $scope.$on(self.CLEAR_MESSAGE, function() { self.clearMessage(); }); /** * Handle get information data source basing on product, attribute, sales channel, product primary scan * code. Return the group information include master data extension, attribute priority...ect */ self.getECommerceViewDataSource = function (productId, scanCodeId, attributeId, salesChannel, headerTitle, typeSource) { self.errorPopup = ''; self.dataSourceTitle = headerTitle; self.isWaitingForResponsePopup = true; self.currentAttributeId = attributeId; self.isEBM = self.isEBMByAttributeId(attributeId); self.htmlMode = false; $('#dataSourceModalType1').modal({backdrop: 'static', keyboard: true}); eCommerceViewApi.getECommerceViewDataSource({ productId: productId, scanCodeId: scanCodeId, attributeId: attributeId, salesChannel: salesChannel }, self.dataSourceResponseSuccess, self.fetchErrorPopup ); }; /** * Response success. Store and handle show data source. * @param result */ self.dataSourceResponseSuccess = function (result) { //handle data to showing self.isWaitingForResponsePopup = false; self.eCommerceViewAttributePriority = angular.copy(result); self.eCommerceViewAttributePriorityOrg = angular.copy(result); self.checkSelectedAt = 0; self.checkSourceEditableAt = 0; self.initDataForReadMoreAndReadLess(); if(self.isEditText == true){ if(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails != null){ for (var i =0; i<self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails.length; i++) { if (self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].selected) { self.checkSelectedAt = i+1; } if (self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].sourceEditable) { self.checkSourceEditableAt = i+1; } } if(self.checkSourceEditableAt > 0 ){ self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[self.checkSelectedAt-1].selected = false; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[self.checkSourceEditableAt-1].selected = true; } } self.isEditText = false; } if(self.eCommerceViewAttributePriority.attributeId === self.LOG_ATTR_ID_SIZE || self.eCommerceViewAttributePriority.attributeId === self.LOG_ATTR_ID_ROMANCE_COPY){ self.getECommerceViewPriorityDetailsByEditableSource(); } self.validateSpellCheckForView(); }; /** * Init data for read more and read less */ self.initDataForReadMoreAndReadLess = function () { for (var i =0; i<self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails.length; i++) { self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].numLimit = self.MIN_LENGTH_READ; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadMore = true; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadLess = false; } }; /** * Read more */ self.readMore = function (eCommerceViewAttributePriorityDetail) { for (var i = 0; i < self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails.length; i++) { if(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i] === eCommerceViewAttributePriorityDetail){ self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].numLimit = eCommerceViewAttributePriorityDetail.length; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadMore = false; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadLess = true; break; } } }; /** * Read less */ self.readLess = function (eCommerceViewAttributePriorityDetail) { for (var i = 0; i < self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails.length; i++) { if(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i] === eCommerceViewAttributePriorityDetail){ self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].numLimit = self.MIN_LENGTH_READ; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadLess = false; self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].isReadMore = true; break; } } }; /** * Show value for radio button data source selected. * @param selected * @returns {*} */ self.valueSourceSelectedRadioButton = function (selected) { if(selected){ return selected; } return !selected; }; /** * Handle change data source selected. * @param index */ self.dataSourceSelectedChangedHandle = function (index) { if(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails != null){ for (var i =0; i<self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails.length; i++){ if(i != index){ self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails[i].selected = false; } } } }; /** * Handle update information data source */ self.saveDataAttributePriorities = function () { self.callbackfunctionAfterSpellCheck = null; self.errorPopup = ''; self.error = ''; self.success = ''; if(angular.toJson(self.eCommerceViewAttributePriority) != angular.toJson(self.eCommerceViewAttributePriorityOrg)){ self.eCommerceViewAttributePriority.productId = self.productMaster.prodId; self.eCommerceViewAttributePriority.primaryScanCode = self.productMaster.productPrimaryScanCodeId; self.eCommerceViewAttributePriority.attributeId = self.currentAttributeId; //correct html text for romance copy attribute if(self.currentAttributeId == 1666 || self.currentAttributeId == 1664 || self.currentAttributeId == 1672 || self.currentAttributeId == self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION){ if(self.eCommerceViewAttributePriority != null && self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails != null){ angular.forEach(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails, function(eCommerceViewPriorityDetails){ if(eCommerceViewPriorityDetails != null && eCommerceViewPriorityDetails.sourceEditable === true){ if(self.htmlMode){ if(eCommerceViewPriorityDetails.htmlContent != null && eCommerceViewPriorityDetails.htmlContent.content != null){ eCommerceViewPriorityDetails.content.content = angular.copy(eCommerceViewPriorityDetails.htmlContent.content); } }else{ if(eCommerceViewPriorityDetails.content != null && eCommerceViewPriorityDetails.content.content != null){ if(self.currentAttributeId == 1666 || self.currentAttributeId == self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION){ //correct html format before save for romance copy attribute //format data changed with html tag (br, bullet) var contentHtml = $('#romanceCopyPopupDiv').html(); contentHtml = contentHtml.split("<br>").join("<div>"); contentHtml = contentHtml.split("</p>").join("<div>"); var contentHtmlArray = contentHtml.split("<div>"); var contentNoneHtml = ''; if(contentHtmlArray.length > 1) { for (var i = 0; i < contentHtmlArray.length; i++) { if(contentHtmlArray[i] != null && contentHtmlArray[i] != ''){ contentNoneHtml = contentNoneHtml.concat(self.htmlToPlaintext(contentHtmlArray[i])); if(i < (contentHtmlArray.length - 1)){ contentNoneHtml = contentNoneHtml.concat(" <br> "); } } } contentNoneHtml = contentNoneHtml.split("&nbsp;").join(" "); var escapeArray = contentNoneHtml.split(" "); var content = ''; for (var i = 0; i < escapeArray.length; i++) { if(escapeArray[i] != " " && escapeArray[i] != "<br>"){ content = content.concat(self.encodeHTMLEntity(escapeArray[i])).concat(" "); }else{ content = content.concat(escapeArray[i]).concat(" "); } } eCommerceViewPriorityDetails.content.content = self.removeBreakTag(content); }else if(contentHtmlArray.length == 1) { eCommerceViewPriorityDetails.content.content = self.removeBreakTag(self.encodeHTMLEntity(self.htmlToPlaintext(contentHtml))); } }else { eCommerceViewPriorityDetails.content.content = self.encodeHTMLEntity(eCommerceViewPriorityDetails.content.content); } } } } }); } } //handle update information eCommerceViewApi.updateECommerceViewDataSource( self.eCommerceViewAttributePriority, self.dataSourceUpdateResponseSuccess, self.fetchError ); $rootScope.$broadcast(self.RELOAD_AFTER_SAVE_POPUP, self.currentAttributeId, false); } $('#dataSourceModalType1').modal("hide"); }; /** * Encode data to HTML entity. * @param data */ self.encodeHTMLEntity = function (data) { //useNamedReferences => encode by name //allowUnsafeSymbols => (&, <, >, ", ', and `) will be ignored, only non-ASCII characters will be encoded. var returnString = he.encode(data, {'useNamedReferences': true, 'allowUnsafeSymbols': true}); //fix like old PM app returnString = returnString.replace(/&middot;/g, "&bull;"); returnString = returnString.replace(/&#x2011;/g, " "); returnString = returnString.replace(/"/g, "&quot;"); return returnString; }; /** * Response success. Store and handle show data source. * @param result */ self.dataSourceUpdateResponseSuccess = function (result) { self.isWaitingForResponse = false; self.error = ''; switch (self.currentAttributeId) { case self.LOG_ATTR_ID_ROMANCE_COPY: self.success = "Romance copy: "+result.message; break; case self.LOG_ATTR_ID_BRAND: self.success = "Brand: "+result.message; break; case self.LOG_ATTR_ID_SIZE: self.success = "Size: "+result.message; break; case self.LOG_ATTR_ID_DIRECTION: self.success = "Direction: "+result.message; break; case self.LOG_ATTR_ID_WARNING: self.success = "Warning: "+result.message; break; case self.LOG_ATTR_ID_TAG: self.success = "Tag: "+result.message; break; case self.LOG_ATTR_ID_DISPLAY_NAME: self.success = "Display name: "+result.message; break; case self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION: self.success = "Favor Item Description: "+result.message; break; default: break; } $rootScope.$broadcast(self.RELOAD_AFTER_SAVE_POPUP, self.currentAttributeId, true); }; /** * Handle reset information data source */ self.resetDataAttributePriorities = function () { self.errorPopup = ''; self.eCommerceViewAttributePriority = angular.copy(self.eCommerceViewAttributePriorityOrg); self.validateSpellCheckForView(); }; /** * Callback for when the backend returns an error. * * @param error The error from the backend. */ self.fetchErrorPopup= function (error) { self.isWaitingForResponse = false; if (error && error.data) { if (error.data.message) { self.errorPopup = (error.data.message); } else if (error.data.error) { self.errorPopup = (error.data.error); } else { self.errorPopup = error; } } else { self.errorPopup = "An unknown error occurred."; } }; /** * Check the current tab is google or not. * * @returns {boolean} true if current is google. */ self.isGoogleTab = function(){ if(self.currentTab.saleChannel != null && self.currentTab.saleChannel !== undefined){ // Set channel code for another tab. if(self.currentTab.saleChannel.id.trim() == '05'){ return true; } } return false; }; /** * Set spell check is working or not. * * @returns {boolean} true or false. */ self.changeSpellCheckStatus = function(status){ self.isSpellCheck = false; /// fix bugs App still shows warning pop-up when the user has clicked the Save button. if(status){ self.isSpellCheck = true; $rootScope.contentChangedFlag = false; if (self.isDataChanged()) { $rootScope.contentChangedFlag = true; } } }; /** * Get attribute mapping information. * @param attributeId */ self.findAttributeMappingByLogicalAttribute = function (attributeId) { self.isWaitingForResponsePopupAttr = true; $('#attributeMapping').modal({backdrop: 'static', keyboard: true}); eCommerceViewApi.findAttributeMappingByLogicalAttribute( { attributeId:attributeId }, //success function (results) { self.isWaitingForResponsePopupAttr = false; self.attributeMappingDataProvider = angular.copy(results); }, function (error) { self.isWaitingForResponsePopupAttr = false; if (error && error.data) { if (error.data.message) { self.errorPopupAttr = (error.data.message); } else if (error.data.error) { self.errorPopupAttr = (error.data.error); } else { self.errorPopupAttr = error; } } else { self.errorPopupAttr = "An unknown error occurred."; } } ); }; /** Allow show multi modal the same time wwith stack**/ $('.modal').on('show.bs.modal', function (event) { var zIndex = 1040 + (10 * $('.modal:visible').length); $(this).css('z-index', zIndex); setTimeout(function() { $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'); }, 0); }); /** * validate text for edit mode. */ self.checkErrors = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse= true; vocabularyService.validateRomancyTextForView(eCommerceViewPriorityDetails.content.content , function (newText, suggestions) { // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = angular.copy(newText); $timeout(function () { vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 1000); }, 100); }); } }; /** * Get eCommerceViewPriorityDetails object from edit source. * @returns {*} */ self.getECommerceViewPriorityDetailsByEditableSource = function(){ var result = null; angular.forEach(self.eCommerceViewAttributePriority.eCommerceViewAttributePriorityDetails, function(eCommerceViewPriorityDetails){ if(result == null && eCommerceViewPriorityDetails.sourceEditable === true){ if((angular.equals(eCommerceViewPriorityDetails.content.content, EMPTY) || eCommerceViewPriorityDetails.content.content === null) && self.eCommerceViewAttributePriority.masterDataExtensionAttribute !== null) { eCommerceViewPriorityDetails.content.content = angular.copy(self.eCommerceViewAttributePriority.masterDataExtensionAttribute.attributeValueText); if(self.eCommerceViewAttributePriority.attributeId !== self.LOG_ATTR_ID_SIZE ){ eCommerceViewPriorityDetails.htmlContent.content = angular.copy(self.eCommerceViewAttributePriority.masterDataExtensionAttribute.attributeValueText); } } result = eCommerceViewPriorityDetails; } }); return result; }; /** * The (select for heb com) button is disable or not. * @param eCommerceViewPriorityDetails the eCommerceViewPriorityDetails */ self.isDisableSelectForHebComButton = function(eCommerceViewPriorityDetails){ if(!self.htmlMode){ if(self.isWaitingForCheckSpellingResponse || self.isWaitingForResponsePopup || (eCommerceViewPriorityDetails.sourceEditable && eCommerceViewPriorityDetails.selected && angular.equals( eCommerceViewPriorityDetails.content.content , EMPTY))){ self.isDisableHebComButton = true; }else { self.isDisableHebComButton = false; } }else{ } }; /** * Error message listener. */ $scope.$on('error_message', function(event, data) { self.error = data.error; }); /** * Validate spell check. */ self.isSpellCheckAttributeId = function(){ var check = false; if(self.LOG_ATTR_ID_ROMANCE_COPY == self.eCommerceViewAttributePriority.attributeId || self.LOG_ATTR_ID_BRAND == self.eCommerceViewAttributePriority.attributeId || self.LOG_ATTR_ID_DISPLAY_NAME == self.eCommerceViewAttributePriority.attributeId || self.LOG_ATTR_ID_FAVOR_ITEM_DESCRIPTION == self.eCommerceViewAttributePriority.attributeId){ check = true; } return check; }; /** * handle when click on return to list button */ self.returnToList = function(){ $rootScope.$broadcast('returnToListEvent'); }; /** * call the search component to search product automatically */ self.searchAutomaticCustomHierarchy = function(){ $rootScope.$broadcast('searchAutomaticCustomHierarchy'); }; /** * call the search component to search product automatically */ self.searchAutomaticCustomHierarchy = function(){ $rootScope.$broadcast('searchAutomaticCustomHierarchy'); } /** * Validate spell check. */ self.validateSpellCheck = function(){ if(self.htmlTabPressing){ self.htmlTabPressing = false; return; } //validation spellcheck $timeout(function () { if(self.eCommerceViewAttributePriority.attributeId == self.LOG_ATTR_ID_BRAND){ self.validateBrandTextForEdit(); } /*if(self.eCommerceViewAttributePriority.attributeId == self.LOG_ATTR_ID_DISPLAY_NAME){ if(!self.clickOnAaOrResetButton) { self.validateDisplayNameTextForEdit(); } self.clickOnAaOrResetButton = false; }*/ }, 200); }; /** * Validate spell check of Romance Copy. */ self.validateSpellCheckRomanceCopy = function(){ if(self.htmlTabPressing){ self.htmlTabPressing = false; return; } if(!self.openRomanceSuggestionsPopup){ self.validateRomanceCopyTextForEdit(); } }; /** * Disable validate spell check of Romance Copy when open suggestions popup. */ $scope.$on('context-menu-opened', function (event, args) { self.openRomanceSuggestionsPopup = true; }); /** * Enable validate spell check of Romance Copy when close suggestions popup. */ $scope.$on('context-menu-closed', function (event, args) { self.openRomanceSuggestionsPopup = false; }); /** * Validate spell check. */ self.validateSpellCheckForView = function(){ //validation spellcheck if(self.eCommerceViewAttributePriority.attributeId == self.LOG_ATTR_ID_BRAND){ self.validateBrandTextForView(); } if(self.eCommerceViewAttributePriority.attributeId == self.LOG_ATTR_ID_DISPLAY_NAME){ self.validateDisplayNameTextForView(); } }; /** * Validate camel case of display name. */ self.doValidateCamelCaseDisplayName = function(){ if(self.eCommerceViewAttributePriority.attributeId == self.LOG_ATTR_ID_DISPLAY_NAME){ self.clickOnAaOrResetButton = true; self.validateCamelCaseDisplayName(); } }; /** * Validate text for view mode of brand. It will call after loaded romance description. */ self.validateBrandTextForView = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateBrandTextForView(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 100); }); } }; /** * Validate text for view mode of display name. It will call after loaded display name. */ self.validateDisplayNameTextForView = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateDisplayNameTextForView(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 100); }); } }; /** * validate text for edit mode of brand. */ self.validateBrandTextForEdit = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateBrandTextForEdit(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 100); }); } }; /** * validate text for edit mode of display name. */ self.validateDisplayNameTextForEdit = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateDisplayNameTextForEdit(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 100); }); } }; /** * validate text for edit mode of display name. */ self.validateCamelCaseDisplayNameOldWay = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateCamelCaseDisplayNameOldWay(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 100); }); } }; self.validateCamelCaseDisplayName = function(){ //if(!self.openSuggestionsPopup){//avoid conflict with suggestion popup var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateCamelCaseDisplayName(eCommerceViewPriorityDetails.content.content, function(newText, suggestions){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = angular.copy(newText); $timeout(function () { vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 1000); }, 100); }); } //} }; /** * Validate text for edit mode of romance copy. */ self.validateRomanceCopyTextForEdit = function(){ var eCommerceViewPriorityDetails = self.getECommerceViewPriorityDetailsByEditableSource(); if(eCommerceViewPriorityDetails != null && !self.isEmpty(eCommerceViewPriorityDetails.content.content)) { var callbackFunction = self.getAfterSpellCheckCallback(); var contentHtml = $('#romanceCopyPopupDiv').html(); contentHtml = contentHtml.split("<br>").join("<div>"); contentHtml = contentHtml.split("</p>").join("<div>"); var contentHtmlArray = contentHtml.split("<div>"); var contentNoneHtml = ''; if(contentHtmlArray.length > 1) { for (var i = 0; i < contentHtmlArray.length; i++) { if(contentHtmlArray[i] != null && contentHtmlArray[i] != ''){ contentNoneHtml = contentNoneHtml.concat(self.htmlToPlaintext(contentHtmlArray[i])); if(i < (contentHtmlArray.length - 1)){ contentNoneHtml = contentNoneHtml.concat(" <br> "); } } } eCommerceViewPriorityDetails.content.content = contentNoneHtml.split("&nbsp;").join(" "); } self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateRomancyTextForEdit(eCommerceViewPriorityDetails.content.content, function(newText){ // Use $timeout and space char to clear cache on layout. eCommerceViewPriorityDetails.content.content = eCommerceViewPriorityDetails.content.content + ' '; $timeout(function () { eCommerceViewPriorityDetails.content.content = newText; //vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; $timeout(function () { // Save or publish if event occurs from save or publish button. self.processAfterSpellCheck(callbackFunction); }, 500); }, 100); }); } }; /** * Handle yes button of confirmation modal. */ self.yesConfirmModal = function(){ //save data self.save(); }; /** * Handle no button of confirmation modal. */ self.noConfirmModal = function(){ if(self.nextTab !== null){//move to next tab self.success = null; $scope.active = self.nextTab; } }; /** * Handle cancel button of confirmation modal. */ self.cancelConfirmModal = function(){ //do nothing self.nextTab = null; self.success = null; self.error = null; }; /** * Change tab handle. Set current tab value. * @param tab */ self.tabSelected = function (tab) { self.eCommerceViewDetails.errorMessages = null; self.eCommerceViewDetails.romanceCopyErrorMessages = null; self.nextTab = null; self.currentTab = tab; self.error = ''; }; /** * Handle event when tab is deactivated. */ self.tabDeselect = function ($event, $selectedIndex) { if(permissionsService.getPermissions("PD_ECOM_01", "EDIT")){ var isChanged = false; if (self.isDataChanged()) { isChanged = true; $rootScope.contentChangedFlag = true; } if(isChanged){//data is changed if($event){ $event.preventDefault(); self.nextTab = $selectedIndex;//save next tab $('#ecommerceViewConfirmationModal').modal("show"); } }else{ //do nothing self.nextTab = null; self.success = null; } } }; /** * Remove all tag html * @param text * @returns {string} */ self.htmlToPlaintext = function(text) { return text ? String(text).replace(/<[^>]+>/gm, '') : ''; }; /** * Prepare callback function for save after spell check is success. */ self.savePressing = function(){ self.callbackfunctionAfterSpellCheck = self.save; }; /** * Prepare callback function for save after spell check is success. */ self.publishPressing = function(){ self.callbackfunctionAfterSpellCheck = self.publish; }; /** * Prepare callback function for save after spell check is success. */ self.saveHebComPressing = function(){ self.callbackfunctionAfterSpellCheck = self.saveDataAttributePriorities; }; /** * Returns the function to do (save or publish) after spell check success. * @return {null} */ self.getAfterSpellCheckCallback = function(){ var callbackFunction = self.callbackfunctionAfterSpellCheck; self.callbackfunctionAfterSpellCheck = null; return callbackFunction; }; /** * Call the function for save or publish after spell check is success. * @param callback */ self.processAfterSpellCheck = function(callback){ if(callback != null && callback !== undefined){ callback(); } }; self.isEBMByAttributeId = function(attributeId){ if(attributeId == self.LOG_ATTR_ID_WARNING){ // warning return permissionsService.getPermissions('PD_ECOM_05', 'EDIT'); }else if(attributeId == self.LOG_ATTR_ID_DIRECTION){ // directions return permissionsService.getPermissions('PD_ECOM_04', 'EDIT'); } return true; }; /** * Set type of text for romance copy field * @param htmlFormat */ self.changeHTMLMode = function (htmlMode) { self.htmlMode = htmlMode; self.htmlTabPressing = false; }; /** * Prepare callback function for after spell check is success. */ self.htmlTabClick = function(){ self.htmlTabPressing = true; }; /** * Remove "<br>" tag at the end of string. * @param string * @returns {string} */ self.removeBreakTag = function(string){ var text = angular.copy(string); var removeData = "<br>"; if(!self.isEmpty(text)) { text = text.trim(); while (_.endsWith(text, removeData)) { text = text.slice(0, -removeData.length); if(!self.isEmpty(text)) { text = text.trim(); } } } return text; }; } })();
let mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect('mongodb://root:Demon5310!@ds115931.mlab.com:15931/node-course-todo'); module.exports = {mongoose};
require('../../touch-input-nav')();
/* * @Author: huangyuhui * @Date: 2020-09-22 16:49:17 * @LastEditors: Please set LastEditors * @LastEditTime: 2020-11-14 12:23:49 * @Description: * @FilePath: \SCM 2.0\src\components\common\Table\component\Column\Operation.js */ import { cloneDeepWith } from 'lodash'; export default { functional: true, render( _, ctx ) { const { parent, data: { props: { schema = {} } = {} } } = ctx; return parent.$createElement( 'el-table-column', { props: { 'class-name': 'scm-table-column-operation', label: parent.$t( schema.label ) ?? '操作', width: schema.width, fixed: 'right', align: schema.align ?? 'center' }, scopedSlots: { default: ( props ) => { return parent.$scopedSlots.operation( cloneDeepWith( props.row ) ); } } } ); } };
/* * @lc app=leetcode id=52 lang=javascript * * [52] N-Queens II * * https://leetcode.com/problems/n-queens-ii/description/ * * algorithms * Hard (55.52%) * Likes: 416 * Dislikes: 138 * Total Accepted: 124.2K * Total Submissions: 221.5K * Testcase Example: '4' * * The n-queens puzzle is the problem of placing n queens on an n×n chessboard * such that no two queens attack each other. * * * * Given an integer n, return the number of distinct solutions to the n-queens * puzzle. * * Example: * * * Input: 4 * Output: 2 * Explanation: There are two distinct solutions to the 4-queens puzzle as * shown below. * [ * [".Q..",  // Solution 1 * "...Q", * "Q...", * "..Q."], * * ["..Q.",  // Solution 2 * "Q...", * "...Q", * ".Q.."] * ] * * */ // @lc code=start /** * @param {number} n * @return {number} */ var totalNQueens = function(n) { }; // @lc code=end
const Grocery = require('../models/grocery.js'); module.exports = class GroceryService { constructor(dao) { this.dao = dao; } _createGrocery(data) { return new Grocery(data); }; async findAll() { const groceries = await this.dao.findAll(); return groceries.map(el => this._createGrocery(el)); }; async findById(id) { const grocery = await this.dao.findById(id); return !grocery ? null : this._createGrocery(grocery); }; async add(data) { const grocery = this._createGrocery(data); return this.dao.persist(grocery); }; async delete(id) { return this.dao.deleteById(id); }; }
/** * Cambia la contraseña del usuario ❌ * @param {*} req * @param {*} res * @param {*} next */ async function cambiarContraseña(req, res, next) { try { res.statusCode = 200; res.send({ status: 'Ok', message: 'Cambiar contraseña', }); } catch (error) { next(error) } } module.exports = cambiarContraseña;
export const data = [ { "id":"1", "name":"One", "template":"<div class='template'><div class='editable' style='color: red; font-size: 18px;'>One</div><div class='container'><div class='editable'>Two</div><div class='editable'>Three</div></div></div>", "modified":1516008350380, }, { "id":"2", "name":"Two", "template":"<div class='template'><div class='container'><div class='editable'>One</div><div class='editable'>Two</div><div class='editable'>Three</div></div><div class='editable'>Four</div></div>", "modified":1516008489616, }, { "id":"3", "name":"Three", "template":"<div class='template'> <div class='editable'> one </div> <div class='editable'> two </div> <div class='editable'> three </div></div>", "modified":1516008564742, } ]
import React from 'react'; import styled from 'styled-components'; import { StyledInput } from '../auth/Register'; import MapContainer from '../../lib/api/MapContainer'; import StyledContainer from '../common/Container'; import palette from '../../lib/styles/palette'; import Header from '../common/Header'; const WritePageContainer = styled.div` position:relative; background-color: skyblue; width: 100%; min-height: 700px; .a11y { position: absolute; width: 1px; height: 1px; overflow: hidden; margin: -1px; clip-path: polygon(0 0, 0 0, 0 0); clip: rect(0 0 0 0); clip: rect(0, 0, 0, 0); } .post-content-wrap { display:flex; align-content:center; justify-content:center; text-align:center; background-color: #fff; } .post-content-left, .post-content-right { width:50%; } .post-content-right { display:flex; flex-flow: row wrap; } .post-content-right label { display:flex; align-items:center; justify-content:center; width:20%; } .post-content-right input, .post-content-right select { width: 80%; } .period-wrap { width:100%; display: flex; text-align:center; justify-content:center; align-items:center; /* background-color: skyblue; */ } .period-wrap label:first-child { width:50%; } .period-wrap input { /* width:70%; */ } .btn-cancel, .btn-add { } .btn-cancel{ position:absolute; top:0; right:40px; } .btn-add{ position:absolute; top:0; right:0; } ` const StyledSelect = styled.select` font-size: 1rem; border: none; border-bottom: 1px solid ${palette.gray[5]}; padding-bottom: 0.5rem; outline: none; color: rgb(118,118,118); /* width: 100%; */ &:focus { color: $oc-teal-7; border-bottom: 1px solid ${palette.gray[7]}; } & + & { margin-top: 1rem; } `; const StyledTextarea = styled.textarea` width:100%; min-height: 500px; resize:none; outline:none; border:none; ` const Write = ({ AuthState, onChange, onSubmit}) => { return ( <> <Header /> <StyledContainer> <WritePageContainer> <div> <h1 className="a11y">모집 공고 등록 페이지</h1> <h2>모집 공고 등록</h2> <form onSubmit={onSubmit}> <legend> <fieldset> <p> <label className="a11y" htmlFor="post-title">공고 제목</label> <StyledInput id="post-title" name="title" type="text" placeholder="모집 공고의 제목을 입력해 주세요" onChange={onChange} /> </p> <div className="post-content-wrap"> <div className="post-content-left"> <MapContainer {...AuthState.company} /> </div> <div className="post-content-right"> <label htmlFor="post-name-">업체명</label> <StyledInput id="post-name" name="companyName" type="text" placeholder="업체명을 입력해주세요." value={AuthState.company.username} onChange={onChange} /> <label htmlFor="post-phone">전화번호</label> <StyledInput id="post-phone" name="phoneNumber" type="text" placeholder="전화번호를 입력해주세요." value={AuthState.company.phoneNumber} onChange={onChange} /> <label htmlFor="post-address">주소</label> <StyledInput id="post-address" name="address" type="text" placeholder="주소를 입력해주세요." value={AuthState.company.address} onChange={onChange} /> <div className="period-wrap"> <label htmlFor="post-period-start">봉사 기간</label> <StyledInput id="post-period-start" name="periodstart" type="date" onChange={onChange} /> <label htmlFor="post-period-end">~</label> <StyledInput id="post-period-end" name="periodend" type="date" onChange={onChange} /> </div> <label htmlFor="post-people">인원수</label> {/* <StyledInput id="post-people" type="text" placeholder="원하는 인원수를 입력해주세요." /> */} <StyledSelect id="post-people" name="number" onChange={onChange} > <option value="">원하는 인원수를 입력해주세요</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </StyledSelect> <label htmlFor="post-gender">성별</label> {/* <StyledInput id="post-gender" type="text" placeholder="성별을 입력해주세요." /> */} <StyledSelect id="post-gender" name="gender" onChange={onChange}> <option value="">원하는 봉사자의 성별을 골라주세요</option> <option value="남">남</option> <option value="여">여</option> <option value="성별무관">성별무관</option> </StyledSelect> </div> </div> <StyledTextarea placeholder="봉사 활동 관련한 상세한 내용을 적어주세요." name="body" onChange={onChange} ></StyledTextarea> <button className="btn-cancel" >취소</button> <button className="btn-add" >등록</button> </fieldset> </legend> </form> </div> </WritePageContainer> </StyledContainer> </> ); }; export default Write;
'use strict'; const Promise = require('bluebird'); module.exports = { getAllActualRates(banksIds) { return ActualRate.findAll({ where: { bankId: banksIds }, raw: true }); }, getRatesByBank(bankId) { return ActualRate.findAll({ where: { bankId: bankId }, raw: true }); }, updateRates(banks, countryCode) { return Promise.all([ CurrencyService.getCurrencyList(), BankService.getBanks(countryCode) ]).spread((currencyResult, banksResult) => { let banksList = {}; banksResult.forEach((bank) => { banksList[bank.bankCode] = bank.id; }); return Promise.map(banks, (bank) => { return bank().then((bankResult) => updateBankRates(bankResult, banksList[bankResult.bankCode], currencyResult)); }); }).then((result) => { sails.log.info(`ActualRateService => updateRates: All Country ${countryCode} banks well be updated`); return ({status: true}); }).catch((err) => { sails.log.error(`ActualRateService => updateRates: error on update ${countryCode} banks with text:`, err.message); return ({status: false}); }) } }; function updateBankRates(bankData = {}, bankId = null, currencies = []) { if (bankData.currencies.length > 0 || bankData.cashlessCurrencies.length > 0) { return deletePreviosRates(bankId).then((result) => { let bankRates = [ ...getParsedRates(bankId, bankData.currencies, currencies, bankData.bankCode), ...getParsedRates(bankId, bankData.cashlessCurrencies, currencies, bankData.bankCode, true) ]; return saveRates(bankRates); }); } else { sails.log.warn(`ActualRateService => updateBankRates: nothing for save in bankCode=${bankData.bankCode}`); return Promise.resolve(); } }; function saveRates(insertionData) { return ActualRate.bulkCreate(insertionData); }; function deletePreviosRates(banksIds) { return ActualRate.destroy({ where: { bankId: banksIds } }); }; function getParsedRates(bankId = null, bankCurrencies = [], currencies = [], bankCode = null, cashless = false) { var actualRates = []; bankCurrencies.forEach((currency) => { let rate = { buy: currency.buy, sell: currency.sell, bankId: bankId, cashless: cashless }; if (currencies.currenciesByCode[currency.name]) { rate.currencyId = currencies.currenciesByCode[currency.name]; actualRates.push(rate); } else { if (currencies.currenciesByName[currency.name]) { rate.currencyId = currencies.currenciesByName[currency.name]; actualRates.push(rate); } else { sails.log.error(`Actual Rate Parser Error: For bank ${bankCode} any variable of currency code not found:`, currency); } } }); return actualRates; };
AKT.operators = `:- op(1200,xfx,'==>'). :- op(300,xfy,causes). :- op(300,xfy,causes1way). :- op(300,xfy,causes2way). :- op(920,fx,if). :- op(920,xfy,if). :- op(915,xfx,then). :- op(917,xfx,else). :- op(870,xfx,until). :- op(880,fx,repeattask). :- op(870,fx,foreach). :- op(860,xfx,do). :- op(850,xfx,in). :- op(870,fx,testeach). :- op(860,xfx,for). :- op(920,xfx,giving). :- op(850,yfx,~>>). :- op(850,xfy,&). :- op(905,xfy,or). :- op(910,xfy,and).`;
import ReactTestUtils from 'react-dom/test-utils' export function checkChild(container, type, extraTest) { const children = ReactTestUtils.scryRenderedComponentsWithType( container, type, ) expect(children.length === 1).toBeTruthy() const child = children[0] expect(child).toBeDefined() expect(child.props.content).toBeDefined() expect(typeof child.props.content).toBe('object') expect(child.getContent).toBeDefined() expect(typeof child.getContent).toBe('function') // eslint-disable-next-line no-unused-expressions extraTest && extraTest(child) }
'use strict'; const faker = require("faker"); module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('Listings', [ { ownerId: 1, typeId: 1, sizeId: 8, brand: 'Trek', model: 'Domane', pricePerDay: 5000, title: `Domane SLR 2020 – hidden features, aero design and gravel capabilities`, description: `Up until now, the rear IsoSpeed on the Domane was adjusted on the seat tube. For the new model, the Trek engineers have moved this to the top tube, just like the current Madone. What’s the advantage? The compliance and adjustment range can be tuned individually for each frame size and an additional elastomer integrated into the design is claimed to offer even more damping and shock absorption.`, nearestCity: "Charleston", isAvailable: true, latitude: 32.864791, longitude: -79.98064 }, { ownerId: 2, typeId: 1, sizeId: 7, brand: 'Trek', model: 'Madone', pricePerDay: 5000, title: `Trek Madone SLR 9 Disc 2019 with Carbon Wheels`, description: `The gorgeous matt black frame, paired with glossy logos and colour accents screams speed. Only when examining it closely will you discover Trek’s individually adjustable IsoSpeed damper, which is designed to provide adjustable flex between the frame and seat tube for comfort. The designers have done a great job of integrating the damper into the overall design. As with the competition, integration is one of the key aspects of the Madone. Cables and hoses are routed internally through the cockpit and the frame and the Di2 junction box is hidden in the handlebars. The chain catcher, as well as the cadence and speed sensor, are hardly visible, and the aerodynamic transition between frame and fork is much smoother when turning than compared to the competition.`, nearestCity: "Charleston", isAvailable: true, latitude: 32.882587, longitude: -79.991741 }, { ownerId: 3, typeId: 1, sizeId: 6, brand: 'Trek', model: 'Emonda', pricePerDay: 5000, title: "Super Light 2018 Trek Emonda SLR Disc", description: `The new Trek Émonda SLR is kitted with many of Trek’s tried-and-tested features like the Ride Tuned seat mast, an E2 Tapered steerer, integrated DuoTrap S speed and cadence sensors – alongside the ultimate decision regarding the more aggressive H1 or comfort-focused H2 geometry.`, nearestCity: "Summerville", isAvailable: true, latitude: 33.016579, longitude: -80.166701 }, { ownerId: 2, typeId: 10, sizeId: 4, brand: 'Cannondale', model: 'Scalpel', pricePerDay: 5000, title: "2014 Cannondale Scalpel Team Carbon", description: `With 4" of travel front and rear, and fairly steep angles, the Scalpel is meant for one thing: racing. The suspension serves to tame the worst of the trail chunder and prevent fatigue, but it doesn’t necessarily improve the rider's ability to hit super gnarly technical trails.` , nearestCity: "Charleston", isAvailable: true, latitude: 32.882587, longitude: -79.991741 }, { ownerId: 4, typeId: 6, sizeId: 3, brand: 'Specialized', model: 'Globe', pricePerDay: 3500, title: `Daily 2: a great commuter`, description: `At the same time I can see everything around me without craning my neck uncomfortably to peer out from under my helmet. I feel very heads-up and I’m able to make good eye contact with drivers, pedestrians, and other bicyclists. Sweet Hubs has commented on how comfortable I look when I ride.`, nearestCity: "North Charleston", isAvailable: true, latitude: 32.864000, longitude: -79.98000 }, { ownerId: 5, typeId: 6, sizeId: 5, brand: 'Specialized', model: 'Globe Daily City', pricePerDay: 4000, title: `All-around city bike perfect for adventure`, description: `The Daily 02 uses a traditional rear derailleur with a cuff protector chainring, and it upgrades to metal pedals. The handlebars are a bit bigger and taller, it keeps the full fenders, but uses a small rear rack with aluminum tray. Actually, for 2011, all Globe models are moving to aluminum trays to replace the better looking wood ones (our opinion). Their product manager says they did it for eco reasons, but on a couple we rode there was a bit of rattling on one of them. Could have just been loose, but we’d still like to see the wood offered, at least as an option.`, nearestCity: "Mount Pleasant", isAvailable: true, latitude: 32.80000, longitude: -79.98540 }, { ownerId: 6, typeId: 7, sizeId: 2, brand: 'Norco', model: 'City Glide 24"', pricePerDay: 2000, title: `Great for around the neighborhood with the family`, description: `The Norco City Glide 24” was a fine bike, but did not meet my needs as a rider. It rode well, but the handle shifters were a bit stiff making it hard to gear down when going up bigger hills. Without fenders and a chain guard, it makes every day, all weather cycling difficult, and the hunched forward positioning put a lot of strain on my wrists and back. Overall, this is not my bike of choice because it needs to be a bike that’s comfortable enough to ride everyday to school, classes, and to hang out with friends.`, nearestCity: "Mount Pleasant", isAvailable: true, latitude: 32.863300, longitude: -79.98064 }, ], {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('Listings', null, {}); } };
const mysql2 = require('mysql2/promise'); const config = require('../config/config'); const pool = mysql2.createPool(config.db_info); module.exports = pool;
var firstName = 'Sally'; var lastName = 'Wieland'; var emailAddress = 'sallybwieland@gmail.com'; var cityDweller = true; var yearsInCollege = 4; var hsGraduation = new Date(); hsGraduation.setFullYear(2011); var numberOfPets = 2; var numberOfChildren = 0; var favoriteMusicGenre = 'Hip-Hop'; var favoriteMovie = 'Groundhog Day'; console.log(firstName, lastName, emailAddress, cityDweller, yearsInCollege, hsGraduation, numberOfPets, numberOfChildren, favoriteMusicGenre, favoriteMovie)
'use strict'; import { createStackNavigator, createBottomTabNavigator } from 'react-navigation' import { configRouter, tabOptions } from './RouterTool'; import StackViewStyleInterpolator from 'react-navigation/src/views/StackView/StackViewStyleInterpolator' import Home from '../page/home/Home' import Mine from '../page/user/Mine' import Setting from '../page/user/Setting' import LoginAndRegistered from '../page/login/LoginAndRegistered' import RecoverPwd from '../page/login/RecoverPwd' import VideoPage from '../page/common/VideoPage'; import Chat from '../page/common/Chat'; import LivePage from '../page/common/LivePage'; const Tab = createBottomTabNavigator({ Home: { screen: Home, navigationOptions: tabOptions({ title: '首页', normalIcon: Images.icon_tabbar_home, selectedIcon: Images.icon_tabbar_home_cur }) }, Mine: { screen: Mine, navigationOptions: tabOptions({ title: '我的', normalIcon: Images.icon_tabbar_mine, selectedIcon: Images.icon_tabbar_mine_cur }) }, }, { tabBarOptions: { showIcon: true, indicatorStyle: { height: 0 }, activeTintColor: "#0085da", style: { backgroundColor: "#fff" }, tabStyle: { margin: 2, }, }, lazy: true, //懒加载 swipeEnabled: false, animationEnabled: false, //关闭安卓底栏动画 tabBarPosition: "bottom", // tabBarComponent: (props) => <TabBarBottom {...props} />, initialRouteName: 'Home' }); const Nav = createStackNavigator(configRouter({ Tab: { screen: Tab }, Mine: { screen: Mine }, Setting: { screen: Setting }, LoginAndRegistered: { screen: LoginAndRegistered }, RecoverPwd: { screen: RecoverPwd }, VideoPage: { screen: VideoPage }, Chat: { screen: Chat }, LivePage: { screen: LivePage }, }), { initialRouteName: 'Tab', cardStyle: { shadowOpacity: 0, shadowRadius: 0, backgroundColor: Theme.pageBackgroundColor, }, navigationOptions: { header: null, gesturesEnabled: true }, transitionConfig: () => { return { screenInterpolator: (sceneProps) => { return StackViewStyleInterpolator.forHorizontal(sceneProps) }, } } }); export default Nav
/** * Created by wjwong on 12/16/15. */ /// <reference path="../server/typings/meteor/meteor.d.ts" /> /// <reference path="genstatesdb.ts" /> GenExps = new Mongo.Collection('genexps');
define([ 'sgc-mongoose-model', 'chai' ], function (SGCMongooseModel, chai) { 'use strict'; return function(){ chai.should(); var Model = SGCMongooseModel.Model; var Collection = SGCMongooseModel.Collection; describe('Helpers', function(){ it('Added items in collection are MongooseModel', function(){ var collection = new Collection(); collection.add('1'); chai.expect(collection.at(0)).to.be.an['instanceof'](Model); }); it('Adding two items with same id in collection (merge it)', function(){ var collection = new Collection(); collection.add('1'); collection.add('1'); collection.length.should.equal(1); collection = new Collection(); collection.add({_id:'1'}); collection.add({_id:'1'}); collection.length.should.equal(1); }); it('Get or create with id', function(){ var collection = new Collection(); collection.add('1'); collection.get('2', {getOrCreate:true}); collection.length.should.equal(2); collection.get({_id:'3515'}, {getOrCreate:true}); collection.length.should.equal(3); collection.get({_id:'3515'}, {getOrCreate:true}); collection.length.should.equal(3); collection.get('3515', {getOrCreate:true}); collection.length.should.equal(3); }); }); }; });
//Q.mini.js (Q.js、Q.Queue.js、Q.core.js、Q.setTimer.js) for jquery 等库 /* * Q.js (包括 通用方法、原生对象扩展 等) for browser or Node.js * https://github.com/devin87/Q.js * author:devin87@qq.com * update:2022/04/14 11:10 */ (function (undefined) { "use strict"; //Node.js中闭包外部this并非global eg:(function(g){})(this); //this not global //严格模式下this不指向全局变量 var GLOBAL = typeof global == "object" ? global : window, toString = Object.prototype.toString, has = Object.prototype.hasOwnProperty, slice = Array.prototype.slice; //严格模式与window识别检测 //2018/10/10: uglify压缩会导致此检测函数失效 //function detect_strict_mode() { // var f = function (arg) { // arguments[0] = 1; // return arg != arguments[0]; // }; // return f(0); //} //默认严格模式,不再通过检测判断 var is_strict_mode = true, //detect_strict_mode(), is_window_mode = GLOBAL == GLOBAL.window; /** * 获取数据类型(小写) undefined|null|string|number|array|function|date|regexp|window|node|list * @param {object} obj 要检测的数据 */ function getType(obj) { if (obj == undefined) return "" + obj; //内置函数,性能最好 (注意:safari querySelectorAll返回值类型为function) if (typeof obj !== "object" && typeof obj !== "function") return typeof obj; //非window模式(Node)下禁用以下检测 if (is_window_mode) { if (typeof obj.nodeType === "number") return "node"; if (typeof obj.length === "number") { //严格模式禁止使用 arguments.callee,调用会报错 //IE9+等使用 toString.call 会返回 [object Arguments],此为兼容低版本IE //if (!is_strict_mode && obj.callee) return "arguments"; //IE9+等使用 toString.call 会返回 [object Window],此为兼容低版本IE if (obj == obj.window) return "window"; //document.getElementsByTagName("*") => HTMLCollection //document.querySelectorAll("*") => NodeList //此处统一为 list if (obj.item) return "list"; } } //在某些最新的浏览器中(IE11、Firefox、Chrome)性能与hash读取差不多 eg: return class2type[toString.call(obj)]; return toString.call(obj).slice(8, -1).toLowerCase(); } /** * 检测是否为函数 * @param {object} fn 要检测的数据 */ function isFunc(fn) { //在IE11兼容模式(ie6-8)下存在bug,当调用次数过多时可能返回不正确的结果 //return typeof fn == "function"; return toString.call(fn) === "[object Function]" || toString.call(fn) === "[object AsyncFunction]"; } /** * 检测是否为对象 * @param {object} obj 要检测的数据 */ function isObject(obj) { //typeof null => object //toString.call(null) => [object Object] return obj && toString.call(obj) === "[object Object]"; } /** * 检测是否为数组 * @param {object} obj 要检测的数据 */ function isArray(obj) { return toString.call(obj) === "[object Array]"; } /** * 检测是否为数组或类数组 * @param {object} obj 要检测的数据 */ function isArrayLike(obj) { var type = getType(obj); return type == "array" || type == "list" || type == "arguments"; } /** * 若value不为undefine,则返回value;否则返回defValue * @param {object} value * @param {object} defValue value不存在时返回的值 */ function def(value, defValue) { return value !== undefined ? value : defValue; } /** * 检测是否是符合条件的数字(n必须为数字类型) * @param {number} n 数字 * @param {number|undefined} min 允许的最小值 * @param {number|undefined} max 允许的最大值 * @param {number|undefined} max_decimal_len 最大小数位数 */ function isNum(n, min, max, max_decimal_len) { if (typeof n != "number" || isNaN(n)) return false; if (min != undefined && n < min) return false; if (max != undefined && n > max) return false; if (max_decimal_len) { var l = ((n + '').split('.')[1] || '').length; if (l > max_decimal_len) return false; } return true; } /** * 检测是否为大于0的数字(n必须为数字类型) * @param {number} n 数字 */ function isUNum(n) { return !isNaN(n) && n > 0; } /** * 检测是否为整数(n必须为数字类型) * @param {number} n 数字 * @param {number|undefined} min 允许的最小值 * @param {number|undefined} max 允许的最大值 */ function isInt(n, min, max) { return isNum(n, min, max) && n === Math.floor(n); } /** * 检测是否为大于0的整数 * @param {number} n 数字 */ function isUInt(n) { return isInt(n, 1); } /** * 判断是否是符合条件的数字 * @param {string|number} str 要检测的字符串或数字 * @param {number|undefined} min 允许的最小值 * @param {number|undefined} max 允许的最大值 * @param {number|undefined} max_decimal_len 最大小数位数 */ function checkNum(str, min, max, max_decimal_len) { if (typeof str == "number") return isNum(str, min, max, max_decimal_len); if (typeof str == "string") { str = str.trim(); return str && isNum(+str, min, max, max_decimal_len); } return false; } /** * 判断是否是符合条件的整数 * @param {string|number} str 要检测的字符串或数字 * @param {number|undefined} min 允许的最小值 * @param {number|undefined} max 允许的最大值 */ function checkInt(str, min, max) { if (typeof str == "number") return isInt(str, min, max); if (typeof str == "string") { str = str.trim(); return str && isInt(+str, min, max); } return false; } /** * 将字符串转为大写,若str不是字符串,则返回defValue * @param {string} str 字符串 * @param {string} defValue str不是字符串时返回的值 */ function toUpper(str, defValue) { return typeof str == "string" ? str.toUpperCase() : defValue; } /** * 将字符串转为小写,若str不是字符串,则返回defValue * @param {string} str 字符串 * @param {string} defValue str不是字符串时返回的值 */ function toLower(str, defValue) { return typeof str == "string" ? str.toLowerCase() : defValue; } /** * 转为数组 * @param {Array|NodeList} obj 数组或类数组 * @param {number} from 开始索引,默认为0 */ function toArray(obj, from) { var tmp = []; for (var i = from || 0, len = obj.length; i < len; i++) { tmp.push(obj[i]); } return tmp; } //将 NodeList 转为 Array var makeArrayNode = (function () { try { slice.call(document.documentElement.childNodes); return function (obj, from) { return slice.call(obj, from); } } catch (e) { return toArray; } })(); /** * 将类数组对象转为数组,若对象不存在,则返回空数组 * @param {Array|arguments|NodeList} obj 数组或类数组 * @param {number} from 开始索引,默认为0 */ function makeArray(obj, from) { if (obj == undefined) return []; switch (getType(obj)) { case "array": return from ? obj.slice(from) : obj; case "list": return makeArrayNode(obj, from); case "arguments": return slice.call(obj, from); } return [obj]; } /** * 按条件产生数组 arr(5,2,2) => [2,4,6,8,10] * eg:按1-10项产生斐波那契数列 =>arr(10, function (value, i, list) { return i > 1 ? list[i - 1] + list[i - 2] : 1; }) * @param {number} length 要产生的数组长度 * @param {number} value 数组项的初始值 * @param {number} step 递增值或处理函数(当前值,索引,当前产生的数组) */ function arr(length, value, step) { if (isFunc(value)) { step = value; value = 0; } if (value == undefined) value = 0; if (step == undefined) step = 1; var list = [], i = 0; if (isFunc(step)) { while (i < length) { value = step(value, i, list); list.push(value); i++; } } else { while (i < length) { list.push(value); value += step; i++; } } return list; } /** * 根据指定的键或索引抽取数组项的值 * eg:vals([{id:1},{id:2}], "id") => [1,2] * eg:vals([[1,"a"],[2,"b"]], 1) => ["a","b"] * @param {Array} list 对象数组 * @param {string} prop 要抽取的属性 * @param {boolean} skipUndefined 是否跳过值不存在的项,默认为true */ function vals(list, prop, skipUndefined) { if (!list) return []; skipUndefined = skipUndefined !== false; var len = list.length, i = 0, item, tmp = []; for (; i < len; i++) { item = list[i]; if (item && item[prop] != undefined) { tmp.push(item[prop]); } else if (!skipUndefined) { tmp.push(undefined); } } return tmp; } /** * 给原型方法或属性添加别名 eg:alias(Array,"forEach","each"); * @param {object} obj 对象 * @param {string|object} name 属性名称或对象 eg: 'forEach' | {forEach:'each'} * @param {string} aliasName 别名 */ function alias(obj, name, aliasName) { if (!obj || !obj.prototype) return; var prototype = obj.prototype; if (typeof name == "string") { prototype[aliasName] = prototype[name]; } else { for (var key in name) { if (has.call(name, key) && has.call(prototype, key)) prototype[name[key]] = prototype[key]; } } return obj; } /** * 将源对象(source)的所有可枚举且目标对象(target)不存在的属性, 复制到目标对象 * @param {object} target 目标对象 * @param {object} source 源对象 * @param {boolean} forced 是否强制复制, 为true时将会覆盖目标对象同名属性, 默认为false */ function extend(target, source, forced) { if (!target || !source) return target; for (var key in source) { if (key == undefined || !has.call(source, key)) continue; if (forced || target[key] === undefined) target[key] = source[key]; } return target; } /** * 数据克隆(深拷贝) * @param {object} data 要克隆的对象 */ function clone(data) { if (!data) return data; switch (typeof data) { case "string": case "number": case "boolean": return data; } var result; if (isArray(data)) { result = []; for (var i = 0, len = data.length; i < len; i++) { result[i] = clone(data[i]); } } else if (isObject(data)) { result = {}; for (var key in data) { if (has.call(data, key)) result[key] = clone(data[key]); } } return result; } /** * 将数组或类数组转换为键值对 eg: ['a','b'] => {a:0,b:1} * @param {Array} list 要转换的数组 * @param {object|function} fv 默认值或处理函数(value,i) => [key,value] * @param {boolean} ignoreCase 是否忽略大小写, 为true时将统一使用小写, 默认为false */ function toMap(list, fv, ignoreCase) { if (!list) return; var map = {}, isFn = isFunc(fv), hasValue = fv !== undefined; for (var i = 0, len = list.length; i < len; i++) { var key = list[i], value; if (key == undefined) continue; if (isFn) { var kv = fv.call(list, key, i); if (!kv) continue; key = kv[0]; value = kv[1]; } else { value = hasValue ? fv : i; } map[ignoreCase ? key.toLowerCase() : key] = value; } return map; } /** * 将对象数组转换为键值对 eg: [{name:'a',value:1},{name:'b',value:2}] => {a:1,b:2} * @param {Array.<object>} list 要转换的对象数组 * @param {string} propKey 对象中作为键的属性 eg: name * @param {string|boolean} propValue 对象中作为值的属性, 为true时将给对象增加index属性, 为空时将整个对象作为值 */ function toObjectMap(list, propKey, propValue) { if (!list) return; var map = {}, isBuildIndex = false; if (propValue === true) { isBuildIndex = propValue; propValue = undefined; } for (var i = 0, len = list.length; i < len; i++) { var obj = list[i]; if (!obj || typeof obj != "object") continue; if (isBuildIndex) obj.index = i; map[obj[propKey]] = propValue ? obj[propValue] : obj; } return map; } /** * 将目标对象中和源对象值不同的数据作为键值对返回 * @param {object} target 目标对象 * @param {object} source 源对象 * @param {Array.<string>} skipProps 要忽略比较的属性数组 * @param {string} skipPrefix 要忽略的属性前缀 */ function getChangedData(target, source, skipProps, skipPrefix) { if (!target) return undefined; if (!source) return target; var map_skip_prop = skipProps ? toMap(skipProps, true) : {}, data_changed = {}, has_changed = false; for (var key in target) { if (!key || !has.call(target, key) || map_skip_prop[key] || (skipPrefix && key.indexOf(skipPrefix) == 0) || target[key] == source[key]) continue; data_changed[key] = target[key]; has_changed = true; } return has_changed ? data_changed : undefined; } /** * 转为字符串(用于排序) * undefined|null => "" * true|false => "true" | "false" * 0 => "0" * @param {object} v */ function to_string(v) { return v == undefined ? "" : v + ""; } /** * 将对象数组按字符串排序 * @param {Array.<object>} list 对象数组 eg: [{k:'a'},{k:'b'}] * @param {string} prop 用于排序的属性 * @param {boolean} desc 是否倒序,默认为false */ function sortString(list, prop, desc) { if (desc) list.sort(function (a, b) { return -to_string(a[prop]).localeCompare(to_string(b[prop])); }); else list.sort(function (a, b) { return to_string(a[prop]).localeCompare(to_string(b[prop])); }); } /** * 将对象数组按数字排序 * @param {Array.<object>} list 对象数组 eg: [{k:10},{k:20}] * @param {string} prop 用于排序的属性 * @param {boolean} desc 是否倒序,默认为false */ function sortNumber(list, prop, desc) { if (desc) list.sort(function (a, b) { return (+b[prop] || 0) - (+a[prop] || 0); }); else list.sort(function (a, b) { return (+a[prop] || 0) - (+b[prop] || 0); }); } /** * 将对象数组按字符串排序 * @param {Array.<object>} list 对象数组 eg: [{k:'2019/09/18 13:20'},{k:'2019/10/18 13:20'}] * @param {string} prop 用于排序的属性 * @param {boolean} desc 是否倒序,默认为false */ function sortDate(list, prop, desc) { list.sort(function (a, b) { var v1 = a[prop], v2 = b[prop]; if (v1 == v2) return 0; var d1 = Date.from(v1), d2 = Date.from(v2), rv = 0; if (d1 != INVALID_DATE && d2 != INVALID_DATE) rv = d1 - d2; else if (d1 == INVALID_DATE && d2 != INVALID_DATE) rv = -1; else if (d1 != INVALID_DATE && d2 == INVALID_DATE) rv = 1; return desc ? -rv : rv; }); } /** * 将IP转为数字(用于排序) * @param {string} ip */ function ip2int(ip) { var ips = ip.split('.'); return (+ips[0] || 0) * 256 * 256 * 256 + (+ips[1] || 0) * 256 * 256 + (+ips[2] || 0) * 256 + (+ips[3] || 0); } /** * 将对象数组按IP排序 * @param {Array.<object>} list 对象数组 eg: [{k:'192.168.2.10'},{k:'192.168.3.1'}] * @param {string} prop 用于排序的属性 * @param {boolean} desc 是否倒序,默认为false */ function sortIP(list, prop, desc) { list.sort(function (a, b) { var v1 = a[prop] || "", v2 = b[prop] || ""; if (v1 == v2) return 0; var rv = ip2int(v1) - ip2int(v2); return desc ? -rv : rv; }); } /** * 对象数组排序 * @param {Array.<object>} list 对象数组 * @param {number} type 排序类型 0:字符串排序|1:数字排序|2:日期排序|3:IP排序 * @param {string} prop 用于排序的属性 * @param {boolean} desc 是否倒序,默认为false */ function sortList(list, type, prop, desc) { switch (type) { case 1: sortNumber(list, prop, desc); break; case 2: sortDate(list, prop, desc); break; case 3: sortIP(list, prop, desc); break; default: sortString(list, prop, desc); break; } } /** * 返回一个绑定到指定作用域的新函数 * @param {function} fn * @param {object} bind 要绑定的作用域 */ function proxy(fn, bind) { if (isObject(fn)) { var name = bind; bind = fn; fn = bind[name]; } return function () { fn.apply(bind, arguments); } } /** * 触发指定函数,如果函数不存在,则不触发 eg:fire(fn,this,arg1,arg2) * @param {function} fn * @param {object} bind 要绑定的作用域 */ function fire(fn, bind) { if (fn != undefined) return fn.apply(bind, slice.call(arguments, 2)); } /** * 函数延迟执行,若fn未定义,则忽略 eg:delay(fn,this,10,[arg1,arg2]) * @param {function} fn * @param {object} bind 要绑定的作用域 * @param {number} time 要延迟的毫秒数 * @param {Array.<object>} args 传给fn的参数 */ function delay(fn, bind, time, args) { if (fn == undefined) return; return setTimeout(function () { //ie6-7,apply第二个参数不能为空,否则报错 fn.apply(bind, args || []); }, def(time, 20)); } /** * 异步执行,相当于setTimeout,但会检查fn是否可用 eg:async(fn,10,arg1,arg2) * @param {function} fn * @param {number} time 要延迟的毫秒数 */ function async(fn, time) { return isFunc(fn) && delay(fn, undefined, time, slice.call(arguments, 2)); } //等待达到条件或超时时,执行一个回调函数 callback(ops,timedout) function _waitFor(ops) { var now_time = +new Date, timeout = ops.timeout, //超时时间 timedout = timeout && now_time - ops.startTime > timeout; //是否超时 //若未超时且未达到条件,则继续等待 if (!timedout && !ops.check(ops)) { ops.count++; return async(_waitFor, ops.sleep, ops); } ops.endTime = now_time; ops.callback(ops, timedout); } /** * 等待达到条件或超时时,执行一个回调函数 callback(ops,timedout) * @param {function} check 检测函数,若返回true则立即执行回调函数 * @param {function} callback 回调函数(ops,timedout) * @param {number} timeout 超时时间(单位:ms),默认10000ms * @param {number} sleep 休眠间隔(单位:ms),默认20ms */ function waitFor(check, callback, timeout, sleep) { _waitFor({ check: check, callback: callback, timeout: timeout, sleep: sleep, count: 0, startTime: +new Date }); } /** * 遍历数组或类数组,与浏览器实现保持一致(忽略未初始化的项,注意:ie8及以下会忽略数组中 undefined 项) * @param {Array} list * @param {function} fn 处理函数(value,i,list) * @param {object} bind fn绑定的作用域对象 */ function each_array(list, fn, bind) { for (var i = 0, len = list.length; i < len; i++) { if (i in list) fn.call(bind, list[i], i, list); } } /** * 函数节流,返回一个在指定时间内最多执行一次的函数,第一次或超过指定时间则立即执行函数 * @param {number} time 指定时间(单位:ms) * @param {function} fn 处理函数(arg1,...) * @param {object} bind fn绑定的作用域对象 */ function throttle(time, fn, bind) { var last_exec_time; return function () { var now = Date.now(); if (last_exec_time && now - last_exec_time < time) return; last_exec_time = now; fn.apply(bind, arguments); }; } /** * 函数防抖,返回一个延迟指定时间且仅执行最后一次触发的函数,若以小于指定时间的频率一直调用,则函数不会执行 * @param {number} time 指定时间(单位:ms) * @param {function} fn 处理函数(arg1,...) * @param {object} bind fn绑定的作用域对象 */ function debounce(time, fn, bind) { var timer; return function () { if (timer) clearTimeout(timer); var args = arguments; timer = setTimeout(function () { fn.apply(bind, args); }, time); } } /** * 简单通用工厂 * @param {function} init 初始化函数 * @param {function} Super 超类 */ function factory(init, Super) { if (Super && isFunc(Super)) { var F = function () { }; F.prototype = Super.prototype; init.prototype = new F(); } var obj = init; obj.constructor = factory; obj.prototype.constructor = obj; //prototype扩展 obj.extend = function (source, forced) { extend(this.prototype, source, forced); }; //函数别名 obj.alias = function (name, aliasName) { alias(this, name, aliasName); }; return obj; }; /* * extend.js:JavaScript核心对象扩展 */ each_array([String, Array, Number, Boolean, Function, Date, RegExp], factory); //----------------------------- Object extend ----------------------------- //扩展Object extend(Object, { //创建一个拥有指定原型的对象,未实现第二个参数 create: function (o) { var F = function () { }; F.prototype = o; return new F(); }, //遍历对象 forEach: function (obj, fn, bind) { for (var key in obj) { if (has.call(obj, key)) fn.call(bind, key, obj[key], obj); } }, //获取对象所有键 keys: function (obj) { var tmp = []; //注意:for in 在ie6下无法枚举 propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor 等属性 //尽量不要使用上述属性作为键 for (var key in obj) { if (has.call(obj, key)) tmp.push(key); } return tmp; }, //获取对象所有值 values: function (obj) { var tmp = []; for (var key in obj) { if (has.call(obj, key)) tmp.push(obj[key]); } return tmp; }, //获取项数量 size: function (obj) { var count = 0; for (var key in obj) { if (has.call(obj, key)) count++; } return count; }, //对象是否拥有子项 hasItem: function (obj) { for (var key in obj) { if (has.call(obj, key)) return true; } return false; } }); //----------------------------- String extend ----------------------------- //String原型扩展(已标准化,此为兼容浏览器原生方法) String.extend({ //去掉首尾空格 trim: function () { //return this.replace(/^\s+|\s+$/g, ""); var str = "" + this, str = str.replace(/^\s\s*/, ""), ws = /\s/, i = str.length; while (ws.test(str.charAt(--i))) { }; return str.slice(0, i + 1); }, //返回将本身重复n次的字符串 eg:"abc".repeat(2) => "abcabc" repeat: function (n) { //if (n < 1) return ""; //return new Array(n + 1).join(this); //二分法,性能大大提升 var str = "" + this, total = ""; while (n > 0) { if (n % 2 == 1) total += str; if (n == 1) break; str += str; n >>= 1; } return total; }, //是否以指定字符串开头 startsWith: function (str, index) { var s = "" + this; return s.substr(index || 0, str.length) === str; }, //是否以指定字符串结尾 endsWith: function (str, index) { var s = "" + this, end = index == undefined || index > s.length ? s.length : index; return s.substr(end - str.length, str.length) === str; }, //是否包含指定字符串 contains: function (str, index) { return this.indexOf(str, index) != -1; } }); //String原型扩展 String.extend({ //删除指定字符串 //pattern:要删除的字符串或正则表达式 //flags:正则表达式标记,默认为g drop: function (pattern, flags) { var regexp = typeof pattern == "string" ? new RegExp(pattern, flags || "g") : pattern; return this.replace(regexp, ""); }, //字符串反转 reverse: function () { return this.split("").reverse().join(""); }, //html编码 eg:\n => <br/> htmlEncode: function () { return this.replace(/\x26/g, "&amp;").replace(/\x3c/g, "&lt;").replace(/\x3e/g, "&gt;").replace(/\r?\n|\r/g, "<br/>").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;").replace(/\s/g, "&nbsp;"); }, //html解码 eg:<br/> => \n htmlDecode: function () { return this.replace(/<br[^>]*>/ig, "\n").replace(/<script[^>]*>([^~]|~)+?<\/script>/gi, "").replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&"); } }); //----------------------------- Number extend ----------------------------- //Number原型扩展 Number.extend({ //将数字按长度和进制转换为一个长度不低于自身的字符串 eg:(13).format(4) ->'0013' //(13).format(1) -> '13' (13).format(4, 16)->'000d' (13).format(4, 2) ->'1101' format: function (length, radix) { var str = this.toString(radix || 10), fix = length - str.length; return (fix > 0 ? "0".repeat(fix) : "") + str; }, //数字转为保留指定的小数位数,整数不受影响 eg: (0.2394).maxDecimal(2) => 0.24 maxDecimal: function (length) { if (this === Math.floor(this)) return this; if (length === 0) return Math.floor(Math.round(this * 100) / 100); var fix = Math.pow(10, +length || 8); return Math.round(this * fix) / fix; } }); //----------------------------- Array extend ----------------------------- //Array原型扩展(已标准化,此为兼容浏览器原生方法) //与浏览器实现保持一致(忽略未初始化的项,注意:ie8及以下会忽略数组中 undefined 项) //部分函数未做参数有效性检测,传参时需注意 Array.extend({ //迭代器:用函数(fn)处理数组的每一项 forEach: function (fn, bind) { var self = this; for (var i = 0, len = self.length; i < len; i++) { if (i in self) fn.call(bind, self[i], i, self); } }, //迭代器:返回经过函数(fn)处理后的新数组 map: function (fn, bind) { var self = this, tmp = []; for (var i = 0, len = self.length; i < len; i++) { if (i in self) tmp.push(fn.call(bind, self[i], i, self)); } return tmp; }, //查找方法(顺序) indexOf: function (item, index) { var self = this, len = self.length, i; if (len == 0) return -1; if (index == undefined) i = 0; else { i = Number(index); if (i < 0) i = Math.max(i + len, 0); } for (; i < len; i++) { if (i in self && self[i] === item) return i; } return -1; }, //查找方法(倒序) lastIndexOf: function (item, index) { var self = this, len = self.length, i; if (len == 0) return -1; if (index == undefined) i = len - 1; else { i = Number(index); i = i >= 0 ? Math.min(i, len - 1) : i + len; } for (; i >= 0; i--) { if (i in self && self[i] === item) return i; } return -1; }, //将所有在给定过滤函数中过滤通过的数组项创建一个新数组 filter: function (fn, bind) { var self = this, tmp = []; for (var i = 0, len = self.length; i < len; i++) { if (i in self) { var val = self[i]; if (fn.call(bind, val, i, self)) tmp.push(val); } } return tmp; }, //如果数组中的每一项都通过给定函数的测试,则返回true every: function (fn, bind) { var self = this; for (var i = 0, len = self.length; i < len; i++) { if (i in self && !fn.call(bind, self[i], i, self)) return false; } return true; }, //如果数组中至少有一个项通过了给出的函数的测试,则返回true some: function (fn, bind) { var self = this; for (var i = 0, len = self.length; i < len; i++) { if (i in self && fn.call(bind, self[i], i, self)) return true; } return false; } }); //Array原型扩展 Array.extend({ //数组中是否存在指定的项 contains: function (item, index) { return this.indexOf(item, index) !== -1; }, //获取数组项 //若index小于0,则从右往左获取 get: function (index) { if (index >= 0) return this[index]; index += this.length; return index >= 0 ? this[index] : undefined; }, //获取数组第一项 first: function () { return this.get(0); }, //获取数组最后一项 last: function () { return this.get(-1); }, //根据索引删除数组中的项 del: function (index, n) { return this.splice(index, n || 1); }, //去掉数组中的重复项 eg:[0,"0",false,null,undefined] 不支持的特殊情况:[ new String(1), new Number(1) ] //如果是对象数组,可以指定对象的键 eg:[{id:1},{id:2}] -> ret.unique("id") unique: function (prop) { var ret = this, tmp = [], hash = {}; for (var i = 0, len = ret.length; i < len; i++) { var item = ret[i], value = prop ? item[prop] : item, key = typeof (value) + value; //typeof -> toString.call,性能略有下降 if (!hash[key]) { tmp.push(item); hash[key] = true; } } return tmp; }, //去掉空的项,并返回一个新数组 clean: function () { var ret = this, tmp = []; for (var i = 0, len = ret.length; i < len; i++) { if (ret[i] != undefined) tmp.push(ret[i]); } return tmp; }, //根据指定的键或索引抽取数组项的值 //eg:[{id:1},{id:2}] -> ret.items("id") => [1,2] //eg:[[1,"a"],[2,"b"]] -> ret.items(1) => ["a","b"] items: function (prop, skipUndefined) { return vals(this, prop, skipUndefined); }, //将数组转换为键值对 //value:若为空,则使用数组索引;为处理函数,需返回包含键值的数组 eg: value(item,i) => [key,value] toMap: function (value, ignoreCase) { return toMap(this, value, ignoreCase); }, //将对象数组转换为键值对 //propKey:对象中作为键的属性 //propValue:对象中作为值的属性,若为空,则值为对象本身;若为true,则给对象添加index属性,值为对象在数组中的索引 toObjectMap: function (propKey, propValue) { return toObjectMap(this, propKey, propValue); } }); //Array静态方法扩展(已标准化,此为兼容浏览器原生方法) extend(Array, { forEach: each_array, isArray: isArray }); //----------------------------- Date extend ----------------------------- var DATE_REPLACEMENTS = [/y{2,4}/, /M{1,2}/, /d{1,2}/, /H{1,2}|h{1,2}/, /m{1,2}/, /s{1,2}/, /S/, /W/, /AP/], FIX_TIMEZONEOFFSET = new Date().getTimezoneOffset(), WEEKS = "日一二三四五六".split(""), APS = ["上午", "下午"], INVALID_DATE = new Date(""), DATE_FNS = ["getFullYear", "getMonth", "getDate", "getHours", "getMinutes", "getSeconds", "getMilliseconds", "getDay", "getHours"]; //获取指定part形式表示的日期 function format_date(part, t) { switch (part) { case "d": case "day": return t / 86400000; case "h": case "hour": return t / 3600000; case "m": case "minute": return t / 60000; case "s": case "second": return t / 1000; } return t; } //Date原型扩展 Date.extend({ //是否有效日期 isValid: function () { return !isNaN(this.valueOf()); }, //格式化日期显示 eg:(new Date()).format("yyyy-MM-dd HH:mm:ss"); format: function (format, ops) { ops = ops || {}; if (!this.isValid()) return ops.invalid || "--"; var months = ops.months, weeks = ops.weeks || WEEKS, aps = ops.aps || APS, len = DATE_REPLACEMENTS.length, i = 0; for (; i < len; i++) { var re_date = DATE_REPLACEMENTS[i], n = this[DATE_FNS[i]](); format = format.replace(re_date, function (match) { var length = match.length; //上午|下午 if (i == 8) return aps[n > 12 ? 1 : 0]; //星期 if (i == 7) return weeks[n]; //月份 if (i == 1) { if (months) return months[n]; //月份索引从0开始,此处加1 n++; } //12小时制 if (i == 3 && match.charAt(0) == "h" && n > 12) n -= 12; //匹配的长度为1时,直接转为字符串输出 H -> 9|19 if (length == 1) return "" + n; //按照指定的长度输出字符串(从右往左截取) return ("00" + n).slice(-length); }); } return format; }, //按照part(y|M|d|h|m|s|ms)添加时间间隔 add: function (part, n) { var date = this; switch (part) { case "y": case "year": date.setFullYear(date.getFullYear() + n); break; case "M": case "month": date.setMonth(date.getMonth() + n); break; case "d": case "day": date.setDate(date.getDate() + n); break; case "h": case "hour": date.setHours(date.getHours() + n); break; case "m": case "minute": date.setMinutes(date.getMinutes() + n); break; case "s": case "second": date.setSeconds(date.getSeconds() + n); break; case "ms": case "millisecond": date.setMilliseconds(date.getMilliseconds() + n); break; } return date; }, //返回两个指定日期之间所跨的日期或时间 part 边界的数目 diff: function (part, date) { return format_date(part, this - date); }, //从UTC时间转为本地时间 fromUTC: function () { this.setMinutes(this.getMinutes() - FIX_TIMEZONEOFFSET); return this; }, //转为UTC时间 toUTC: function () { this.setMinutes(this.getMinutes() + FIX_TIMEZONEOFFSET); return this; }, //返回一个日期副本,对该副本所做的修改,不会同步到原日期 clone: function () { return new Date(this.getTime()); } }); //Date静态方法扩展(已标准化,此为兼容浏览器原生方法) extend(Date, { //获取当前日期和时间所代表的毫秒数 now: function () { return +new Date; } }); //Date静态方法扩展 extend(Date, { //将字符串解析为Date对象 from: function (s) { if (typeof s == "number") return new Date(s); if (typeof s == "string") { if (!s) return INVALID_DATE; if (!isNaN(s) && s.length > 6) return new Date(+s); //将年、月、横线(-)替换为斜线(/),将时、分替换为冒号(:),去掉日、号、秒 //var ds = s.replace(/[-\u5e74\u6708]/g, "/").replace(/[\u65f6\u5206\u70b9]/g, ":").replace(/[T\u65e5\u53f7\u79d2]/g, ""), date = new Date(ds); var isUTC = s.slice(s.length - 1) == "Z", ds = s.replace(/[-\u5e74\u6708]/g, "/").replace(/[\u65f6\u5206\u70b9]/g, ":").replace("T", " ").replace(/[Z\u65e5\u53f7\u79d2]/g, ""), //毫秒检测 index = ds.lastIndexOf("."), date, ms; if (index != -1) { ms = +ds.slice(index + 1, index + 4); ds = ds.slice(0, index); } date = new Date(ds); //兼容只有年月的情况 eg:2014/11 if (!date.isValid() && ds.indexOf("/") > 0) { var ps = ds.split(' '), s_date = (ps[0] + (ps[0].endsWith("/") ? "" : "/") + "1/1").split('/').slice(0, 3).join("/"); date = new Date(s_date + ' ' + (ps[1] || "")); } //设置毫秒 if (ms) date.setMilliseconds(ms); return date.isValid() ? (isUTC ? date.fromUTC() : date) : INVALID_DATE; } return toString.call(s) == "[object Date]" ? s : INVALID_DATE; }, //获取秒转化的时间部分 parts: function (t) { var days = 0, hours = 0, minutes = 0; days = Math.floor(t / 86400); if (days > 0) t -= days * 86400; hours = Math.floor(t / 3600); if (hours > 0) t -= hours * 3600; minutes = Math.floor(t / 60); if (minutes > 0) t -= minutes * 60; //mintues: 之前拼写错误,此为兼容之前的调用 return { days: days, hours: hours, minutes: minutes, mintues: minutes, seconds: t }; }, //计算时间t所代表的总数 total: format_date }); //---------------------- 事件监听器 ---------------------- /** * 自定义事件监听器 * @param {Array.<string>} types 自定义事件列表 * @param {object} bind 事件函数绑定的上下文 eg:fn.call(bind) */ function Listener(types, bind) { var self = this; self.map = {}; self.bind = bind; types.forEach(function (type) { self.map[type] = []; }); } Listener.prototype = { constructor: Listener, //添加自定义事件 eg:listener.add("start",fn); add: function (type, fn) { var map = this.map; if (typeof type == "string") { if (isFunc(fn)) { (type + "").split(",").forEach(function (type) { map[type].push(fn); }); } } else if (isObject(type)) { Object.forEach(type, function (k, v) { if (map[k] && isFunc(v)) map[k].push(v); }); } return this; }, //移除自定义事件,若fn为空,则移除该类型下的所有事件 remove: function (type, fn) { if (fn != undefined) { var list = this.map[type], i = list.length; while (--i >= 0) { if (list[i] == fn) list = list.splice(i, 1); } } else { this.map[type] = []; } return this; }, //触发自定义事件 eg:listener.trigger("click",args); trigger: function (type, args) { var self = this, list = self.map[type], len = list.length, i = 0; for (; i < len; i++) { if (list[i].apply(self.bind, [].concat(args)) === false) break; } return self; } }; //-------------------------- 搜索 -------------------------- var SE = { //获取搜索对象 get: function (words) { var pattern = words.replace(/\\(?!d|B|w|W|s|S)/g, "\\\\").replace(/\./g, "\\.").replace(/[\[\]\(\)]/g, "\\$&").replace(/\*/, ".*"); return new RegExp(pattern, "i"); }, //在列表内搜索 //props:要搜索的属性数组 //keywords:搜索关键字 //highlight:是否记录高亮信息 search: function (list, props, keywords, highlight) { if (!list || list.length <= 0) return []; if (!keywords) { list.forEach(function (u) { u.__match = undefined; }); return list; } var tester = SE.get(keywords); var tmp = list.filter(function (data) { var matched = false; var map_match = {}; props.forEach(function (prop) { var text = data[prop]; if (!text || !tester.test(text)) return; if (highlight) map_match[prop] = (text + "").replace(tester, '`#`{$&}`#`'); matched = true; }); data.__match = matched && highlight ? map_match : undefined; return matched; }); return tmp; }, //读取数据,若搜索时启用了高亮,则返回高亮字符串 read: function (data, prop) { var match = data.__match; if (match && match[prop]) { return match[prop].htmlEncode().replace(/`#`{(.+?)}`#`/g, function (m, m1) { return '<span class="light">' + m1 + '</span>'; }); } return ((data[prop] || "") + "").htmlEncode(); } }; //---------------------- 其它 ---------------------- //正则验证 var RE_MAIL = /^[\w\.-]+@[\w-]+(\.[\w-]+)*\.[\w-]+$/, //验证邮箱 RE_PHONE = /^(1\d{10}|(\d{3,4}-?)?\d{7,8}(-\d{1,4})?)$/, //验证电话号码(手机号码、带区号或不带区号、带分机号或不带分机号) RE_TEL = /^1\d{10}$/, //验证手机号码 RE_MAC = /^[a-fA-F0-9]{2}([:-][a-fA-F0-9]{2}){5}$/, //验证MAC地址 RE_HTTP = /^https?:\/\//i; /** * 判断是否为可用IP格式(IPv4) * @param {string} ip eg: 192.168.1.1 */ function isIP(ip) { var parts = ip.split("."), length = parts.length; if (length != 4) return false; for (var i = 0; i < length; i++) { var part = +parts[i]; if (!parts[i] || isNaN(part) || part < 0 || part > 255) return false; } return true; } /** * 判断是否为可用邮箱格式 * @param {string} str eg: test@my.com */ function isMail(str) { return RE_MAIL.test(str); } /** * 判断是否符合电话号码格式 * @param {string} str eg: 18688889999 | 027-88889999-3912 */ function isPhone(str) { return RE_PHONE.test(str); } /** * 判断是否符合手机号码格式 * @param {string} str eg: 18688889999 */ function isTel(str) { return RE_TEL.test(str); } /** * 判断是否符合MAC地址格式 * @param {string} str eg: 00:11:22:33:44:ff */ function isMAC(str) { return RE_MAC.test(str); } /** * 判断是否http路径(以 http:// 或 https:// 开头) * @param {string} url */ function isHttpURL(url) { return RE_HTTP.test(url); } /** * 格式化访问地址 eg: 192.168.1.50 => http://192.168.1.50/ * @param {string} host IP或访问地址 eg: 192.168.1.50 | http://192.168.1.50 */ function formatHost(host) { if (!host) return ''; host = (host + '').trim(); if (!host) return ''; if (!Q.isHttpURL(host)) host = 'http://' + host; if (!host.endsWith('/')) host += '/'; return host; } /** * 按照进制解析数字的层级 eg:时间转化 -> parseLevel(86400,[60,60,24]) => { value=1, level=3 } * @param {number} size 要解析的数字 * @param {number|Array.<number>} steps 步进,可以是固定的数字(eg:1024),也可以是具有层次关系的数组(eg:[60,60,24]) * @param {number} limit 限制解析的层级,正整数,默认为100 */ function parseLevel(size, steps, limit) { size = +size; steps = steps || 1024; var level = 0, isNum = typeof steps == "number", stepNow = 1, count = isUInt(limit) ? limit : (isNum ? 100 : steps.length); while (size >= stepNow && level < count) { stepNow *= (isNum ? steps : steps[level]); level++; } if (level && size < stepNow) { level--; stepNow /= (isNum ? steps : steps[level]); } return { value: level ? size / stepNow : size, level: level }; } var UNITS_FILE_SIZE = ["B", "KB", "MB", "GB", "TB", "PB", "EB"]; /** * 格式化数字输出,将数字转为合适的单位输出,默认按照1024层级转为文件单位输出 * @param {number} size 要解析的数字 * @param {object} ops 配置对象 {all:false,steps:1024,limit:100,trim:true,join:'',units:['B','KB','MB','GB'],digit:2,start:0,defValue:'--'} */ function formatSize(size, ops) { ops = ops === true ? { all: true } : ops || {}; if (isNaN(size) || size == undefined || size < 0) { var defValue = ops.defValue || "--"; return ops.all ? { text: defValue } : defValue; } var pl = parseLevel(size, ops.steps, ops.limit), value = pl.value, text = value.toFixed(def(ops.digit, 2)); if (ops.trim !== false && text.lastIndexOf(".") != -1) text = text.replace(/\.?0+$/, ""); pl.text = text + (ops.join || "") + (ops.units || UNITS_FILE_SIZE)[pl.level + (ops.start || 0)]; return ops.all ? pl : pl.text; } var encodeUrlParam = encodeURIComponent; /** * 解码url参数值 eg:%E6%B5%8B%E8%AF%95 => 测试 * @param {string} param 要解码的字符串 eg:%E6%B5%8B%E8%AF%95 */ function decodeUrlParam(param) { try { return decodeURIComponent(param); } catch (e) { return param; } } /** * 将参数对象转为查询字符串 eg: {a:1,b:2} => a=1&b=2 * @param {object} obj 参数对象 eg: {a:1,b:2} */ function joinUrlParams(obj) { if (!obj) return ""; if (typeof obj == "string") return obj; var tmp = []; Object.forEach(obj, function (k, v) { if (v != undefined && typeof v != "function") tmp.push(encodeUrlParam(k) + "=" + encodeUrlParam(v)); }); return tmp.join("&"); } /** * 连接url和查询字符串(支持传入对象) * @param {string} url URL地址 */ function joinUrl(url) { var params = [], args = arguments; for (var i = 1, len = args.length; i < len; i++) { var param = args[i]; if (param) params.push(joinUrlParams(param)); } var index = url.indexOf("#"), hash = ""; if (index != -1) { hash = url.slice(index).trim(); url = url.slice(0, index); } url = url.trim().replace(/\?&$|\?$|\&$/, ''); var str_params = params.join("&"); if (str_params) url += (url.contains("?") ? "&" : "?") + str_params; return url + hash; } /** * 解析url参数 eg:url?id=1 * @param {string} search 查询字符串 eg: ?id=1 */ function parseUrlParams(search) { if (!search) return {}; var i = search.indexOf("?"); if (i != -1) search = search.slice(i + 1); var j = search.indexOf("#"); if (j != -1) search = search.slice(0, j); if (!search) return {}; var list = search.split("&"), map = {}; for (var i = 0, len = list.length; i < len; i++) { //跳过空字符串 if (!list[i]) continue; var kv = list[i].split("="), key = kv[0], value = kv[1]; if (key) map[decodeUrlParam(key)] = value ? decodeUrlParam(value) : ""; } return map; } /** * 转换或解析查询字符串 * @param {string|object} obj 为string类型时将解析为参数对象,否则将转换为查询字符串 */ function processUrlParam(obj) { if (obj == undefined) return; return typeof obj == "string" ? parseUrlParams(obj) : joinUrlParams(obj); } var DEF_LOC = GLOBAL.location || { protocol: "", hash: "", pathname: "" }; /** * 解析URL路径 => {href,origin,protocol,host,hostname,port,pathname,search,hash} * @param {string} url URL地址 */ function parseUrl(url) { //return new URL(url); var m = url.match(/(^[^:]*:)?\/\/([^:\/]+)(:\d+)?(.*)$/), protocol = m[1] || DEF_LOC.protocol, hostname = m[2], port = (m[3] || "").slice(1), host = hostname + (port ? ":" + port : ""), pathname = m[4] || "", search = "", hash = "", i = pathname.indexOf("#"); if (i != -1) { hash = pathname.slice(i); pathname = pathname.slice(0, i); } i = pathname.indexOf("?"); if (i != -1) { search = pathname.slice(i); pathname = pathname.slice(0, i); } return { href: protocol + "//" + host + pathname + search + hash, origin: protocol + "//" + host, protocol: protocol, host: host, hostname: hostname, port: port, pathname: pathname || "/", search: search, hash: hash }; } /** * 解析 URL hash值 eg:#net/config!/wan => {nav:"#net/config",param:"wan"} * @param {string} hash eg:#net/config!/wan */ function parseUrlHash(hash) { if (!hash) hash = DEF_LOC.hash; //可能对后续处理造成影响,比如 param 中有/等转码字符 //if(hash) hash = decode_url_param(hash); var nav = hash, param; if (hash) { var index = hash.indexOf("!/"); if (index != -1) { nav = hash.slice(0, index); param = hash.slice(index + 2); } } return { nav: nav, param: param }; } /** * 获取当前页名称 eg: /app.html?id=1#aa => app.html * @param {string} path eg: /app.html?id=1#aa * @param {boolean} keepQueryHash 是否保留查询字符串和Hash字符串,默认为false */ function getPageName(path, keepQueryHash) { var pathname = (path || DEF_LOC.pathname).replace(/\\/g, "/"), start = pathname.lastIndexOf("/") + 1; if (keepQueryHash) return pathname.slice(start); var end = pathname.indexOf("?", start); if (end == -1) end = pathname.indexOf("#", start); return end != -1 ? pathname.slice(start, end) : pathname.slice(start); } /** * 解析JSON,解析失败时返回undefined * @param {string} text 要解析的JSON字符串 */ function parseJSON(text) { if (!text || typeof text !== 'string') return text; try { return JSON.parse(text); } catch (err) { } } //---------------------- export ---------------------- var Q = { version: "1.2.2", G: GLOBAL, strict: is_strict_mode, type: getType, isFunc: isFunc, isObject: isObject, isArray: Array.isArray, isArrayLike: isArrayLike, def: def, isNum: isNum, isUNum: isUNum, isInt: isInt, isUInt: isUInt, checkNum: checkNum, checkInt: checkInt, toUpper: toUpper, toLower: toLower, toArray: toArray, makeArray: makeArray, arr: arr, vals: vals, alias: alias, extend: extend, clone: clone, toMap: toMap, toObjectMap: toObjectMap, getChangedData: getChangedData, ip2int: ip2int, sortNumber: sortNumber, sortString: sortString, sortDate: sortDate, sort: sortList, proxy: proxy, fire: fire, delay: delay, async: async, waitFor: waitFor, throttle: throttle, debounce: debounce, factory: factory, isIP: isIP, isMail: isMail, isPhone: isPhone, isTel: isTel, isMAC: isMAC, isHttpURL: isHttpURL, formatHost: formatHost, parseLevel: parseLevel, formatSize: formatSize, parseUrlParams: parseUrlParams, joinUrlParams: joinUrlParams, param: processUrlParam, join: joinUrl, parseUrl: parseUrl, parseHash: parseUrlHash, getPageName: getPageName, parseJSON: parseJSON, Listener: Listener, SE: SE }; GLOBAL.Q = Q; if (typeof module === "object" && typeof module.exports === "object") { module.exports = Q; } })(); /* * Q.Queue.js 队列 for browser or Node.js * author:devin87@qq.com * update:2021/06/23 12:53 */ (function (undefined) { "use strict"; var delay = Q.delay, extend = Q.extend, fire = Q.fire, isFunc = Q.isFunc, isObject = Q.isObject, isArrayLike = Q.isArrayLike, isUInt = Q.isUInt, getType = Q.type, makeArray = Q.makeArray, factory = Q.factory, Listener = Q.Listener; var QUEUE_TASK_TIMEDOUT = -1, //任务已超时 QUEUE_TASK_READY = 0, //任务已就绪,准备执行 QUEUE_TASK_PROCESSING = 1, //任务执行中 QUEUE_TASK_OK = 2, //任务已完成 //自定义事件 LIST_CUSTOM_EVENT = ["add", "start", "end", "stop", "complete", "limit"]; /** * 异步队列 * @param {object} ops 配置对象 eg: {tasks:[],count:10000,limitMode:1,auto:true,workerThread:1,timeout:0,injectIndex:1,injectCallback:'complete',exec:function(task,next){},process:function(task,next){},processResult:function(tasks){}} */ function Queue(ops) { ops = ops || {}; var self = this, tasks = ops.tasks; //队列自定义事件 self._listener = new Listener(LIST_CUSTOM_EVENT, self); self.count = +ops.count || 10000; //队列长度,超过后将清理已完成的任务 self.limitMode = ops.limitMode || 1; //队列在超出长度后的限制模式(1:禁止添加|2:清理早期的任务) self.auto = ops.auto !== false; //是否自动开始 self.workerThread = ops.workerThread || 1; //工作线程 self.timeout = ops.timeout; //超时时间(毫秒) self.id = 0; if (ops.rtype == "auto") self.rtype = getType(tasks); LIST_CUSTOM_EVENT.forEach(function (type) { var fn = ops[type]; if (fn) self.on(type, fn); }); if (ops.inject) self.inject = ops.inject; if (ops.process) self.process = ops.process; if (ops.processResult) self.processResult = ops.processResult; self.ops = ops; self.reset(); self.addList(tasks); } factory(Queue).extend({ //添加自定义事件 on: function (type, fn) { this._listener.add(type, fn); return this; }, //触发自定义事件 trigger: function (type, args) { this._listener.trigger(type, args); return this; }, //重置队列 reset: function () { var self = this; self.tasks = []; self.index = 0; self.id = 0; self.workerIdle = self.workerThread; return self; }, //添加任务 _add: function (args, key, auto) { var self = this, tasks = self.tasks, count = self.count, is_add = true; var task = { id: ++self.id, args: makeArray(args), state: QUEUE_TASK_READY }; if (key != undefined) task.key = key; if (tasks.length >= count) { if (self.index) { tasks = tasks.slice(self.index); self.index = 0; } if (tasks.length >= count) { var is_dropped = self.limitMode == 2, dropped_tasks; if (is_dropped) { dropped_tasks = tasks.slice(0, tasks.length - count + 1); tasks = tasks.slice(-count + 1); self.index = 0; } else { is_add = false; } self.trigger("limit", is_dropped ? dropped_tasks : task); } self.tasks = tasks; } if (is_add) { tasks.push(task); self.trigger("add", task); } if (auto) self.start(); return self; }, //添加任务 add: function () { return this._add(arguments, undefined, this.auto); }, //批量添加任务 addList: function (tasks) { var self = this; if (!tasks) return self; if (isArrayLike(tasks)) { Array.forEach(tasks, function (v, i) { self._add(v, i, false); }); } else { Object.forEach(tasks, function (k, v) { self._add(v, k, false); }); } if (self.auto) self.start(); return self; }, //返回队列长度,可指定任务状态 size: function (state) { return state != undefined ? this.tasks.filter(function (task) { return task.state == state; }).length : this.tasks.length; }, //运行队列 _run: function () { var self = this; if (self.stopped || self.workerIdle <= 0 || self.index >= self.tasks.length) return self; var task = self.tasks[self.index++], timeout = self.timeout; self.workerIdle--; self.trigger("start", task); //跳过任务 if (task.state != QUEUE_TASK_READY) return self.ok(task); task.state = QUEUE_TASK_PROCESSING; //超时检测 if (isUInt(timeout)) task._timer = delay(self.ok, self, timeout, [task, QUEUE_TASK_TIMEDOUT]); //处理任务 self.process(task, function () { self.ok(task, QUEUE_TASK_OK); }); return self.workerIdle ? self._run() : self; }, //启动队列,默认延迟10ms start: function () { var self = this; self.stopped = false; if (!self.auto) self.auto = true; delay(self._run, self, 10); return self; }, //暂停队列,可以调用start方法重新启动队列 //time:可选,暂停的毫秒数 stop: function (time) { var self = this; self.stopped = true; if (isUInt(time)) delay(self.start, self, time); return self; }, //回调函数注入(支持2级注入) inject: function (task, callback) { var self = this, ops = self.ops, injectIndex = ops.injectIndex || 0, //执行函数中回调函数所在参数索引 injectCallback = ops.injectCallback, //如果该参数是一个对象,需指定参数名称,可选 args = (task.args || []).slice(0); //自执行函数 if (!ops.exec && isFunc(args[0])) injectIndex++; //task.args 克隆,避免对原数据的影响 var data = args[injectIndex], originalCallback; //注入回调函数 var inject = function (result) { //注入结果仅取第一个返回值,有多个结果的请使用数组或对象传递 task.result = result; //执行原回调函数(如果有) if (isFunc(originalCallback)) originalCallback.apply(this, arguments); //触发任务完成回调,并执行下一个任务 callback(); }; if (injectCallback != undefined) { if (!data) data = {}; //避免重复注入 var qcallback = data.__qcallback; originalCallback = qcallback || data[injectCallback]; if (!qcallback && originalCallback) data.__qcallback = originalCallback; data[injectCallback] = inject; args[injectIndex] = data; } else { originalCallback = data; args[injectIndex] = inject; } return args; }, //处理队列任务 process: function (task, callback) { var self = this, ops = self.ops, exec = ops.exec, //执行函数 bind = ops.bind, //执行函数绑定的上下文,可选 args = self.inject(task, callback); if (exec) return exec.apply(bind, args); var fn = args[0]; if (!fn) return; if (fn instanceof Queue) fn.start(); else if (Q.isFunc(fn)) fn.apply(bind, args.slice(1)); }, //队列完成时,任务结果处理,用于complete事件参数 processResult: function (tasks) { switch (this.rtype) { case "array": case "list": case "arguments": return tasks.items("result"); case "object": return tasks.toObjectMap("key", "result"); } return [tasks]; }, //所有任务是否已完成 isCompleted: function (tasks) { return (tasks || this.tasks).every(function (task) { return task.state == QUEUE_TASK_OK || task.state == QUEUE_TASK_TIMEDOUT; }); }, //设置任务执行状态为完成并开始新的任务 ok: function (task, state) { var self = this; if (task.state != QUEUE_TASK_PROCESSING) return self._run(); if (++self.workerIdle > self.workerThread) self.workerIdle = self.workerThread; if (task._timer) clearTimeout(task._timer); if (state != undefined) task.state = state; //触发任务完成事件 self.trigger("end", task); if (self.stopped) { //任务已停止且完成时触发任务停止事件 if (self.isCompleted(self.tasks.slice(0, self.index))) self.trigger("stop", self.processResult(self.tasks)); } else { //当前队列任务已完成 if (self.isCompleted()) { self.trigger("complete", self.processResult(self.tasks)); //队列完成事件,此为提供注入接口 fire(self.complete, self); } } return self._run(); } }); //队列任务状态 Queue.TASK = { TIMEDOUT: QUEUE_TASK_TIMEDOUT, READY: QUEUE_TASK_READY, PROCESSING: QUEUE_TASK_PROCESSING, OK: QUEUE_TASK_OK }; /** * 函数排队执行 * @param {Array} tasks 任务数组 * @param {function} complete 队列完成处理函数 * @param {object} ops 配置对象 eg: {tasks:[],count:10000,limitMode:1,auto:true,workerThread:1,timeout:0,injectIndex:1,injectCallback:'complete',exec:function(task,next){},process:function(task,next){},processResult:function(tasks){}} * @param {number} workerThread 同时执行的任务数量 */ function series(tasks, complete, ops, workerThread) { if (isObject(complete)) { ops = complete; complete = undefined; } return new Queue(extend(ops || {}, { rtype: "auto", workerThread: workerThread, tasks: tasks, complete: complete })); } /** * 函数并行执行 * @param {Array} tasks 任务数组 * @param {function} complete 队列完成处理函数 * @param {object} ops 配置对象 eg: {tasks:[],count:10000,limitMode:1,auto:true,workerThread:1,timeout:0,injectIndex:1,injectCallback:'complete',exec:function(task,next){},process:function(task,next){},processResult:function(tasks){}} * @param {number} workerThread 同时执行的任务数量 */ function parallel(tasks, complete, ops, workerThread) { return series(tasks, complete, ops, workerThread || (isArrayLike(tasks) ? tasks.length : Object.size(tasks))); } var jslib = (Q.G || {}).$ || {}; /** * ajax队列 * @param {object} ops 配置对象 eg: {tasks:[],count:10000,limitMode:1,auto:true,workerThread:1,timeout:0,injectIndex:1,injectCallback:'complete',exec:function(task,next){},process:function(task,next){},processResult:function(tasks){}} */ function ajaxQueue(ops) { ops = ops || {}; return new Queue(extend(ops, { exec: ops.ajax || Q.ajax || Q.http || jslib.ajax, injectIndex: 1, injectCallback: "complete" })); } //------------------------- export ------------------------- extend(Q, { Queue: Queue, series: series, parallel: parallel, ajaxQueue: ajaxQueue }); })(); /* * Q.core.js (包括 通用方法、JSON、Cookie、Storage 等) for browser * author:devin87@qq.com * update:2021/09/24 10:58 */ (function (undefined) { "use strict"; var isObject = Q.isObject, isFunc = Q.isFunc, isHttpURL = Q.isHttpURL, getType = Q.type, makeArray = Q.makeArray, extend = Q.extend, fire = Q.fire, join_url = Q.join, waitFor = Q.waitFor; var window = Q.G, document = window.document, html = document.documentElement, head = document.head || document.getElementsByTagName("head")[0], is_quirk_mode = document.compatMode == "BackCompat", body, root; //编码url参数 var encode_url_param = encodeURIComponent; //解码url参数值 eg:%E6%B5%8B%E8%AF%95 => 测试 function decode_url_param(param) { try { return decodeURIComponent(param); } catch (e) { return param; } } var map_loaded_resource = {}, GUID_RESOURCE = Date.now(), //LOAD_READY = 0, LOAD_PROCESSING = 1, LOAD_COMPLETE = 2; //通过创建html标签以载入资源 //init:初始化函数,返回html标签 eg:init(url) -> script|link function load_with_html(urls, callback, ops, init) { var list = makeArray(urls), length = list.length; if (length <= 0) return; ops = ops || {}; if (isObject(callback)) { ops = callback; callback = ops.complete; } var create_element = ops.init || init, count = 0; var afterLoad = function (url, element) { if (map_loaded_resource[url] == LOAD_COMPLETE) return; map_loaded_resource[url] = LOAD_COMPLETE; if (ops.removed) head.removeChild(element); fire(ops.after, element, url, element); doComplete(url); }; //所有资源加载完毕 var doComplete = function (url) { if (++count >= length) fire(callback, undefined, url); }; list.forEach(function (url) { if (ops.data) url = join_url(url, ops.data); else if (ops.cache === false) url = join_url(url, "_=" + (++GUID_RESOURCE)); //避免加载重复资源 if (ops.once !== false && map_loaded_resource[url]) { //已加载过,直接返回 if (map_loaded_resource[url] == LOAD_COMPLETE) return doComplete(url); //正在加载,等待加载完成 return waitFor(function () { return map_loaded_resource[url] == LOAD_COMPLETE; }, function () { doComplete(url); }); } var element = create_element(url); map_loaded_resource[url] = LOAD_PROCESSING; element.onreadystatechange = function () { if (this.readyState == "loaded" || this.readyState == "complete") afterLoad(url, this); }; element.onload = function () { afterLoad(url, this); }; fire(ops.before, element, url, element); head.insertBefore(element, head.lastChild); }); list = null; } //加载脚本文件 //callback:回调函数 function loadJS(urls, callback, ops) { load_with_html(urls, callback, ops, function (url) { var script = document.createElement("script"); script.type = "text/javascript"; script.src = url; return script; }); } //加载样式文件 //callback:回调函数 function loadCSS(urls, callback, ops) { load_with_html(urls, callback, ops, function (url) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; return link; }); } //---------------------- browser.js ---------------------- var browser_ie, engine_name = "unknown", engine = {}; //ie11 开始不再保持向下兼容(例如,不再支持 ActiveXObject、attachEvent 等特性) if (window.ActiveXObject || window.msIndexedDB) { //window.ActiveXObject => ie10- //window.msIndexedDB => ie11+ engine.ie = browser_ie = document.documentMode || (!!window.XMLHttpRequest ? 7 : 6); engine["ie" + (browser_ie < 6 ? 6 : browser_ie)] = true; engine_name = "trident"; } else if (window.opera) { engine_name = "opera"; } else if (window.mozInnerScreenX != undefined || isFunc(document.getBoxObjectFor)) { //document.getBoxObjectFor => firefox3.5- //window.mozInnerScreenX => firefox3.6+ engine_name = "gecko"; } else if (window.webkitMediaStream || window.WebKitPoint) { //window.WebKitPoint => chrome38- //window.webkitMediaStream => chrome39+ engine_name = "webkit"; } engine[engine_name] = true; extend(Q, engine); engine.name = engine_name; //----------------------- JSON.js ----------------------- var has = Object.prototype.hasOwnProperty, JSON_SPECIAL = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, JSON_NULL = "null"; //字符转义 function json_replace(c) { //return JSON_SPECIAL[c]||'\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); return JSON_SPECIAL[c] || c; } //json转化 function json_encode(obj) { switch (getType(obj)) { case "string": return '"' + obj.replace(/[\x00-\x1f\\"]/g, json_replace) + '"'; case "list": case "array": var tmp = []; for (var i = 0, len = obj.length; i < len; i++) { if (typeof obj[i] !== "function") tmp.push(obj[i] != undefined ? json_encode(obj[i]) : JSON_NULL); } return "[" + tmp + "]"; case "object": case "arguments": var tmp = []; for (var k in obj) { if (has.call(obj, k) && typeof obj[k] !== "function") tmp.push("\"" + k + "\":" + json_encode(obj[k])); } return "{" + tmp.toString() + "}"; case "boolean": return obj + ""; case "number": return isFinite(obj) ? obj + "" : JSON_NULL; case "date": return isFinite(obj.valueOf()) ? "\"" + obj.toUTC().format("yyyy-MM-ddTHH:mm:ss.SZ") + "\"" : JSON_NULL; case "function": return; default: return typeof obj == "object" ? "{}" : JSON_NULL; } } //json解析 //secure:是否进行安全检测 function json_decode(text, secure) { //安全检测 if (secure !== false && !/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) throw new Error("JSON SyntaxError"); try { return (new Function("return " + text))(); } catch (e) { } } if (!window.JSON) { window.JSON = { stringify: json_encode, parse: json_decode }; } JSON.encode = json_encode; JSON.decode = json_decode; //------------------------------- cookie.js ------------------------------- //解析cookie值 function parseCookieValue(s) { if (s.indexOf('"') === 0) s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); return decode_url_param(s.replace(/\+/g, ' ')); } //读取cookie值或返回整个对象 function getCookie(key) { var result = key ? undefined : {}, cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0, len = cookies.length; i < len; i++) { var parts = cookies[i].split('='), name = decode_url_param(parts[0]), cookie = parts.slice(1).join('='); if (key && key === name) { result = parseCookieValue(cookie); break; } if (!key && (cookie = parseCookieValue(cookie)) !== undefined) { result[name] = cookie; } } return result; } //设置cookie function setCookie(key, value, ops) { ops = ops || {}; var expires = ops.expires; if (typeof expires === "number") expires = new Date().add("d", expires); document.cookie = [ encode_url_param(key), '=', encode_url_param(value), expires ? '; expires=' + expires.toUTCString() : '', ops.path ? '; path=' + ops.path : '', ops.domain ? '; domain=' + ops.domain : '', ops.secure ? '; secure' : '' ].join(''); } //移除cookie function removeCookie(key) { if (getCookie(key) != undefined) setCookie(key, '', { expires: -1 }); } //清空cookie function clearCookie() { var cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0, len = cookies.length; i < len; i++) { var parts = cookies[i].split('='), key = decode_url_param(parts[0]); removeCookie(key); } } var cookie = { get: getCookie, set: setCookie, remove: removeCookie, clear: clearCookie }; //------------------------------- Storage.js ------------------------------- //type:localStorage | sessionStorage //useCookie:在其它特性不支持的情况下是否启用cookie模拟 function Storage(type, useCookie) { var isLocal = type != "sessionStorage"; if (!isLocal && !location.host) return; var STORE_NAME = type, storage = window[STORE_NAME], adapter = storage && "getItem" in storage ? "storage" : null; if (!adapter) { var userData = document.documentElement, TEST_KEY = "_Q_"; try { //ie userdata userData.addBehavior('#default#userdata'); //7天后过期 if (isLocal) userData.expires = new Date().add("d", 7).toUTCString(); STORE_NAME = location.hostname || "local"; userData.save(STORE_NAME); storage = { getItem: function (key) { userData.load(STORE_NAME); return userData.getAttribute(key); }, setItem: function (key, value) { userData.setAttribute(key, value); userData.save(STORE_NAME); }, removeItem: function (key) { userData.removeAttribute(key); userData.save(STORE_NAME); }, clear: function () { userData.load(STORE_NAME); var now = new Date().add("d", -1); userData.expires = now.toUTCString(); userData.save(STORE_NAME); } }; if (storage.getItem(TEST_KEY) === undefined) { storage.setItem(TEST_KEY, 1); storage.removeItem(TEST_KEY); } adapter = "userdata"; } catch (e) { } //cookie 模拟 if (!adapter && useCookie) { storage = { getItem: getCookie, //setItem: setCookie, setItem: isLocal ? function (key, value) { setCookie(key, value, { expires: 7 }); } : setCookie, removeItem: removeCookie, clear: clearCookie }; adapter = "cookie"; } } var support = !!adapter; var store = { //是否支持本地缓存 support: support, //适配器:storage|userdata|cookie|null adapter: adapter, //获取本地缓存 get: function (key, isJSON) { if (support) { try { var value = storage.getItem(key); return isJSON ? (value ? JSON.parse(value) : null) : value; } catch (e) { } } return undefined; }, //设置本地缓存 set: function (key, value) { if (support) { try { storage.setItem(key, typeof value == "string" ? value : JSON.stringify(value)); return true; } catch (e) { } } return false; }, //删除本地缓存 remove: function (key) { if (support) { try { storage.removeItem(key); return true; } catch (e) { } } return false; }, //清空本地缓存 clear: function () { if (support) { try { storage.clear(); return true; } catch (e) { } } return false; } }; return store; } //----------------------- view ----------------------- //页面视图 var view = { //获取可用宽高 getSize: function () { return { width: root.clientWidth, height: root.clientHeight }; }, //获取可用宽度 getWidth: function () { return root.clientWidth; }, //获取可用高度 getHeight: function () { return root.clientHeight; }, //获取页面宽度(包括滚动条) getScrollWidth: function () { //fix webkit bug:document.documentElement.scrollWidth等不能准确识别 return Math.max(html.scrollWidth, body.scrollWidth); }, //获取页面高度(包括滚动条) getScrollHeight: function () { //fix webkit bug return Math.max(html.scrollHeight, body.scrollHeight); }, //获取左边的滚动距离 getScrollLeft: function () { //fix webkit bug return html.scrollLeft || body.scrollLeft; }, //获取上边的滚动距离 getScrollTop: function () { //fix webkit bug return html.scrollTop || body.scrollTop; } }; //---------------------- 其它 ---------------------- //是否是输入按键 function isInputKey(code) { //65-90 : A-Z //32 : 空格键 //229 : 中文输入 //48-57 : 大键盘0-9 //96-105 : 小键盘0-9 //106-111 : * + Enter - . / if ((code >= 65 && code <= 90) || code == 32 || code == 229 || (code >= 48 && code <= 57) || (code >= 96 && code <= 111 && code != 108)) return true; //186-192 : ;: =+ ,< -_ .> /? `~ //219-222 : [{ \| ]} '" if ((code >= 186 && code <= 192) || (code >= 219 && code <= 222)) return true; //8 : BackSpace //46 : Delete if (code == 8 || code == 46) return true; return false; }; //判断指定路径与当前页面是否同域(包括协议检测 eg:http与https不同域) function isSameHost(url) { if (!isHttpURL(url)) return true; var start = RegExp.lastMatch.length, end = url.indexOf("/", start), host = url.slice(0, end != -1 ? end : undefined); return host.toLowerCase() == (location.protocol + "//" + location.host).toLowerCase(); } //清除文本选区 function clearSelection() { if (window.getSelection) { var sel = getSelection(); if (sel.removeAllRanges) sel.removeAllRanges(); else if (sel.empty) sel.empty(); //old chrome and safari } else if (document.selection) { //ie document.selection.empty(); } } //---------------------- export ---------------------- function ready(fn) { waitFor(function () { return Q.root; }, fn); } extend(Q, { html: html, head: head, quirk: is_quirk_mode, ready: ready, loadJS: loadJS, loadCSS: loadCSS, engine: engine, isInputKey: isInputKey, isSameHost: isSameHost, clearSelection: clearSelection, cookie: cookie, store: new Storage("localStorage", true), session: new Storage("sessionStorage", true), view: view, Storage: Storage }); //调用涉及到 body 操作的方法时,推荐在body标签闭合之前引入 Q.core.js 库 function init() { Q.body = body = document.body; Q.root = root = is_quirk_mode ? body : html; } //确保 document.body 已就绪 if (document.body) init(); else waitFor(function () { return document.body; }, init); //暴露接口 window.request = Q.parseUrlParams(location.search); })(); /* * Q.setTimer.js 计时器 * author:devin87@qq.com * update:2017/11/22 15:14 */ (function (undefined) { "use strict"; var fire = Q.fire; //---------------------- 计时器 ---------------------- //计时器 //ops: { box:".uptime",time:1566, pad:true, step:1, sleep:1000, join:"",units:["天", "时", "分", "秒"],process:function(total, text, days, hours, mintues, seconds){} } function setTimer(ops) { var box = ops.box, process = ops.process, length = ops.pad ? 2 : 1, time = ops.time, step = ops.step || 1, sleep = ops.sleep || 1000, max = +ops.max || 0, str_join = ops.join || "", units = ops.units || ["天", "小时", "分", "秒"]; if ((!box && !process) || time == undefined || isNaN(time)) return; var total = +time, timer; var pad = function (n, len) { return n > 9 || len == 1 ? n : "0" + n; }; var update = function () { total += step; if (total < max) return fire(ops.over); if (timer) clearTimeout(timer); var t = Date.parts(total), days = t.days, hours = t.hours, mintues = t.mintues, seconds = t.seconds; var text = days + units[0] + str_join + pad(hours, length) + units[1] + str_join + pad(mintues, length) + units[2] + str_join + pad(seconds, length) + units[3], result = fire(process, undefined, total, text, days, hours, mintues, seconds); if (result !== false) { $(box).html(typeof result == "string" ? result : text); timer = setTimeout(update, sleep); } }; update(); var api = { start: update, stop: function () { if (timer) clearTimeout(timer); } }; return api; } //------------------------- export ------------------------- Q.setTimer = setTimer; })(); /* * Q.UI.adapter.jquery.js * author:devin87@qq.com * update:2017/12/25 13:44 */ (function (undefined) { "use strict"; var window = Q.G, isFunc = Q.isFunc, isObject = Q.isObject, isArrayLike = Q.isArrayLike, extend = Q.extend, makeArray = Q.makeArray, view = Q.view; //---------------------- event.js ---------------------- function stop_event(event, isPreventDefault, isStopPropagation) { var e = new jQuery.Event(event); if (isPreventDefault !== false) e.preventDefault(); if (isStopPropagation !== false) e.stopPropagation(); } jQuery.Event.prototype.stop = function () { stop_event(this); }; var SUPPORT_W3C_EVENT = !!document.addEventListener; //添加DOM事件,未做任何封装 function addEvent(ele, type, fn) { if (SUPPORT_W3C_EVENT) ele.addEventListener(type, fn, false); else ele.attachEvent("on" + type, fn); //注意:fn的this并不指向ele } //移除DOM事件 function removeEvent(ele, type, fn) { if (SUPPORT_W3C_EVENT) ele.removeEventListener(type, fn, false); else ele.detachEvent("on" + type, fn); } //添加事件 function add_event(ele, type, selector, fn, once, stops) { var handle = fn; if (once) { handle = function (e) { fn.call(this, e); $(ele).off(type, selector, handle); }; } $(ele).on(type, selector, handle); if (!once) stops.push([ele, type, handle, selector]); } //批量添加事件 //types:事件类型,多个之间用空格分开;可以为对象 //selector:要代理的事件选择器或处理句柄 function add_events(elements, types, selector, handle, once) { if (typeof types == "string") { types = types.split(' '); if (isFunc(selector)) { once = once || handle; handle = selector; selector = undefined; } } else { if (selector === true || handle === true) once = true; if (selector === true) selector = undefined; } var stops = []; makeArray(elements).forEach(function (ele) { if (isArrayLike(types)) { makeArray(types).forEach(function (type) { add_event(ele, type, selector, handle, once, stops); }); } else if (isObject(types)) { Object.forEach(types, function (type, handle) { add_event(ele, type, selector, handle, once, stops); }); } }); //返回移除事件api return { es: stops, off: function (types, selector) { remove_events(stops, types, selector); } }; } //批量移除事件 //es:事件句柄对象列表 eg:es => [[ele, type, handle, selector],...] function remove_events(es, types, selector) { es.forEach(function (s) { $(s[0]).off(s[1], s[3], s[2]); }); } //批量添加事件,执行一次后取消 function add_events_one(elements, types, selector, handle) { return add_events(elements, types, selector, handler, true); } Q.event = { fix: function (e) { return new jQuery.Event(e); }, stop: stop_event, trigger: function (el, type) { $(el).trigger(type); }, //原生事件添加(建议使用add) addEvent: addEvent, //原生事件移除 removeEvent: removeEvent, //添加事件,并返回操作api add: add_events, //注意:批量移除事件,与一般事件移除不同;移除事件请使用add返回的api removeEs: remove_events, one: add_events_one }; //---------------------- dom.js ---------------------- //var _parseFloat = parseFloat; //当元素的css值与要设置的css值不同时,设置css function setCssIfNot(el, key, value) { var $el = $(el); if (el && $el.css(key) != value) $el.css(key, value); } //创建元素 function createEle(tagName, className, html) { var el = document.createElement(tagName); if (className) el.className = className; if (html) el.innerHTML = html; return el; } //动态创建样式 function createStyle(cssText) { var style = document.createElement("style"); style.type = "text/css"; style.styleSheet && (style.styleSheet.cssText = cssText) || style.appendChild(document.createTextNode(cssText)); Q.head.appendChild(style); return style; } //解析html为元素,默认返回第一个元素节点 //all:是否返回所有节点(childNodes) function parseHTML(html, all) { var _pNode = createEle("div", undefined, html); return all ? _pNode.childNodes : Q.getFirst(_pNode); } //移除指定内联样式 function removeCss(el, key) { var cssText = el.style.cssText; if (cssText) el.style.cssText = cssText.drop(key + "(-[^:]+)?\\s*:[^;]*;?", "gi").trim(); } //将输入框样式设为错误模式 //value:重置后输入框的值,默认为空字符串 function setInputError(input, hasBorder, value) { if (hasBorder) input.style.borderColor = "red"; else input.style.border = "1px solid red"; input.value = value || ""; input.focus(); } //恢复输入框默认样式 function setInputDefault(input) { removeCss(input, "border"); } var NODE_PREV = "previousSibling", NODE_NEXT = "nextSibling", NODE_FIRST = "firstChild", NODE_LAST = "lastChild"; //遍历元素节点 function walk(el, walk, start, all) { var el = el[start || walk]; var list = []; while (el) { if (el.nodeType == 1) { if (!all) return el; list.push(el); } el = el[walk]; } return all ? list : null; } var DEF_OFFSET = { left: 0, top: 0 }; extend(Q, { camelCase: $.camelCase, attr: function (el, key, value) { return $(el).attr(key, value); }, prop: function (el, key, value) { return $(el).prop(key, value); }, width: function (el, w) { return $(el).width(w); }, height: function (el, h) { return $(el).height(h); }, getStyle: function (el, key) { return $(el).css(key); }, setStyle: function (el, key, value) { if (value === null) return removeCss(el, key); $(el).css(key, value); }, setOpacity: function (el, value) { return $(el).css("opacity", value); }, removeCss: removeCss, css: function (el, key, value) { return $(el).css(key, value); }, show: function (el) { $(el).show(); }, hide: function (el) { $(el).hide(); }, toggle: function (el) { $(el).toggle(); }, isHidden: function (el) { return $(el).is(":hidden"); }, offset: function (el, x, y) { var $el = $(el); if (x === undefined && y === undefined) { var offset = $el.offset(); offset.width = $el.outerWidth(); offset.height = $el.outerHeight(); return offset; } setCssIfNot(el, "position", "absolute"); if (x !== undefined) $el.css("left", x); if (y !== undefined) $el.css("top", y); }, //getPos: function (el, pNode) { // if (!pNode) pNode = el.offsetParent; // var $el = $(el), // $pl = $(pNode), // offset = $el.offset(), // poffset = $pl.offset(); // offset.left -= poffset.left + _parseFloat($pl.css("borderLeftWidth")) + _parseFloat($el.css("marginLeft")); // offset.top -= poffset.top + _parseFloat($pl.css("borderTopWidth")) + _parseFloat($el.css("marginTop")); // return offset; //}, setCssIfNot: setCssIfNot, setCenter: function (el, onlyPos) { setCssIfNot(el, "position", "absolute"); var size = view.getSize(), offset = $(el.offsetParent).offset() || DEF_OFFSET, left = Math.round((size.width - $(el).outerWidth()) / 2) - offset.left + view.getScrollLeft(), top = Math.round((size.height - $(el).outerHeight()) / 2) - offset.top + view.getScrollTop(), pos = { left: Math.max(left, 0), top: Math.max(top, 0) }; return onlyPos ? pos : $(el).css(pos); }, getFirst: function (el) { return el.firstElementChild || walk(el, NODE_NEXT, NODE_FIRST, false); }, getLast: function (el) { return el.lastElementChild || walk(el, NODE_PREV, NODE_LAST, false); }, getPrev: function (el) { return el.previousElementSibling || walk(el, NODE_PREV, null, false); }, getNext: function (el) { return el.nextElementSibling || walk(el, NODE_NEXT, null, false); }, getChilds: function (el) { //walk方式性能要好于通过childNodes筛选 return el.children ? makeArray(el.children) : walk(el, NODE_NEXT, NODE_FIRST, true); }, findTag: function (el, tagName) { while (el && el.tagName != "BODY") { if (el.tagName == tagName) return el; el = el.parentNode; } }, createEle: createEle, createStyle: createStyle, parseHTML: parseHTML, removeEle: function (el) { $(el).remove(); }, hasClass: function (el, clsName) { return $(el).hasClass(clsName); }, addClass: function (el, clsName) { $(el).addClass(clsName); }, removeClass: function (el, clsName) { $(el).removeClass(clsName); }, replaceClass: function (el, oldName, clsName) { $(el).removeClass(oldName).addClass(clsName); }, toggleClass: function (el, clsName) { $(el).toggleClass(clsName); }, setInputError: setInputError, setInputDefault: setInputDefault }); window.$$ = Q.query = $.find; })(); /* * Q.UI.Box.js (包括遮罩层、拖动、弹出框) * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2022/04/14 11:10 */ (function (undefined) { "use strict"; var window = Q.G, document = window.document, isObject = Q.isObject, isFunc = Q.isFunc, isUNum = Q.isUNum, isUInt = Q.isUInt, def = Q.def, fire = Q.fire, async = Q.async, extend = Q.extend, makeArray = Q.makeArray, getStyle = Q.getStyle, setStyle = Q.setStyle, getFirst = Q.getFirst, getNext = Q.getNext, //getLast = Q.getLast, setWidth = Q.width, setHeight = Q.height, createEle = Q.createEle, removeEle = Q.removeEle, cssShow = Q.show, cssHide = Q.hide, isHidden = Q.isHidden, addClass = Q.addClass, setCssIfNot = Q.setCssIfNot, setCenter = Q.setCenter, setInputError = Q.setInputError, setInputDefault = Q.setInputDefault, clearSelection = Q.clearSelection, query = Q.query, factory = Q.factory, browser_ie = Q.ie, isIE6 = browser_ie < 7, view = Q.view, Listener = Q.Listener, E = Q.event; //------------------------- Mask ------------------------- var GLOBAL_MASK_SETTINGS = { color: "#999", opacity: 0.3 }; //构造器:遮罩层 function MaskBox(ops) { var box = createEle("div", "x-mask"); Q.body.appendChild(box); if (isIE6) box.style.height = view.getScrollHeight() + "px"; this.box = box; this.set(extend(ops || {}, GLOBAL_MASK_SETTINGS)); this.count = isHidden(box) ? 0 : 1; } factory(MaskBox).extend({ //设置透明度 opacity: function (opacity) { return this.set({ opacity: opacity }); }, //设置遮罩层样式 eg:{color,zIndex,width,height} set: function (ops) { var box = this.box; Object.forEach(ops, function (key, value) { if (value !== undefined) setStyle(box, key != "color" ? key : "backgroundColor", value); }); return this; }, //显示遮罩层 show: function () { if (this.removed) { Q.body.appendChild(this.box); this.removed = false; } cssShow(this.box); this.count++; return this; }, //隐藏遮罩层 hide: function () { if (this.count > 0) this.count--; if (this.count <= 0) cssHide(this.box); return this; }, //移除遮罩层 remove: function () { removeEle(this.box); this.removed = true; this.count = 0; return this; } }); var GLOBAL_MASK_BOX; //获取通用遮罩层(默认配置) function getMaskBox() { if (GLOBAL_MASK_BOX) { GLOBAL_MASK_BOX.show(); return GLOBAL_MASK_BOX; } GLOBAL_MASK_BOX = new MaskBox(); return GLOBAL_MASK_BOX; } //修改遮罩层全局配置 function maskSetup(ops, isUpdateUI) { extend(GLOBAL_MASK_SETTINGS, ops, true); if (isUpdateUI && GLOBAL_MASK_BOX) GLOBAL_MASK_BOX.reset(ops); } //------------------------- Drag ------------------------- //获取所有顶层窗口(parent) function getTops(w) { var parents = [], cwin = w || window; while (cwin.top != cwin) { var pwin = cwin.parent; parents.push(pwin); cwin = pwin; } return parents; } /*//获取所有内嵌框架 function _getFrames(w, ret) { var frames = w.frames, len = frames.length; if (len <= 0) return; for (var i = 0; i < len; i++) { ret.push(frames[i]); _getFrames(frames[i], ret); } } //获取所有内嵌框架 function getFrames(w) { var frames = []; _getFrames(w || window, frames); return frames; }*/ var DEF_INDEX = 1000, CURRENT_INDEX = DEF_INDEX, MASK_FOR_FRAME; //基础拖动对象 function DragX(init) { var self = this; fire(init, self); self._apis = []; self.start(); } factory(DragX).extend({ //开始拖动 start: function () { var self = this, ops = self.ops, win = ops.scope || window, document = win.document, ele = ops.ele, target = ops.target || ele, autoIndex = ops.autoIndex !== false, autoMask = !!ops.autoMask, autoCss = ops.autoCss !== false, autoCursor = ops.autoCursor !== false, zIndex = ele.nodeType == 1 ? +getStyle(ele, "z-index") : 0, doDown = self.doDown, doMove = self.doMove, doUp = self.doUp, onCheck = ops.onCheck, onDown = ops.onDown, onMove = ops.onMove, onUp = ops.onUp, topWins = getTops(win), //frameWins, hasCapture = !!ele.setCapture, hasListen = !hasCapture && topWins.length > 0; //是否需要监听其它窗口 if (zIndex >= CURRENT_INDEX) CURRENT_INDEX = zIndex + 1; //初始化元素状态 if (autoCss) setCssIfNot(ele, "position", "absolute"); if (autoCss && autoCursor) setCssIfNot(target, "cursor", "move"); //设置元素居中 if (ops.center) { setCenter(ele); self._api_resize = E.add(win, "resize", function () { setCenter(ele); }); } //鼠标按下事件 var mousedown = function (e) { if (isFunc(onCheck) && onCheck.call(self, e) === false) return; if (autoIndex) { var _zIndex = +getStyle(ele, "z-index") || 0; if (_zIndex < CURRENT_INDEX) { CURRENT_INDEX++; ele.style.zIndex = CURRENT_INDEX; } } self._unbind(); if (hasCapture) { ele.setCapture(); self._bind(ele, "losecapture", mouseup); } else { self._bind(win, "blur", mouseup); } self._bind(document, { "mousemove": mousemove, "mouseup": mouseup }); if (hasListen) self._bind(topWins, "mouseup", mouseup); //frameWins = getFrames(win); //var hasMask = autoMask && !hasCapture && frameWins.length > 0; //创建一个遮罩层,在遮罩层上拖动 //1. 避免某些浏览器在经过iframe时鼠标事件响应不正常 //2. 避免拖动过程产生文本选区 if (autoMask) { if (!MASK_FOR_FRAME) MASK_FOR_FRAME = new MaskBox({ color: null, opacity: null, zIndex: 999999 }); if (isIE6) MASK_FOR_FRAME.set({ height: view.getScrollHeight() }); } //清除文本选区 async(clearSelection, 20); fire(doDown, self, e); fire(onDown, self, e); }; //鼠标移动事件 var mousemove = function (e) { if (self._pause) return; fire(doMove, self, e); fire(onMove, self, e); }; //鼠标释放事件 var mouseup = function (e) { self._unbind(); if (hasCapture) ele.releaseCapture(); if (autoMask && MASK_FOR_FRAME) { MASK_FOR_FRAME.remove(); MASK_FOR_FRAME = null; } clearSelection(); fire(doUp, self, e); fire(onUp, self, e); }; self._up = mouseup; self._api = E.add(target, "mousedown", mousedown); return self; }, //绑定事件 _bind: function () { this._apis.push(E.add.apply(E, arguments)); }, //清理事件绑定 _unbind: function () { var apis = this._apis; if (apis.length > 0) { apis.forEach(function (api) { api.off(); }); this._apis = []; } }, //暂停拖动 pause: function (flag) { var self = this; self._pause = flag; self._up && self._up(); return self; }, //停止拖动 stop: function () { var self = this, api = self._api; self._unbind(); if (api) { api.off(); self._api = null; } return self; }, destroy: function () { var self = this, api_resize = self._api_resize; self.stop(); if (api_resize) { api_resize.off(); self._api_resize = null; } return self; } }); var ELE_DRAG_SHADOW; //设置拖动 function setDrag(ele, ops) { return new DragX(function () { if (ele.nodeType != 1) { ops = ele; ele = ops.ele; } else { ops = ops || {}; ops.ele = ele; } var base = this, range = ops.range || { x: 0, y: 0 }, hasShadow = !!ops.shadow, w = ele.offsetWidth, h = ele.offsetHeight, target = ele, startLeft, startTop, startX, startY, movedX, movedY, _isX, _isY; if (hasShadow) { if (!ELE_DRAG_SHADOW) { ELE_DRAG_SHADOW = createEle("div", "x-drag-shadow"); Q.body.appendChild(ELE_DRAG_SHADOW); } target = ELE_DRAG_SHADOW; } //实现ops接口 base.ops = ops; //实现doDown接口 base.doDown = function (e) { startX = e.clientX; startY = e.clientY; var offset = hasShadow ? $(ele).offset() : $(ele).position(); startLeft = offset.left; startTop = offset.top; if (hasShadow) { Object.forEach({ left: startLeft, top: startTop, width: w, height: h }, function (key, value) { target.style[key] = value + "px"; }); //cssShow(target); } }; //实现doMove接口 base.doMove = function (e) { cssShow(target); if (_isX) { movedX = e.clientX - startX; var x = startLeft + movedX; if (range) { if (x < range.x) x = range.x; else if (range.w && x + w > range.x + range.w) x = range.x + range.w - w; } target.style.left = x + "px"; } if (_isY) { movedY = e.clientY - startY; var y = startTop + movedY; if (range) { if (y < range.y) y = range.y; else if (range.h && y + h > range.y + range.h) y = range.y + range.h - h; } target.style.top = y + "px"; } }; if (hasShadow) { base.doUp = function () { cssHide(target); ele.style.left = (ele.offsetLeft + movedX) + "px"; ele.style.top = (ele.offsetTop + movedY) + "px"; }; } //设置拖动方向 base.setLock = function (isX, isY) { _isX = isX; _isY = isY; return base.pause(!isX && !isY); }; //设置拖动范围 base.setRange = function (x, y, w, h) { range = isObject(x) ? x : { x: x, y: y, w: w, h: h }; return base; }; base.setLock(ops.isX !== false, ops.isY !== false); }); } $.fn.extend({ drag: function (ops) { return this.each(function (i, el) { setDrag(el, ops); }); } }); //------------------------- Box ------------------------- //Box全局事件处理 var listener_box = new Listener(["init", "show", "hide", "remove"]); //接口,构造器:Box对象 function Box(init) { this._es = []; fire(init, this); listener_box.trigger("init", [this]); } factory(Box).extend({ //在弹出框内查找对象 find: function (pattern, context) { return typeof pattern == "string" ? query(pattern, context || this.box) : makeArray(pattern); }, //在弹出框内查找对象 $: function (pattern, context) { return $(this.find(pattern, context)); }, //获取弹出框内查找到的第一个对象 get: function (pattern, context) { return this.find(pattern, context)[0]; }, //触发回调函数 fire: function () { fire(this.callback, this, this.data); return this; }, //获取事件回调函数 getEventCallback: function (fn, data) { var self = this; if (fn == "hide") return function () { self.data = data; self.hide(); }; if (fn == "remove") return function () { self.data = data; self.remove(); }; return fn; }, //绑定事件,同 Event.add,不过会缓存事件句柄,用于统一销毁 bind: function (selector, types, fn, data) { var self = this; self._es.push(E.add(self.find(selector), types, self.getEventCallback(fn, data))); return self; }, //事件代理,将事件代理到box上执行 on: function (types, selector, fn, data) { var self = this; self._es.push(E.add(self.box, types, selector, self.getEventCallback(fn, data))); return self; }, //显示 show: function () { var self = this; if (self.onShow) self.onShow(); cssShow(self.box); if (self.mbox) self.mbox.show(); listener_box.trigger("show", [self]); return self; }, //隐藏 hide: function () { var self = this; cssHide(self.box); if (self.mbox) self.mbox.hide(); if (self.onHide) self.onHide(); listener_box.trigger("hide", [self]); return self.fire(); }, //自动切换显示或隐藏 toggle: function () { return isHidden(this.box) ? this.show() : this.hide(); }, //移除 remove: function () { var self = this; if (!self.box) return; removeEle(self.box); //遮罩层 if (self.mbox) self.mbox.hide(); //拖动框 if (self.dr) self.dr.destroy(); //解除绑定的事件 self._es.forEach(function (api) { api.off(); }); self.box = self.mbox = self.dr = null; if (self.onRemove) self.onRemove(); listener_box.trigger("remove", [self]); return self.fire(); } }); Box.alias({ "$": "query", "remove": "destroy" }); //添加全局事件 type: init、show、hide、remove Box.on = function (type, fn) { listener_box.add(type, fn); return Box; }; //弹出层语言 var LANG_BOX = { titleBox: "弹出框", titleAlert: "提示信息", titleConfirm: "确认信息", titlePrompt: "输入信息", titleClose: "点击关闭", titleLoading: "加载数据", buttonSubmit: "确定", buttonCancel: "取消", textLoading: "正在加载数据,请稍后…" }; //配置弹出层 function setBoxLang(langs) { extend(LANG_BOX, langs, true); } //构造器:弹出层 function WinBox(ops) { ops = ops || {}; return new Box(function () { var self = this, width = ops.width, height = ops.height, maxHeight = def(ops.maxHeight, view.getHeight() - 60), isDrag = ops.drag !== false, isCenter = isDrag && ops.center !== false, className = ops.className; self.ops = ops; self.callback = ops.callback; var html = '<div class="x-head">' + '<h2 class="x-title">' + (ops.title || LANG_BOX.titleBox) + '</h2>' + '<a class="x-close" title="' + LANG_BOX.titleClose + '">X</a>' + '</div>' + '<div class="x-main">' + '<div class="x-view">' + (ops.html || '') + '</div>' + '</div>'; //解决ie6中 div 无法遮盖 select 的问题 if (isIE6) { html += '<iframe class="x-ie-fix" style="position: absolute;top:0;left:0;z-index:-1;" scrolling="no" frameborder="0"></iframe>'; } var box = createEle("div", "x-box" + (className ? " " + className : ""), html); Q.body.appendChild(box); self.box = box; var zIndex = ops.zIndex || 0; if (CURRENT_INDEX > DEF_INDEX) zIndex = Math.max(zIndex, CURRENT_INDEX); if (zIndex) box.style.zIndex = zIndex; var boxHead = getFirst(box), boxMain = getNext(boxHead); //设置标题 self.setTitle = function (title) { $(".x-title", boxHead).html(title); return self; }; //设置宽度 self.setWidth = function (width) { ops.width = width; setWidth(box, width); fire(ops.resize, self); return self; }; //设置高度 self.setHeight = function (height) { ops.height = height; setHeight(boxMain, height - boxHead.offsetHeight - 20); return self; }; //设置最大高度,超出后出现滚动条 self.setMaxHeight = function (maxHeight) { ops.maxHeight = maxHeight; var height = ops.height; if (isUNum(height) && height > maxHeight) height = maxHeight; if (box.scrollHeight > maxHeight) { height = maxHeight; addClass(box, "x-box-auto"); } if (isUNum(height)) self.setHeight(height); if (isCenter) setCenter(box); fire(ops.resize, self); return self; }; //自动调整高度以适应maxHeight self.autoHeight = function () { var maxHeight = ops.maxHeight; if (!maxHeight) return self; var height_head = self.get(".x-head").offsetHeight, height_main = maxHeight - height_head - 20, max_height_main = maxHeight - height_head; boxMain.style.height = boxMain.scrollHeight > max_height_main ? height_main + "px" : "auto"; if (isCenter) setCenter(box); return self; }; //兼容性考虑,width最好指定固定值 if (isUNum(width)) setWidth(box, width); if (boxHead.offsetWidth < 10) setWidth(boxHead, box.offsetWidth); //高度设置 if (maxHeight) self.setMaxHeight(maxHeight); else if (isUNum(height)) self.setHeight(height); //遮罩层 if (ops.mask !== false) self.mbox = ops.mask == "new" ? new MaskBox() : getMaskBox(); var action_close = ops.close || "hide", callback_close = self.getEventCallback(action_close); //点击关闭事件 self.bind(".x-close", "click", action_close); //按ESC关闭事件 if (ops.esc !== false) { self.bind(document, "keyup", function (e) { if (e.keyCode == 27) callback_close(); }); } //指定时间后自动关闭弹出框 var time = ops.time; if (isUInt(time)) async(callback_close, time); fire(ops.init, self, box, ops); //拖动 if (isDrag) { self.dr = setDrag(box, { target: boxHead, center: isCenter, shadow: ops.shadow, autoMask: true, //1.由于拖动会创建一个遮罩层,点击关闭时不会触发 .x-close 的click事件,此处检查点击元素,只有非 .x-close 元素才会执行拖动操作 //2.亦可将 .x-close 的click事件替换为mousedown事件以优先执行,可不必传入onCheck onCheck: function (e) { var target = e.target; return target && target.className != "x-close"; } }); } $(".x-ie-fix", box).width(box.offsetWidth - 2).height(box.offsetHeight - 2); }); } //创建对话框 function createDialogBox(ops) { if (!ops.width) ops.width = 320; var width = ops.width; if (ops.icon || ops.iconHtml) { var html = '<div class="fl x-ico">' + (ops.iconHtml || '<img alt="" src="' + ops.icon + '"/>') + '</div>' + '<div class="fl x-dialog"' + (isUNum(width) ? ' style="width:' + (width - 60) + 'px;"' : '') + '>' + ops.html + '</div>' + '<div class="clear"></div>'; ops.html = html; var oldInit = ops.init; ops.resize = function () { var self = this, contentWidth = self.get(".x-view").offsetWidth - self.get(".x-ico").offsetWidth; $(".x-dialog", self.box).width(contentWidth); }; ops.init = function (box, ops) { var self = this; ops.resize.call(self); fire(oldInit, self, box, ops); }; } else { ops.html = '<div class="x-dialog">' + ops.html + '</div>'; } if (ops.bottom) ops.html += ops.bottom; if (!ops.close) ops.close = "remove"; return WinBox(ops); } //获取底部模板代码 function get_bottom_html(mode, style) { var buttonStyle = 'inline-block w-button w-' + (style || "dark"), html = '<div class="x-bottom">' + '<div class="' + buttonStyle + ' x-submit">' + LANG_BOX.buttonSubmit + '</div>' + (mode == 2 ? '<div class="' + buttonStyle + ' x-cancel">' + LANG_BOX.buttonCancel + '</div>' : '') + '</div>'; return html; } //获取弹出框配置对象 function get_dialog_ops(title, msg, fn, ops) { if (typeof fn === "object") { ops = fn; fn = ops; } ops = extend({}, ops); if (isFunc(fn)) ops.callback = fn; if (!ops.title) ops.title = title; ops.html = msg; return ops; } var dialog = { //创建自定义弹出框 createDialogBox: createDialogBox, //提示框 alert: function (msg, fn, ops) { ops = get_dialog_ops(LANG_BOX.titleAlert, msg, fn, ops); //ops.icon = 'images/Q/alert.gif'; ops.iconHtml = '<div class="ico x-alert"></div>'; return createDialogBox(ops); }, //确认框 confirm: function (msg, fn, ops) { ops = get_dialog_ops(LANG_BOX.titleConfirm, msg, fn, ops); if (!ops.bottom) ops.bottom = get_bottom_html(2); ops.mask = ops.mask !== false; var box = createDialogBox(ops); return box.bind(".x-submit", "click", "remove", true).bind(".x-cancel", "click", "remove", false); }, prompt: function (msg, fn, ops) { ops = get_dialog_ops(LANG_BOX.titlePrompt, undefined, fn, ops); fn = ops.callback; ops.callback = undefined; var html = '<div class="x-text">' + msg + '</div>' + '<div class="x-input"><input type="' + (ops.pwd ? 'password' : 'text') + '" /></div>'; ops.html = html; if (!ops.bottom) ops.bottom = get_bottom_html(2); var box = createDialogBox(ops), input = box.get(".x-input>input"); input.focus(); input.value = def(ops.value, ""); var submit = function () { var v = fire(fn, input, input.value); if (v !== false) box.remove(); else setInputError(input); }; //输入框快捷提交 box.bind(input, "keyup", function (e) { if (e.keyCode == 13) submit(); else setInputDefault(this); }); //确定与取消 return box.bind(".x-submit", "click", submit).bind(".x-cancel", "click", "remove"); }, bottom: get_bottom_html, //显示加载框 showLoading: function (ops) { ops = extend({}, ops); if (!ops.title) ops.title = LANG_BOX.titleLoading; if (!ops.html) ops.html = LANG_BOX.textLoading; //ops.icon = 'images/Q/loading.gif'; ops.iconHtml = '<div class="ico x-loading"></div>'; return createDialogBox(ops); } }; extend(Q, dialog); //------------------------- export ------------------------- extend(Q, { getMaskBox: getMaskBox, maskSetup: maskSetup, setDrag: setDrag, setBoxLang: setBoxLang, MaskBox: MaskBox, DragX: DragX, Box: Box, WinBox: WinBox }); })(); /* * Q.UI.ContextMenu.js 多级上下文菜单(右键菜单) * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2015/11/26 17:19 */ (function (undefined) { "use strict"; var document = window.document, //isObject = Q.isObject, fire = Q.fire, extend = Q.extend, makeArray = Q.makeArray, getStyle = Q.getStyle, getOffset = Q.offset, hasClass = Q.hasClass, addClass = Q.addClass, removeClass = Q.removeClass, createEle = Q.createEle, factory = Q.factory, E = Q.event; var POS_VALUE_HIDDEN = -10000; //设置元素位置 function set_pos(el, x, y) { if (x != undefined) el.style.left = x + "px"; if (y != undefined) el.style.top = y + "px"; } //---------------------- 上下文菜单 ---------------------- function ContextMenu(data, ops) { this.set(ops).init(data); } factory(ContextMenu).extend({ //初始化菜单 init: function (data) { var self = this; self.draw(data); if (self.autoHide !== false) { self._e0 = E.add(document, "click", function () { self.hide(); }); } return self; }, //菜单设置 {x,y,rangeX,rangeY} set: function (ops) { extend(this, ops, true); return this; }, //生成所有菜单 draw: function (data) { var self = this; //数据重置 self._menus = []; self._items = []; self._map_menu = {}; self._map_item = {}; self.i = self.j = 0; self._active = undefined; //生成菜单 var tmp = self._tmp = [], args; self.drawMenu(data); while ((args = tmp.shift())) { self.drawMenu.apply(self, args); } self._tmp = null; self.i = self.j = 0; //主菜单 var box = self._getMenu(0).node; self.box = box; //------------ 菜单事件 ------------ var list_box = []; self._menus.forEach(function (m) { if (m && !m.linked) list_box.push(m.node); }); //移除之前绑定的事件 if (self._e1) self._e1.off(); self._e1 = E.add(list_box, { click: function (e) { var el = this, j = el._j; if (hasClass(el, "x-disabled") || (self._getSubMenu(j) && !self.isFireAll)) return false; var item = self._getItem(j); fire(item.data.click, el, e, item); fire(self.onclick, el, e, item); self.hide(); }, mouseenter: function (e) { var el = this, i = el._i, j = el._j; self._hideSub(i, j); addClass(el, "x-on"); var item = self._getItem(j); fire(item.data.mouseover, el, e, item); fire(self.onmouseover, el, e, item); if (hasClass(el, "x-disabled")) return; self._showSub(i, j, el); }, mouseleave: function (e) { var el = this, i = el._i, j = el._j, sub_menu = self._getSubMenu(j); if (hasClass(el, "x-disabled") || !sub_menu) removeClass(el, "x-on"); else if (i == 0) self._active = j; var item = self._getItem(j); fire(item.data.mouseout, el, e, item); fire(self.onmouseout, el, e, item); } }, ".x-item"); if (self._e2) self._e2.off(); self._e2 = E.add(list_box, "mousedown", E.stop); return self.hide(); }, //生成菜单 drawMenu: function (data, pid) { var self = this, list_menu = self._menus, list_item = self._items, map_menu = self._map_menu, map_item = self._map_item, box = data.box, is_linked_box = !!box, menu_index = self.i++; if (!box) { var className = data.className, box = createEle("div", "x-panel" + (className ? " " + className : "")); box.style.width = (data.width || 120) + "px"; } list_menu[menu_index] = { node: box, linked: is_linked_box, j: pid, data: data }; if (pid) map_menu[pid] = menu_index; //链接菜单 if (is_linked_box) return self; var global_submenu = self.subMenu !== false //循环生成菜单项 for (var i = 0, data_items = data.items; i < data_items.length; i++) { var m = data_items[i]; if (!m) continue; var item = document.createElement("div"), item_index = self.j++; item._i = menu_index; item._j = item_index; list_item[item_index] = { node: item, i: menu_index, j: item_index, data: m }; if (m.id != undefined) map_item[m.id] = item_index; if (m.split) { item.className = "x-split"; } else { item.className = "x-item" + (m.disabled ? " x-disabled" : ""); item.x = m.x != undefined ? m.x : ""; //自定义值 var group = m.group, has_submenu = global_submenu && group && (group.box || (group.items && group.items.length > 0)), ico = m.ico; var html = m.html || '<div class="x-icon">' + (ico ? /^<.+>$/.test(ico) ? ico : '<img alt="" src="' + ico + '">' : '') + '</div>' + '<div class="x-text"' + (m.title ? ' title="' + m.title + '"' : '') + '>' + m.text + '</div>' + (has_submenu ? '<div class="arrow"></div>' : ''); item.innerHTML = html; if (has_submenu) self._tmp.push([group, item_index]); } box.appendChild(item); } Q.body.appendChild(box); return self; }, //根据菜单索引获取菜单 _getMenu: function (i) { return this._menus[i]; }, //根据菜单项索引获取子菜单 _getSubMenu: function (j) { var i = this._map_menu[j]; return i != undefined ? this._getMenu(i) : undefined; }, //根据菜单项索引获取菜单项 _getItem: function (j) { return this._items[j]; }, //根据指定的id获取菜单项 getItem: function (id) { var j = this._map_item[id]; return j != undefined ? this._items[j] : undefined; }, //更改菜单项的值 setItemText: function (id, text) { var item = this.getItem(id); if (!item) return; item.data.text = text; var node_text = item.node.childNodes[1]; if (node_text) node_text.innerHTML = text; }, //处理菜单项 processItems: function (ids, fn) { var self = this; makeArray(ids).forEach(function (id) { var item = self.getItem(id); if (item) fn(item.node, item); }); return self; }, //处理菜单项(className) _processItems: function (ids, fn, className) { return this.processItems(ids, function (node) { fn(node, className); }); }, //启用菜单项 enableItems: function (ids) { return this._processItems(ids, removeClass, "x-disabled"); }, //禁用菜单项 disableItems: function (ids) { return this._processItems(ids, addClass, "x-disabled"); }, //显示菜单项 showItems: function (ids) { return this._processItems(ids, removeClass, "hide"); }, //隐藏菜单项 hideItems: function (ids) { return this._processItems(ids, addClass, "hide"); }, //元素智能定位 _setPos: function (menu, x, y, pbox) { var self = this, rangeX = self.rangeX, rangeY = self.rangeY, box = menu.node, width = box.offsetWidth, height = box.offsetHeight, data = menu.data || {}, maxHeight = data.maxHeight; //如果菜单高度超出最大高度,则启用垂直滚动条 if (maxHeight) { var realHeight = Math.max(height, box.scrollHeight), hasScrollbar = realHeight > maxHeight; box.style.height = hasScrollbar ? maxHeight + "px" : "auto"; //是否固定宽度,默认菜单宽度会增加17px if (!self.fixedWidth) box.style.width = (data.width + (hasScrollbar ? 17 : 0)) + "px"; height = box.offsetHeight; } if (x == undefined) x = self.x || 0; if (y == undefined) y = self.y || 0; if (rangeX && x + width > rangeX) { x = rangeX - width; if (pbox) x = x - pbox.offsetWidth + 3; } if (rangeY && y + height > rangeY) y = rangeY - height - 1; if (x < 0) x = 0; if (y < 0) y = 0; set_pos(box, x, y); self.x = x; self.y = y; return self; }, //显示子菜单(如果有) _showSub: function (i, j, el) { var self = this, menu = self._getMenu(i), sub_menu = self._getSubMenu(j); if (sub_menu) { var node = menu.node, sub_node = sub_menu.node, offset = getOffset(el), zIndex = +getStyle(node, "zIndex"), zIndex_sub = +getStyle(sub_node, "zIndex"); if (zIndex_sub <= zIndex) sub_node.style.zIndex = zIndex + 1; self._setPos(sub_menu, offset.left + el.offsetWidth - 2, offset.top, node); } self.i = i; self.j = j; return self; }, //取消高亮的项 _inactive: function (j) { var item = this._getItem(j); if (item) removeClass(item.node, "x-on"); return this; }, //隐藏子菜单 _hideSub: function (i, j) { var self = this; if (i <= self.i && j != self.j) { var list_menu = self._menus, k; //隐藏子一级菜单(当前菜单以后的菜单) for (k = list_menu.length - 1; k > i; k--) { self._hide(list_menu[k]); } //移除子一级菜单高亮的项 if (i < self.i) { for (k = self.i; k > i; k--) { var p_menu = self._getMenu(k); self._inactive(p_menu.j); } } } //移除同一菜单里上次高亮的项(有子菜单的项) if (i == self.i && j != self.j && self._getSubMenu(self.j)) self._inactive(self.j); return self; }, //隐藏指定菜单 _hide: function (menu) { if (menu) { var node = menu.node; if (node.style.left != POS_VALUE_HIDDEN) set_pos(node, POS_VALUE_HIDDEN, POS_VALUE_HIDDEN); } return this; }, //显示 show: function (x, y) { return this._setPos(this._menus[0], x, y); }, //隐藏 hide: function () { var self = this; self._menus.forEach(function (m) { self._hide(m); }); if (self._active != undefined) { self._inactive(self._active); self._active = undefined; } return self; }, //菜单是否为隐藏状态 isHidden: function () { var self = this, box = self.box, x = parseFloat(box.style.left), y = parseFloat(box.style.top); return x <= -box.offsetWidth || y <= -box.offsetHeight; }, //自动切换显示或隐藏 toggle: function (x, y) { return this.isHidden() ? this.show(x, y) : this.hide(); }, //注销菜单 destroy: function () { var self = this; if (self._e0) self._e0.off(); if (self._e1) self._e1.off(); self._menus.forEach(function (menu) { menu.node.innerHTML = ''; $(menu.node).remove(); }); Object.forEach(self, function (prop) { self[prop] = null; }); return self; } }); //------------------------- export ------------------------- Q.ContextMenu = ContextMenu; })(); /* * Q.UI.DropdownList.js 下拉列表 * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2018/11/28 19:10 */ (function (undefined) { "use strict"; var document = window.document, def = Q.def, fire = Q.fire, isObject = Q.isObject, getFirst = Q.getFirst, getLast = Q.getLast, getWidth = Q.width, setWidth = getWidth, hasClass = Q.hasClass, addClass = Q.addClass, removeClass = Q.removeClass, createEle = Q.createEle, factory = Q.factory, ie = Q.ie, E = Q.event; //---------------------- 下拉列表 ---------------------- function DropdownList(ops) { ops = ops || {}; var self = this; self.box = ops.box; self.items = ops.items || []; self.multiple = ops.multiple; self.canInput = ops.canInput; self.textProp = ops.textProp || "text"; //默认值或索引 self.value = ops.value; self.index = ops.index || 0; self.ops = ops; } factory(DropdownList).extend({ init: function () { var self = this, ops = self.ops, box = self.box, isDropdownList = !self.multiple, canInput = self.canInput, placeholder = ops.placeholder; var html = (isDropdownList ? '<div class="x-sel-tag">' + (canInput ? '<input type="text" class="x-sel-text"' + (placeholder ? ' placeholder="' + placeholder + '"' : '') + ' />' : '<div class="x-sel-text"></div>') + '<div class="x-sel-arrow">' + '<div class="arrow arrow-down"></div>' + '</div>' + '</div>' : '') + '<div class="x-panel x-sel-list' + (isDropdownList ? '' : ' x-sel-multiple') + '"></div>'; addClass(box, "x-sel"); box.innerHTML = html; var elList = getLast(box), elTag, elText, elArrow; setWidth(elList, ops.width || box.offsetWidth - 2); if (isDropdownList) { elTag = getFirst(box); elText = getFirst(elTag); elArrow = getLast(elTag); self.elText = elText; self.elArrow = elArrow; } self.elList = elList; //------------- Event -------------- //item 相关事件 var listener_item; //下拉列表 if (isDropdownList) { if (ops.autoHide !== false) { E.add(document, "mousedown", function () { self.hide(); }); E.add(box, "mousedown", function (e) { E.stop(e, false, true); }); } E.add(canInput ? elArrow : elTag, "mousedown", function (e) { self.toggle(); return false; }); listener_item = { //mousedown: E.stop, mouseup: function (e) { var index = this.x, item = self.items[index]; fire(self.onclick, self, item, index); if (item.disabled) return; self.hide(); if (index != self.index) self.select(index); }, mouseenter: function () { var index = this.x, item = self.items[index]; if (!item.disabled) self.active(index); } }; } else { self.selectedItems = []; self.seletedMap = {}; //多选框事件 listener_item = { mousedown: function (e) { var el = this; if (hasClass(el, "x-disabled")) return; var index = this.x, //items = self.items, firstItem = self.selectedItems[0], shiftKey = e.shiftKey, ctrlKey = e.ctrlKey; if (shiftKey || !ctrlKey) self.clearSelect(); if (shiftKey) { var start = firstItem ? firstItem.index : index, end = index; if (start > end) { end = start; start = index; } for (var i = start; i <= end; i++) { self.active(i); } } else { if (ctrlKey && self.seletedMap[index]) self.inactive(index); else self.select(index); } } }; if (ie < 10) listener_item.selectstart = E.stop; } E.add(elList, listener_item, ".x-item"); self.draw(); fire(self.oninit, self); return self; }, //绘制下拉视图 draw: function () { var self = this, ops = self.ops, items = self.items, elList = self.elList, hasTitle = ops.hasTitle, maxHeight = ops.maxHeight, map = {}; elList.innerHTML = ""; items.forEach(function (m, i) { m.index = i; map[m.value] = m; var text = m.text || '', node = createEle("div", "x-item" + (m.group ? " x-sel-group" : m.disabled ? " x-disabled" : ""), text); if (hasTitle) node.title = m.title || text.toText(); node.x = i; m.node = node; elList.appendChild(node); }); self.map = map; if (maxHeight) { var realHeight = elList.offsetHeight; if (realHeight > maxHeight) elList.style.height = maxHeight + "px"; } fire(self.ondraw, self); var value = self.value, index = self.index; if (value) { var item = self.find(value); if (item) index = item.index; } self.select(index); return self.multiple ? self : self.hide(); }, //添加下拉项,类似option add: function (text, value, title) { this.items.push(isObject(text) ? text : { text: text, value: value, title: title }); return this; }, //查找指定值的项 eg:{text,value,index} find: function (value) { return this.map[value]; }, //清除选中项 clearSelect: function () { var self = this; var inactive = function (item) { if (item.node) removeClass(item.node, "selected"); }; //多选框 if (self.multiple) { self.selectedItems.forEach(inactive); self.selectedItems = []; self.seletedMap = {}; } else { inactive({ node: self._el }); } return self; }, //设置项高亮 active: function (index) { var self = this, item = self.items[index]; if (!item) return self; var node = item.node, flag; //多选框 if (self.multiple) { if (!item.disabled && !self.seletedMap[index]) { self.selectedItems.push(item); self.seletedMap[index] = true; flag = true; } } else { self.clearSelect(); flag = true; self._el = node; } if (flag) addClass(node, "selected"); return this; }, //取消项高亮 inactive: function (index) { var self = this, item = self.items[index]; if (self.multiple) { self.selectedItems = self.selectedItems.filter(function (item) { return item.index != index; }); self.seletedMap[index] = undefined; } removeClass(item.node, "selected"); return self; }, //选中指定索引的项 //isNotChange:是否不触发change事件 select: function (index, isNotChange) { var self = this, items = self.items, item = items[index]; if (!item) return self; self.text = def(item.text, ""); self.value = def(item.value, ""); if (self.elText) self.elText[self.canInput ? "value" : "innerHTML"] = self[self.textProp]; //多选框 self.active(index); if (!isNotChange && index != self.index) fire(self.onchange, self, item, index); self.index = index; return self; }, //显示下拉列表 show: function () { this.elList.style.display = ""; return this.select(this.index); }, //隐藏下拉列表 hide: function () { this.elList.style.display = "none"; return this; }, //自动切换显示或隐藏下拉列表 toggle: function () { return this.elList.style.display == "none" ? this.show() : this.hide(); }, //获取当前项文本,当canInput为true时可调用此方法获取输入文本 getText: function () { return this.canInput ? this.elText.value : this.text; } }); //------------------------- export ------------------------- Q.DropdownList = DropdownList; })(); /* * Q.UI.DataPager.js 数据分页 * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2018/12/18 10:48 */ (function (undefined) { "use strict"; var extend = Q.extend, factory = Q.factory; var LANG = { prevPage: "&lt;上一页", nextPage: "下一页&gt;", pageSize: "每页{0}条", totalCount: "共{0}条数据" }; //配置语言 function setLang(langs) { extend(LANG, langs, true); } //---------------------- 数据分页 ---------------------- //生成分页页码数据 eg:create_pager_bar_data(9,28,5) => [1,0,4,5,6,7,8,0,28] 0表示省略号,其它表示页码 //size:要显示的页码数量(包括省略号),不小于7的奇数 //totalPage:总页数 //page:当前页索引 function create_pager_bar_data(size, totalPage, page) { var tmp = [1]; //只有一页的情况 if (totalPage == 1) return tmp; //if (size < 7) size = 7; //else if (size % 2 == 0) size++; var first = 2, last; //总页数小于或等于页码数量 if (totalPage <= size) { last = totalPage; } else { var sideCount = (size - 5) / 2; //左边无省略号 eg: [1,2,3,4,5,0,20] if (page <= sideCount + 3) { last = size - 2; } else if (page > totalPage - sideCount - 3) { //右边无省略号 eg: [1,0,16,17,18,19,20] first = totalPage - size + 3; //=last-(size-4) last = totalPage - 1; } else { //左右均有省略号 eg: [1,0,8,9,10,0,20] first = page - ~~sideCount; last = first + size - 5; } } if (first > 2) tmp.push(0); for (var i = first; i <= last; i++) tmp.push(i); if (totalPage > size) { if (last < totalPage - 1) tmp.push(0); tmp.push(totalPage); } return tmp; } //构造器:分页对象 function DataPager(ops) { var self = this; self.ops = ops; self.size = ops.size || 9; self.cache = {}; if (ops.href == undefined) { var boxNav = ops.boxNav; if (boxNav) { $(boxNav).on("click", "li", function () { self.go($(this).attr("x")); if (self.onclick) self.onclick.call(self, self.page); }); } } else { ops.cache = ops.preload = false; } self.set(ops.totalCount, ops.pageSize || ops.pageCount || 10).setData(ops.data).go(ops.page); } factory(DataPager).extend({ //设置总的数据条数和每页显示的数据条数 set: function (totalCount, pageSize) { var self = this; if (totalCount != undefined) self.totalCount = totalCount; if (pageSize != undefined) self.pageSize = pageSize; if (self.totalCount != undefined) self.totalPage = Math.ceil(self.totalCount / self.pageSize); //重置页码 //self.page = undefined; return self; }, //设置数据列表(用于ops.load) //data:数据列表 setData: function (data) { if (data) { this.data = data; this.set(data.length); } return this; }, //加载数据 _load: function (page, callback) { var self = this, ops = self.ops, onload = self.onload; self.page = page; var complete = function (list) { if (onload) onload.call(self, list); if (callback) callback.call(self, list); return self; }; //本地数据分页 if (!ops.load) { var pageSize = self.pageSize, start = (page - 1) * pageSize; return complete(self.data.slice(start, start + pageSize)); } //使用缓存 var list = ops.cache ? self.cache[page] : undefined; if (list) return complete(list); //获取远程数据 ops.load(page, function (data) { list = data.data || []; if (ops.cache) self.cache[page] = list; self.set(data.totalCount, data.pageSize || data.pageCount); complete(list); }); return self; }, //加载并渲染数据 load: function (page) { return this._load(page, this.draw); }, //重新载入当前数据并渲染 reload: function (page) { return this.load(page || this.page); }, //跳转到指定页 //forced:是否强制跳转 go: function (page, forced) { var self = this; if (isNaN(page)) return self; page = +page; if (self.totalPage != undefined && page > self.totalPage) page = self.totalPage; if (page < 1) page = 1; if (page == self.page && !forced) return self; self.load(page); if (self.ops.load && self.ops.preload) self._load(page + 1); if (self.onchange) self.onchange.call(self, page); return self; }, //绘制导航区(分页按钮) drawNav: function () { var self = this, ops = self.ops, boxNav = ops.boxNav; if (!boxNav) return self; var totalCount = self.totalCount, pageSize = self.pageSize, totalPage = self.totalPage, page = self.page, href = ops.href, text = ops.text || {}, list_bar = create_pager_bar_data(self.size, totalPage, page); if (href != undefined) href += href.indexOf("?") != -1 ? "&" : "?"; var get_html_bar = function (i, title, className) { if (!className) className = i == page ? "on" : (i ? "" : "skip"); return '<li' + (className ? ' class="' + className + '"' : '') + ' x="' + i + '">' + (href ? '<a' + (i ? ' href="' + href + 'page=' + i + '"' : '') + '>' + title + '</a>' : title) + '</li>'; }; var draw_size = ops.drawSize || function (self, html_page, html_count) { return html_page + '/' + html_count; }; var html = '<div class="inline-block pager-bar' + (href ? ' pager-link' : '') + '">' + '<ul>' + get_html_bar(Math.max(page - 1, 1), text.prev || LANG.prevPage, "prev") + list_bar.map(function (i) { return get_html_bar(i, i || "…"); }).join('') + get_html_bar(Math.min(page + 1, totalPage), text.next || LANG.nextPage, "next") + '</ul>' + '</div>' + (ops.showSize !== false ? '<div class="inline-block pager-count">' + draw_size(self, LANG.pageSize.replace("{0}", '<span class="page-size">' + pageSize + '</span>'), LANG.totalCount.replace("{0}", '<span class="total-count">' + totalCount + '</span>')) + '</div>' : ''); $(boxNav).html(html); }, //绘制UI draw: function (list) { this.drawNav(); this.ops.draw.call(this, list); return this; } }); //------------------------- export ------------------------- DataPager.setLang = setLang; Q.DataPager = DataPager; })(); /* * Q.UI.Tabs.js 选项卡插件 * author:devin87@qq.com * update:2020/03/26 15:48 */ (function () { "use strict"; var async = Q.async, getFirst = Q.getFirst, parseHash = Q.parseHash, $$ = $.find; //选项卡对象 function Tabs(ops) { ops = ops || {}; var self = this, context = ops.context, tabs = ops.tabs || $$(".tab-title li.tab,.tabTitle>li", context), conts = ops.conts || $$(".tab-cont>.turn-box,.tabCont>.turn-box", context); self.tabs = tabs; self.conts = conts; self.map_loaded = {}; self.map_index = {}; self.ops = ops; //扫描index和对应的hash tabs.forEach(function (el, i) { //优先显示 if (el.getAttribute("x-def") == "1") ops.index = i; var link = getFirst(el); if (!link) return; var hash = link.href.split("#")[1] || "", nav = parseHash(hash).nav; if (nav) self.map_index[nav] = i; }); //选项卡点击事件 tabs.forEach(function (el, i) { if ($(el).hasClass("skip")) return; $(el).click(function () { self.showTab(i); }); }); $(conts).hide(); //显示默认的选项卡 setTimeout(function () { var hash = ops.hash || parseHash().nav.slice(1), index = self.map_index[hash]; if (index == undefined) index = ops.index || 0; //默认显示顺序 location hash -> html定义(x-def属性) -> ops.index -> 0 self.showTab(index); }, 20); } Q.factory(Tabs).extend({ //获取选项卡元素 getTab: function (i) { return this.tabs[i]; }, //获取对应的视图元素 getCont: function (i) { return this.conts[i]; }, //该视图是否已加载过 hasLoaded: function (i) { return !!this.map_loaded[i]; }, //显示指定索引的选项卡 showTab: function (index) { var self = this, ops = self.ops, lastIndex = self.index; if (index === lastIndex) return; if (lastIndex !== undefined) { var lastTab = self.getTab(lastIndex), lastCont = self.getCont(lastIndex); $(lastTab).removeClass("on"); $(lastCont).hide(); } var tab = self.getTab(index), cont = self.getCont(index), map_loaded = self.map_loaded; $(tab).addClass("on"); $(cont).show(); self.index = index; //触发选项卡切换事件 var data = { index: index, tab: tab, cont: cont, loaded: map_loaded[index] }; async(self.onchange, 100, data); if (ops.triggerTabChange !== false) async(window["onTabChange" + (ops.name ? "_" + ops.name : "")], 200, data); if (!map_loaded[index]) map_loaded[index] = true; } }); //设置选项卡切换 function setTabs(ops) { return new Tabs(ops); } //------------------------- export ------------------------- Q.Tabs = Tabs; Q.setTabs = setTabs; })(); /* * Q.UI.Marquee.js 无缝滚动插件 * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2022/02/14 17:01 */ (function (undefined) { "use strict"; var fire = Q.fire, factory = Q.factory; //---------------------- 无缝滚动插件 ---------------------- /* 调用示例如下: new Q.Marquee({ box: box, //顶层DOM对象,下列ul、boxControl等都基于此对象 ul: ".slide-ul", //要滚动的ul对象 boxControl: ".slide-control", //下方滚动按钮容器,可选 btnPrev: ".prev", //向左滚动按钮 btnNext: ".next", //向右滚动按钮 way: i == 2 ? "top" : "left", //滚动方向,top:向上滚动,left:向左滚动,默认left sleep: 5000, //自动滚动的时间间隔(ms) isSlideKeydown: true, //是否允许键盘(左右方向键)控制滚动,默认为true isStoppedHover: true, //鼠标移上去时停止自动滚动,移出时开始自动滚动,默认为true auto: true //是否自动滚动 }); */ function Marquee(ops) { var self = this, box = ops.box; self._$box = $(box); self._$ul = $(ops.ul, box); self._$control = $(ops.boxControl, box); self._$btnPrev = $(ops.btnPrev, box); self._$btnNext = $(ops.btnNext, box); self.auto = !!ops.auto; self.way = ops.way || "left"; self.speed = ops.speed || "slow"; self.sleep = ops.sleep || 5000; self.step = ops.step || 1; self.isSlideKeydown = ops.isSlideKeydown !== false; self.isStoppedHover = ops.isStoppedHover !== false; self.clsActive = ops.clsActive || "slide-on"; self.index = 0; self.fns = ops.on || {}; self.init(); } factory(Marquee).extend({ //初始化 init: function () { var self = this, fns = self.fns, $box = self._$box, $ul = self._$ul, $lis = $ul.children(), $control = self._$control, size = $lis.length, $controls; if (size > 0) { //追加首尾元素,以实现无缝滚动 $ul.prepend($lis.last()[0].cloneNode(true)); $ul.append($lis.first()[0].cloneNode(true)); } if (size > 1) { $control.html('<a></a>'.repeat(size)); } else { self._$btnPrev.hide(); self._$btnNext.hide(); } $lis = $ul.children(); $lis.each(function (i, li) { li.style[self.way] = (i - 1) * 100 + "%"; }); $controls = $control.children(); $controls.each(function (i) { this.x = i; }); self._$lis = $lis; self._$controls = $controls; self._cssBox = $box.prop("className"); self.size = size; var el = $lis.get(1); $(el).addClass(self.clsActive); self.updateControl(0); fire(fns.init, self, 0, el); self.start(); return self.initEvent(); }, //初始化事件 initEvent: function () { var self = this; if (self.size > 1) { //点击控制区域切换滚动 self._$control.on("click", "a", function () { self.play(this.x); }); //向左滚动 self._$btnPrev.click(function () { self.playPrev(); }); //向右滚动 self._$btnNext.click(function () { self.playNext(); }); } if (self.isSlideKeydown) { //键盘控制滚动 $(document).keydown(function (e) { switch (e.keyCode) { case 37: self.playPrev(); break; case 39: self.playNext(); break; } }); } //鼠标放在banner上时暂停播放,移除后继续 if (self.auto && self.isStoppedHover) { self._$ul.hover(function () { self.stop(); }, function () { self.start(); }); } return self; }, //更新控制按钮 updateControl: function (i) { var self = this, clsName = self._cssBox || ""; self._$box.prop("className", clsName + (clsName ? " " : "") + "b" + (i + 1)); self._$controls.prop("className", "").eq(i).prop("className", self.clsActive); return self; }, //无缝滚动(-1<=i<=size) play: function (i) { var self = this, fns = self.fns, clsActive = self.clsActive, $ul = self._$ul, $lis = self._$lis, size = self.size; if (size <= 1) return self; self.stop(); var i_valid = i; if (i_valid >= size) i_valid = 0; else if (i_valid < 0) i_valid = size - 1; var el = $lis.get(i + 1); $lis.removeClass(clsActive); $(el).addClass(clsActive); self.updateControl(i_valid); fire(fns.beforeSlide, self, i_valid, el); fire(self.onPlay, self, i_valid); var params = {}; params[self.way] = (-i * 100) + "%"; $ul.animate(params, self.speed, function () { if (i == size || i == -1) { $lis.removeClass(clsActive).eq(i_valid + 1).addClass(clsActive); $ul.css(self.way, (-i_valid * 100) + "%"); self.index = i_valid; fire(self.onPlayed, self, i_valid); } fire(fns.slide, self, i_valid, el); self.start(); }); self.index = i; return self; }, //向前滚动 playPrev: function () { return this.play(this.index - this.step); }, //向后滚动 playNext: function () { return this.play(this.index + this.step); }, //开始自动滚动 start: function () { var self = this; self.stop(); if (!self.auto || self.size <= 1) return self; self.timer = setTimeout(function () { self.playNext(); }, self.sleep); return self; }, //停止自动滚动 stop: function () { var self = this; if (self.timer) { clearTimeout(self.timer); self.timer = undefined; } return self; } }); //------------------------- export ------------------------- Q.Marquee = Marquee; })(); /* * Q.UI.ColorPicker.js 颜色选择器 * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2020/11/20 15:04 */ (function (undefined) { "use strict"; var document = window.document, isFunc = Q.isFunc, extend = Q.extend, //fire = Q.fire, getFirst = Q.getFirst, getNext = Q.getNext, getLast = Q.getLast, //getOffset = Q.offset, createEle = Q.createEle, factory = Q.factory, E = Q.event; var LANG = { cubic_color: "立方色", series_color: "连续色调", gray_color: "灰度等级" }; //配置语言 function setLang(langs) { extend(LANG, langs, true); } var POS_VALUE_HIDDEN = -10000; //设置元素位置 function set_pos(el, x, y) { if (x != undefined) el.style.left = x + "px"; if (y != undefined) el.style.top = y + "px"; } //---------------------- util ---------------------- //int值转为16进制颜色 function int2hex(n, a) { return "#" + (a ? Math.round(a * 255).toString(16) : "") + ("00000" + n.toString(16)).slice(-6); //faster } //RGB颜色转为16进制颜色 function rgb2hex(r, g, b, a) { return int2hex(r * 65536 + g * 256 + b * 1, a); } //解析为rgba数组,若解析失败,则返回空数组 => [r,g,b,a] //支持 #ffffff|#80ffffff|rgb(0,0,0)|rgba(0,0,0,0.5) function parseColor(color) { var rgba = []; if (typeof color == "number") color = int2hex(color); if (color.indexOf("#") == 0) { var len = color.length; if (len == 4 || len == 5) { color = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3); if (len == 5) color += color.charAt(4) + color.charAt(4); } if (color.length == 9) { rgba[3] = Math.round(parseInt(color.substr(1, 2), 16) * 100 / 255) / 100; color = "#" + color.slice(3); } if (color.length == 7) { rgba[0] = parseInt(color.substr(1, 2), 16); rgba[1] = parseInt(color.substr(3, 2), 16); rgba[2] = parseInt(color.substr(5, 2), 16); } return rgba; } color = color.replace(/\s+/g, ""); var start = color.indexOf('('); if (start != -1) { rgba = color.slice(start + 1, -1).split(','); } return rgba; } //转为16进制颜色 eg: rgb(153,204,0) => #99CC00 function toHex(color) { var rgba = parseColor(color); if (rgba.length <= 0) return color; return rgb2hex.apply(undefined, rgba.slice(0, 3)); } //转为16进制颜色 eg: rgba(153,204,0,0.5) => #8099CC00 function toAHex(color) { var rgba = parseColor(color); if (rgba.length <= 0) return color; return rgb2hex.apply(undefined, rgba); } //转为RGB颜色,转换失败则返回原颜色 eg: #99CC00 => rgba(153,204,0) function toRGB(color) { var rgba = parseColor(color); if (rgba.length <= 0) return color; return "rgb(" + rgba.slice(0, 3).join(",") + ")"; } //转为RGBA颜色,转换失败则返回原颜色 eg: #8099CC00 => rgba(153,204,0,0.5) function toRGBA(color) { var rgba = parseColor(color); if (rgba.length <= 0) return color; return "rgba(" + rgba.join(",") + ")"; } Q.parseColor = parseColor; Q.toHex = toHex; Q.toAHex = toAHex; Q.toRGB = toRGB; Q.toRGBA = toRGBA; //---------------------- ColorPicker ---------------------- var LIST_COLOR = ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff', '#ff00ff']; //颜色选择器 function ColorPicker(ops) { var self = this; //默认行数与列数 self.row = 12; //不得超过 LIST_COLOR.length self.col = 21; self.set(ops).init(); } factory(ColorPicker).extend({ //初始化 init: function () { var self = this; var html = '<div class="xp-title">' + '<div class="xp-preview"></div>' + '<div class="xp-val"></div>' + '<div class="xp-type">' + '<select>' + '<option value="Cube" selected="selected">' + LANG.cubic_color + '</option>' + '<option value="Series">' + LANG.series_color + '</option>' + '<option value="Gray">' + LANG.gray_color + '</option>' + '</select>' + '</div>' + '</div>' + '<div class="xp-table">' + '<table>' + ('<tr>' + '<td></td>'.repeat(self.col) + '</tr>').repeat(self.row) + '</table>' + '</div>'; var box = createEle("div", "x-picker", html), boxTitle = getFirst(box), boxPreview = getFirst(boxTitle), boxValue = getNext(boxPreview), boxType = getLast(boxTitle), boxTable = getLast(box), table = getFirst(boxTable); Q.body.appendChild(box); self.box = box; self.table = table; self.boxPreview = boxPreview; self.boxValue = boxValue; //------------------- init event ------------------- //类型切换 E.add(getFirst(boxType), "change", function () { self["draw" + this.value + "Color"](); }); E.add(table, { //鼠标移动,预览颜色 mouseover: function (e) { self.setPreview(this.style.backgroundColor); }, //选择并设置颜色 click: function (e) { var color = this.style.backgroundColor; self.fire(color).hide(); } }, "td"); E.add(box, "click", E.stop); E.add(document, "click", function (e) { self.hide(); }); return self.drawCubeColor().hide(); }, //设置 { isHex,callback } //isHex:输出为16进制颜色 set: function (ops) { extend(this, ops, true); return this.setPreview((ops || {}).color); }, //触发回调函数 fire: function (color) { var self = this; if (isFunc(self.callback)) self.callback.call(self, self.isHex ? toHex(color) : color); return self; }, //设置预览颜色 setPreview: function (color) { var self = this; if (color) { self.boxPreview.style.backgroundColor = color; self.boxValue.innerHTML = toHex(color).toUpperCase(); } return self; }, //填充单元格颜色 fillColor: function (i, j, color) { this.table.rows[i].cells[j].style.backgroundColor = color; return this; }, //画左边的颜色 drawLeftColor: function () { var self = this, row = self.row; for (var i = 0; i < row; i++) { self.fillColor(i, 0, "#000").fillColor(i, 1, LIST_COLOR[i]).fillColor(i, 2, "#000"); } return self; }, //画立方色 drawCubeColor: function () { var self = this, row = self.row, col = self.col, start = 0, step = 0x330000, color; self.drawLeftColor(); for (var i = 0; i < row; i++) { if (i > 5) color = start = 0x990000 + (i - 6) * 0x000033; else color = start = 0x0 + i * 0x000033; for (var j = 3; j < col; j++) { self.fillColor(i, j, int2hex(color)); color += 0x003300; if ((j - 2) % 6 == 0) start += step, color = start; } } return self; }, //画连续色 drawSeriesColor: function () { var self = this, row = self.row, col = self.col, start = 0xCCFFFF, step = 0x660000, flag = 1, color; self.drawLeftColor(); for (var i = 0; i < row; i++) { if (i > 5) color = start = 0xFF00FF + (i - 6) * 0x003300; else color = start = 0xCCFFFF - i * 0x003300; flag = 1; for (var j = 3; j < col; j++) { self.fillColor(i, j, int2hex(color)); color -= 0x000033 * flag; if ((j - 2) % 6 == 0) { flag *= -1; start -= step; color = start - ((flag > 0) ? 0 : 0x0000FF); } } } return self; }, //画灰度等级色 drawGrayColor: function () { var self = this, row = self.row, col = self.col, color = 0xffffff; for (var i = 0; i < row; i++) { for (var j = 0; j < col; j++) { self.fillColor(i, j, int2hex(color)); if (color <= 0) color = 0x000000; else color -= 0x010101; } } return self; }, //显示 show: function (x, y) { var self = this; if (x == undefined) x = self.x; else self.x = x; if (y == undefined) y = self.y; else self.y = y; set_pos(self.box, x, y); return self; }, //隐藏 hide: function () { set_pos(this.box, POS_VALUE_HIDDEN, POS_VALUE_HIDDEN); return this; }, //是否为隐藏状态 isHidden: function () { var self = this, box = self.box, x = parseFloat(box.style.left), y = parseFloat(box.style.top); return x <= -box.offsetWidth || y <= -box.offsetHeight; }, //自动切换显示或隐藏 toggle: function (x, y) { return this.isHidden() ? this.show(x, y) : this.hide(); } }); ColorPicker.setLang = setLang; //------------------------- export ------------------------- Q.ColorPicker = ColorPicker; })(); /* * Q.UI.Progressbar.js 进度条 * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2015/07/15 11:46 */ (function (undefined) { "use strict"; var fire = Q.fire, createEle = Q.createEle, factory = Q.factory; //---------------------- 进度条 ---------------------- //进度条,颜色、高度等设置可以在样式表里控制 //ops:{box:进度条所在容器,speed:速度(0-100),wait:每隔多长时间更新一次进度(ms),onprogress(progress,speed,time):进度更新时回调函数} function Progressbar(ops) { ops = ops || {}; var container = ops.box, boxBar = createEle("div", "progress-bar"), boxNode = createEle("div", "progress"); boxBar.appendChild(boxNode); container.appendChild(boxBar); var self = this; self._bar = boxBar; self._node = boxNode; self.speed = ops.speed || 1; self.wait = ops.wait || 100; self.progress = 0; self.time = 0; self.onprogress = ops.onprogress; } factory(Progressbar).extend({ //启动进度条 start: function () { var self = this; if (self.progress >= 100) return; self._timer = setInterval(function () { self.update(); }, self.wait); return self; }, //停止进度条 stop: function () { if (this._timer) clearInterval(this._timer); return this; }, //重新启动进度条(进度归0) restart: function () { return this.stop().update(0).start(); }, //更新进度条进度 update: function (progress) { var self = this; if (progress != undefined) self.progress = Math.max(progress, 0); else self.progress += self.speed; if (self.progress > 100) { self.progress = 100; self.stop(); } self._node.style.width = self.progress.toFixed(2) + "%"; self.time += self.wait; fire(self.onprogress, self, self.progress, self.speed, self.time); return self; }, //设置速度和等待时间 set: function (speed, wait) { if (speed) this.speed = speed; if (wait) this.wait = wait; return this.stop().start(); } }); //------------------------- export ------------------------- Q.Progressbar = Progressbar; })(); /* * Q.UI.RangeSlider.js 滑动条(input[type=range]) * https://github.com/devin87/Q.UI.js * author:devin87@qq.com * update:2019/04/24 11:14 */ (function (undefined) { "use strict"; var fire = Q.fire, createEle = Q.createEle, factory = Q.factory, DragX = Q.DragX; //---------------------- 滑动条 ---------------------- //滑动条,颜色、高度等设置可以在样式表里控制 /* ops配置: { box: el, //滑动条容器 min: 0, //滑动条最小值 max: 100, //滑动条最大值 step: 1, //滑动步进 value: 0 //滑动条当前值 } */ function RangeSlider(ops) { ops = ops || {}; var container = ops.box, elBar = createEle("div", "range-slider-bar"), elProgress = createEle("div", "range-progress"), elSlider = createEle("div", "range-slider"); elBar.appendChild(elProgress); elBar.appendChild(elSlider); container.appendChild(elBar); var self = this; self._elBar = elBar; self._elProgress = elProgress; self._elSlider = elSlider; self.min = +ops.min || 0; self.max = +ops.max || 100; self.step = +ops.step || 1; self.value = +ops.value || 0; var str = self.step + '', i = str.lastIndexOf('.'), n = i != -1 ? str.length - i - 1 : 0; //修复step非整数时精度不准确的问题 var FIX_INT = Math.pow(10, n); self.onchange = ops.onchange; self.val(self.value); self._drag = new DragX(function () { var base = this, totalWidth, startWidth, //初始宽度 startX, //初始x坐标 maxLeft; //elSlider最大偏移 //实现ops接口 base.ops = { ele: elSlider, autoCursor: false }; //实现doDown接口 base.doDown = function (e) { totalWidth = elBar.offsetWidth; startWidth = elProgress.offsetWidth; startX = e.clientX; maxLeft = totalWidth - elSlider.offsetWidth; }; //实现doMove接口 base.doMove = function (e) { //水平移动的距离 var x = e.clientX - startX, w = startWidth + x; if (w < 0) w = 0; else if (w > totalWidth) w = totalWidth; var steps = ~~(w * (self.max - self.min) / (totalWidth * self.step)), v = (self.min * FIX_INT + self.step * FIX_INT * steps) / FIX_INT; elProgress.style.width = (w * 100 / totalWidth) + '%'; elSlider.style.left = (Math.min(w, maxLeft) * 100 / totalWidth) + '%'; if (v != self.value) { self.value = v; fire(self.onchange, self, self.value); } }; }); } factory(RangeSlider).extend({ val: function (v) { var self = this; if (v == undefined) return self.value; if (v < self.min) v = self.min; else if (v > self.max) v = self.max; var elProgress = self._elProgress, elSlider = self._elSlider, totalWidth = self._elBar.offsetWidth; self.value = v; elProgress.style.width = ((v - self.min) * 100 / (self.max - self.min)) + '%'; elSlider.style.left = (Math.min(elProgress.offsetWidth, totalWidth - elSlider.offsetWidth) * 100 / totalWidth) + '%'; return self; } }); //------------------------- export ------------------------- Q.RangeSlider = RangeSlider; })();
class Autocomplete { static search() { $('nav #product-search-terms').keyup(function() { Autocomplete.clean(); if ($(this).val().length > 1) { var formSearch = $(this).parent("#product-search"); event.preventDefault(); $.ajax({ url: 'index.php', method: "POST", data: formSearch.serialize() + "&controller=search&method=new&remote=true", dataType: "JSON", success: function(results, status) { Autocomplete.appendProductTemplate(results.books); }, error: function(result, status, error) { console.log(error) }, }) } }) }; static activateNavigation() { $(".autocomplete-zone .up").click(function() { var autocompleteZone = $(this).siblings(".block"); var scrollPos = autocompleteZone.scrollTop(); autocompleteZone.scrollTop(scrollPos - 50); }); $(".autocomplete-zone .down").click(function() { var autocompleteZone = $(this).siblings(".block"); var scrollPos = autocompleteZone.scrollTop(); autocompleteZone.scrollTop(scrollPos + 50); }); } static appendProductTemplate(results) { results.forEach(result => { $('.autocomplete-zone').css({ 'display': 'block' }); const productTemplate = ( `<div class="card-autocomplete"> <div class="poster-container"> <img src="${result.book.image_path}" alt="poster"> </div> <div class="description-container"> <h2><a href ="index.php?controller=book&method=show&id=${result.book.id}">${result.book.title}</a></h2> <p class="description">${result.book.description}</p> <hr class="light my-2"> <ul class="other-details my-2"> <li>${result.category.name}</li> <li>${result.book.price} &euro; </li> </ul> </div> </div>`).trim(); $('.autocomplete-zone .block').append(productTemplate) }); $(window).on("mousemove", function(event) { if (event.pageX > ($(window).width() * .75)) { Autocomplete.clean(); } }) } static clean() { if ($('.card-autocomplete').length > 0) { $('.autocomplete-zone').css({ 'display': 'none' }); $('.card-autocomplete').remove(); }; } }
import React, {Component} from 'react'; import {connect} from 'react-redux'; const addButton = {type : 'ADD'}; const removeButton = {type : 'REMOVE'}; export class CounterComponent extends Component { render() { const {counter,dispatch} = this.props; return ( <div className="CounterContainer"> <p>{counter}</p> <button onClick = {() => dispatch(addButton)}>ADD</button> <button onClick = {() => dispatch(removeButton)}>REMOVE</button> </div> ); } } const mapStateToProps = state => ({ counter : state }); const CounterContainer = connect(mapStateToProps)(CounterComponent); export default CounterContainer;
import React from 'react'; import { Switch, Route, } from "react-router-dom"; import Element from './Element'; import MyContext from '../context/context'; import EditElementInput from './EditElementInput'; import AddElementInput from './AddElementInput'; function Elements () { const elementContext = React.useContext(MyContext); return ( <div> {elementContext.modeEdit ? <EditElementInput></EditElementInput> : <AddElementInput></AddElementInput>} <Switch> <Route exact path="/"> <Element category=''></Element> </Route> <Route path="/important"> <Element category="important"></Element> </Route> <Route path="/other"> <Element category="other"></Element> </Route> </Switch> </div> ); } export default Elements;
import style from './style'; const s = Object.create(style); s.title = { fontSize: '28px', marginTop: '20px', marginBottom: '0.5vh', textAlign: 'center' }; s.subtitle = { fontSize: '18px', marginTop: '10px', marginBottom: '0.5vh', textAlign: 'center' }; export default s;
// if (gon.user) { // swal({ // title: "สวัสดีครับ -- Thank you for visiting as our guest!", // text: "You are logged in as a temporary guest for one hour. Please be aware that any work you do while logged in as a 'temporary guest' will not be recorded after you have logged out. But if you decide to Join BSC English Online (while still logged in this time!), all your work from this visit will be retained.", // timer: 20000, // showConfirmButton: true, // animation: "slide-from-bottom" // }); // }
var index = 0; var x = 0; var y = 0; var dom = null; var path = []; var num = 0; var running = false; var step = 10; function prev() { init(); if (index > 0) { index--; pushNextNode(); } } function next() { init(); if (index < array.length - 1) { index++; pushNextNode(); } } function replay() { if (!running) { init(); for (var i = 0; i < array.length; i++) { index = i; pushNextNode(); } x = path[path.length - 3].x; y = path[path.length - 3].y; num = path.length - 3; } } function init() { if (dom == null) { var node = array[0]; x = node.x + node.w / 2; y = node.y + node.h / 2; path.push({ count: step, x: x, y: y }); dom = document.createElement('img'); document.body.appendChild(dom); dom.style.position = 'absolute'; dom.src = 'images/icons/user.png'; dom.style.left = x + 'px'; dom.style.top = y + 'px'; } } function pushNextNode() { var node = array[index]; var lastNode = path[path.length - 1]; var nextNode = { count: 0, x: node.x + node.w / 2, y: node.y + node.h / 2 }; nextNode.dx = (nextNode.x - lastNode.x) / step; nextNode.dy = (nextNode.y - lastNode.y) / step; path.push(nextNode); setTimeout('execute()', 1000 / step); } function execute() { if (num < path.length - 1) { running = true; var nextNode = path[num + 1]; if (nextNode.count < step) { nextNode.count++; x += nextNode.dx; y += nextNode.dy; dom.style.left = (x - 10) + 'px'; dom.style.top = (y - 10) + 'px'; setTimeout('execute()', 1000 / step); } else { if (num == path.length - 2) { num++; running = false; } else { num++; setTimeout('execute()', 1000 / step); } } } else { running = false; } }
/* * Mercury Project * Pick Up File * Displays Package info for those ready to be picked up * * After using the ESLint extension to change the formatting */ import React, { useState } from 'react'; import { View, Text, ScrollView, SafeAreaView } from 'react-native'; import { SearchBar } from 'react-native-elements'; import { globalStyles } from '../styles/global'; export default function PickUp() { const [query, setQuery] = useState(''); // ** fill this function definition later ** const queryFunction = (text) => { setQuery(text); }; return ( // Create Deskie and Student buttons <SafeAreaView> <ScrollView> <View> <SearchBar round placeholder='Search...' searchIcon={{ size: 25 }} inputStyle={{ color: 'white' }} containerStyle={{ borderWidth: 1, borderRadius: 20, margin: 10, }} placeholderTextColor={'white'} onChangeText={(text) => queryFunction(text)} onClear={(text) => queryFunction('')} value={query} /> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> <Text style={globalStyles.sampleDataContainer}>Package data...</Text> </View> </ScrollView> </SafeAreaView> ); }
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class OrgManagement extends Component { render() { return( <div className="container-fluid"> <main className="adjust-top"> <h4 className="text-size">Organization Management</h4> <div className="card shadow p-3 mt-3 mb-5"> <div className="table-responsive"> <table className="table table-bordered table-hover table-sm table-striped" id="myTable"> <thead className="thead-light"> <tr> <th>Username</th> <th>Full Name</th> <th>Address</th> <th>Email</th> <th>Position</th> <th className="text-center">Action</th> </tr> </thead> <tbody> <tr> <td><Link to="/OrgLoad">Test</Link></td> <td></td> <td></td> <td></td> <td></td> <td class="text-center p-1"> <a href="#" className="btn btn-info btn-circle btn-sm"> <i className="fas fa-pencil-alt"></i> </a> <a href="#" className="btn btn-danger btn-circle btn-sm"> <i className="fas fa-trash"></i> </a> </td> </tr> </tbody> </table> </div> </div> </main> </div> ) } } export default OrgManagement;
import axios from 'axios'; import { LOGIN_URL, SIGNUP_URL } from './index'; //Login User export const LOGIN_USER = 'LOGIN_USER'; export const LOGIN_USER_SUCCESS = 'LOGIN_USER_SUCCESS'; export const LOGIN_USER_FAILURE = 'LOGIN_USER_FAILURE'; //logout user export const LOGOUT_USER = 'LOGOUT_USER'; //Signup User export const SIGNUP_USER = 'SIGNUP_USER'; export const SIGNUP_USER_SUCCESS = 'SIGNUP_USER_SUCCESS'; export const SIGNUP_USER_FAILURE = 'SIGNUP_USER_FAILURE'; //Login User export function loginUser(formValues) { return function (dispatch) { axios.post(`${LOGIN_URL}`, { email: formValues.email, password: formValues.password }) .then(function (response) { sessionStorage.setItem('authToken', response.data.auth_token); sessionStorage.setItem('loggedInUser', JSON.stringify(response.data.user)); dispatch(loginUserSuccess(response.data)); }) .catch(function (error) { console.log('An error occured.', error.response.data.errors); dispatch(loginUserFailure(error)); }); }; } export function loginUserSuccess(user) { return { type: LOGIN_USER_SUCCESS, payload: user }; } export function loginUserFailure(error) { return { type: LOGIN_USER_FAILURE, payload: error }; } //Logout User export function logoutUser() { return { type: LOGOUT_USER }; } //Signup User export function signupUser(formValues) { return function (dispatch) { axios.post(`${SIGNUP_URL}`, { user: { email: formValues.email, password: formValues.password, username: formValues.username } }) .then(function (response) { sessionStorage.setItem('authToken', response.data.auth_token); sessionStorage.setItem('loggedInUser', JSON.stringify(response.data.user)); dispatch(signupUserSuccess(response.data)); }) .catch(function (errors) { let errorString = ''; const errorMessages = errors.response.data.errors; if (errors.response.data.errors instanceof Array) { errorString = errorMessages.join(', '); } else { errorString = errorMessages; } console.log('An error occured.', errorString); dispatch(signupUserFailure(errors)); }); }; } export function signupUserSuccess(user) { return { type: SIGNUP_USER_SUCCESS, payload: user }; } export function signupUserFailure(errors) { return { type: SIGNUP_USER_FAILURE, payload: errors }; }
import React, { Component } from 'react' import logo from '../meetup.png' class Header extends Component { render() { return ( <div className="headerWrapper"> <span className="top"> <img src={logo} height={180} width={256}/> <h1>Belgrade</h1> </span> </div> ) } } export default Header;
const injectProvider = require("./inject-providers"); module.exports = injectProvider;
import React, {PureComponent} from 'react'; import PropTypes from "prop-types" import {ELEMENTS, DISPLAY} from "../helpers/enums"; import withForm from "../helpers/with-form"; import renderElement from "../helpers/render-element"; class Message extends PureComponent { state = {value: this.props.value || null, ran: false}; facade = (() => { const self = this; return { type: ELEMENTS.MESSAGE, get name(){return self.props.name;}, get value(){return self.state.value;}, get isValid(){return self.isValid} } })(); componentDidMount(){ this.props.form.register(this.facade, this.challenge, [...this.props.watch]); } componentWillUnmount(){ this.props.form.unregister(this.facade); } get isValid() { if(!this.state.ran){this.challenge()} return this.props.check ? this.props.check() : !this.state.value; }; challenge = () => { const message = this.props.validate(this.props.form.fields); if(message !== this.state.value || !this.state.ran){ this.setState({...this.state, value: message, ran: true}) } if(this.props.required){ const field = this.props.form.fields[this.name]; if(field && !field.value && this.state.value !== this.props.required){ this.setState({...this.state, value: this.props.required, ran: true}) } } }; componentDidUpdate(prevProps, prevState){ if(prevProps.name !== this.props.name){ prevProps.form.unregister(this.facade); this.props.form.register(this.facade, this.challenge); } if(prevState !== this.state){ this.props.onChange(this.facade); } } render() { let {component, render, children, name, display, hide, className, ...rest} = this.props; const value = this.state.value; const field = this.props.form.fields[name]; if(!value){return null;} const submitted = this.props.form.submitted; if(display === DISPLAY.NEVER || hide){return null;} if(display === DISPLAY.SUBMITTED && !submitted){return null;} if(display === DISPLAY.TOUCHED && !field.touched && !submitted){return null;} if(display === DISPLAY.DIRTY && !field.dirty){return null;} if(display === DISPLAY.CHANGED && !field.dirty && !field.touched && !submitted){return null;} return hide ? null : renderElement( {component, render, children, className}, {message: value, name, display, hide, ...rest}); } } Message.propTypes = { name: PropTypes.string.isRequired, hide: PropTypes.bool, display: PropTypes.number, render: PropTypes.func, children: PropTypes.any, component: PropTypes.any, validate: PropTypes.func, onChange: PropTypes.func, required: PropTypes.string, watch: PropTypes.oneOfType([PropTypes.array, PropTypes.string]), form: PropTypes.shape({ fields: PropTypes.object, submitted: PropTypes.bool }).isRequired }; Message.defaultProps = { display: DISPLAY.TOUCHED, onChange: () => {}, validate: () => {}, hide: false, watch: [] }; export default withForm(Message);
import React from 'react'; import {useParams} from "react-router-dom"; const ChangeFilm = ({title, description, pathImage, popularity, realiseDate, genres, averageVote, voteCount, isAdult, genresMap, changeInput, adultInputChange, validateInputs, genresInputChange, idF}) => { let isAvailable = idF !== undefined const {id} = useParams() return ( isAvailable && (Number(idF) === Number(id)) ? (<div> <h1>ChangeFilm id: {id}</h1> {[[title, 'title'], [description, 'description'], [pathImage, 'pathImage'], [popularity, 'popularity'], [averageVote, 'averageVote'], [voteCount, 'voteCount']].map(el => <div key={el[1]}> <input placeholder={el[1]} className={el[0].valid ? '' : 'inputError'} onChange={(ev) => changeInput(el[1], ev.target.value)} value={el[0].value}/> {el[0].valid ? '' : `Incorrect ${el[1]}`}</div>)} <input type="date" placeholder={'realiseDate'} className={realiseDate.valid ? '' : 'inputError'} onChange={(ev) => changeInput('realiseDate', ev.target.value)} value={realiseDate.value}/> {realiseDate.valid ? '' : `Incorrect realiseDate`} <label><input placeholder='Alult' type="checkbox" checked={isAdult.value ? 'checked' : ''} onChange={(ev) => adultInputChange(isAdult.value)}/>Adult</label> <h3>Genres</h3> <div className={genres.valid ? 'genres' : 'genres inputError'}> {genresMap.map(el => <label key={el.name}><input type="checkbox" checked={genres.value.indexOf(el.id) !== -1 ? 'checked' : ''} onChange={(ev) => genresInputChange(el.id)}/>{el.name}</label>)} {genres.valid ? '' : 'Incorrect genres'} </div> <button onClick={() => validateInputs('addFilm', 'title', 'description', 'pathImage', 'popularity', 'realiseDate', 'genres','averageVote', 'voteCount', 'isAdult')}>Change</button> </div>) : (<p>Невозможно выбрать фильм, перейдите пожалуйста с главной</p>) ); }; export default ChangeFilm;
var mylocalstorage=[] var padContant var addto //בפתיחת הדף טען מסימות קימות addEventListener("load", loadTasks) function loadTasks() { if(localStorage["notepad"] !== "null") { mylocalstorage=JSON.parse(localStorage["notepad"]) for(i = 0; i < mylocalstorage.length; i++) { var singlePadTxt = mylocalstorage[i] var padDiv = document.createElement("div") var padTextearea = document.createElement("textarea") var padSpan = document.createElement("span") padTextearea.setAttribute("class","padTextearea") padTextearea.innerHTML = singlePadTxt padDiv.addEventListener("mouseover", addx) padDiv.appendChild(padSpan) padDiv.appendChild(padTextearea) document.getElementById("pads").appendChild(padDiv) } } } document.getElementById("submit").addEventListener("click", newNote) function newNote() { //אם מילאת הכל המשך if(document.getElementById("textarea").value !== "" && document.getElementById("date").value !== "") { // פתיחת קובץ במחשב(לוקאל [נוטפאד]) כדי שיווצר קובץ כזה בלוקאל ונוכל לישמור אליו localStorage.setItem("notepad",JSON.stringify( mylocalstorage)) if(localStorage["notepad"] !== "null") { //לקיחת הנתונים מלוקאל כדי שמאוחר יותר נוכל להכניס בפוש את הפאד החדש mylocalstorage=JSON.parse(localStorage["notepad"]) } //מחיקת האזהרה של "לא מילאת הכל" אם היתה אזהרה document.getElementById("warning").innerHTML=null //יצירת הפאד var padDiv = document.createElement("div") var padTextearea = document.createElement("textarea") var padSpan = document.createElement("span") padTextearea.setAttribute("class","padTextearea") padTextearea.innerHTML = document.getElementById("textarea").value+ "\n" + "\n" +"date:"+document.getElementById("date").value padDiv.addEventListener("mouseover", addx) padDiv.appendChild(padSpan) padDiv.appendChild(padTextearea) document.getElementById("pads").appendChild(padDiv) // שמירת הכיתוב של הפאד ללוכאל var singlePadTxt = padTextearea.innerHTML mylocalstorage.push(singlePadTxt) localStorage.setItem("notepad",JSON.stringify( mylocalstorage)) //עידכון הוואר לאחר הוספת פאד בשביל אפשרות מחיקה מיידית mylocalstorage=JSON.parse(localStorage["notepad"]) //מחיקה וחידוש אזור הכתיבה document.getElementById("textarea").value="" document.getElementById("date").value="" } else { //אם לא מילאת הכל לא תוכל להמשיך var warning1 = document.createElement("h5") warning1.innerHTML="Please fill all fields" document.getElementById("warning").appendChild(warning1) alert("Please fill all fields") } } function addx() { //הוספת אייקון מבוטסטראפ ושמירת הפאד המסויים שהועבר עליו העכבר addto=this var c= this.childNodes padContant = this.childNodes[1].innerHTML var padSpan= c[0] padSpan.setAttribute("class", "glyphicon glyphicon-remove") //הוספת פונקציה למחיקת הפאד מהדף ומהלוקאל padSpan.addEventListener("click", deletefromlocal) } //מחיקת הפאד מהדף ומהלוקאל function deletefromlocal() { //אזהרה לפני מחיקה if (confirm("Are you sure you want to delete this task")) { for(i=0;i<mylocalstorage.length;i++) { if(JSON.stringify( mylocalstorage[i])===JSON.stringify( padContant)) { mylocalstorage.splice(i, 1); } localStorage["notepad"]=JSON.stringify( mylocalstorage) } //מחיקת כל הפאדים והוספתם מחדש בכדי שלא יווצרו חורים בדף document.getElementById("pads").innerHTML=null loadTasks() } }
// Your web app's Firebase configuration // Initialize Firebase function visibleAbout() { var visible = document.getElementById('topicname'); visible.innerHTML = ` <div class="row"> <div class="col-4 sm-4"></div><div class="col-4 sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; padding-bottom:0; margin-bottom:0px; font-weight:bold;">About</h1></div><div class="col-4 sm-4"></div> </div> <div class="row" id="detailsSection"> <div class="col-sm-12"> <br> <h5 class="nameAbout text-white">Hello there I'm <strong class="text-primary">Kavindu Gayantha</strong> , I am an enthusiastic individual who is eager to learn new things perpetually while getting myself up-to-date with cutting edge technologies. I am good at being a team player as well as leading a team. I am more keen on Web development, Mobile Development, and Data Science, and seek an opportunity related to one of these areas. </h5> <div class="row"> <div class="col-sm-4"></div><div class="col-sm-4"></div><div class="col-sm-4"></div> </div> </div> <table class="table table-borderless bg-transparent" style="float:left; color:rgb(67, 147, 200);"> <tbody> <tr> <!-- <th scope="row">1</th> --> <td>Phone</td> <td>+94 71 873 2730 { whatsapp }</td> <tr><td></td><td>+94 76 027 3663</td></tr> </tr> <tr> <!-- <th scope="row">2</th> --> <td>Email</td> <td>s.kavindu.gayantha@gmail.com</td> <!-- <td>@fat</!--> </tr> <tr> <!-- <th scope="row">3</!--> <td>Date of birth</td> <td>27<sup>th</sup> of june, 1996</td> <!-- <td>@twitter</!--> </tr> </tbody> </table> <!-- progress bar --> <tr> </tr> `; } function visibleEducation() { var visible = document.getElementById("topicname"); visible.innerHTML = ` <div class="row"> <div class="col-4 sm-4"></div><div class="col-4 sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; padding-bottom:0; margin-bottom:0px; font-weight:bold;">Education</h1></div><div class="col-4 sm-4"></div> </div> <div class="row "> <!-- details of education--> <div class="col-12-wd"> <div class="row"> <!-- details of education--> <div class="col-sm-12"> <br> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody> <tr> <td class="col-sm-12" style="float:right"><img src="images/Kelaniya.png" style="width:150px;"> </td> <td class="col-sm-12"><h2 class="text-white">University of Kelaniya</h2> <h6><strong class="text-primary">Undergraduate of B.Sc(Hon's) in Software Engineering</strong></h6><h6>2018-2022</h6> </tr><tr> <p> <td style="float:right;"><img src="images/pcm.png" style="width:150px"> </td><td class="col-sm-12"><h3 class="text-white" style="padding-top:20px">President's college Maharagama</h3> <h6><strong class="text-primary">Maths stream</strong> <h6>2002-2015</h6> </td> </tr><tr> <td style="float:right;"><img src="images/diploma2.png" style="width:150px"> </td><td class="col-sm-12"><h3 class="text-white" style="padding-top:20px">Diploma in English</h3> <h6><strong class="text-primary">Buddhist and Pali university, Colombo</strong> <h6>2017</h6> </td> </tr> </tbody> </table> </div> </div> `; } function visibleExtra() { var visible = document.getElementById("topicname"); visible.innerHTML = ` <div class="row"> <div class="col-sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; float:center; padding-bottom:0; padding-left:25% ; margin-bottom:0px; font-weight:bold;">Extra Curricular Activities</h1></div> </div> <div class="row"> <!-- details of education--> <div class="col-12-wd"> <div class="row"> <!-- details of extra curricular activities--> <div class="col-sm-12"> <br> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody > <tr> <td style="padding-bottom:2%";><img src="images/badminton.png" style="width:150px;"> </td><br><td class="col-sm-12"><h4 class="text-white">Represents University Badminton team</h4> <h6><strong class="text-primary">2018-present</strong></h6> </td> </tr><p> <tr > <div class="row" > <td ><img src="images/ieee.png" style="width:150px;"> </td><td class="col-sm-12"><h4 class="text-white">IEEE committee member, Kelaniya branch</h4> <h6><strong class="text-primary">2019-present</strong></h6> </td> </div> </tr> <tr > <div class="row" > <td ><img src="images/medium222.png" style="width:150px;"> </td><td class="col-sm-12"><h4 class="text-white" style="padding-top:5%"><a href="https://medium.com/@96kavindugayantha" target="_blank" style="text-decoration:none;color:white">Blogger at Medium</a></h4> <h6><strong class="text-primary">Technical writer at Analytics Vidhya medium publication</strong></h6> <h6><strong class="text-primary"></strong></h6> </td> </div> </tr> <tr > <div class="row" > <td ><img src="images/youtube2.jpg" style="width:150px;"> </td><td class="col-sm-12"><h4 class="text-white" style="padding-top:5%">Youtube Content creator</h4> <h6><strong class="text-primary"><a target="_blank" href="https://www.youtube.com/channel/UC6RVPaqYWHRwBDpl7RFRrdg?view_as=subscriber">CODE Storm </a> youtube channel</strong></h6> </td> </div> </tr> </tbody> </table> </div> </div> <!-- row ends--> </div> </div> `; } function visibleAchievements() { var visible = document.getElementById("topicname"); visible.innerHTML = ` <div class="row"> <div class="col-sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; float:center; padding-bottom:0; padding-left:25% ; margin-bottom:0px; font-weight:bold;">Achievements & Awards</h1></div> </div> <div class="row"> <!-- details of achievements--> <div class="col-12-wd"> <div class="row"> <!-- details of achievements--> <div class="col-sm-12"> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody> <tr> <td style="padding-bottom:1%";><img src="images/badminton.png" style="width:150px;"> </td><br><td class="col-wd"><h4 class="text-white">Vice-Captain-2020</h4> <h6><strong class="text-primary">University of Kelaniya Badminton(Boys) Team</strong></h6> </td> </tr> <tr> <td style="padding-bottom:1%";><img src="images/awardssss.png" style="width:150px;"> </td><br><td class="col-wd"><h4 class="text-white" style="padding-top:7%">University Colours - 2019</h4> <h6><strong class="text-primary">Awarded colours for Badminton 2019</strong></h6> </td> </tr> <tr> <td style="padding-bottom:1%";><img src="images/ieeextreme.png" style="width:150px;"> </td><br><td class="col-wd"><h4 class="text-white">IEEE Xtreme programming competition-13.0</h4> <h6><strong class="text-primary">Participated for the competition-2019</strong></h6> </td> </tr> <tr> <td><img src="images/awardssss.png" style="width:150px;"> </td><td class="col-wd"><h4 class="text-white" style="padding-top:7%">University Colours - 2018</h4> <h6><strong class="text-primary">Awarded colours for Badminton 2018</strong></h6> </td> </tr> </tbody> </table> </div> </div> </div> </div> `; } function visibleProject() { var visible = document.getElementById("topicname"); visible.innerHTML = ` <div class="row"> <div class="col-4 sm-4"></div><div class="col-4 sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; padding-bottom:0; margin-bottom:0px; font-weight:bold;">Projects</h1></div><div class="col-4 sm-4"></div> </div> <div class="row" style="padding-top:2px"> <!-- details of projects--> <div class="col-sm-12"> <div class="row"> <!-- details of projects--> <div class="col-12-wd"> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody> <tr> <td style="padding-bottom:0%";><img src="images/edoc.png" style="width:150px;"> </td><br><td class="col-wd"><h4 style="text-decoration:underline" class="text-white">E-Channeling App-<i style="font-size:20px">(Individual-Non Academic)</i></h4> <h6><strong class="text-white">Docters can register in app and patients can see docter details and can make appointments with doctors</strong></h6> <h5><strong class="text-primary">Flutter | MongoDB | Nodejs | Socket.io</strong></h5> <h6><strong class="text-primary">{ On-Going }</strong></h6> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="row" style="padding-top:2px"> <!-- details of projects--> <div class="col-sm-12"> <div class="row"> <!-- details of projects--> <div class="col-12-wd"> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody> <tr> <td style="padding-bottom:0%";><img src="images/attendance-mark.png" style="width:150px;"> </td><br><td class="col-wd"><h4 style="text-decoration:underline" class="text-white">Attendance Marking App-<i style="font-size:20px">(Individual-Non Academic)</i></h4> <h6><strong class="text-white">Marking attendance of team players of university Badminton Team</strong></h6> <h5><strong class="text-primary">Flutter | Firebase</strong></h5> <h6><strong class="text-primary">{ On-Going }</strong></h6> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="row" style="padding-top:2px"> <!-- details of projects--> <div class="col-sm-12"> <div class="row"> <!-- details of projects--> <div class="col-12-wd"> <table class="table table-borderless bg-transparent text-white" style="float:center"> <tbody> <tr> <td style="padding-bottom:0%";><img src="images/student mgt sys.png" style="width:150px;"> </td><br><td class="col-wd"><h4 class="text-white" style="text-decoration:underline">Student Management System-<i style="font-size:20px">(Individual-Academic)</i></h4> <h5><strong class="text-primary">HTML | CSS | JS | PHP | MySQL | Bootstrap</strong></h5> </td> </tr> </tbody> </table> </div> </div> </div> </div> `; } function visibleContact() { var visible = document.getElementById("topicname"); visible.innerHTML =` <div class="row"> <div class="col-4 sm-4"></div><div class="col-4 sm-12"><h1 class="nameAbout text-white" style="font-size: 25px; padding-bottom:0; margin-bottom:0px; font-weight:bold;">Contact me</h1></div><div class="col-4 sm-4"></div> </div> <div class="row"> <!-- details of contact--> <div class="col"> <br> <div class="col" id="contactME"> <form class="text-white" id="feedbackform"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div><br> <div class="form-group"> <label for="exampleInputname">Name</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="your name"> </div><br> <div class="form-group"> <label for="exampleFormControlTextarea1">Send feedback</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="4"></textarea> </div> <button type="submit" class="btn btn-primary">Send feedback</button> </form> </div> <!-- row ends--> </div> </div> `; }
var StudentModel = Backbone.Model.extend({ // Modèle d'élève. Contient les données: // NOM // Prénom // Image // Présence defaults: { surname: '', name: '', picture: 'http://bit.ly/1OMRr64', here: false } });