text
stringlengths
7
3.69M
import {connect} from 'react-redux'; import OrderPage from '../../../components/OrderPage'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import helper, {fetchJson, postOption, showError, showSuccessMsg, getJsonResult} from '../../../common/common'; import {search2} from '../../../common/search'; import {showImportDialog} from '../../../common/modeImport'; import {exportExcelFunc} from '../../../common/exportExcelSetting'; import {toFormValue} from "../../../common/check"; import showEditDialog from './EditDialog/EditDialogContainer'; import {showColsSetting} from '../../../common/tableColsSetting'; const STATE_PATH = ['customerPriceDetail']; const URL_LIST = '/api/config/customerPriceDetail/freightList'; const URL_CUSTOMER = '/api/config/customerPriceDetail/customer'; const URL_DISTRICT = '/api/config/customerPriceDetail/district'; const URL_CONSIGNOR = '/api/config/customerPriceDetail/consignor'; const URL_CARMODE = '/api/config/customerPriceDetail/carMode'; const URL_DELETE = '/api/config/customerPriceDetail/freightDelete'; const URL_ABLE = '/api/config/customerPriceDetail/freightAble'; const URL_ADD = '/api/config/customerPriceDetail/freightAdd'; const URL_EDIT = '/api/config/customerPriceDetail/freightEdit'; const URL_BATCHEDIT = '/api/config/customerPriceDetail/freightBatchEdit'; const URL_CAOMODE = '/api/config/customerPriceDetail/carMode'; const URL_CURRENCY = '/api/config/customerPriceDetail/currency'; const URL_CHARGEITEM = '/api/config/customerPriceDetail/chargeItem'; const URL_CONTRACT = '/api/config/customerPriceDetail/contract'; const action = new Action(STATE_PATH); const DIALOG_API = { search_customer: URL_CUSTOMER, search_carMode: URL_CAOMODE, search_chargeItem: URL_CHARGEITEM, search_currency: URL_CURRENCY, search_contract: URL_CONTRACT, search_district: URL_DISTRICT, search_consignor: URL_CONSIGNOR, newAdd: URL_ADD, editSave: URL_EDIT, batchEdit: URL_BATCHEDIT }; const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const resetActionCreator = (dispatch) => { dispatch(action.assign({searchData: {}})); }; const searchActionCreator = async (dispatch, getState) => { const {pageSize, searchData} = getSelfState(getState()); return search2(dispatch, action, URL_LIST, 1, pageSize, searchData, {currentPage: 1}); }; const changeActionCreator = (key, value) => action.assign({[key]: value}, 'searchData'); const formSearchActionCreator = (key, value) => async (dispatch, getState) => { const {filters} = getSelfState(getState()); let result, params = {maxNumber: 20, filter: value}; switch (key) { case 'customerId': { result = getJsonResult(await fetchJson(URL_CUSTOMER, postOption(params))); break; } case 'departure': case 'destination': { result = getJsonResult(await fetchJson(URL_DISTRICT, postOption(params))); break; } case 'consignorId': case 'consigneeId': { result = getJsonResult(await fetchJson(URL_CONSIGNOR, postOption(params))); break; } case 'carModeId': { result = getJsonResult(await fetchJson(URL_CARMODE, postOption(params))); break; } } const options = result.data ? result.data : result; const index = filters.findIndex(item => item.key === key); dispatch(action.update({options}, 'filters', index)); }; const afterEdit = async (dispatch, getState) => { const {currentPage, pageSize, searchData={}} = getSelfState(getState()); return search2(dispatch, action, URL_LIST, currentPage, pageSize, toFormValue(searchData)) }; const addActionCreator = async (dispatch, getState) => { const {controls} = getSelfState(getState()); const result = await showEditDialog({type: 0, controls, DIALOG_API}); result && await afterEdit(dispatch, getState); }; const copyActionCreator = async (dispatch, getState) => { const {controls, tableItems} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if (index === -1) return showError('请勾选一条数据!'); const value = tableItems[index]; const result = await showEditDialog({type: 1, controls, value, DIALOG_API}); result && await afterEdit(dispatch, getState); }; const editActionCreator = async (dispatch, getState) => { const {controls, tableItems} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if (index === -1) return showError('请勾选一条数据!'); const value = tableItems[index]; if (value['enabledType'] !== 'enabled_type_unenabled') { return showError('只能编辑未启用状态记录!'); } const result = await showEditDialog({type: 2, controls, value, DIALOG_API}); result && await afterEdit(dispatch, getState); }; const batchActionCreator = async (dispatch, getState) => { const {batchEditControls, tableItems} = getSelfState(getState()); const checkList = tableItems.filter(o => o.checked); if (checkList.length < 1) return showError('请勾选一条数据!'); if (checkList.find(o => o.enabledType === 'enabled_type_disabled')) { return showError('禁用状态的数据不能进行批量修改!') } const customerPriceIds = Array.from(new Set(checkList.map(o => o.customerPriceId))); if (customerPriceIds.length > 1) return showError('请勾选同一个报价合同下的数据!'); const {customerPriceId, customerPriceCode, customerId} = checkList[0]; const defaultValue = { customerPriceId, customerPriceCode, customerId, contractNumber: { title: customerPriceCode, value: customerPriceId } }; const value = {...defaultValue, idList: checkList.map(o => o.id)}; const result = await showEditDialog({type: 3, controls: batchEditControls, value, DIALOG_API}); result && await afterEdit(dispatch, getState); }; const doubleClickActionCreator = (rowIndex) => async (dispatch, getState) => { const {controls, tableItems} = getSelfState(getState()); const value = tableItems[rowIndex]; if (value['enabledType'] !== 'enabled_type_unenabled') { return showError('只能编辑未启用状态记录!'); } const result = await showEditDialog({type: 2, controls, value, DIALOG_API}); result && await afterEdit(dispatch, getState); }; const deleteActionCreator = async (dispatch, getState) => { const {tableItems} = getSelfState(getState()); const checkItems = tableItems.filter(o => o.checked); if(checkItems.length < 1) return showError('请勾选一条数据!'); if (checkItems.some(o => o.enabledType !== 'enabled_type_unenabled')) return showError('请选择未启用状态的数据!'); const {returnCode, returnMsg} = await fetchJson(URL_DELETE, postOption(checkItems.map(o=>o.id))); if (returnCode !== 0) return showError(returnMsg); showSuccessMsg(returnMsg); await afterEdit(dispatch, getState); }; const ableActionCreator = (type='enabled_type_enabled') => async (dispatch, getState) => { const {tableItems} = getSelfState(getState()); const checkItems = tableItems.filter(o=>o.checked); if(checkItems.length < 1) return showError('请勾选一条数据!'); if(type === 'enabled_type_enabled') { if (checkItems.some(o=> o.enabledType === 'enabled_type_enabled')) return showError('请选择未启用或禁用状态的数据!'); } else if(type === 'enabled_type_disabled') { if (checkItems.some(o=> o.enabledType !== 'enabled_type_enabled')) return showError('请选择已启用状态的数据!'); } const params = { ids: checkItems.map(o => o.id), type }; const {returnCode, returnMsg} = await fetchJson(URL_ABLE, postOption(params)); if (returnCode !== 0) return showError(returnMsg); showSuccessMsg(returnMsg); await afterEdit(dispatch, getState); }; const enableActionCreator = ableActionCreator('enabled_type_enabled'); const disableActionCreator = ableActionCreator('enabled_type_disabled'); const importActionCreator = () => showImportDialog('customer_price_master_import_detail_code'); const exportActionCreator = async (dispatch, getState) =>{ const {cols, tableItems} = getSelfState(getState()); exportExcelFunc(cols, tableItems); }; const configActionCreator = async (dispatch, getState) => { const {tableCols} = getSelfState(getState()); const okFunc = (newCols) => { dispatch(action.assign({tableCols: newCols})); }; showColsSetting(tableCols, okFunc, 'customerPriceDetail_freight_tablecols'); }; const toolbarActions = { reset: resetActionCreator, search: searchActionCreator, add: addActionCreator, copy: copyActionCreator, edit: editActionCreator, batchEdit: batchActionCreator, delete: deleteActionCreator, enable: enableActionCreator, disable: disableActionCreator, import: importActionCreator, export: exportActionCreator, config: configActionCreator, }; const clickActionCreator = (key) => { if (toolbarActions.hasOwnProperty(key)) { return toolbarActions[key]; } else { return {type: 'unknown key'}; } }; const checkActionCreator = (isAll, checked, rowIndex) => { isAll && (rowIndex = -1); return action.update({checked}, 'tableItems', rowIndex); }; const pageNumberActionCreator = (currentPage) => (dispatch, getState) => { const {pageSize, searchData} = getSelfState(getState()); return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchData, {currentPage}); }; const pageSizeActionCreator = (pageSize, currentPage) => async (dispatch, getState) => { const {searchData} = getSelfState(getState()); return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchData, {pageSize, currentPage}); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onClick: clickActionCreator, onChange: changeActionCreator, onSearch: formSearchActionCreator, onCheck: checkActionCreator, onDoubleClick: doubleClickActionCreator, onPageNumberChange: pageNumberActionCreator, onPageSizeChange: pageSizeActionCreator, }; const Container = connect(mapStateToProps, actionCreators)(OrderPage); export default Container;
import React,{Component} from 'react' import LazyLoad from 'react-lazyload'; // lg: >750px; // sm: <750px const datas_sm = [ { src:'./images/main/mobile/logo_a.png', }, { src:'./images/main/mobile/logo_b.png', }, { src:'./images/main/mobile/logo_c.png', }, { src:'./images/main/mobile/logo_d.png', }, { src:'./images/main/mobile/logo_e.png', }, { src:'./images/main/mobile/logo_f.png', }, { src:'./images/main/mobile/logo_g.png', }, { src:'./images/main/mobile/logo_h.png', }, { src:'./images/main/mobile/logo_i.png', }, { src:'./images/main/mobile/logo_j.png', }, { src:'./images/main/mobile/logo_k.png', }, { src:'./images/main/mobile/logo_l.png', }, { src:'./images/main/mobile/logo_m.png', }, { src:'./images/main/mobile/logo_n.png', }, { src:'./images/main/mobile/logo_o.png', }, { src:'./images/main/mobile/logo_p.png', }, { src:'./images/main/mobile/logo_q.png', }, { src:'./images/main/mobile/logo_r.png', }, { src:'./images/main/mobile/logo_s.png', }, { src:'./images/main/mobile/logo_t.png', }, { src:'./images/main/mobile/logo_u.png', }, { src:'./images/main/mobile/logo_v.png', }, { src:'./images/main/mobile/logo_w.png', }, { src:'./images/main/mobile/logo_x.png', }, { src:'./images/main/mobile/logo_y.png', }, { src:'./images/main/mobile/logo_z.png', }, { src:'./images/main/mobile/logo_z1.png', }, { src:'./images/main/mobile/logo_z2.png', }, ] const datas_lg = [ { src:'./images/main/pc/logo_a.png', }, { src:'./images/main/pc/logo_b.png', }, { src:'./images/main/pc/logo_c.png', }, { src:'./images/main/pc/logo_d.png', }, { src:'./images/main/pc/logo_e.png', }, { src:'./images/main/pc/logo_f.png', }, { src:'./images/main/pc/logo_g.png', }, { src:'./images/main/pc/logo_h.png', }, { src:'./images/main/pc/logo_i.png', }, { src:'./images/main/pc/logo_j.png', }, { src:'./images/main/pc/logo_k.png', }, { src:'./images/main/pc/logo_l.png', }, { src:'./images/main/pc/logo_m.png', }, { src:'./images/main/pc/logo_n.png', }, { src:'./images/main/pc/logo_o.png', }, { src:'./images/main/pc/logo_p.png', }, { src:'./images/main/pc/logo_q.png', }, { src:'./images/main/pc/logo_r.png', }, { src:'./images/main/pc/logo_s.png', }, { src:'./images/main/pc/logo_t.png', }, { src:'./images/main/pc/logo_u.png', }, { src:'./images/main/pc/logo_v.png', }, { src:'./images/main/pc/logo_w.png', }, { src:'./images/main/pc/logo_x.png', }, { src:'./images/main/pc/logo_y.png', }, { src:'./images/main/pc/logo_z.png', }, { src:'./images/main/pc/logo_z1.png', }, { src:'./images/main/pc/logo_z2.png', }, ] const BrandsBox = (props) => { let datas; if(props.screenWidth>750){ datas = datas_lg }else{ datas = datas_sm } return ( <div className="brandsBox"> <p className="title">{`${props.screenWidth > 750 ? '全商业生态合作 资源交互提升用户价值' : '全商业生态合作'}`}</p> {props.screenWidth > 750 ? '' : <p className="title">资源交互提升用户价值</p>} <div className="blueline"></div> {/*<p className="title">&nbsp;全商业生态合作 资源交互提升用户价值</p>*/} <div className="logosBox"> {datas.map((data,index)=>{ return (<div className="logo" key={index}> <LazyLoad><img src={data.src} alt=""/></LazyLoad> </div>) })} </div> </div> ) } export default BrandsBox
const MyPoly = class Poly { getPolyName() { ChromeSample.log('Hi. I was created with a Class expression. My name is ' + Poly.name); } }; let inst = new MyPoly(); inst.getPolyName();
import { Button as AntdButton } from 'antd'; import cs from 'classnames'; import styles from './style.module.scss'; const Button = ({ className, ...props }) => ( <AntdButton /** merge the classname */ className={cs(styles.button, className)} /** pass rest of the props to the component, in other word extends the AntdButton component */ {...props} /> ); export default Button;
import { createStore, applyMiddleware, combineReducers } from 'redux'; import thunk from 'redux-thunk'; import axios from 'axios'; const LOAD = 'LOAD'; const CREATE = 'CREATE'; const DELETE = 'DELETE'; const UPDATE = 'UPDATE'; //reducer const usersReducer = (state = [], action)=> { if(action.type === LOAD){ state = action.users; } if(action.type === CREATE){ state = [...state, action.user]; } if(action.type === DELETE){ state = state.filter(user => user.id !== action.user.id); } if(action.type === UPDATE){ state = state.map(user => user.id !== action.user.id ? user : action.user); } return state; } //combined reducer const reducer = combineReducers({ users: usersReducer }); //thingy that talks to reducer const _loadUsers = users => ({ type: LOAD, users }); //thingy that gets called in index const loadUsers = ()=>{ return async(dispatch)=> { const users = (await axios.get('/api/users')).data; dispatch(_loadUsers(users)); }; }; const _createUser = user => ({ type: CREATE, user }); const createUser = (name, history)=>{ return async(dispatch)=> { const user = (await axios.post('/api/users', { name })).data; dispatch(_createUser(user)); //history is from other props..... not realy sure how this is working //I think i get it history.push(`/users/${user.id}`); }; }; const _destroyUser = user => ({ type: DELETE, user }); const destroyUser = (user, history)=>{ return async(dispatch)=> { await axios.delete(`/api/users/${user.id}`); dispatch(_destroyUser(user)); history.push(`/users`); }; }; const _updateUser = user => ({ type: UPDATE, user }); const updateUser = (id, name, history)=>{ return async(dispatch)=> { const user = (await axios.put(`/api/users/${id}`, { name })).data; dispatch(_updateUser(user)); history.push(`/users`); }; }; //making store const store = createStore(reducer, applyMiddleware(thunk)); //exporting export default store; export { loadUsers, createUser, destroyUser, updateUser };
adminModule.service('notificationRequest', NotificationRequest); NotificationRequest.$inject = [ '$http' ]; function NotificationRequest($http) { var ctrl = this; ctrl.getNotifications = getNotifications; ctrl.getSections = getSections; ctrl.sendNotification = sendNotification; /** * Retrieve notifications of the section. * * @return promise. */ function getNotifications() { return $http({ method: 'GET', url: Routing.generate( 'api_notifications_list' ) }).then(function (result) { return result.data; }); } /** * Retrieve all the sections. * * @return promise. */ function getSections() { return $http({ method: 'GET', url: Routing.generate( 'api_sections_get' ) }).then(function (result) { return result.data; }); } /** * Send notifications of the section. * * @return promise. */ function sendNotification(notification, sections) { notification.sections = sections; return $http({ method: 'POST', url: Routing.generate( 'api_notifications_send', notification ) }).then(function (result) { return result.data; }); } }
import React, { Component } from 'react'; import axios from 'axios'; import './Table.css' import TableMapper from './TableMapper/TableMapper' export default class Table extends Component { constructor() { super(); this.state = { standings: [] } } handleGetStandings() { console.log('started') axios.get(`/api/standings`) .then(res => { console.log('returned') this.setState({ standings: res.data }) }) return ( <div> {console.log(this.state.standings)} <TableMapper standings={this.state.standings} /> </div> ) } render() { return ( <div> {this.handleGetStandings()} </div > ) } }
import "../styles/globals.css"; import { ChakraProvider } from "@chakra-ui/react"; import Head from "next/head"; import { useRouter } from "next/router"; import React from "react"; import Footer from "../components/Footer"; import NavBar from "../components/NavBar"; import theme from "../theme"; const TITLE = "Title"; const DESCRIPTION = "Description"; const URL = "http://localhost:3000"; const SiteHead = ({ title }) => ( <Head> <title>{title}</title> <meta name="title" content={TITLE} /> <meta name="description" content={DESCRIPTION} /> <link rel="icon" href="/favicon.ico" /> <link rel="apple-touch-icon" href="/logo192.png" /> <meta property="og:type" content="website" /> <meta property="og:url" content={URL} /> <meta property="og:title" content={TITLE} /> <meta property="og:description" content={DESCRIPTION} /> <meta property="og:image" content="/logo512.png" /> <meta property="twitter:card" content="summary_large_image" /> <meta property="twitter:url" content={URL} /> <meta property="twitter:title" content={TITLE} /> <meta property="twitter:description" content={DESCRIPTION} /> <meta property="twitter:image" content="/logo512.png" /> </Head> ); const PageWrapper = ({ children, title }) => ( <div className="container"> <SiteHead title={title} /> <NavBar /> <main className="main">{children}</main> <Footer /> </div> ); function App({ Component, pageProps }) { const { pathname } = useRouter(); const pathToTitle = { "/": TITLE, }; return ( <ChakraProvider theme={theme}> <PageWrapper title={pathToTitle[pathname]}> <Component {...pageProps} /> </PageWrapper> </ChakraProvider> ); } export default App;
var level = 1; let tentativas = 5; var rand = random(); function advinhar() { let input = document.getElementById('input'); let t = document.getElementById('text-t'); let n = parseInt(input.value); if (input.value.length == 0) { alert('Por favor insira um número!'); } else { if (tentativas > 1 || (tentativas == 1 && n == rand)) { if (n == rand) { proxLevel(); } else if (rand > n) { tentativas--; t.innerHTML = `<span style="color: rgb(212, 49, 49);">Incorreto! ${tentativas} tentativas restando.</span>`; t.innerHTML += `<br><span style="color: #067d00;">Dica: o número é maior!</span>`; } else if (rand < n) { tentativas--; t.innerHTML = `<span style="color: rgb(212, 49, 49);">Incorreto! ${tentativas} tentativas restando.</span>`; t.innerHTML += `<br><span style="color: #067d00;">Dica: o número é menor!</span>`; } } else { gameOver(); } } } function proxLevel() { let leveltxt = document.getElementById('level-txt'); let leveln = document.getElementById('level-n'); let img = document.getElementById('dif'); let t = document.getElementById('text-t'); let win = document.getElementById('win'); let game = document.getElementById('game'); let audio = new Audio('https://www.mboxdrive.com/vitoria.mp3'); if (level == 1) { level = 2; leveltxt.innerHTML = `Nível - 2`; leveln.innerHTML = `Advinhe o número de 0 a 15`; img.src = 'https://svgshare.com/i/VPg.svg'; tentativas = 4; rand = random(); t.innerHTML = `<span style="color: #067d00;">Você acertou e avançou de nível!</span>`; t.innerHTML += `<br><span style="color: #067d00;">Você tem ${tentativas} tentativas nesse nivel!</span>`; } else if (level == 2) { level = 3; leveltxt.innerHTML = `Nível - 3`; leveln.innerHTML = `Advinhe o número de 0 a 20`; img.src = 'https://svgshare.com/i/VNN.svg'; tentativas = 3; rand = random(); t.innerHTML = `<span style="color: #067d00;">Você acertou e avançou de nível!</span>`; t.innerHTML += `<br><span style="color: #067d00;">Você tem ${tentativas} tentativas nesse nivel!</span>`; } else { game.style.display = 'none'; win.style.display = 'unset'; audio.play(); audio.volume = 0.05; } } function gameOver() { let game = document.getElementById('game'); let gameover = document.getElementById('gameover'); game.style.display = 'none'; gameover.style.display = 'unset'; } function random() { switch (level) { case 1: var rand = Math.floor(Math.random() * 10); return rand; case 2: var rand = Math.floor(Math.random() * 15); return rand; case 3: var rand = Math.floor(Math.random() * 20); return rand; } }
var webglGraphicsSeq=1; function BBHtml5Game( canvas ){ BBGame.call( this ); BBHtml5Game._game=this; this._canvas=canvas; this._loading=0; this._timerSeq=0; this._gl=null; if( CFG_OPENGL_GLES20_ENABLED=="1" ){ //can't get these to fire! canvas.addEventListener( "webglcontextlost",function( event ){ event.preventDefault(); // print( "WebGL context lost!" ); },false ); canvas.addEventListener( "webglcontextrestored",function( event ){ ++webglGraphicsSeq; // print( "WebGL context restored!" ); },false ); var attrs={ alpha:false }; this._gl=this._canvas.getContext( "webgl",attrs ); if( !this._gl ) this._gl=this._canvas.getContext( "experimental-webgl",attrs ); if( !this._gl ) this.Die( "Can't create WebGL" ); gl=this._gl; } // --- start gamepad api by skn3 --------- this._gamepads = null; this._gamepadLookup = [-1,-1,-1,-1];//support 4 gamepads var that = this; window.addEventListener("gamepadconnected", function(e) { that.connectGamepad(e.gamepad); }); window.addEventListener("gamepaddisconnected", function(e) { that.disconnectGamepad(e.gamepad); }); //need to process already connected gamepads (before page was loaded) var gamepads = this.getGamepads(); if (gamepads && gamepads.length > 0) { for(var index=0;index < gamepads.length;index++) { this.connectGamepad(gamepads[index]); } } // --- end gamepad api by skn3 --------- } BBHtml5Game.prototype=extend_class( BBGame ); BBHtml5Game.Html5Game=function(){ return BBHtml5Game._game; } // --- start gamepad api by skn3 --------- BBHtml5Game.prototype.getGamepads = function() { return navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); } BBHtml5Game.prototype.connectGamepad = function(gamepad) { if (!gamepad) { return false; } //check if this is a standard gamepad if (gamepad.mapping == "standard") { //yup so lets add it to an array of valid gamepads //find empty controller slot var slot = -1; for(var index = 0;index < this._gamepadLookup.length;index++) { if (this._gamepadLookup[index] == -1) { slot = index; break; } } //can we add this? if (slot != -1) { this._gamepadLookup[slot] = gamepad.index; //console.log("gamepad at html5 index "+gamepad.index+" mapped to monkey gamepad unit "+slot); } } else { console.log('Monkey has ignored gamepad at raw port #'+gamepad.index+' with unrecognised mapping scheme \''+gamepad.mapping+'\'.'); } } BBHtml5Game.prototype.disconnectGamepad = function(gamepad) { if (!gamepad) { return false; } //scan all gamepads for matching index for(var index = 0;index < this._gamepadLookup.length;index++) { if (this._gamepadLookup[index] == gamepad.index) { //remove this gamepad this._gamepadLookup[index] = -1 break; } } } BBHtml5Game.prototype.PollJoystick=function(port, joyx, joyy, joyz, buttons){ //is this the first gamepad being polled if (port == 0) { //yes it is so we use the web api to get all gamepad info //we can then use this in subsequent calls to PollJoystick this._gamepads = this.getGamepads(); } //dont bother processing if nothing to process if (!this._gamepads) { return false; } //so use the monkey port to find the correct raw data var index = this._gamepadLookup[port]; if (index == -1) { return false; } var gamepad = this._gamepads[index]; if (!gamepad) { return false; } //so now process gamepad axis/buttons according to the standard mappings //https://w3c.github.io/gamepad/#remapping //left stick axis joyx[0] = gamepad.axes[0]; joyy[0] = -gamepad.axes[1]; //right stick axis joyx[1] = gamepad.axes[2]; joyy[1] = -gamepad.axes[3]; //left trigger joyz[0] = gamepad.buttons[6] ? gamepad.buttons[6].value : 0.0; //right trigger joyz[1] = gamepad.buttons[7] ? gamepad.buttons[7].value : 0.0; //clear button states for(var index = 0;index <32;index++) { buttons[index] = false; } //map html5 "standard" mapping to monkeys joy codes /* Const JOY_A=0 Const JOY_B=1 Const JOY_X=2 Const JOY_Y=3 Const JOY_LB=4 Const JOY_RB=5 Const JOY_BACK=6 Const JOY_START=7 Const JOY_LEFT=8 Const JOY_UP=9 Const JOY_RIGHT=10 Const JOY_DOWN=11 Const JOY_LSB=12 Const JOY_RSB=13 Const JOY_MENU=14 */ buttons[0] = gamepad.buttons[0] && gamepad.buttons[0].pressed; buttons[1] = gamepad.buttons[1] && gamepad.buttons[1].pressed; buttons[2] = gamepad.buttons[2] && gamepad.buttons[2].pressed; buttons[3] = gamepad.buttons[3] && gamepad.buttons[3].pressed; buttons[4] = gamepad.buttons[4] && gamepad.buttons[4].pressed; buttons[5] = gamepad.buttons[5] && gamepad.buttons[5].pressed; buttons[6] = gamepad.buttons[8] && gamepad.buttons[8].pressed; buttons[7] = gamepad.buttons[9] && gamepad.buttons[9].pressed; buttons[8] = gamepad.buttons[14] && gamepad.buttons[14].pressed; buttons[9] = gamepad.buttons[12] && gamepad.buttons[12].pressed; buttons[10] = gamepad.buttons[15] && gamepad.buttons[15].pressed; buttons[11] = gamepad.buttons[13] && gamepad.buttons[13].pressed; buttons[12] = gamepad.buttons[10] && gamepad.buttons[10].pressed; buttons[13] = gamepad.buttons[11] && gamepad.buttons[11].pressed; buttons[14] = gamepad.buttons[16] && gamepad.buttons[16].pressed; //success return true } // --- end gamepad api by skn3 --------- BBHtml5Game.prototype.ValidateUpdateTimer=function(){ ++this._timerSeq; if( this._suspended ) return; var game=this; var seq=game._timerSeq; var maxUpdates=4; var updateRate=this._updateRate; if( !updateRate ){ var reqAnimFrame=(window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame); if( reqAnimFrame ){ function animate(){ if( seq!=game._timerSeq ) return; game.UpdateGame(); if( seq!=game._timerSeq ) return; reqAnimFrame( animate ); game.RenderGame(); } reqAnimFrame( animate ); return; } maxUpdates=1; updateRate=60; } var updatePeriod=1000.0/updateRate; var nextUpdate=0; function timeElapsed(){ if( seq!=game._timerSeq ) return; if( !nextUpdate ) nextUpdate=Date.now(); for( var i=0;i<maxUpdates;++i ){ game.UpdateGame(); if( seq!=game._timerSeq ) return; nextUpdate+=updatePeriod; var delay=nextUpdate-Date.now(); if( delay>0 ){ setTimeout( timeElapsed,delay ); game.RenderGame(); return; } } nextUpdate=0; setTimeout( timeElapsed,0 ); game.RenderGame(); } setTimeout( timeElapsed,0 ); } //***** BBGame methods ***** BBHtml5Game.prototype.SetUpdateRate=function( updateRate ){ BBGame.prototype.SetUpdateRate.call( this,updateRate ); this.ValidateUpdateTimer(); } BBHtml5Game.prototype.GetMetaData=function( path,key ){ if( path.indexOf( "monkey://data/" )!=0 ) return ""; path=path.slice(14); var i=META_DATA.indexOf( "["+path+"]" ); if( i==-1 ) return ""; i+=path.length+2; var e=META_DATA.indexOf( "\n",i ); if( e==-1 ) e=META_DATA.length; i=META_DATA.indexOf( ";"+key+"=",i ) if( i==-1 || i>=e ) return ""; i+=key.length+2; e=META_DATA.indexOf( ";",i ); if( e==-1 ) return ""; return META_DATA.slice( i,e ); } BBHtml5Game.prototype.PathToUrl=function( path ){ if( path.indexOf( "monkey:" )!=0 ){ return path; }else if( path.indexOf( "monkey://data/" )==0 ) { return "data/"+path.slice( 14 ); } return ""; } BBHtml5Game.prototype.GetLoading=function(){ return this._loading; } BBHtml5Game.prototype.IncLoading=function(){ ++this._loading; return this._loading; } BBHtml5Game.prototype.DecLoading=function(){ --this._loading; return this._loading; } BBHtml5Game.prototype.GetCanvas=function(){ return this._canvas; } BBHtml5Game.prototype.GetWebGL=function(){ return this._gl; } BBHtml5Game.prototype.GetDeviceWidth=function(){ return this._canvas.width; } BBHtml5Game.prototype.GetDeviceHeight=function(){ return this._canvas.height; } //***** INTERNAL ***** BBHtml5Game.prototype.UpdateGame=function(){ if( !this._loading ) BBGame.prototype.UpdateGame.call( this ); } BBHtml5Game.prototype.SuspendGame=function(){ BBGame.prototype.SuspendGame.call( this ); BBGame.prototype.RenderGame.call( this ); this.ValidateUpdateTimer(); } BBHtml5Game.prototype.ResumeGame=function(){ BBGame.prototype.ResumeGame.call( this ); this.ValidateUpdateTimer(); } BBHtml5Game.prototype.Run=function(){ var game=this; var canvas=game._canvas; var xscale=1; var yscale=1; var touchIds=new Array( 32 ); for( i=0;i<32;++i ) touchIds[i]=-1; function eatEvent( e ){ if( e.stopPropagation ){ e.stopPropagation(); e.preventDefault(); }else{ e.cancelBubble=true; e.returnValue=false; } } function keyToChar( key ){ switch( key ){ case 8:case 9:case 13:case 27:case 32:return key; case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 45:return key|0x10000; case 46:return 127; } return 0; } function mouseX( e ){ var x=e.clientX+document.body.scrollLeft; var c=canvas; while( c ){ x-=c.offsetLeft; c=c.offsetParent; } return x*xscale; } function mouseY( e ){ var y=e.clientY+document.body.scrollTop; var c=canvas; while( c ){ y-=c.offsetTop; c=c.offsetParent; } return y*yscale; } function touchX( touch ){ var x=touch.pageX; var c=canvas; while( c ){ x-=c.offsetLeft; c=c.offsetParent; } return x*xscale; } function touchY( touch ){ var y=touch.pageY; var c=canvas; while( c ){ y-=c.offsetTop; c=c.offsetParent; } return y*yscale; } canvas.onkeydown=function( e ){ game.KeyEvent( BBGameEvent.KeyDown,e.keyCode ); var chr=keyToChar( e.keyCode ); if( chr ) game.KeyEvent( BBGameEvent.KeyChar,chr ); if( e.keyCode<48 || (e.keyCode>111 && e.keyCode<122) ) eatEvent( e ); } canvas.onkeyup=function( e ){ game.KeyEvent( BBGameEvent.KeyUp,e.keyCode ); } canvas.onkeypress=function( e ){ if( e.charCode ){ game.KeyEvent( BBGameEvent.KeyChar,e.charCode ); }else if( e.which ){ game.KeyEvent( BBGameEvent.KeyChar,e.which ); } } canvas.onmousedown=function( e ){ switch( e.button ){ case 0:game.MouseEvent( BBGameEvent.MouseDown,0,mouseX(e),mouseY(e) );break; case 1:game.MouseEvent( BBGameEvent.MouseDown,2,mouseX(e),mouseY(e) );break; case 2:game.MouseEvent( BBGameEvent.MouseDown,1,mouseX(e),mouseY(e) );break; } eatEvent( e ); } canvas.onmouseup=function( e ){ switch( e.button ){ case 0:game.MouseEvent( BBGameEvent.MouseUp,0,mouseX(e),mouseY(e) );break; case 1:game.MouseEvent( BBGameEvent.MouseUp,2,mouseX(e),mouseY(e) );break; case 2:game.MouseEvent( BBGameEvent.MouseUp,1,mouseX(e),mouseY(e) );break; } eatEvent( e ); } canvas.onmousemove=function( e ){ game.MouseEvent( BBGameEvent.MouseMove,-1,mouseX(e),mouseY(e) ); eatEvent( e ); } canvas.onmouseout=function( e ){ game.MouseEvent( BBGameEvent.MouseUp,0,mouseX(e),mouseY(e) ); game.MouseEvent( BBGameEvent.MouseUp,1,mouseX(e),mouseY(e) ); game.MouseEvent( BBGameEvent.MouseUp,2,mouseX(e),mouseY(e) ); eatEvent( e ); } canvas.onclick=function( e ){ if( game.Suspended() ){ canvas.focus(); } eatEvent( e ); return; } canvas.oncontextmenu=function( e ){ return false; } canvas.ontouchstart=function( e ){ if( game.Suspended() ){ canvas.focus(); } for( var i=0;i<e.changedTouches.length;++i ){ var touch=e.changedTouches[i]; for( var j=0;j<32;++j ){ if( touchIds[j]!=-1 ) continue; touchIds[j]=touch.identifier; game.TouchEvent( BBGameEvent.TouchDown,j,touchX(touch),touchY(touch) ); break; } } eatEvent( e ); } canvas.ontouchmove=function( e ){ for( var i=0;i<e.changedTouches.length;++i ){ var touch=e.changedTouches[i]; for( var j=0;j<32;++j ){ if( touchIds[j]!=touch.identifier ) continue; game.TouchEvent( BBGameEvent.TouchMove,j,touchX(touch),touchY(touch) ); break; } } eatEvent( e ); } canvas.ontouchend=function( e ){ for( var i=0;i<e.changedTouches.length;++i ){ var touch=e.changedTouches[i]; for( var j=0;j<32;++j ){ if( touchIds[j]!=touch.identifier ) continue; touchIds[j]=-1; game.TouchEvent( BBGameEvent.TouchUp,j,touchX(touch),touchY(touch) ); break; } } eatEvent( e ); } window.ondevicemotion=function( e ){ var tx=e.accelerationIncludingGravity.x/9.81; var ty=e.accelerationIncludingGravity.y/9.81; var tz=e.accelerationIncludingGravity.z/9.81; var x,y; switch( window.orientation ){ case 0:x=+tx;y=-ty;break; case 180:x=-tx;y=+ty;break; case 90:x=-ty;y=-tx;break; case -90:x=+ty;y=+tx;break; } game.MotionEvent( BBGameEvent.MotionAccel,0,x,y,tz ); eatEvent( e ); } canvas.onfocus=function( e ){ if( CFG_MOJO_AUTO_SUSPEND_ENABLED=="1" ){ game.ResumeGame(); }else{ game.ValidateUpdateTimer(); } } canvas.onblur=function( e ){ for( var i=0;i<256;++i ) game.KeyEvent( BBGameEvent.KeyUp,i ); if( CFG_MOJO_AUTO_SUSPEND_ENABLED=="1" ){ game.SuspendGame(); } } canvas.updateSize=function(){ xscale=canvas.width/canvas.clientWidth; yscale=canvas.height/canvas.clientHeight; game.RenderGame(); } canvas.updateSize(); canvas.focus(); game.StartGame(); game.RenderGame(); }
const me = { name: 'change', 'phone number': '1577-1577', product: { phone: 'iphone', notebook: 'mac', } } // console.log(me['name']) // 되긴 하지만 .접근을 주로 사용 // console.log(me.product.notebook) // let books = ['javascript', 'python'] // let comics = { // DC: ['Aquaman', 'Superman'], // Marvel: ['Avengers', 'Ironman'], // } // let bookStore = { // books, // comics // } // console.log(bookStore) // JSON const jsonData = JSON.stringify(me) console.log(me) console.log(jsonData) // json형식은 사용이 안되므로 object형식으로 바꿔서 사용한다. const parseData = JSON.parse(jsonData) console.log(parseData)
//@ts-check const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = env => { // use the --env.production switch to switch between development & production builds const isProduction = env.production === true; if (!isProduction) { console.warn('running in DEVELOPMENT mode'); } const webPackConfig = { entry: './src/index.ts', devtool: isProduction ? undefined : 'inline-source-map', mode: isProduction ? 'production' : 'development', watch: isProduction ? false : true, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ }, { test: /\.hbs/, loader: 'handlebars-loader' } ] }, resolve: { extensions: ['.ts', '.js'] }, output: { filename: 'bundle.min.js', path: path.resolve('dist') } }; // setup uglifyJS for production builds if (isProduction) { webPackConfig.optimization = { minimizer: [new UglifyJsPlugin()] }; } return webPackConfig; };
'use strict'; /* * Update the in-memory user record AND the database with the new (blank) memories. */ module.exports = async function __executeActionWipeMemory (action, recUser) { if (!recUser) { throw new Error(`Cannot execute action "wipe memory" unless a user is provided.`); } const database = this.__dep(`database`); const scheduler = this.__dep(`scheduler`); const wipeProfile = (typeof action.wipeProfile === `undefined` ? true : action.wipeProfile); const wipeMessages = (typeof action.wipeMessages === `undefined` ? true : action.wipeMessages); await this.__wipeUserMemory(wipeProfile, recUser); // Wipe the user's messages. if (wipeMessages) { await database.deleteWhere(`Message`, { _user: recUser._id }); } // Remove all scheduled tasks. if (scheduler) { await scheduler.removeAllTasksForUser(recUser._id); } };
import { extendObservable, computed, action } from 'mobx'; function simpleFetch(url) { return new Promise((resolve, reject) => { window.fetch(url) .then(res => { if (res.ok) { res.json().then(resolve).catch(reject) } else { reject(res) } }) .catch(reject) }); } class Counter { constructor() { extendObservable(this, { count: 0, currentPath: computed(() => process.env.PUBLIC_URL + `/${this.count}`), isOdd: computed(() => this.count % 2 === 1) }); } increment = action(() => this.count++); decrement = action(() => this.count--); setCount = action((i) => this.count = +i); fetchCount = (path => { simpleFetch(path) .then(action(data => { this.count = data.value; })) .catch(err => { console.log('error', err); }); }); } export default Counter;
({ doInit : function(component, event, helper) { console.log('Paused task ID'+component.get("v.taskflow")); var currentTaskflow = component.get("v.currentTaskFlow"); console.log("current task flow "+currentTaskflow); var chatperName = ""; if (!$A.util.isEmpty(currentTaskflow)) { helper.fetchTaskChapters(component,currentTaskflow); } else { console.log("currentTaskFlow attribute is null"); } }, handleNavigation : function(component, event, helper){ console.log('In event handler'); var agency=event.getParam("Agency"); component.set("v.showSpinner",true); component.set("v.Agency",agency); component.set("v.Producer",producer); var producer=event.getParam("Producer"); console.log('Option'+event.getParam("option")); if(event.getParam("option")){ var sequence=component.get("v.currentChapterSequence"); sequence=sequence+1; component.set("v.currentChapterSequence",sequence); } component.set("v.showSpinner",true); helper.handleNavigateNext(component); }, navigateBack : function(component, event, helper){ component.set("v.showSpinner",true); var cellinfo=event.getParam('cellinfo'); console.log('Event handled'+JSON.stringify(cellinfo)); var dependent=event.getParam('AllDependent'); console.log('All dependents in parent'+dependent); var obj = { 'cellinfo': cellinfo, 'Dependent' : dependent, }; component.set("v.StoredValues",obj); helper.handleNavigatePrevious(component); } })
const Hello = (ticketData) => { console.log('ticketData', ticketData) return ` <!DOCTYPE html> <html style="margin: 0; padding: 0;"> <head> <title>Hello</title> </head> <body style="margin: 0; padding: 0;"> <p> Click here to view Tickets </p <p>https://ticketupdater.herokuapp.com//</p <div> <table style="width:100%"> <tr> <th>${ticketData[0].headin}</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> </div> </body> </html> `; }; export default Hello
import * as recordActions from "./recordActions"; import * as types from "./actionTypes"; import { records } from "../../../tools/mockData"; import thunk from "redux-thunk"; import fetchMock from "fetch-mock"; import configureMockStore from "redux-mock-store"; // Test an async action const middleware = [thunk]; const mockStore = configureMockStore(middleware); describe("Async Actions", () => { afterEach(() => { fetchMock.restore(); }); describe("Load Records Thunk", () => { it("should create BEGIN_API_CALL and LOAD_RECORDS_SUCCESS when loading records", () => { fetchMock.mock("*", { body: records, headers: { "content-type": "application/json" } }); const expectedActions = [ { type: types.BEGIN_API_CALL }, { type: types.LOAD_RECORDS_SUCCESS, records } ]; const store = mockStore({ records: [] }); return store.dispatch(recordActions.loadRecords()).then(() => { expect(store.getActions()).toEqual(expectedActions); }); }); }); }); describe("createRecordSuccess", () => { it("should create a CREATE_RECORD_SUCCESS action", () => { //arrange const record = records[0]; const expectedAction = { type: types.CREATE_RECORD_SUCCESS, record }; //act const action = recordActions.createRecordSuccess(record); //assert expect(action).toEqual(expectedAction); }); });
import {init} from "../pack/invite"; init();
import React from "react"; import PropTypes from "prop-types"; import { useLocation } from "react-router-dom"; import { NavLink } from "react-router-dom"; import DataTableInstance from "../uitils/DataTableUtils"; const DataTable = ({ table }) => { const location = useLocation(); return ( <div className="scrollbar"> <table className="table table-striped"> <thead className="table-dark"> <tr> {table.headers.map((header, index) => ( <th key={index}>{header}</th> ))} {table.showActionColumn ? <th>Action</th> : ""} </tr> </thead> <tbody> {table.data?.entities?.map((eachData) => ( <tr key={eachData?.id}> {table.data?.entityKeys?.map((property, index) => ( <td key={index}>{eachData[property]}</td> ))} <td> {table.actions.map((action, index) => { return action.actionType === DataTableInstance.DELETE_ACTION ? ( <button className="btn-border-less" data-bs-toggle="modal" data-bs-target="#targetModal" key={index} > <i table-data={eachData.id} onClick={action.actionHandaler} className={action.actionClasses} aria-hidden="true" ></i> </button> ) : ( <NavLink to={ action.actionType === DataTableInstance.VIEW_ACTION ? `${location.pathname}/${eachData.id}` : `${location.pathname}/${eachData.id}/edit` } key={index} > <i className={action.actionClasses} aria-hidden="true" ></i> </NavLink> ); })} </td> </tr> ))} </tbody> </table> </div> ); }; export default DataTable; DataTable.propTypes = { table: PropTypes.instanceOf(DataTableInstance).isRequired, };
export * from "./layout"; export * from "./slider"; export * from "./paypal";
const { Pool } = require("pg"); const databaseConfiguration = require("./secret/databaseConfiguration"); const pool = new Pool(databaseConfiguration); module.exports = pool; pool.query("SELECT foo FROM generation", (err, res) => { if (err) return console.log(err); console.log(res.rows); });
// see types of prompts: // https://github.com/SBoudrias/Inquirer.js#prompt-types // // and for examples for prompts: // https://github.com/SBoudrias/Inquirer.js/tree/master/examples module.exports = [ { type: 'input', name: 'name', message: 'What is the name of your vue component? (PascalCase)', }, { type: 'list', name: 'dir', message: 'Which dir should your new component be in?', choices: [ 'buttons', 'forms', 'hoc', 'icons', 'layout', 'menus', 'misc', 'scheduler', 'semantic', ], }, { type: 'input', name: 'description', message: 'Give your component a quick description?', }, ]
var DS_PO, DS_DonVi, DS_PO_Con, DS_BangKe_Cap1, DS_VatTu_PO, DS_VatTu; var Path, Path_Sua; $(document).ready(function () { //document.oncontextmenu = function () { return false; } $("#main-menu-toggle").click(); //#region bộ lọc $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); $("#cmb_BoLoc").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "Tình trạng PO", value: "1" }, { text: "Loại PO", value: "2" }, { text: "Ngày kí PO", value: "3" }, { text: "Nhà thầu", value: "4" }, { text: "Số hợp đồng", value: "5" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; switch (value) { case "1": $("#grid_PO").data("kendoGrid").dataSource.filter({}); //$("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").show(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); break; case "2": $("#grid_PO").data("kendoGrid").dataSource.filter({}); //$("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").show(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); break; case "3": $("#txt_TuNgay").val(""); $("#txt_DenNgay").val(""); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").show(); $("#Tr_Loc_NgayKi_PO_2").show(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); break; case "4": $("#grid_PO").data("kendoGrid").dataSource.filter({}); //$("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").show(); $("#Tr_Loc_NhaThau_2").show(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); break; case "5": $("#grid_PO").data("kendoGrid").dataSource.filter({}); //$("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").show(); $("#Tr_Loc_SoHD_2").show(); break; default: $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_Loai_PO").hide(); $("#Tr_Loc_NgayKi_PO_1").hide(); $("#Tr_Loc_NgayKi_PO_2").hide(); $("#Tr_Loc_NhaThau_1").hide(); $("#Tr_Loc_NhaThau_2").hide(); $("#Tr_Loc_SoHD_1").hide(); $("#Tr_Loc_SoHD_2").hide(); } } }); ////Lọc tình trang///////////// $("#cmb_Loc_TinhTrang").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "Chưa xuất PO lớn", value: "0" }, { text: "Đã xuất PO lớn", value: "1" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; //if (value == "") { // $("#grid_PO").data("kendoGrid").dataSource.filter({}); // $("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); //} //else { // $("#grid_PO").data("kendoGrid").dataSource.filter({ field: "Check_PO", operator: "eq", value: parseInt(value) }); // $("#grid_PO_ex").data("kendoGrid").dataSource.filter({ field: "Check_PO", operator: "eq", value: parseInt(value) }); //} var ds; if (value == "") { ds = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_byTinhTrang", data: { TinhTrang: parseInt(value) } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); } }); ///////////////Lọc loại PO//////////////// $("#cmb_Loc_Loai_PO").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "PO VTTP", value: "0" }, { text: "PO Tập đoàn", value: "1" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; //if (value == "") { // $("#grid_PO").data("kendoGrid").dataSource.filter({}); // $("#grid_PO_ex").data("kendoGrid").dataSource.filter({}); //} //else { // $("#grid_PO").data("kendoGrid").dataSource.filter({ field: "Check_PO_TapDoan", operator: "eq", value: parseInt(value) }); // $("#grid_PO_ex").data("kendoGrid").dataSource.filter({ field: "Check_PO_TapDoan", operator: "eq", value: parseInt(value) }); //} var ds; if (value == "") { ds = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_byLoaiPO", data: { LoaiPO: parseInt(value) } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); } }); ////////////Lọc ngày kí////////////// $("#txt_TuNgay").kendoDatePicker({ format: "dd/MM/yyyy" }); $("#txt_DenNgay").kendoDatePicker({ format: "dd/MM/yyyy" }); $("#btn_huy_loc_ngay").click(function () { $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); }); $("#btn_loc_ngay").click(function () { DS_PO_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'Lay_DS_PO_Ngay', TuNgay: $("#txt_TuNgay").val(), DenNgay: $("#txt_DenNgay").val() }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc); //$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc); }); ///////////////Lọc theo nhà thầu/////////////////////////////// $("#cmb_Loc_NhaThau").kendoDropDownList({ autoBind: true, optionLabel: "--Chọn nhà thầu--", dataTextField: "TenNhaThau", dataValueField: "NhaThau_ID", dataSource: new kendo.data.DataSource({ serverFiltering: true, transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_DanhMuc.aspx", data: { cmd: 'DS_NhaThau' }, dataType: 'json', success: function (result) { //options.success(result); if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } }) }); $("#btn_huy_loc_nt").click(function () { $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); }); $("#btn_loc_nt").click(function () { DS_PO_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'Lay_DS_PO_NT', NhaThau_ID: $("#cmb_Loc_NhaThau").data("kendoDropDownList").value() }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc); //$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc); }); ///////////////////Lọc hợp đồng /////////////////////// $("#cmb_Loc_SoHD").kendoComboBox({ placeholder: "--Chọn hợp đồng--", dataTextField: "MaHD", dataValueField: "HopDong_ID", filter: "startswith", dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'Lay_DS_PO_HD_Ctr' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } } } }); $("#btn_huy_loc_hd").click(function () { $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); }); $("#btn_loc_hd").click(function () { if ($("#cmb_Loc_SoHD").data("kendoComboBox").select() == -1) { //alert("Chưa chọn đúng mã hợp đồng!"); $("#notification").data("kendoNotification").show({ title: "Chưa chọn đúng mã hợp đồng!", message: "Hãy chọn hợp đồng!" }, "error"); } else { DS_PO_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'Lay_DS_PO_HD', HopDong_ID: $("#cmb_Loc_SoHD").data("kendoComboBox").value() }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc); //$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc); } }); //#endregion //#region DataSource DS_VatTu = new kendo.data.DataSource({ data: [] }); DS_PO = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); DS_DonVi = new kendo.data.DataSource({ sort: { field: "ID", dir: "asc" }, transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_DanhMuc.aspx", data: { cmd: 'DS_DonVi' }, dataType: 'json', success: function (result) { //options.success(result); if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } }); //#endregion //#region Upload $('#files_upload').kendoUpload({ async: { autoUpload: false, saveUrl: 'UploadFileVB.aspx' }, error: function (e) { this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger'); }, localization: { dropFilesHere: 'Kéo thả file vào đây để upload', headerStatusUploaded: 'Đã upload xong', headerStatusUploading: 'Đang upload', select: 'Chọn file...', statusFailed: 'Upload không thành công', statusUploaded: 'Đã upload xong', statusUploading: 'Đang upload', uploadSelectedFiles: 'Upload' }, multiple: false, success: function (e) { Path = e.response.FilePath; this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath); this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success'); }, upload: function (e) { e.data = { LoaiFile: 'VBPO_Lon' }; }, select: function (e) { var ext = e.files[0].extension.toLowerCase(); if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") { e.preventDefault(); //alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>'); $("#notification").data("kendoNotification").show({ title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>", message: "Hãy upload lại!" }, "error"); return; } if (e.files[0].size > 10485760) { e.preventDefault(); //alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!'); $("#notification").data("kendoNotification").show({ title: "Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!", message: "Hãy upload lại!" }, "error"); return; } } }); $('#files_upload_sua').kendoUpload({ async: { autoUpload: false, saveUrl: 'UploadFileVB.aspx' }, error: function (e) { this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger'); }, localization: { dropFilesHere: 'Kéo thả file vào đây để upload', headerStatusUploaded: 'Đã upload xong', headerStatusUploading: 'Đang upload', select: 'Chọn file...', statusFailed: 'Upload không thành công', statusUploaded: 'Đã upload xong', statusUploading: 'Đang upload', uploadSelectedFiles: 'Upload' }, multiple: false, success: function (e) { Path_Sua = e.response.FilePath; this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath); this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success'); }, upload: function (e) { e.data = { LoaiFile: 'VBPO_Lon' }; }, select: function (e) { var ext = e.files[0].extension.toLowerCase(); if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") { e.preventDefault(); //alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>'); $("#notification").data("kendoNotification").show({ title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>", message: "Hãy upload lại!" }, "error"); return; } if (e.files[0].size > 10485760) { e.preventDefault(); //alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!'); $("#notification").data("kendoNotification").show({ title: "Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!", message: "Hãy upload lại!" }, "error"); return; } } }); $('#btn_sua_upload').click(function () { $("#tr_download").hide(); $("#tr_upload").show(); Path_Sua = ""; }); //#endregion //#region Control var notification = $("#notification").kendoNotification({ position: { pinned: true, top: 50, right: 450 }, autoHideAfter: 2000, stacking: "down", templates: [ { type: "error", template: $("#errorTemplate").html() }, { type: "upload-success", template: $("#successTemplate").html() } ], show: function (e) { e.element.parent().css('z-index', 22222); } }).data("kendoNotification"); $("#txt_NgayKy").kendoDatePicker({ format: "dd/MM/yyyy" }); $("#txt_NgayKy_Sua").kendoDatePicker({ format: "dd/MM/yyyy" }); $("#wd_PO_them").kendoWindow({ draggable: false, height: "100%", width: "90%", actions: false, modal: true, resizable: false, title: "Tạo mới PO", visible: false }).data("kendoWindow"); $("#wd_PO_Sua").kendoWindow({ draggable: false, height: "auto", width: "auto", actions: false, modal: true, resizable: false, title: "Sửa PO", visible: false }).data("kendoWindow"); $("#wd_List_Option").kendoWindow({ draggable: false, modal: true, resizable: false, title: "Tạo mới vật tư thường theo:", visible: false, height: "30%", width: "30%", actions: false }).data("kendoWindow"); $("#wd_Show_VatTu").kendoWindow({ draggable: false, height: "100%", width: "100%", //actions: false, modal: true, resizable: false, title: "Tìm vật tư", visible: false }).data("kendoWindow"); $("#wd_PhanRa").kendoWindow({ draggable: false, height: "60%", width: "40%", actions: false, modal: true, resizable: false, title: "Phân rã PO", visible: false }).data("kendoWindow"); $("#wd_Show_VatTu").kendoWindow({ draggable: false, height: "100%", width: "100%", //actions: false, modal: true, resizable: false, title: "Tìm vật tư", visible: false }).data("kendoWindow"); $("#wd_VatTu_PO_Sua").kendoWindow({ draggable: false, height: "auto", width: "auto", actions: false, modal: true, resizable: false, title: "Sửa vật tư PO lớn", visible: false }).data("kendoWindow"); $("#wd_ChonVatTu_Vuot").kendoWindow({ draggable: false, height: "70%", width: "90%", actions: false, modal: true, resizable: false, title: "Tạo mới vật tư thường PO lớn", visible: false }).data("kendoWindow"); $("#txt_SoLuong_PO").kendoNumericTextBox({ format: 'n3', decimals: 3 }); $("#txt_SoLuong_PO_Sua").kendoNumericTextBox({ format: 'n3', decimals: 3, min: "0" }); //#endregion //#region Load Danh sach PO $("#grid_PO").empty(); var gvData = $("#grid_PO").kendoGrid({ toolbar: kendo.template($("#Templ_PO").html()), detailTemplate: kendo.template($("#Templ_ChiTiet_PO").html()), dataBound: function () { this.expandRow(this.tbody.find("tr.k-master-row").first()); }, detailExpand: function (e) { this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow)); }, pageable: { messages: { display: 'Dòng {0} - {1} / {2} dòng', empty: 'Không có dữ liệu', first: 'Trang đầu', itemsPerPage: 'dòng / trang', last: 'Trang cuối', next: 'Trang sau', of: '/ {0} trang', page: 'Trang', previous: 'Trang trước' }, pageSize: 5, pageSizes: [5, 10, 20] }, detailInit: Ham_ChiTiet_PO, sortable: true, columns: [ { title: "Khóa PO", headerAttributes: { class: "header_css" }, template: function (data) { if (data.TinhTrang == '0') { return '<center><input type="button" style="cursor: text;" class="button_mokhoa" /></center>'; } else { return '<center><input type="button" style="cursor: text;" class="button_khoa" /></center>'; } }, width: "7%" }, { template: function (data) { if (data.Check_PO == '0') { return '<center><span class="label label-success">Chưa xuất</span></center>'; } else { return '<center><span class="label label-important">Đã xuất</span></center>'; } }, width: "8%" }, { title: "Số PO", headerAttributes: { class: "header_css" }, field: "SoPO", attributes: { class: "row_css" } }, { title: "Ngày ký PO", headerAttributes: { class: "header_css" }, field: "NgayKyPO", attributes: { class: "row_css" }, template: "#= NgayKyPO_f #" //format: '{0:dd/MM/yyyy}' }, { title: "Số văn bản", headerAttributes: { class: "header_css" }, field: "SoVanBan", attributes: { class: "row_css" } }, { title: "Người lập PO", headerAttributes: { class: "header_css" }, field: "NguoiTaoPO", attributes: { class: "row_css" } }, { title: "File văn bản", headerAttributes: { class: "header_css" }, field: "FileVB", template: function (data) { if (data.FileVB == "" || data.FileVB == null) { return ''; } else { //return '<center><a href= "' + value + '" class="k-button" target="_blank" style="font-size: 0.85em !important;min-width:8px !important;" ><span class="k-icon k-i-seek-s"></span></a></center>'; return '<center><a href= "' + data.FileVB + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i> Tải</a></center>'; } }, width: "9%" }, //{ // template: function (data) { // if (data.TinhTrang == '0') { // return '<center><a class="btn btn-info" onclick="Ham_SuaPO(' + data.PO_ID + ');" ><i class="fa fa-edit "></i> Sửa</a></center>' // } else { // return ''; // } // }, // width: "9%" //}, //{ // template: function Ham_HienThi_Xoa_PO(data) { // if (data.TinhTrang == '0') { // return '<center><a class="btn btn-danger" onclick="Ham_XoaPO(' + data.PO_ID + ');"><i class="fa fa-trash-o "></i> Xóa</a></center>' // } else { // return ''; // } // }, // width: "8%" //} ] }); $("#txt_search_soPO").kendoAutoComplete({ dataTextField: "SoPO", filter: "contains", dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'Lay_DS_SoPO' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } } }); $('#txt_search_soPO').keydown(function (e) { if (e.which === 13) filterPO(); }); $('#btn_tim_soPO').click(function (e) { e.preventDefault(); filterPO(); }); $('#btn_clear_soPO').click(function (e) { e.preventDefault(); $('#txt_search_soPO').val(''); filterPO(); }); //#endregion //#region Load danh sách đơn vị tạo PO $("#grid_DonVi_Sua").empty(); $("#grid_DonVi_Sua").kendoGrid({ dataSource: DS_DonVi, scrollable: true, columns: [ { field: "ID", hidden: true }, { field: "select_dv", title: "Chọn", headerAttributes: { class: "header_css" }, template: '<center><input type=\'checkbox\' /></center>', sortable: false, width: 80, attributes: { style: "background-color:lightyellow;" } }, { title: "Mã đơn vị", headerAttributes: { class: "header_css" }, field: "DonVi_ID", attributes: { class: "row_css" } }, { title: "Tên đơn vị", headerAttributes: { class: "header_css" }, field: "TenDonVi", attributes: { class: "row_css" } } ] }); ///////// Load danh sách đơn vị\\\\\\\\\\\ $("#grid_DonVi").empty(); var grid_donvi = $("#grid_DonVi").kendoGrid({ dataSource: DS_DonVi, toolbar: kendo.template($("#Templ_DonVi").html()), columns: [ { field: "ID", hidden: true }, { field: "select_dv", title: "<input id='chk_all' type='checkbox' />", headerAttributes: { class: "header_css" }, template: '<center><input type=\'checkbox\' /></center>', sortable: false, width: 80, }, { title: "Mã đơn vị", headerAttributes: { class: "header_css" }, field: "DonVi_ID", attributes: { class: "row_css" } }, { title: "Tên đơn vị", headerAttributes: { class: "header_css" }, field: "TenDonVi", attributes: { class: "row_css" } } ] }); var dropDown = grid_donvi.find("#dl_KhuVuc").kendoDropDownList({ dataTextField: "text", dataValueField: "value", optionLabel: "--Tất cả--", dataSource: [ { text: "VNPT khu vực phía Bắc", value: "B" }, { text: "VNPT khu vực phía Nam", value: "N" } ], change: function () { var value = this.value(); if (value) { grid_donvi.data("kendoGrid").dataSource.filter({ field: "KhuVuc", operator: "eq", value: value }); document.getElementById('chk_all').checked = false; } else { grid_donvi.data("kendoGrid").dataSource.filter({}); } } }); $("#chk_all").click(function () { if (document.getElementById('chk_all').checked) { for (var j = 1; j < $("#grid_DonVi tr").length; j++) { $("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = true; } } else { for (var j = 1; j < $("#grid_DonVi tr").length; j++) { $("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = false; } } }); //#endregion //#region Hiển thị danh sách Vật tư var grid_vattu = $("#grid_VatTu").kendoGrid({ dataSource: DS_VatTu, pageable: true, pageable: { messages: { display: "Tổng số {2} vật tư", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, sortable: true, dataBound: function (e) { var view = this.dataSource.view(); for (var i = 0; i < view.length; i++) { if (ItemChecked[view[i].uid]) { this.tbody.find("tr[data-uid='" + view[i].uid + "']") .addClass("k-state-selected") .find(".checkbox") .attr("checked", "checked"); } } }, toolbar: kendo.template($("#Templ_VatuTu").html()), columns: [ { field: "select", title: "Chọn", headerAttributes: { class: "header_css" }, template: '<center><input type=\'checkbox\' class=\'checkbox\' /></center>', sortable: false, width: 80, attributes: { style: "background-color:lightyellow;" } }, { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Mã vật tư tập đoàn", headerAttributes: { class: "header_css" }, field: "MaVatTu_TD", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Số lượng khả dụng", headerAttributes: { class: "header_css" }, field: "SoLuong_KhaDung", type: "number", template: "#= OnChangeFormat(SoLuong_KhaDung) #", attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Số HĐ", headerAttributes: { class: "header_css" }, field: "MaHD", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Nhà thầu", headerAttributes: { class: "header_css" }, field: "NhaThau_Ten", attributes: { class: "row_css" } } ] }).data("kendoGrid"); //bind click event to the checkbox grid_vattu.table.on("click", ".checkbox", selectRow); var cboSearchBy_VT_Thuong = $('#cboSearchBy_VT_Thuong').kendoDropDownList({ dataSource: { data: ['Số hợp đồng', 'Tên vật tư', 'Mã vật tư'] } }).data('kendoDropDownList'); $('#btn_loc_vt_VT_Thuong').click(function (e) { e.preventDefault(); filterVatTuHopDong(); }); $('#btn_clear_VT_Thuong').click(function (e) { e.preventDefault(); $('#txtSearchValue_VT_Thuong').val(''); filterVatTuHopDong(); }); //#endregion $("#grid_PO").data("kendoGrid").setDataSource(DS_PO); }); //#region Hiển thị chi tiết PO function Ham_ChiTiet_PO(f) { BienChiTietPO = f; var detailRow = f.detailRow; detailRow.find("#tabstrip").kendoTabStrip({ animation: { open: { effects: "fadeIn" } }, select: function (e) { var content_tab = $(e.item).find("> .k-link").text().trim(); switch (content_tab) { case "Danh sách đơn vị tham gia PO": //#region Hiển thị danh sách đơn vị tham gia PO detailRow.find("#tab_DonVi").empty(); detailRow.find("#tab_DonVi").kendoGrid({ dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PO_DonVi_SelectbyPO_ID', PO_ID: f.data.PO_ID }, dataType: 'json', success: function (result) { //options.success(result); if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } }, pageSize: 8 }), sortable: true, pageable: { messages: { display: "Tổng số {2} đơn vị", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, columns: [ { title: "STT", headerAttributes: { class: "header_css" }, field: "STT", attributes: { class: "row_css" }, width: "30%" }, { title: "Đơn vị", headerAttributes: { class: "header_css" }, field: "DonVi_Ten", attributes: { class: "row_css" } } ] }); //#endregion break; case "Hiển thị phân rã đơn vị": //#region Hiển thị Phân rã đơn vị detailRow.find("#tab_PhanRa_DV").empty(); detailRow.find("#tab_PhanRa_DV").kendoGrid({ dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Con.aspx", data: { cmd: 'Lay_DS_PO_Con', PO_ID: f.data.PO_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } }), pageable: { messages: { display: "Tổng số {2} đơn vị", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, dataBound: function () { this.expandRow(this.tbody.find("tr.k-master-row").first()); }, detailExpand: function (e) { this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow)); }, detailInit: function (e) { e.detailCell.empty(); $("<div/>").appendTo(e.detailCell).kendoGrid({ dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_CT.aspx", data: { cmd: 'PO_CT_SelectByPO_ID_Con', PO_ID_Con: e.data.PO_ID_Con }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } }, aggregate: [ { field: "ThanhTien", aggregate: "sum" } ] }), columns: [ { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", attributes: { class: "row_css" } }, { title: "Số lượng", headerAttributes: { class: "header_css" }, field: "SoLuong", template: "#= OnChangeFormat(SoLuong) #", attributes: { class: "row_css" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Thành tiền", headerAttributes: { class: "header_css" }, field: "ThanhTien", template: "#= OnChangeFormat(ThanhTien) #", attributes: { class: "row_css" }, aggregates: ["sum"], footerTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>", groupFooterTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>", }, { title: "VAT", headerAttributes: { class: "header_css" }, field: "VAT", template: "#= OnChangeFormat(VAT) #", attributes: { class: "row_css" } } ] }); }, columns: [ { title: "Đơn vị", headerAttributes: { class: "header_css" }, field: "DonVi_Ten", attributes: { class: "row_css", style: "font-weight: bold !important;text-align: left !important;" } } ] }); //#endregion case "Danh sách PO con đã xuất": //#region Hiển thị Danh sách PO con đã xuất DS_PO_Con = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PONT_Select_By_PO', PO_ID: f.data.PO_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { if (result.length == 0) { $("#tab_PO_Con .k-grid-header").css('display', 'none'); } else { options.success(result); } } } }); } } //pageSize: 8 }); detailRow.find("#tab_PO_Con").empty(); detailRow.find("#tab_PO_Con").kendoGrid({ dataSource: DS_PO_Con, sortable: true, pageable: { messages: { display: "Tổng số {2} PO con", empty: "Chưa xuất PO con ", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, columns: [ { title: "Số hợp đồng", headerAttributes: { class: "header_css" }, field: "MaHD", attributes: { class: "row_css" } }, { title: "Nhà thầu", headerAttributes: { class: "header_css" }, field: "NhaThau_Ten", attributes: { class: "row_css" } }, { title: "Số VB gửi nhà thầu", headerAttributes: { class: "header_css" }, field: "SoVB", attributes: { class: "row_css" } }, { title: "File VB", headerAttributes: { class: "header_css" }, field: "FileVB", template: function (data) { if (data.FileVB == "" || data.FileVB == null) { return ''; } else { return '<center><a href= "' + data.FileVB + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i> Tải</a></center>'; } }, width: "9%" }, { title: "Tổng thanh toán", headerAttributes: { class: "header_css" }, field: "TongTienThanhToan", template: "#= OnChangeFormat(TongTienThanhToan) #", attributes: { class: "row_css", style: "font-weight:bold;" }, width: "15%" } ] }); //#endregion } } }); //#region Hiển thị phân rã vật tư var toolbar_vattu; var columns_vattu; if (BienChiTietPO.data.TinhTrang == "0") { toolbar_vattu = kendo.template($("#Templ_PO_VatTu").html()); columns_vattu = [ { title: "Số hợp đồng", headerAttributes: { class: "header_css" }, field: "MaHD", groupHeaderTemplate: "#= Ham_HienThi_Xuat_PO( value ) #", hidden: true, attributes: { class: "row_css" } }, { title: "Tên nhà thầu", headerAttributes: { class: "header_css" }, field: "TenNhaThau", attributes: { class: "row_css", style: "font-weight:bold;color:blue;" }, hidden: true }, { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>", attributes: { class: "row_css", style: "font-weight:bold;" }, width: "20%" }, { title: "Số lượng tổng PO", headerAttributes: { class: "header_css" }, field: "SoLuong_PO", template: "#= OnChangeFormat(SoLuong_PO) #", attributes: { class: "row_css", style: "color:red;font-weight:bold;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Thành tiền", headerAttributes: { class: "header_css" }, field: "ThanhTien_PO", template: "#= OnChangeFormat(ThanhTien_PO) #", attributes: { class: "row_css" }, aggregates: ["sum"], groupFooterTemplate: "<div class=\"row_css\">Tổng cộng: #=OnChangeFormat(sum) #</div>", width: "12%" }, //{ // template: function (data) { // if (data.Check_XuatPO_HD == "0") { // return '<center><a onclick="Ham_PhanRa(' + data.PO_ID + ',' + data.PO_HD_ID + ',' + data.VatTu_ID + ');" class="btn btn-info"><i class="fa fa-list"></i> Phân rã</a></center>' // } else { // return ''; // } // }, // width: "12%" //}, //{ // template: function (data) { // if (data.Check_XuatPO_HD == "0") { // return '<center><a class="btn btn-info" onclick="Ham_Sua_PO_HD_CT(' + data.PO_HD_ID + ',\'' + data.VatTu_Ten + '\',' + data.SoLuongTongHD + ',' + data.HopDong_ID + ',' + data.VatTu_ID + ',' + data.SoLuong_PO + ');"><i class="fa fa-edit "></i> Sửa</a></center>' // } else { // return '' // } // }, // width: "9%" //}, //{ // template: function (data) { // if (data.Check_XuatPO_HD == "0") { // return '<center><a class="btn btn-danger" onclick="Ham_Xoa_PO_HD_CT(' + data.PO_HD_ID + ');"><i class="fa fa-trash-o "></i> Xóa</a></center>' // } else { // return '' // } // }, // width: "8%" //} ]; } else { toolbar_vattu = ""; columns_vattu = [ { title: "Số hợp đồng", headerAttributes: { class: "header_css" }, field: "MaHD", groupHeaderTemplate: "#= Ham_HienThi_MaHD( value ) #", hidden: true, attributes: { class: "row_css" } }, { title: "Tên nhà thầu", headerAttributes: { class: "header_css" }, field: "TenNhaThau", attributes: { class: "row_css", style: "font-weight:bold;color:blue;" }, hidden: true }, { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>", attributes: { class: "row_css" }, width: "20%" }, { title: "Số lượng tổng PO", headerAttributes: { class: "header_css" }, field: "SoLuong_PO", template: "#= OnChangeFormat(SoLuong_PO) #", attributes: { class: "row_css", style: "color:red;font-weight:bold;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Thành tiền", headerAttributes: { class: "header_css" }, field: "ThanhTien_PO", template: "#= OnChangeFormat(ThanhTien_PO) #", attributes: { class: "row_css" }, aggregates: ["sum"], groupFooterTemplate: "<div class=\"row_css\">Tổng cộng: #=OnChangeFormat(sum) #</div>" }, ]; } DS_BangKe_Cap1 = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_DonVi_SelectbyPO_ID', PO_ID: f.data.PO_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } }, pageSize: 8, group: [ { field: "MaHD", aggregates: [ { field: "ThanhTien_PO", aggregate: "sum" } ] } ] }); /////////////////////////////////////// detailRow.find("#tab_VatTu").empty(); detailRow.find("#tab_VatTu").kendoGrid({ dataSource: DS_BangKe_Cap1, sortable: true, pageable: { messages: { display: "Tổng số {2} vật tư", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, toolbar: toolbar_vattu, columns: columns_vattu, dataBound: function () { this.expandRow(this.tbody.find("tr.k-master-row").first()); }, detailExpand: function (e) { this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow)); }, detailInit: Ham_ChiTiet_VatTu }); /////////////////////////////////////// //#endregion } function Ham_HienThi_Xuat_PO(value) { var arr_dv = value.split("*"); if ($("[id$=_hf_quyen_capnhat]").val() == "true") { if ($("[id$=_hf_quyen_GoXuatPO]").val() == "true") { if (arr_dv[0] == "0") { return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span><span style='margin-left:50px !important;margin-right:10px !important;' class='btn btn-info' onclick ='Ham_Xuat_DonHang(\" " + arr_dv[1] + " \");'><i class='fa fa-star-half-o'></i> Xuất PO con</span><span class='btn btn-info' style='margin-right:10px !important;' onclick='Ham_Xuat_Ex(\" " + value + " \");'><i class='fa fa-download'></i> Xuất Excel</span><span class='btn btn-info' onclick='Ham_Xuat_TDH(\" " + arr_dv[1] + " \");'><i class='fa fa-envelope'></i> Xuất thư đặt hàng</span>"; } else { return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span><span style="margin-left:160px !important;" class="btn btn-info" onclick ="Ham_Go_DonHang(\' ' + arr_dv[1] + ' \');"><i class="fa fa-mail-reply"></i> Gỡ xuất PO con</span>'; } } else { if (arr_dv[0] == "0") { return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span><span style='margin-left:50px !important;margin-right:10px !important;' class='btn btn-info' onclick ='Ham_Xuat_DonHang(\" " + arr_dv[1] + " \");'><i class='fa fa-star-half-o'></i> Xuất PO con</span><span class='btn btn-info' style='margin-right:10px !important;' onclick='Ham_Xuat_Ex(\" " + value + " \");'><i class='fa fa-download'></i> Xuất Excel</span><span class='btn btn-info' onclick='Ham_Xuat_TDH(\" " + arr_dv[1] + " \");'><i class='fa fa-envelope'></i> Xuất thư đặt hàng</span>"; } else { return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span>'; } } } else { if (arr_dv[0] == "0") { return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span>"; } else { return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span>'; } } } //#endregion //#region Hiển thị chi tiết vật tư function Ham_ChiTiet_VatTu(e) { Bien_ChiTiet_VatTu = e; DS_BangKe_Cap2 = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Con.aspx", data: { cmd: 'BangKe_Cap2', PO_ID: BienChiTietPO.data.PO_ID, VatTu_ID: e.data.VatTu_ID, }, dataType: 'json', success: function (result) { //options.success(result); if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } }); e.detailCell.empty(); $("<div/>").appendTo(e.detailCell).kendoGrid({ dataSource: DS_BangKe_Cap2, pageable: { messages: { display: "Tổng số {2} đơn vị", empty: "Chưa phân rã", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, columns: [ { title: "Đơn vị", headerAttributes: { class: "header_css" }, field: "TenDonVi", attributes: { class: "row_css" } }, { title: "Số lượng", headerAttributes: { class: "header_css" }, field: "SoLuong", //template: "#= OnChangeFormat(SoLuong) #", template: function (data) { if (data.TinhTrang_DC == 0) { return '' + OnChangeFormat(data.SoLuong) + ''; } else { return '' + OnChangeFormat(data.SoLuong) + '</br><a>(Đã điều chỉnh)</a>'; } }, attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Thành tiền", headerAttributes: { class: "header_css" }, field: "ThanhTien", template: "#= OnChangeFormat(ThanhTien) #", attributes: { class: "row_css" } }, { title: "VAT", headerAttributes: { class: "header_css" }, field: "VAT", template: "#= OnChangeFormat(VAT) #", attributes: { class: "row_css" } } ] }); } function Ham_HienThi_MaHD(value) { var arr_dv = value.split("*"); return "<b>Số hợp đồng: " + arr_dv[1] + "</b>"; } //#endregion //#region Thêm mới PO function Ham_Them_PO() { $("#wd_PO_them").data("kendoWindow").center().open(); } function Ham_Them_PO_Luu() { var str_id_dv = ''; for (var j = 1; j < $("#grid_DonVi tr").length; j++) { var chb_dv = $("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0]; var id = $("#grid_DonVi tr")[j].cells[0].childNodes[0].textContent; if (chb_dv.checked == true) { str_id_dv += '' + id + ','; } } str_id_dv = str_id_dv.replace(/^,|,$/g, ''); var check = 0; if ($("#txt_SoPO").val() == "") { check = 1; alert("Chưa nhập số PO!"); return; } if ($("#txt_NgayKy").val() == "") { check = 1; alert("Chưa nhập ngày ký PO!"); return; } if (str_id_dv == '') { check = 1; alert("Chưa chọn đơn vị tham gia!"); return; } if (check == 0) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PO_Create', SoPO: $("#txt_SoPO").val(), NgayKyPO: $("#txt_NgayKy").val(), SoVanBan: $("#txt_VB").val(), DonViPO: str_id_dv, SoNgayGH: 0, NgayGiaoHang: "", NgayXacNhanGH: "", NgayKeHoachGH: "", FileVB: Path }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { $("#notification").data("kendoNotification").show({ message: "Đã tạo mới thành công PO!" }, "upload-success"); $("#wd_PO_them").data("kendoWindow").close(); DS_PO.read(); Ham_Clear_Form_PO(); uploadReset(); $("#txt_search_soPO").data("kendoAutoComplete").dataSource.read(); } else { $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } function Ham_Them_PO_Huy() { $("#wd_PO_them").data("kendoWindow").close(); uploadReset(); } function Ham_Clear_Form_PO() { $("#txt_SoPO").val(""); $("#txt_NgayKy").val(""); $("#txt_VB").val(""); for (var j = 1; j < $("#grid_DonVi tr").length; j++) { $("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = false; } } //#endregion //#region Sửa PO function Ham_SuaPO(p_PO_ID) { $("#wd_PO_Sua").data("kendoWindow").center().open(); PO_ID_Sua = p_PO_ID; var grid_data = $("#grid_PO").data("kendoGrid"), data = grid_data.dataSource.data(); var res = $.grep(data, function (d) { return d.PO_ID == p_PO_ID; }); $("#txt_SoPO_Sua").val(res[0].SoPO); $("#txt_NgayKy_Sua").val(res[0].NgayKyPO_f); $("#txt_VB_Sua").val(res[0].SoVanBan); //Load check đơn vị var arr_dv = res[0].Str_PO_DonVi.split(","); for (var j = 1; j < $("#grid_DonVi_Sua tr").length; j++) { $("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0].checked = false; arr_dv.forEach(function (entry) { if ($("#grid_DonVi_Sua tr")[j].cells[0].childNodes[0].textContent == entry) { $("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0].checked = true; } }); } Path_Sua = res[0].FileVB; if (res[0].FileVB == "" || res[0].FileVB == null) { $("#tr_download").hide(); $("#tr_upload").show(); } else { $("#tr_download").show(); $("#tr_upload").hide(); $("#btn_download").attr("href", "" + res[0].FileVB + ""); } } function Ham_Sua_PO_Luu() { var str_id_dv = ''; for (var j = 1; j < $("#grid_DonVi_Sua tr").length; j++) { var chb_dv = $("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0]; var id = $("#grid_DonVi_Sua tr")[j].cells[0].childNodes[0].textContent; if (chb_dv.checked == true) { str_id_dv += '' + id + ','; } } str_id_dv = str_id_dv.replace(/^,|,$/g, ''); var check = 0; if ($("#txt_SoPO_Sua").val() == "") { check = 1; //alert("Chưa nhập số PO!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập số PO!", message: "Hãy nhập số PO!" }, "error"); return; } if ($("#txt_NgayKy_Sua").val() == "") { check = 1; //alert("Chưa nhập ngày ký PO!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập ngày ký PO", message: "Hãy nhập ngày ký PO!" }, "error"); return; } if ($("#txt_VB_Sua").val() == "") { check = 1; //alert("Chưa nhập văn bản xác nhận PO!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập văn bản xác nhận PO", message: "Hãy nhập văn bản xác nhận PO" }, "error"); return; } if (str_id_dv == '') { check = 1; //alert("Chưa chọn đơn vị tham gia!"); $("#notification").data("kendoNotification").show({ title: "Chưa chọn đơn vị tham gia", message: "Hãy nhập số PO!" }, "error"); return; } if (check == 0) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PO_Update', PO_ID: PO_ID_Sua, SoPO: $("#txt_SoPO_Sua").val(), NgayKyPO: $("#txt_NgayKy_Sua").val(), SoVanBan: $("#txt_VB_Sua").val(), DonViPO: str_id_dv, SoNgayGH: 0, NgayGiaoHang: "", NgayXacNhanGH: "", NgayKeHoachGH: "", FileVB: Path_Sua }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { $("#notification").data("kendoNotification").show({ message: "Đã sửa thành công PO!" }, "upload-success"); $("#wd_PO_Sua").data("kendoWindow").close(); var ds; if ($('#txt_search_soPO').val().trim() == '') { ds = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO", data: { SoPO: $('#txt_search_soPO').val().trim() } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } $('#grid_PO').data('kendoGrid').setDataSource(ds); uploadReset(); } else { //alert(msg[0].ErrorMessage); $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } function Ham_Sua_PO_Huy() { $("#wd_PO_Sua").data("kendoWindow").close(); uploadReset(); } //#endregion //#region Xóa PO function Ham_XoaPO(PO_ID) { if (confirm("Bạn có chắc muốn xóa PO này không? Xóa tất cả từ PO con,PO chi tiết")) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PO_Delete', PO_ID: PO_ID }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { $("#notification").data("kendoNotification").show({ message: "Đã xóa thành công PO!" }, "upload-success"); var ds = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); $("#grid_PO").data("kendoGrid").setDataSource(ds); $("#txt_search_soPO").data("kendoAutoComplete").dataSource.read(); } else { //alert(msg[0].ErrorMessage); $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } //#endregion //#region Hàm reset Upload function uploadReset(id) { if (id) { //if an id is passed as a param, only reset the element's child upload controls (in case many upload widgets exist) $("#" + id + " .k-upload-files").remove(); $("#" + id + " .k-upload-status").remove(); $("#" + id + " .k-upload.k-header").addClass("k-upload-empty"); $("#" + id + " .k-upload-button").removeClass("k-state-focused"); } else { //reset all the upload things! $(".k-upload-files").remove(); $(".k-upload-status").remove(); $(".k-upload.k-header").addClass("k-upload-empty"); $(".k-upload-button").removeClass("k-state-focused"); } } //#endregion //#region Tìm và chọn Vật tư function Ham_TaoMoiVatTu() { $("#wd_List_Option").data("kendoWindow").center().open(); } function Ham_Chon_TaoMoiVatTu() { if ($("#rdo_sl").is(":checked")) { Ham_TaoMoiVatTu_KhaDung(); } else { Ham_TaoMoiVatTu_HD(); } } function Ham_TaoMoiVatTu_KhaDung() { $("#wd_Show_VatTu").data("kendoWindow").center().open(); $('#grid_VatTu').data('kendoGrid').dataSource.read(); //#region hiển thị danh sách vật tư được chọn DS_VatTu_PO = new kendo.data.DataSource({ data: [], schema: { model: { fields: { SoLuong_KhaDung: { editable: false, type: "number" }, SoLuong_PO: { type: "number", validation: { //required: { message: "Chưa nhập số lượng!" } ////////////////////////////////// NameValidation: function (input) { var grid = $("#grid_VatTu_PO").data("kendoGrid"); var tr = $(input).closest('tr'); var dataRow = grid.dataItem(tr); var SL_PO = $(input).val(); var SL_KhaDung = dataRow.SoLuong_KhaDung; if (input.is("[name='SoLuong_PO']") && input.val() == "") { input.attr("data-NameValidation-msg", "Chưa nhập số lượng!"); return false; } if (input.is("[name='SoLuong_PO']") && SL_PO > SL_KhaDung) { input.attr("data-NameValidation-msg", "Số lượng PO vượt quá số lượng khả dụng!"); return false; } return true; } } } } } } }); $("#grid_VatTu_PO").empty(); $("#grid_VatTu_PO").kendoGrid({ dataSource: DS_VatTu_PO, pageable: { messages: { display: "Tổng số {2} vật tư của PO", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, editable: true, edit: function (e) { var input = e.container.find(".k-input"); input.val(""); }, toolbar: kendo.template($("#Templ_VatuTu_PO").html()), columns: [ { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", //template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Số lượng khả dụng", headerAttributes: { class: "header_css" }, field: "SoLuong_KhaDung", template: "#= OnChangeFormat(SoLuong_KhaDung) #", attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Số lượng PO", headerAttributes: { class: "header_css" }, field: "SoLuong_PO", template: function (data) { if (data.SoLuong_PO == 0) { return data.SoLuong_PO; } else { return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>'; } }, editor: function (container, options) { $('<input name="' + options.field + '"/>') .appendTo(container) .kendoNumericTextBox({ format: 'n3', decimals: 3 }) }, attributes: { class: "row_css", style: "background-color:lightyellow;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Số HĐ", headerAttributes: { class: "header_css" }, field: "MaHD", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Nhà thầu", headerAttributes: { class: "header_css" }, field: "NhaThau_Ten", attributes: { class: "row_css" } }, { template: '<center><a class="btn btn-danger" onclick="Ham_Xoa_VatTu_PO(#= STT #);"><i class="fa fa-trash-o "></i> Xóa</a></center>', width: "8%" } ] }); //#endregion } function Ham_TaoMoiVatTu_HD() { $("#wd_ChonVatTu_Vuot").data("kendoWindow").center().open(); $("#grid_VatTu_Vuot").empty(); $("#grid_VatTu_Vuot").kendoGrid({ pageable: { messages: { display: "Tổng số {2} vật tư của PO", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, editable: true, edit: function (e) { var input = e.container.find(".k-input"); input.val(""); }, toolbar: kendo.template($("#Templ_VatTu_Vuot").html()), columns: [ { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", //template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Số lượng hợp đồng", headerAttributes: { class: "header_css" }, field: "SoLuong", template: "#= OnChangeFormat(SoLuong) #", attributes: { class: "row_css", //style: "font-weight:bold;color:green;" } }, { title: "Số lượng khả dụng", headerAttributes: { class: "header_css" }, field: "SoLuong_KhaDung", template: "#= OnChangeFormat(SoLuong_KhaDung) #", attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Số lượng PO", headerAttributes: { class: "header_css" }, field: "SoLuong_PO", //template: function (data) { // if (data.SoLuong_PO == 0) { // return data.SoLuong_PO; // } else { // return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>'; // } //}, template: function (data) { if (data.SoLuong_PO == "null" || data.SoLuong_PO == null) { return 0; } else { return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>'; } }, editor: function (container, options) { $('<input name="' + options.field + '"/>') .appendTo(container) .kendoNumericTextBox({ format: 'n3', decimals: 3 }) }, attributes: { class: "row_css", style: "background-color:lightyellow;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } } ] }); $("#div_GTHD").hide(); var txt_search_sohd_vuot = $("#txt_search_sohd_vuot").kendoComboBox({ dataTextField: "MaHD", dataValueField: "HopDong_ID", filter: "contains", dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_DonVi.aspx", data: { cmd: 'HopDong_By_DonVi' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } } }), change: function () { GiaTriHopDong_ConLai = txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriConLai_HD; //$("#lb_GTHD").text(OnChangeFormat(txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriTruocThue)); $("#lb_GTHD_ConLai").text(OnChangeFormat(txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriConLai_HD)); var ds = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong_CT.aspx", data: { cmd: 'Lay_DS_HopDong_CT', HopDong_ID: txt_search_sohd_vuot.value() }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, schema: { model: { fields: { SoLuong_KhaDung: { editable: false, type: "number" }, SoLuong_PO: { type: "number" } } } } }); $("#grid_VatTu_Vuot").data("kendoGrid").setDataSource(ds); $("#div_GTHD").show(); } }).data("kendoComboBox"); } function Ham_Huy_ChonTaoMoiVatTu() { $("#wd_List_Option").data("kendoWindow").close(); } var ItemChecked = {}; function selectRow() { var checked = this.checked, row = $(this).closest("tr"), grid = $("#grid_VatTu").data("kendoGrid"), dataItem = grid.dataItem(row); ItemChecked[dataItem.uid] = checked; if (checked) { //-select the row row.addClass("k-state-selected"); } else { //-remove selection row.removeClass("k-state-selected"); } } //#endregion //#region Hàm chọn vật tư function Ham_Chon_VatTu() { //http://docs.telerik.com/kendo-ui/web/grid/how-to/Selection/grid-selection-checkbox for (var i in ItemChecked) { if (ItemChecked[i]) { var grid = $("#grid_VatTu").data("kendoGrid"); var selectedTopic = grid.dataSource.getByUid(i); var check = 0; for (var i = 0; i < DS_VatTu_PO.data().length; i++) { if (DS_VatTu_PO.data()[i].STT == selectedTopic.STT) { check = 1; break; } } if (check == 0) { DS_VatTu_PO.add(selectedTopic); } } } for (var i = 0; i < $("#grid_VatTu tr").length; i++) { var className_ = $("#grid_VatTu tr")[i].className; if (className_ == 'k-state-selected' || className_ == 'k-alt k-state-selected') { $($("#grid_VatTu tr")[i]).removeClass("k-state-selected"); $("#grid_VatTu tr")[i].cells[0].childNodes[0].childNodes[0].checked = false; } } ItemChecked = {}; //var grid = $("#grid_VatTu").data("kendoGrid"); //var selectedTopic = grid.dataSource.getByUid(grid.select().data("uid")); //if (selectedTopic == undefined) { // alert("Chưa chọn vật tư!"); // return; //} //else { // /////////////////////////////////////////////////////////// // var check = 0; // for (var i = 0; i < DS_VatTu_PO.data().length; i++) { // if (DS_VatTu_PO.data()[i].STT == selectedTopic.STT) { // check = 1; // break; // } // } // if (check == 0) { // DS_VatTu_PO.add(selectedTopic); // } // else { // alert("Vật tư đã được chọn!"); // } // //////////////////////////////////////////////////////////// // //$("#wd_Show_VatTu").data("kendoWindow").close(); // //$("#txt_VatTu_PO").text(selectedTopic.VatTu_Ten); // //VatTu_ID_PO = selectedTopic.VatTu_ID; // //$("#txt_SoLuong_HD").text(OnChangeFormat(selectedTopic.SoLuong_KhaDung)); // //HopDong_ID = selectedTopic.HopDong_ID; // //var request = $.ajax({ // // type: "POST", // // url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", // // data: { // // cmd: 'PO_HopDong_CT_SLTong', // // HopDong_ID: selectedTopic.HopDong_ID, // // VatTu_ID: selectedTopic.VatTu_ID // // }, // // dataType: 'json' // //}); // //request.done(function (msg) { // // if (msg[0].SoLuongKhaDung == "0") { // // alert("Vật tư này đã được đặt hết!"); // // $("#txt_SoLuong_PO").val(""); // // } else { // // $("#wd_VatTu_PO").data("kendoWindow").center().open(); // // $("#txt_SoLuong_KD").text(OnChangeFormat(msg[0].SoLuongKhaDung)); // // } // //}); // //request.fail(function (jqXHR, textStatus) { // // alert("Request failed: " + textStatus); // //}); //} } //#endregion //#region Hàm xóa vật tư tạm trong danh sách vật tư PO function Ham_Xoa_VatTu_PO(p_STT) { for (var i = 0; i < DS_VatTu_PO.data().length; i++) { var item = DS_VatTu_PO.data()[i]; if (item.STT == p_STT) { DS_VatTu_PO.remove(item); } } } //#endregion //#region Hàm lưu thiệt vật tư PO theo danh sách chọn function Ham_Luu_VatTu_PO_Vuot() { var DS_Grid_Vuot = $("#grid_VatTu_Vuot").data("kendoGrid").dataSource.data(); if (DS_Grid_Vuot.length == 0) { alert("Chưa chọn hợp đồng!"); } else { var TongSoLuong = 0; for (var j = 0; j < DS_Grid_Vuot.length; j++) { var p_soluong = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO; TongSoLuong += DS_Grid_Vuot[j].DonGia * parseFloat(ReplaceComma('' + p_soluong + '')); } if (parseFloat(TongSoLuong) > parseFloat(GiaTriHopDong_ConLai)) { alert("Vượt quá giá trị hợp đồng!"); } else { for (var j = 0; j < DS_Grid_Vuot.length; j++) { var p_HopDong_ID = $("#txt_search_sohd_vuot").data("kendoComboBox").value(); var p_VatTu_ID = DS_Grid_Vuot[j].VatTu_ID; var p_SoLuong_PO = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO; if (p_SoLuong_PO != 0) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_Create', PO_ID: BienChiTietPO.data.PO_ID, HopDong_ID: p_HopDong_ID, VatTu_ID: p_VatTu_ID, SoLuong_PO: p_SoLuong_PO }, dataType: 'json' }); } } //alert("Đã thêm thành công vật tư!"); $("#notification").data("kendoNotification").show({ message: "Đã thêm thành công vật tư!" }, "upload-success"); $("#wd_ChonVatTu_Vuot").data("kendoWindow").close(); $("#wd_List_Option").data("kendoWindow").close(); BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read(); DS_VatTu.read(); DS_PO.read(); } } } function Ham_Huy_VatTu_PO_Vuot() { $("#wd_ChonVatTu_Vuot").data("kendoWindow").close(); } function Ham_Luu_VatTu_PO() { var DS_Grid = $("#grid_VatTu_PO").data("kendoGrid").dataSource.data(); var check = 0; for (var j = 0; j < DS_Grid.length; j++) { var p_HopDong_ID = DS_Grid[j].HopDong_ID; var p_VatTu_ID = DS_Grid[j].VatTu_ID; var p_SoLuong_PO = DS_Grid[j].SoLuong_PO; if (p_SoLuong_PO == 0) { //alert("Chưa nhập số lượng PO!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập số lượng PO!", message: "Hãy nhập số lượng PO!" }, "error"); check = 1; break; } else { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_Create', PO_ID: BienChiTietPO.data.PO_ID, HopDong_ID: p_HopDong_ID, VatTu_ID: p_VatTu_ID, SoLuong_PO: p_SoLuong_PO }, dataType: 'json' }); } } if (check == 0) { //alert("Đã thêm thành công vật tư!"); $("#notification").data("kendoNotification").show({ message: "Đã thêm thành công vật tư!" }, "upload-success"); $("#wd_Show_VatTu").data("kendoWindow").close(); $("#wd_List_Option").data("kendoWindow").close(); DS_PO.read(); BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read(); DS_VatTu.read(); } } //#endregion //#region Hàm lưu vật tư PO đơn lẻ (ver cũ) function Ham_Luu_ThemPO_HD_CT() { //var str_id_vattu = ''; //var hopdong_id; //for (var j = 1; j < $("#grid_HD_CT tr").length; j++) { // var chb_dv = $("#grid_HD_CT tr")[j].cells[2].childNodes[0].childNodes[0]; // var id = $("#grid_HD_CT tr")[j].cells[1].childNodes[0].textContent; // if (chb_dv.checked == true) { // str_id_vattu += '' + id + ','; // hopdong_id = $("#grid_HD_CT tr")[j].cells[0].childNodes[0].textContent; // } //} //str_id_vattu = str_id_vattu.replace(/^,|,$/g, ''); //if (str_id_vattu=='') { // alert("Chưa chọn vật tư!"); // check = 1; // return; //} var check = 0; if ($("#txt_SoLuong").val() == "" || $("#txt_SoLuong").val() == "0") { check = 1; //alert("Chưa nhập số lượng!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập số lượng!", message: "Hãy nhập số lượng!" }, "error"); return; } if (check == 0) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_Create', PO_ID: BienChiTietPO.data.PO_ID, HopDong_ID: HopDong_ID, VatTu_ID: VatTu_ID_PO, SoLuong_PO: parseFloat($("#txt_SoLuong_PO").val()) }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { //alert("Đã thêm thành công vật tư!"); $("#notification").data("kendoNotification").show({ message: "Đã thêm thành công vật tư!" }, "upload-success"); $("#wd_VatTu_PO").data("kendoWindow").close(); $("#wd_List_Option").data("kendoWindow").close(); DS_PO.read(); Ham_ChiTiet_PO(BienChiTietPO); //$("#txt_SoLuong_PO").val(""); $("#txt_SoLuong_PO").data("kendoNumericTextBox").value(""); } else { //alert(msg[0].ErrorMessage); $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } function Ham_Huy_ThemPO_HD_CT() { $("#wd_VatTu_PO").data("kendoWindow").close(); } //#endregion //#region Sửa vật tư PO function Ham_Sua_PO_HD_CT(p_PO_HD_ID, VatTu_Ten, SoLuongTongHD, HopDong_ID, VatTu_ID, SoLuong_PO) { $("#wd_VatTu_PO_Sua").data("kendoWindow").center().open(); $("#txt_VatTu_PO_Sua").text(VatTu_Ten); $("#txt_SoLuong_HD_Sua").text(OnChangeFormat(SoLuongTongHD)); $("#txt_SoLuong_PO_Sua").data("kendoNumericTextBox").value(SoLuong_PO); PO_HD_ID = p_PO_HD_ID; var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_SLTong', HopDong_ID: HopDong_ID, VatTu_ID: VatTu_ID }, dataType: 'json' }); request.done(function (msg) { $("#txt_SoLuong_KD_Sua").text(OnChangeFormat(msg[0].SoLuongKhaDung)); }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } function Ham_Luu_SuaPO_HD_CT() { var check = 0; var SoLuong_PO = parseFloat(ReplaceComma($("#txt_SoLuong_PO_Sua").val())); var SoLuong_HD = parseFloat(ReplaceComma($("#txt_SoLuong_HD_Sua").text())); if (SoLuong_PO > SoLuong_HD) { check = 1; //alert("Số lượng vượt số lượng khả dụng!"); $("#notification").data("kendoNotification").show({ title: "Số lượng vượt số lượng khả dụng!", message: "Hãy nhập lại!" }, "error"); return; } if ($("#txt_SoLuong_Sua").val() == "" || $("#txt_SoLuong_Sua").val() == "0") { check = 1; //alert("Chưa nhập số lượng!"); $("#notification").data("kendoNotification").show({ title: "Chưa nhập số lượng!", message: "Hãy nhập số lượng!" }, "error"); return; } if (check == 0) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_Update_SL', PO_HD_ID: PO_HD_ID, SoLuong_PO: parseFloat($("#txt_SoLuong_PO_Sua").val()) }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { //alert("Đã sửa thành công vật tư!"); $("#notification").data("kendoNotification").show({ message: "Đã sửa thành công vật tư! Hãy phân rã lại vật tư" }, "upload-success"); $("#wd_VatTu_PO_Sua").data("kendoWindow").close(); DS_PO.read(); BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read(); } else { //alert(msg[0].ErrorMessage); $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } function Ham_Huy_SuaPO_HD_CT() { $("#wd_VatTu_PO_Sua").data("kendoWindow").close(); } //#endregion //#region Xóa vật tư PO function Ham_Xoa_PO_HD_CT(p_PO_HD_CT) { if (confirm("Bạn có chắc muốn xóa vật tư này không?")) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_HopDong_CT_Delete', PO_HD_CT: p_PO_HD_CT }, dataType: 'json' }); request.done(function (msg) { if (msg[0].ErrorMessage == null) { //alert("Đã xóa thành công vật tư!"); $("#notification").data("kendoNotification").show({ message: "Đã xóa thành công vật tư!" }, "upload-success"); DS_PO.read(); BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read(); } else { //alert(msg[0].ErrorMessage); $("#notification").data("kendoNotification").show({ title: msg[0].ErrorMessage, message: "Hãy thao tác lại!" }, "error"); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); $("#notification").data("kendoNotification").show({ title: "Request failed: " + textStatus, message: "Hãy thao tác lại!" }, "error"); }); } } //#endregion //#region Hiển thị phân rã vật tư PO function Ham_PhanRa(p_PO_ID, p_PO_HD_ID, p_VatTu_ID) { $("#wd_PhanRa").data("kendoWindow").center().open(); var ds = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_HopDong_CT.aspx", data: { cmd: 'PO_DonVi_SelectbyPO_ID', PO_ID: p_PO_ID }, dataType: 'json', success: function (result) { //options.success(result); if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } }, filter: { field: "PO_HD_ID", operator: "eq", value: p_PO_HD_ID } }); ds.fetch(function () { var view = ds.view(); $("#txt_VatTu").text(view[0].VatTu_Ten); $("#txt_MaVatTu").text(view[0].MaVatTu_TD); VatTu_ID = view[0].VatTu_ID; $("#txt_DonGia").text(OnChangeFormat(view[0].DonGia)); MaDVT = view[0].MaDVT; $("#txt_DVT").text(view[0].TenDVT); $("#txt_SoLuong_Tong").text(OnChangeFormat(view[0].SoLuong_PO)); }); $("#grid_PhanRa").kendoGrid({ dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PhanRa_ShowSL', PO_ID: p_PO_ID, VatTu_ID: p_VatTu_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=PO_DonVi.aspx"; } else { options.success(result); } } }); } }, schema: { model: { fields: { PO_DV_ID: { editable: false, type: "number" }, DonVi_Ten: { editable: false, type: "string" }, SoLuong_DV: { type: "number", validation: { required: { message: "Chưa nhập số lượng!" } } } } } } }), height: 300, editable: true, edit: function (e) { var input = e.container.find(".k-input"); input.val(""); //input.keyup(function () { // value = input.val(); //}); //$("[name='SoLuong_DV']", e.container).blur(function () { // var input = $(this); // var grid = $("#grid_PhanRa").data("kendoGrid"); // var row = $(this).closest("tr"); // var item = grid.dataItem(row); // //alert(item.SoLuong_DV); //}); }, columns: [ { field: "PO_DV_ID", hidden: true }, { title: "Đơn vị", headerAttributes: { class: "header_css" }, field: "DonVi_Ten", attributes: { class: "row_css" }, width: "50%" }, { title: "Số lượng", headerAttributes: { class: "header_css" }, field: "SoLuong_DV", template: function (data) { if (data.SoLuong_DV == 0) { return data.SoLuong_DV; } else { return '<b style="color:green;">' + OnChangeFormat(data.SoLuong_DV) + '</b>'; } }, editor: function (container, options) { $('<input name="' + options.field + '"/>') .appendTo(container) .kendoNumericTextBox({ format: 'n3', decimals: 3 }) }, attributes: { class: "row_css", style: "background-color:lightyellow;" }, width: "50%" } ] }); } //#endregion //#region Lưu phân rã function Ham_Luu_PhanRa() { var TongSL_PO = parseFloat(ReplaceComma($("#txt_SoLuong_Tong").text())); var Chuoi_JSON = ""; var TongSL_DV = 0; for (var j = 1; j < $("#grid_PhanRa tr").length; j++) { var PO_DV_ID = parseInt($("#grid_PhanRa tr")[j].cells[0].childNodes[0].textContent); var ClassName = $("#grid_PhanRa tr")[j].cells[2].className; var SoLuong = parseFloat(ReplaceComma($("#grid_PhanRa tr")[j].cells[2].textContent)); if (ClassName == "row_css k-dirty-cell") { Chuoi_JSON += "{'PO_DV_ID':" + PO_DV_ID + ",'VatTu_ID':" + VatTu_ID + ",'SoLuong':" + SoLuong + "},"; } TongSL_DV += SoLuong; } Chuoi_JSON = Chuoi_JSON.replace(/^,|,$/g, ''); var check = 0; if ((TongSL_DV).toFixed(3) > (TongSL_PO).toFixed(3)) { check = 1; //alert("Số lượng phân rã vượt quá số lượng tổng PO!"); $("#notification").data("kendoNotification").show({ title: "Số lượng phân rã vượt số lượng tổng PO!", message: "Hãy nhập lại!" }, "error"); return; } if (((TongSL_DV).toFixed(3) < (TongSL_PO).toFixed(3)) && ((TongSL_DV).toFixed(3) != (TongSL_PO).toFixed(3))) { check = 1; //alert("Chưa phân rã hết số lượng vật tư"); $("#notification").data("kendoNotification").show({ title: "Chưa phân rã hết số lượng vật tư!", message: "Hãy nhập lại!" }, "error"); } if (check == 0) { var request = $.ajax({ type: "POST", url: "assets/ajax/Ajax_PO_Cha.aspx", data: { cmd: 'PhanRa_Luu', gData: "[" + Chuoi_JSON + "]", VatTu_ID: VatTu_ID, MaDVT: MaDVT, DonGia: ReplaceComma($("#txt_DonGia").text()) }, dataType: 'json' }); request.done(function (msg) { if (msg == "OK") { //alert("Đã cập nhật phân rã!"); $("#notification").data("kendoNotification").show({ message: "Đã cập nhật phân rã!" }, "upload-success"); $("#wd_PhanRa").data("kendoWindow").close(); BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read(); DS_BangKe_Cap2.read(); } }); request.fail(function (jqXHR, textStatus) { //alert("Request failed: " + textStatus); }); } } function Ham_Huy_PhanRa() { $("#wd_PhanRa").data("kendoWindow").close(); } //#endregion function filterPO() { var ds; if ($('#txt_search_soPO').val().trim() !== '') { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO", data: { SoPO: $('#txt_search_soPO').val().trim() } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else { ds = new kendo.data.DataSource({ requestEnd: function (e) { e.response.d = JSON.parse(e.response.d); }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'PO_ID', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO" }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD); //$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD); } function filterVatTuHopDong() { var ds; if ($('#txtSearchValue_VT_Thuong').val().trim() !== '') { var value_cbo = $('#cboSearchBy_VT_Thuong').data('kendoDropDownList').text(); if (value_cbo === 'Số hợp đồng') { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) { e.response.d = JSON.parse(e.response.d); } }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'STT', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/HopDong_CT_SelectAll_HD", data: { MaHD: $('#txtSearchValue_VT_Thuong').val().trim() } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else if (value_cbo === 'Tên vật tư') { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) { e.response.d = JSON.parse(e.response.d); } }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'STT', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/HopDong_CT_SelectAll_TenVT", data: { TenVT: $('#txtSearchValue_VT_Thuong').val().trim() } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } else if (value_cbo === 'Mã vật tư') { ds = new kendo.data.DataSource({ requestEnd: function (e) { if (e.type) { e.response.d = JSON.parse(e.response.d); } }, schema: { data: 'd.Data', total: 'd.Total[0].Total' }, pageSize: 5, serverPaging: true, serverSorting: true, sort: { field: 'STT', dir: 'desc' }, transport: { read: { contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', url: "assets/ajax/Ajax_PO_DonVi.aspx/HopDong_CT_SelectAll_MaVT", data: { MaVT: $('#txtSearchValue_VT_Thuong').val().trim() } }, parameterMap: function (options, operation) { return kendo.stringify(options); } } }); } } else { ds = new kendo.data.DataSource({ data: [] }); } $("#grid_VatTu").data("kendoGrid").setDataSource(ds); }
import React from 'react'; import ContentRightTop from '../components/ContentRightTop'; import ContentRightBottom from '../components/ContentRightBottom'; class ContentRight extends React.Component { render () { return ( <div className="med right-side"> <ContentRightTop /> <ContentRightBottom /> </div> ); } } export default ContentRight;
define('app/models/manager', [ 'app/models/model', 'magix' ], function (Model, Magix) { var M = Magix.Manager.create(Model) // 新增网站 M.registerModels([ // 获取导购推广类目 { name: 'get_self_cat', url: '/common/site/generalize/guideGetCategory.json', method: 'GET' } ]) // 设置推广位 M.registerModels([ // 获取自助推广的推广位 { name: 'get_self_adzone', url: '/common/adzone/newSelfAdzone2.json', method: 'GET', actionId: 10 }, // 创建自助推广的推广位 { name: 'create_self_adzone', url: '/common/adzone/selfAdzoneCreate.json', method: 'POST', actionId: 11 } ]) // 获取代码 M.registerModels([ // 单品代码 { name: 'get_item_code', url: '/common/code/getAuctionCode.json', method: 'GET', actionId: 30 }, // 批量单品代码 { name: 'get_batch_item_code', url: '/common/code/getAuctionCode.json', method: 'GET', actionId: 30 } ]) // 定向计划 M.registerModels([ // 获取定向计划列表 { name: 'get_campaign_list', url: '/pubauc/getCommonCampaignByItemId.json', method: 'GET', actionId: 60 }, // 申请定向计划 { name: 'apply_campaign', url: '/pubauc/applyForCommonCampaign.json', method: 'POST', actionId: 61 } ]) // 选品分组 M.registerModels([ // 创建与修改 { name: 'selection_group_save', url: '/favorites/group/save.json', method: 'POST', actionId: 202 }, // 删除分组 { name: 'selection_group_del', url: '/favorites/group/delete.json', method: 'POST', actionId: 203 }, // 获取选品分组列表 { name: 'get_selection_group_list', url: '/favorites/group/newList.json', method: 'GET', actionId: 201 }, // 添加选品到分组 { name: 'selection_add_group', url: '/favorites/item/batchAdd.json', method: 'POST', actionId: 301 }, // 获取选品商品列表 { name: 'selection_item_goods', url: '/favorites/item/list.json', method: 'GET', actionId: 300 }, { name: 'selection_goods_del', url: '/favorites/item/batchDelete.json', method: 'GET', actionId: 302 }, { name: 'selection_invalid_goods_items_del', url: '/favorites/item/deleteInvalidItems.json', method: 'GET', actionId: 304 } ]) // 搜索结果 M.registerModels([ // 获取列表 { name: 'search_item_lists', url: '/items/search.json', method: 'GET', actionId: 100 }, //获取店铺信息 { name: 'shop_info', url: '/pubauc/searchPromotionInfo.json', method: 'GET', actionId: 51 } ]) // 频道页面 M.registerModels([ // 女装尖货 { name: 'item_channel_nzjh', url: '/items/channel/nzjh.json', method: 'GET', actionId: 455 }, // 母婴热推 { name: 'item_channel_muying', url: '/items/channel/muying.json', method: 'GET', actionId: 456 }, // 淘宝客活动 { name: 'item_channel_qqhd', url: '/items/channel/qqhd.json', method: 'GET', actionId: 453 }, // 定向计划 { name: 'item_channel_dxjh', url: '/items/channel/dxjh.json', method: 'GET', actionId: 454 }, // 9块9包邮 { name: 'item_channel_9k9', url: '/items/channel/9k9.json', method: 'GET', actionId: 450 }, // 20元封顶 { name: 'item_channel_20k', url: '/items/channel/20k.json', method: 'GET', actionId: 451 }, // 特价好货 { name: 'item_channel_tehui', url: '/items/channel/tehui.json', method: 'GET', actionId: 452 }, // 极有家 { name: 'item_channel_jyj', url: '/items/channel/jyj.json', method: 'GET', actionId: 457 }, // 酷动城 { name: 'item_channel_kdc', url: '/items/channel/kdc.json', method: 'GET', actionId: 458 }, //亲宝贝 { name: 'item_channel_qbb', url: '/items/channel/qbb.json', method: 'GET', actionId: 459 }, //ifashion { name: 'item_channel_ifs', url: '/items/channel/ifs.json', method: 'GET', actionId: 460 }, // 潮电街 { name: 'item_channel_cdj', url: '/items/channel/cdj.json', method: 'GET', actionId: 461 }, //汇吃 { name: 'item_channel_hch', url: '/items/channel/hch.json', method: 'GET', actionId: 462 }, // 淘宝diy { name: 'item_channel_diy', url: '/items/channel/diy.json', method: 'GET', actionId: 463 } ]) // 销货区块 M.registerModels([ { name: 'get_sales_list', url: '/items/hot/list.json', method: 'GET', actionId: 500 } ]) // 我的招商 M.registerModels([ // 获取我的招商列表 { name: 'get_zhaoshang_list', url: '/itemevent/event/list.json', method: 'GET', actionId: 400 }, // 获取招商个数限制 { name: 'get_zhaoshang_limit', url: '/itemevent/event/creationLimit.json', method: 'GET', actionId: 406 }, // 获取选品库失效商品个数 { name: 'selection_goods_invalid_count', url: '/favorites/item/invalidItemCount.json', method: 'GET', actionId: 305 }, // 删除招商需求 { name: 'del_zhaoshang', url: '/itemevent/event/delete.json', method: 'POST', actionId: 407 }, // 获取指定groupId对应的信息 { name: 'get_zhaoshang_group_info', url: '/favorites/group/baseInfo.json', method: 'GET' }, // 获取招商商品列表 { name: 'get_zhaoshang_item_list', url: '/itemevent/item/list.json', method: 'GET', actionId: 404 }, // 获取指定eventId对应的招商活动信息 { name: 'get_zhaoshang_detail', url: '/itemevent/event/detail.json', method: 'GET', actionId: 401 }, // 保存招商需求 { name: 'zhaoshang_save', url: '/itemevent/event/save.json', method: 'POST', actionId: 402 }, // 保存修改单个商品佣金 { name: 'zhaoshang_commission_modify', url: '/itemevent/item/commission/modify.json', method: 'POST', actionId: 405 } ]) // 通用接口 M.registerModels([ // 获取tms内容 { name: 'get_tms_content', url: '/common/getTmsContent.json', method: 'GET' } ]) M.registerModels([ { name: 'get_sign', url: '/common/pubSigned.json', method: 'GET' } ]) M.registerModels([ { name: 'set_sign', url: '/common/pubSign.json', method: 'post' } ]) // 达人 M.registerModels([ { name: 'talent_member_status', url: '/talent/status.json', method: 'GET', skipTip: true }, { name: 'recordCreate', url: '/talent/save.json', method: 'POST' }, { name: 'recordUpdate', url: '/talent/update.json', method: 'POST' }, { name: 'channelRecord', url: '/talent/record.json', method: 'GET' } ]); return M })
const express = require('express'); const { rejectUnauthenticated } = require('../modules/authentication-middleware'); const pool = require('../modules/pool'); const router = express.Router(); router.get('/', rejectUnauthenticated, (req, res) => { console.log('req.user:', req.user); if(req.user.clearance_level >= 18) { pool .query('SELECT * FROM "secret";') .then((results) => res.send(results.rows)) .catch((error) => { console.log('Error making SELECT for secrets:', error); res.sendStatus(500); }); } else if(req.user.clearance_level < 11 && req.user.clearance_level > 5){ pool .query(`SELECT * FROM "secret" WHERE "secrecy_level" <= 10;`) .then((results) => res.send(results.rows)) .catch((error) => { console.log('Error making SELECT for secrets:', error); res.sendStatus(500); }) } else if(req.user.clearance_level < 5 && req.user.clearance_level > 3) { pool .query(`SELECT * FROM "secret" WHERE "secrecy_level" <= 4;`) .then((results)=> res.send(results.rows)) .catch((error)=> { console.log('Error making SELECT for secrets:', error); res.sendStatus(500) }) }else { res.sendStatus(403) } }); module.exports = router; // else if(req.isAuthenticated()){ // pool.query(`SELECT * FROM "secret" JOIN "user" on ${req.user.clearance_level} >= "secret"."secrecy_level";`) // .then((results) => res.send(results.rows)) // .catch((error)=> { // console.log('error in making select for secrets', error); // res.sendStatus(500); // })
angular.module('manager') .controller('ContactsController', [ '$scope', '$filter', '$http', '$modal', 'settingsService', 'Str', function ($scope, $filter, $http, $modal, $db, str) { var api = $db.getApi("Contacts"); $scope.current = { user: 0, category: 0, search: "" }; $scope.contactsGridData = []; $scope.selectedcontacts = []; $scope.getCurrentContact = function () { var contact = ""; if ($scope.selectedcontacts.length == 0) return contact; var c = $scope.selectedcontacts[0]; for (var l in c.ContactLines) { var i = c.ContactLines[l]; contact += i.Name; if (i.Description != null || i.Description != "") contact += " (" + i.Description + ") "; } contact += ", " + c.Name ; if (c.Description != null || c.Description != "") { contact += ", (" + c.Description + ") "; } return contact; } api.getCategories().success(function (data) { $scope.categories = data; }); var contactsTemplate = '<table >' + '<tr ng-repeat="c in row.entity[col.field]">' + '<td class="data" title="{{c.Description}}">{{c.Name}}</td>' + '<td class="description">{{c.Description}}</td></tr></table>'; $scope.contactsGrid = { data: 'contactsGridData', multiSelect: false, selectedItems: $scope.selectedcontacts, enableColumnResize: true, enableCellSelection: false, enableRowSelection: true, enableCellEdit: false, enableRowEdit: false, columnDefs: [ { field: 'Date', displayName: str.grid_Date, cellFilter: 'date:\'yyyy-MM-dd\'', width: '100px' }, { field: 'Category.Name', displayName: str.grid_Category }, { field: 'Name', displayName: str.grid_Name }, { field: 'ContactLines', displayName: str.grid_Contacts, cellClass: 'contactLines', cellTemplate: contactsTemplate }, { field: 'Description', displayName: str.grid_Description, enableCellEdit: true }, { field: 'Owner.UserName', displayName: str.grid_Owner, width: '80px' }, { displayName: str.grid_Actions, cellTemplate: '<div style="text-align:center;">' + '<button class="btn btn-warning btn-xs" ng-click="addContact(true,$index)" title="' + str.action_Edit + '">' + '<span class="glyphicon glyphicon-pencil"></span>' + '</button>' + '<button class="btn btn-danger btn-xs" type="button" ng-click="deleteContact($index)" title="' + str.action_Remove + '">' + '<span class="glyphicon glyphicon-remove"></span>' + '</button>' + '</div>', width: '80px', enableCellEdit: false } ], }; $scope.update = function () { api.getItems($scope.current.user, $scope.current.category, $scope.current.search) .success(function (data) { $scope.contactsGridData = data; }); }; $scope.update(); $scope.addContact = function (editable) { var contact = {}; var category = {}; var title; if (editable) { angular.copy(this.row.entity, contact); category = _.find($scope.categories, function (c) { return c.Id == contact.Category.Id; } ); title = str.ttl_EditContact; } else { contact = { ContactLines: [] }; title = str.ttl_AddContact; } $modal.open({ templateUrl: 'addContact.html', controller: [ '$scope', '$modalInstance', function ($mscope, $modalInstance) { $mscope.Title = title; $mscope.c = contact; $mscope.c.Category = category; $mscope.categories = $scope.categories; function clean() { $mscope.line = ''; $mscope.description = ''; } $mscope.removeLine = function (c) { _.remove($mscope.c.ContactLines, function (r) { return r == c; }); }; $mscope.addLine = function (c, d) { $mscope.c.ContactLines.push( { Name: c, Description: d } ); clean(); }; clean(); $mscope.ok = function () { $modalInstance.close($mscope.c); }; $mscope.cancel = function () { $modalInstance.dismiss('cancel'); }; } ] }).result.then(function (item) { api.updateItem(item).then($scope.update); }); }; $scope.deleteContact = function () { var exp = this.row.entity; $modal.open({ templateUrl: 'deleteContact.html', controller: [ '$scope', '$modalInstance', function ($mscope, $modalInstance) { $mscope.Title = str.ttl_DeleteContact; $mscope.c = exp; $mscope.ok = function () { $modalInstance.close(); }; $mscope.cancel = function () { $modalInstance.dismiss('cancel'); }; } ] }).result.then(function() { api.deleteItem(exp).then($scope.update); }); }; } ]);
// eslint-disable-next-line strict 'use strict'; const images = require('images'); images('./WechatIMG6.jpeg').save('w.jpeg', { quality: 50 });
import RoleRoute from './Role'; import UserRoute from './User'; export { RoleRoute, UserRoute };
var express = require('express'), router = express.Router(), wall = require('../../controllers/wall/wall'), pool = require('../../controllers/db_connection'); gf = require('../../controllers/commong_controllers/global_functions'); var passport = require('passport'); router.get('/',gf.authenticationMiddleware(),wall.index.bind(wall)); module.exports = router;
define(function(require, exports, module) { var global = require('../../lib/global/global'); var request = require('../../lib/http/request'); var bodyParse = require('../../lib/http/bodyParse'); var template = require('../../lib/template/template'); var monsary = require('../../lib/plugin/dom/monsary'); var jsonToUrl = require('../../lib/json/jsonToUrl'); var saveData =require('../../lib/dom/saveData.js'); var globalFnDo = require('../../lib/module/globalFnDo'); function CaseSearch() { this.schemeDataUrl = '/index.php/view/scheme/search'; this.roomDataUrl = '/index.php/view/room/search' this.scheme_temp_id = 'scheme_search'; this.room_temp_id = 'room_search'; this.getOptionUrl = this.judePage() == 'scheme' ? '/index.php/view/scheme/option' : '/index.php/view/room/option'; this.optionTemp = '{{each data as $value $key}}' + '<div class="tiplist clearfix" type="{{$key}}">'+ '<span class="pr_20 fl">{{$value.option_name}}</span>'+ '<ul class="fl">'+ '<li>'+ '{{each $value.tag_list}}'+ '<a href="#" tag_id="{{$value.tag_id}}" script-role="tag" location_type="{{$key}}">{{$value.tag_name}}</a>'+ '{{/each}}'+ '</li>'+ '</ul>'+ '</div>'+ '{{/each}}' this.oTagWrap = $('[script-role = tag_wrap]'); this.oInput = $('[script-role = case_search_area]'); this.oSearchBtn = $('[script-role = case_search_btn]'); this.oSearchWrap = $('[script-role = search_wrap]'); this.paramListLength = 4; this.actClassName = 'act'; this.paramData = {}; } CaseSearch.prototype = { init: function() { var _this = this; this.paramData = this.getParam(); this.load(function(data){ _this.renderTag(_this.oTagWrap, data); _this.showUrlData(_this.paramData); _this.location(); }); }, getParam: function() { var t1, t2, t3, t4, keyword, sort, p, dataParam, newJson; newJson = {}; dataParam = bodyParse(); if(!dataParam) { t1 = '0'; t2 = '0'; t3 = '0'; t4 = '0'; keyword = ''; sort = '1'; p = '1'; } else { t1 = dataParam.t1 ? dataParam.t1 : '0'; t2 = dataParam.t2 ? dataParam.t2 : '0'; t3 = dataParam.t3 ? dataParam.t3 : '0'; t4 = dataParam.t4 ? dataParam.t4 : '0'; keyword = dataParam.keyword ? dataParam.keyword : ''; sort = dataParam.sort ? dataParam.sort : '1'; p = dataParam.p ? dataParam.p : '1'; } newJson.t1 = t1; newJson.t2 = t2; newJson.t3 = t3; newJson.t4 = t4; newJson.keyword = keyword; newJson.sort = sort; newJson.p = p; return newJson; }, showUrlData: function(data) { var i, num, _this; i = 0; num = this.paramListLength; _this = this; for (i=0; i<num; i++) { var aTag = this.oTagWrap.find('[type = t'+ (i+1) +']').find('[script-role = tag]'); aTag.each(function(k){ if(aTag.eq(k).attr('tag_id') == data['t' + (i+1)]) { aTag.eq(k).addClass(_this.actClassName); } }); } this.oInput.val(data.keyword); }, load: function(callBack) { request({ url: this.getOptionUrl, sucDo: function(data) { callBack && callBack(data); }, noDataDo: function(msg) { alert(msg); } }); }, renderTag: function(oWrap, data) { var render = template.compile(this.optionTemp); var html = render(data); oWrap.html(html); }, selectTag: function() { }, judePage: function() { var type; type = window.location.href.indexOf('scheme') !=-1 ? 'scheme' : 'room'; return type; }, location: function() { var sType, oTarget, _this, url; _this = this; this.oSearchWrap.on('click', function(e){ oTarget = $(e.target); if(typeof(oTarget.attr('location_type')) != 'undefined') { sType = oTarget.attr('location_type'); if(sType == 'sort') { _this.paramData[sType] = oTarget.attr('value'); } else if(sType == 'keyword') { _this.paramData[sType] = _this.oInput.val(); } else { _this.paramData[sType] = oTarget.attr('tag_id'); } window.location = window.location.pathname + '?' + jsonToUrl(_this.paramData); } }); } }; var search = new CaseSearch(); search.init(); var type = search.judePage(); var aList; if(type == 'scheme') { var mon = new monsary({ oWrap: $('[script-role=monsary_wrap]'), url: search.schemeDataUrl, tplId: search.scheme_temp_id, param: search.paramData, isStartLoadingShow: 'false', renderDo: function(data) { aList = $('[script-role = content_list_jia178]'); saveData(aList, data); } }); mon.init(); } else { var mon = new monsary({ oWrap: $('[script-role=monsary_wrap]'), url: search.roomDataUrl, tplId: search.room_temp_id, param: search.paramData, isStartLoadingShow: 'false', renderDo: function(data) { aList = $('[script-role = content_list_jia178]'); saveData(aList, data); } }); mon.init(); } var pageDo = new globalFnDo({ oWrap : $('[script-role = monsary_wrap]') }); pageDo.init(); });
module.exports = (req, res, next) => { if (req.method == 'POST' || req.method === 'PUT') { let data = ''; req.on('data', chunk => { data += chunk; }); req.on('end', () => { try { req.body = JSON.parse(data); } catch (error) { return next(new Error('JSON NOT VALID')); } }) } return next(); }
// Створіть клас Планета. // Конструктор класу повинен приймати назву та діаметр планети, а також викликати метод класу для // підрахунку об'єму планети (припустимо, що планета це сфера). // Також клас повинен мати метод, що виводить в консоль назву планети та її об'єм. // Приклад: Планета *** має об'єм *** . // Створити ще один клас Земля, унаслідуватися від класу class Planet { constructor( title, diameter){ this.title = title this.diameter = diameter } get volume(){ return (4/3) * Math.PI * (this.diameter/2)**3 } toString(){ return `Planet ${this.title} has volume ${this.volume}` } } class Earth extends Planet { constructor(diameter){ super('Earth', diameter) } } const mars = new Planet ('Mars', 6779) console.log(mars) const earth = new Planet ('Earth', 12742000) console.log(earth + '')
/* BENEFICIARY */ export const LEGAL_INDIVIDUAL= 'Personne morale'; export const PHYSICAL_INDIVIDUAL= 'Personne Physique'; export const NATURAL= 'Personel'; export const PHYSICAL= 'physique'; export const LEGAL= 'morale'; //ACCOUNTS CHARTS export const EARNING = 'earning_funds' export const SPENDING = 'spending_funds' export const BALANCE = 'balance'
var ops = 0; db = connect("localhost:27017/dashboard") prompt = function () { let time = new Date(); return `${time.getHours()}:${time.getMinutes()}:${time.getSeconds()} ${db} ${++ops}$ ` }
import { makeStyles } from '@material-ui/core/styles' const tableToolBarStyled = makeStyles(theme => ({ root: { background: '#fff', borderBottom: '1px solid #e0e0e0', minHeight: '8rem', fontSize: '1.6rem', paddingLeft: theme.spacing(2), paddingRight: theme.spacing(2), }, highlight: theme.palette.type === 'light' ? { color: '#202124', backgroundColor: '#c2dbff', } : { color: theme.palette.text.primary, backgroundColor: theme.palette.secondary.dark, }, link: { color: '#202124', }, tableTitle: { position: 'absolute', left: '40%', fontFamily: 'Century Gothic, Futura, sans-serif', fontWeight: 600, padding: '0 2rem', '@media(max-width: 850px)': { display: 'none', }, }, title: { color: '#f50057', flex: '1', fontFamily: 'Century Gothic, Futura, sans-serif', fontSize: '1.6rem', }, })) export default tableToolBarStyled
const postRepo = require("../repositories/post-repo"); class PostService { add(userId,post) { return postRepo.save(userId, post); } getAll() { return postRepo.findAll(); } getById(id) { return postRepo.findOne(id); } getByCargo(cargo) { return postRepo.findByCargo(cargo); } getQty(qty){ return postRepo.getByQty(qty) } update(id, post) { return postRepo.update(id, post); } delete(id) { return postRepo.delete(id); } } module.exports = PostService;
require('dotenv').config(); const express = require('express'); // Express web server framework const request = require('request'); // "Request" library const cors = require('cors'); const bodyParser = require('body-parser'); const querystring = require('querystring'); const cookieParser = require('cookie-parser'); const {generateRandomString} = require('./utils'); const checkPermission = require('./middleware/checkPermission'); const sse = require('./middleware/sse'); const SpotifyWebApi = require('spotify-web-api-node'); const {Pool} = require('pg'); const client_id = process.env.CLIENT_ID; // Your client id const client_secret = process.env.CLIENT_SECRET; // Your secret const redirect_uri = `${process.env.BASE_URL || "http://localhost:8888"}/callback`; // Your redirect uri const stateKey = 'spotify_auth_state'; const app = express(); const pool = new Pool({ connectionString: process.env.DATABASE_URL, // ssl: true }); const spotifyApi = new SpotifyWebApi(); app.use(express.static(`${__dirname}/public`)) .use(cors()) .use(cookieParser()) .use(checkPermission({pool})) .use(bodyParser.json()) .use(sse); const refreshToken = function () { pool.query("SELECT refresh_token FROM spotify", (err, res) => { const options = { url: 'https://accounts.spotify.com/api/token', headers: {'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))}, form: { grant_type: 'refresh_token', refresh_token: res.rows[0].refresh_token }, json: true }; request.post(options, function (error, response, body) { if (!error && response.statusCode === 200) { const access_token = body.access_token; spotifyApi.setAccessToken(access_token); } }); }); }; refreshToken(); function pollSpotify(request, response) { let previouslyPlaying; let first = true; console.log("Polling started"); const interval = setInterval(function () { spotifyApi.getMyCurrentPlayingTrack() .then( function (data) { if (!data.body.item) { if (previouslyPlaying || first) { response.write(`data: ${JSON.stringify({})}`); } else { response.write(`\n`); } if (previouslyPlaying) previouslyPlaying = false; } else { pool.query("SELECT current_song_id FROM spotify", (err, res) => { const currentSongId = res.rows[0].current_song_id; if (!previouslyPlaying || currentSongId !== data.body.item.id || first) { pool.query({ text: "UPDATE spotify SET current_song_id = $1", values: [data.body.item.id] }); response.write(`data: ${JSON.stringify(data.body.item)}`); } else { response.write(`\n`); } if (!previouslyPlaying) previouslyPlaying = true; }); } if (first) first = false; }, function (err) { console.log(err) } ); }, 1000); request.on('close', () => { console.log("Polling ended"); clearInterval(interval); }); } app.get('/stream', function (request, response) { response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); pollSpotify(request, response) }); app.get('/top_track', function (req, res) { const {time_range} = req.query; spotifyApi.getMyTopTracks({limit: 5, time_range}) .then( function (data) { const random = Math.floor(Math.random() * Math.floor(5)); res.send(data.body.items[random]); }, function (err) { res.sendStatus(401); console.log(err); } ) }); app.get('/playlist', function (req, res) { spotifyApi.getPlaylistTracks(process.env.PLAYLIST_ID, {fields: "items(track(album(artists, images, external_urls), name, uri))"}) .then( function (data) { let tracks = data.body.items; const retObj = {items: []}; tracks.map(({track}) => { retObj.items.push(track) }); res.send(retObj); }, function (err) { res.sendStatus(401); console.log(err); } ) }); app.post('/playlist', function (req, res) { const {track} = req.body; spotifyApi.addTracksToPlaylist(process.env.PLAYLIST_ID, [track]) .then( function (data) { res.sendStatus(200); }, function (err) { res.sendStatus(401); console.log(err); } ); }); app.get('/search', function (req, res) { const {title} = req.query; spotifyApi.searchTracks(title) .then( function (data) { res.send(data.body); }, function (err) { res.sendStatus(401); console.log(err); } ) }); app.get('/login', function (req, res) { const state = generateRandomString(16); res.cookie(stateKey, state); // your application requests authorization const scope = 'user-read-currently-playing user-top-read'; res.redirect('https://accounts.spotify.com/authorize?' + querystring.stringify({ response_type: 'code', client_id: client_id, scope: scope, redirect_uri: redirect_uri, state: state })); }); startRefresh = function (expires_in) { setInterval(function () { refreshToken(); console.log("refreshed token") }, expires_in * 1000) }; app.get('/callback', function (req, res) { // your application requests refresh and access tokens // after checking the state parameter const code = req.query.code || null; const state = req.query.state || null; const storedState = req.cookies ? req.cookies[stateKey] : null; if (state === null || state !== storedState) { res.send("state_mismatch") } else { res.clearCookie(stateKey); const authOptions = { url: 'https://accounts.spotify.com/api/token', form: { code: code, redirect_uri: redirect_uri, grant_type: 'authorization_code' }, headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, json: true }; request.post(authOptions, function (error, response, body) { if (!error && response.statusCode === 200) { const {refresh_token, access_token, expires_in} = body; // Store Refresh and Access token pool.query({ text: "UPDATE spotify SET refresh_token = $1", values: [refresh_token] }); spotifyApi.setAccessToken(access_token); startRefresh(expires_in); res.send("Successfully authenticated"); } else { res.send("Invalid Token") } }); } }); console.log('Listening on 8888'); app.listen(process.env.PORT || 8888);
// =============================== Global Library Functions/Methods/Vars // keep track of requests var xhrs = {}; // flag indicating whether the reqs have been // aborted on the beforunload/unload events var unloaded = false; /** * @description [Aborts the provided http request object.] * @param {Object} _ [The http object to abort.] * @return {Object} [The http object.] */ function abort(_) { // get the XHR object var xhr = _.xhr, properties = _.properties; // check if already aborted, if so return if (properties.aborted) return xhr; // only abort if req is has not been resolved or rejected if (!properties.resolved && !properties.rejected) { // abort the request xhr.abort(); // set aborted property to true properties.aborted = true; // update the path properties.path += ";aborted"; delete xhrs[properties.id]; // remove xhr from pool } // else the req was already aborted return xhr; // return the xhr } /** * @description [Global library abort method. Aborts all requests.] * @return {Undefined} [Nothing is returned.] * @concept {http://stackoverflow.com/questions/32497035/abort-ajax-request-in-a-promise} */ library.abortAll = function() { // loop over xhrs for (var id in xhrs) { if (xhrs.hasOwnProperty(id)) { // abort the xhr abort(xhrs[id]); } } }; /** * @description [Unload event handler. Aborts all requests when the * page is unloaded (refreshed, tab closed).] * @param {Object} event [The event object.] * @return {Undefined} [Nothing is returned.] */ function unload(e) { // http://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-problem-with-chrome // http://stackoverflow.com/questions/6895564/difference-between-onbeforeunload-and-onunload // prevent double execution of function if (unloaded) return; // abort all requests library.abortAll(); // check if xhr pool is empty if (!Object.keys(xhrs) .length) { // set flag to true unloaded = true; // remove the event listeners window.removeEventListener("beforeunload", unload, false); window.removeEventListener("unload", unload, false); } } // set unload listeners window.addEventListener("beforeunload", unload, false); window.addEventListener("unload", unload, false);
"use strict"; /** @module EquivalentJS/Manager/Module */ /** * @interface * @classdesc Module class interface representation * @typedef {Object} EquivalentJS.Manager.Module.class * @constructs * @tutorial MODULE_MANAGER * @see if the module class is initialized by DOM application * the reference is appended to * class property EquivalentJS.Manager.Module.class.__markup__ */ EquivalentJS.define('EquivalentJS.Manager.Module.class', new function () { /** * @description indicates a layout stylesheet DOM is loaded * if {@link EquivalentJS.Manager.Module.class.layout} is set true * @event EquivalentJS.Manager.Module.class#ready:layout */ /** * @description indicates a template DOM is loaded * if {@link EquivalentJS.Manager.Module.class.template} is set true * @event EquivalentJS.Manager.Module.class#ready:template */ /** * @description bind public properties or methods from inner scope * @memberOf EquivalentJS.Manager.Module.class * @private * @alias {EquivalentJS.Manager.Module.class} * @example var _ = this; */ var _ = this; /** * @description the manager assigns this property automatically * @memberOf EquivalentJS.Manager.Module.class * @typedef {string} EquivalentJS.Manager.Module.class.type * @tutorial MODULE_MANAGER */ _.type = 'EquivalentJS.Manager.Module.class'; /** * @description extend from another module class; * this property is optional * @memberOf EquivalentJS.Manager.Module.class * @typedef {string} EquivalentJS.Manager.Module.class.extend */ _.extend = 'EquivalentJS.Manager.Module.class'; /** * @description bind a stylesheet on module; * if true then add sass css file to the corresponding module class folder; * the file name pattern is lowercase dash separated module class name parts * like MyNamespace/MyApp.js => MyNamespace/my-app.scss; * the stylesheet DOM link element get removed if * the module will be removed from DIC; * this property is optional * @memberOf EquivalentJS.Manager.Module.class * @typedef {boolean} EquivalentJS.Manager.Module.class.layout * @see EquivalentJS.Manager.Module.class.__layout__ the css reference */ _.layout = false; /** * @description bind a template on module; * if true then add markup fragment file to the corresponding module class folder; * the file name pattern is lowercase dash separated module class name parts * like MyNamespace/MyApp.js => MyNamespace/my-app.html; * the template DOM element get removed if * the module will be removed from DIC; * this property is optional * @memberOf EquivalentJS.Manager.Module.class * @typedef {boolean} EquivalentJS.Manager.Module.class.template */ _.template = false; /** * @description construct the module class; * the method get destroyed by manager after module is loaded; * this method is optional * @memberOf EquivalentJS.Manager.Module.class * @typedef {function} EquivalentJS.Manager.Module.class.construct */ _.construct = function () {}; /** * @description the module class manager interface; * the manager assigns this property automatically; * the usage of this property is optional but better for * test cases with mocked manager instance * @memberOf EquivalentJS.Manager.Module.class * @typedef {EquivalentJS.Manager} EquivalentJS.Manager.Module.class.__manager__ */ _.__manager__ = {}; /** * @description get the application DOM reference if module initialized from [data-application] attribute; * the manager assigns this property automatically; * @memberOf EquivalentJS.Manager.Module.class * @typedef {HTMLElement} EquivalentJS.Manager.Module.class.__markup__ */ _.__markup__ = {}; /** * @description get the css reference if module layout is true; * the manager assigns this property automatically; * @memberOf EquivalentJS.Manager.Module.class * @typedef {HTMLLinkElement} EquivalentJS.Manager.Module.class.__layout__ */ _.__layout__ = {}; /** * @description get the template reference if module template is true; * the manager assigns this property automatically; * @memberOf EquivalentJS.Manager.Module.class * @typedef {jQuery} EquivalentJS.Manager.Module.class.__template__ */ _.__template__ = {}; });
'use strict'; const Koa = require('koa'); const app = new Koa(); const hbs = require('koa-hbs'); const serve = require('koa-static'); const logger = require('koa-logger'); const session = require('koa-session'); const send = require('koa-send'); const bodyparser = require('koa-bodyparser'); const soap = require('soap'); const parseString = require('xml2js').parseString; const js2xmlparser = require('js2xmlparser'); const path = require('path'); const router = require('./router'); const sg = require('./lib/email'); console.log('NODE_ENV', process.env.NODE_ENV); if (process.env.NODE_ENV === 'development') { const webpackDevMiddleware = require('koa-webpack-dev-middleware'); const webpack = require('webpack'); const config = require('./webpack.config'); const compiler = webpack(config); const WEBPACK_CONFIG = { history: true, noInfo: true, publicPath: '/', contentBase: path.resolve(__dirname, 'dist') }; app.use(webpackDevMiddleware(compiler, WEBPACK_CONFIG)); } // ERROR HANDLER app.use(async (ctx, next) => { try { await next(); } catch (e) { ctx.status = 500; ctx.body = { success: false, status: 500, data: 'Internal Server Error' }; console.error(e.message); console.error(e.stack || e); } }); // LOGGER app.use(logger()); //CONNECT DBs // start postgres client const postgres = require('./lib/postgres'); // start redis client const redis = require('./lib/redis'); // Connect to Ship Compliant require('./lib/ship_compliant'); // Register Shopify webhooks on startup require('./lib/shopify').registerWebhooks(); // add middleware app.use(postgres.middleware); app.use(redis.middleware); app.use(session({}, app)); //VIEW app.use( hbs.middleware({ viewPath: `${__dirname}/views`, partialsPath: `${__dirname}/views/partials`, layoutsPath: `${__dirname}/views/layouts`, defaultLayout: `main` }) ); // MIDDLEWARE app.keys = [process.env.SESSION_KEY]; app.use(bodyparser()); app.use(serve(path.resolve(__dirname, 'dist'))); // Add ctx.respond function app.use(async (ctx, next) => { ctx.respond = (status, data) => { status = Number(status); ctx.status = status; ctx.body = { status, data, success: status >= 200 && status <= 299 }; }; await next(); }); // ROUTING app.use(router.routes()); app.use(router.allowedMethods()); app.use(async ctx => { await send(ctx, 'index.html', { root: __dirname + '/dist' }); }); app.listen(process.env.PORT, function () { console.log(`Listening on port ${process.env.PORT}...`); });
import React, { Component } from 'react'; import Palette from './palette'; import Workspace from './workspace'; import './css/plan.css'; let testRug = { type: 'rug', x: 80, y: 47, width: 30, height: 50, fill: '#EEE' } let testLamp = { type: 'lamp', cx: 31, cy: 53, r: 30, fill: '#AAA' } let testPlan = { items: { testRug, testLamp } } class Plan extends Component { constructor(props) { super(props); this.state = { plan: testPlan } } render() { let onMouseDown = (item, reactEvent) => { let x = reactEvent.clientX; let y = reactEvent.clientY; } let onMouseUp = (item, reactEvent) => { let x = reactEvent.clientX; let y = reactEvent.clientY; } return ( <div className="Plan"> <Palette className="Palette"/> <Workspace plan={this.state.plan} onMouseDown={onMouseDown} onMouseUp={onMouseUp}/> </div> ); } } export default Plan;
import { Link, Img } from "gatsby" import PropTypes from "prop-types" import React from "react" import { Grid, Box, Flex } from 'theme-ui' import Logo from "../images/logo.png" import Search_logo from "../images/search_logo.png" function Header ({ menuLinks,siteTitle }) { return( <header style={{ background: `#fdd021`, }} > <Flex> <Link to="/"> <img src={Logo} alt="Logo" style={{width:"40px", height:"auto", margin:"5px"}}/> </Link> <Box sx={{ flex: '1 1 auto' }} style={{display:"flex"}} > {menuLinks.map(link => ( <p key={link.name} style={{margin: "5px"}}> <Link to={link.Link} style={{color: "#bb2205"}}> {link.name} </Link> </p> ))} <Link style={{color: "#bb2205", margin: "5px"}} href="mailto:lenoxnguyen2014@gmail.com">hire me</Link> </Box> <Box> <Link to="/"> <img src={Search_logo} alt="Logo" style={{width:"40px", height:"auto", margin:"5px"}}/> </Link> </Box> </Flex> </header> ) } Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
import React from 'react'; import PropTypes from 'prop-types'; import {withRouter} from 'react-router-dom'; import classes from './index.module.css'; import {MDBAvatar, MDBRow} from 'mdbreact'; import ReplyContent from './content'; import ReplyFooter from './footer'; import {urlPrefix, generateHeaders, defaultAva, get} from '../../../../../../../tool/api-helper'; import {timeHelper} from '../../../../../../../tool/time-helper'; class ReplyCard extends React.Component{ constructor(props){ super(props); this.state={ backend:null, authorAvatar:null, }; } componentDidMount(){ let userAll = this.props.data.creator; let authorAvatar; if((userAll !== null) && (userAll.avatar_url.length > 10)){ authorAvatar = userAll.avatar_url; get(`/static/${authorAvatar}`).then((res)=>{ this.setState(()=>({ authorAvatar:res.content, backend:{...this.props.data}, })); }); } else { authorAvatar = defaultAva; this.setState(()=>({ authorAvatar, backend:{...this.props.data}, })); } } // 点赞 onVote = () => { let evaluateStatus = this.state.backend.evaluateStatus; let upvoteCount = this.state.backend.upvoteCount; let downvoteCount = this.state.backend.downvoteCount; const data = { id:Number(window.localStorage.id) }; // 取消点赞 if (evaluateStatus === 1) { evaluateStatus = 3; upvoteCount--; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/vote`, { method: 'DELETE', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, upvoteCount } })); } else if(evaluateStatus === 2) { // 取消反对 evaluateStatus = 1; upvoteCount++; downvoteCount--; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/upvote`, { method: 'PUT', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, upvoteCount, downvoteCount } })); } else { evaluateStatus = 1; upvoteCount++; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/upvote`, { method: 'PUT', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, upvoteCount } })); } }; // 反对 onDownVote = () => { let evaluateStatus = this.state.backend.evaluateStatus; let upvoteCount = this.state.backend.upvoteCount; let downvoteCount = this.state.backend.downvoteCount; const data = { id:Number(window.localStorage.id) }; if (evaluateStatus === 2) { evaluateStatus = 3; downvoteCount--; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/vote`, { method: 'DELETE', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, downvoteCount } })); } else if(evaluateStatus === 3) { evaluateStatus = 2; downvoteCount++; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/downvote`, { method: 'PUT', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, downvoteCount } })); } else { evaluateStatus = 2; downvoteCount++; upvoteCount--; try { fetch( `${urlPrefix}/replies/${this.props.data.id}/downvote`, { method: 'PUT', headers: generateHeaders(), body: JSON.stringify(data) }, ); } catch (e) { alert(e); } this.setState(() => ({ backend: { ...this.state.backend, evaluateStatus, downvoteCount, upvoteCount } })); } }; render(){ const {backend, authorAvatar} = this.state; return (backend !== null) ? ( <div className={classes.wrapper}> <div> <MDBRow className={classes.mdbRow}> <MDBAvatar className={classes.avatar}> <img src={authorAvatar} alt="avatar" className={`rounded-circle ${classes.imgStyle}`} /> </MDBAvatar> <div className={classes.commentWrapper}> <ReplyContent user={backend.creator} time={timeHelper(backend.create_at)} content={backend.body} /> <ReplyFooter onVote={this.onVote} onDownVote={this.onDownVote} upvoteCount={backend.upvoteCount} downvoteCount={backend.downvoteCount} evaluateStatus={backend.evaluateStatus} /> </div> </MDBRow> </div> </div> ):( <div> loading </div> ); } } ReplyCard.propTypes = { data: PropTypes.object.isRequired, history: PropTypes.object.isRequired, }; export default withRouter(ReplyCard);
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const outdoorFeaturesSchema = new Schema({ listingID: Schema.Types.ObjectId, fencedYard: Boolean, sprinklerSystem: Boolean, firePit: Boolean, pool: Boolean, parking : String, garage: String }); module.exports = mongoose.model('Outdoor-Feature', outdoorFeaturesSchema);
import React from "react" import { connect } from 'react-redux' import { voteAnecdote } from "../reducers/anecdoteReducer" import { notificationVoteChange } from "../reducers/notificationReducer" const AnecdoteList = (props) => { const anecdotes = props.anecdotes //console.log(anecdotes) anecdotes.sort((a, b) => (a.votes < b.votes ? 1 : -1)) const vote = anecdote => { props.voteAnecdote(anecdote) props.notificationVoteChange("Created a anecdote with id " + anecdote.id + ".", 5) } return ( <div> {anecdotes.map(anecdote => ( <div key={anecdote.id}> <div>{anecdote.content}</div> <div> has {anecdote.votes} <button onClick={() => vote(anecdote)}>vote</button> </div> </div> ))} </div> ) } const mapStateToProps = state => { return { anecdotes: state.anecdotes } } const mapDispatchToProps = { voteAnecdote, notificationVoteChange } const ConnectedAnecdotes = connect(mapStateToProps, mapDispatchToProps)(AnecdoteList) export default ConnectedAnecdotes
var express = require('express'), xrpc = require('./static/scripts/connect-xmlrpc'), app = express(); //app.configure(function () { // app.use(xrpc.xmlRpc); //}); app.post('/RPC', xrpc.route({ 'calc.add': function (a, b, callback) { callback(null, (a|0)+(b|0)); } })); app.listen(3000);
// $Id: ajax_vote_up_down.js,v 1.6.2.5 2009/01/29 19:44:05 lut4rp Exp $ /** * Pre-processing for the vote database object creation. */ Drupal.behaviors.voteUpDownAutoAttach = function () { var vdb = []; $('span.vote-up-inact, span.vote-down-inact, span.vote-up-act, span.vote-down-act').each(function () { // Read in the path to the PHP handler. var uri = $(this).attr('title'); // Remove the title, so no tooltip will displayed. $(this).removeAttr('title'); // Remove the href link. $(this).html(''); // Create an object with this uri, so that we can attach events to it. if (!vdb[uri]) { vdb[uri] = new Drupal.VDB(this, uri); } }); } /** * The Vote database object */ Drupal.VDB = function (elt, uri) { var db = this; this.elt = elt; this.uri = uri; this.id = $(elt).attr('id'); this.dir1 = this.id.indexOf('vote_up') > -1 ? 'up' : 'down'; this.dir2 = this.dir1 == 'up' ? 'down' : 'up'; $(elt).click(function () { // Ajax POST request for the voting data $.ajax({ type: 'GET', url: db.uri, success: function (data) { // Extract the cid so we can change other elements for the same cid var cid = db.id.match(/[0-9]+$/); var pid = 'vote_points_' + cid; // Update the voting arrows $('#' + db.id + '.vote-' + db.dir1 + '-inact').removeClass('vote-' + db.dir1 + '-inact').addClass('vote-' + db.dir1 + '-act'); $('#' + 'vote_' + db.dir2 + '_' + cid).removeClass('vote-' + db.dir2 + '-act').addClass('vote-' + db.dir2 + '-inact'); // Update the points $('#' + pid).html(data); }, error: function (xmlhttp) { alert('An HTTP '+ xmlhttp.status +' error occured. Your vote was not submitted!\n'); } }); }); }
const MongoClient = require('mongodb').MongoClient; const uri = `mongodb+srv://david:${process.env.DB_PASS}@cluster0-2jplm.gcp.mongodb.net/test?retryWrites=true`; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(err => { if (err) { console.log(err); client.close(); return; } console.log("Connected to MongoDB"); const collection = client.db("test").collection("scripts-demo"); collection.insertOne({ firstName: "David", lastName: "Mac" }, function(err) { if (err) { console.log(err); client.close(); return; } console.log("Inserted record"); client.close(); }); });
import articles from './articles' import patients from './patients' export default { articles, patients }
var url = "https://www.google.com"; if(url.startsWith("https://") || url.startsWith("http://") && url.endsWith(".com")) { console.log("valid url") } else { console.log("invalid Url") }
import ModeButton from './ModeButton/ModeButton' import './header.module.css' import { FiPaperclip } from 'react-icons/fi'; import {DiGithubBadge} from 'react-icons/di' export function Header({mode, setMode}) { return ( <header> <h2>CV Maker <FiPaperclip size = "25px"/></h2> <ModeButton mode = {mode} setMode = {setMode}/> <a href = "https://github.com/minho-sama/CV-maker">minh 2021<DiGithubBadge size = '16px'/></a> </header> ) } export default Header
(function () { window.addEventListener("keydown", function (e) { switch (e.keyCode) { // Left case 37: LOGIC.snakeRunLeft(); break; // Up case 38: LOGIC.snakeRunUp(); break; // Right case 39: LOGIC.snakeRunRight(); break; // Down case 40: LOGIC.snakeRunDown(); break; } }); }());
// Countries datas const map= { "Blog": { "Link": "blog.html", "Images": [ "img/machineLearning.jpeg" ] }, "Travel": { "Link": "travel.html", "Images": [ "media/202003/88200724_214775729927376_7998703320516527320_n_17907107089422525.jpg" ] }, "Trails": { "Link": "trails.html", "Images": [ "img/teaGarden.jpg" ] }, "Food": { "Link": "food.html", "Images": [ "media/food/ShrimpWithCurry/image001.jpg" ] }, "Ancestry": { "Link": "ancestry/main.html", "Images": [ "ancestry/ThumbNail2.jpg" ] }, "Video": { "Link": "video.html", "Images": [ "img/videoSpillianShort.jpg" ] }, "Carpentry": { "Link": "carpentry.html", "Images": [ "media/carpentry/table/image008.jpg" ] }, "Code": { "Link": "https://kanhar.github.io/leetcode", "Images": [ "img/Code.jpg" ] } }; var path = window.location.pathname; var page = path.split("/").pop(); // Get the URL param const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const datas = Object.entries(map); const levelBValue = urlParams.get('levelB'); const levelAValue = urlParams.get('levelA'); var headerOutput = "Kanhar.Net - A life in Progress" let output = ''; var countriesDisplayed = new Set() for(let key of datas) { var Name = key[0]; var Link = key[1]["Link"]; var Imag = key[1]["Images"][0]; output += ` <a href="${Link}" class="item"> <div class="img-container"> <img src="${Imag}" alt=""> </div> <span>${Name}</span> </a> `; } // Create element const div = document.createElement("div"); div.className = 'generic-items'; div.innerHTML = output; document.querySelector(".generic-leaf-container").insertAdjacentElement("beforeend", div); document.querySelector(".generic-header").innerHTML = headerOutput;
// Jasmine Unit Testing Suite // -------------------------- define(['sample'], function(App) { describe("Basic Test Suite", function() { it("contains a spec (test) with an expectation", function() { expect(App.test()).toBe(true); }); }); });
// Jquery Plugin // Created - Gunjan Kothari // Date - 24/04/2014 // Improved - Carlos Cortés // Date - 30/12/2015 // Plugin to Draw a line between to elements var _nodes = new Array(); (function($) { $.fn.connect = function(param) { var _canvas; var _ctx; var _me = this; var _parent = param || document; //Initialize Canvas object _canvas = $('<canvas/>') .addClass('line-canvas') .attr('width', $(_parent).width()) .attr('height', $(_parent).height()); $(this).append(_canvas); this.drawLine = function(option) { _nodes.push(option); this.connect(option); }; this.drawAllLine = function(option) { /*Mandatory Fields------------------ left_selector = '.class', data_attribute = 'data-right', */ if (option.left_selector != '' && typeof option.left_selector !== 'undefined' && $(option.left_selector).length > 0) { $(option.left_selector).each(function(index) { var option2 = new Object(); $.extend(option2, option); option2.left_node = $(this).attr('id'); option2.right_node = $(this).data(option.data_attribute); if (option2.right_node != '' && typeof option2.right_node !== 'undefined') { _me.drawLine(option2); } }); } }; //This Function is used to connect two different div with a dotted line. this.connect = function(option) { _ctx = _canvas[0].getContext('2d'); _ctx.beginPath(); try { var _color; var _shadowColor; var _dash; var _left = new Object(); //This will store _left elements offset var _right = new Object(); //This will store _right elements offset var _error = (option.error == 'show') || false; /* option = { left_node - Left Element by ID - Mandatory right_node - Right Element ID - Mandatory status - accepted, rejected, modified, (none) - Optional style - (dashed), solid, dotted - Optional horizantal_gap - (0), Horizantal Gap from original point error - show, (hide) - To show error or not width - (2) - Width of the line } */ if (option.left_node != '' && typeof option.left_node !== 'undefined' && option.right_node != '' && typeof option.right_node !== 'undefined' && $(option.left_node).length > 0 && $(option.right_node).length > 0) { //To decide colour of the line switch (option.status) { case 'positiva': _color = '#FFFFFF'; _shadowColor = 'rgba(255,255,255,0.7)'; break; case 'distante': _shadowColor = 'rgba(255,252,0,0.7)'; _color = '#FFFC00'; break; case 'conflictiva': _shadowColor = 'rgba(255,144,0,0.7)'; _color = '#FF9000'; break; case 'ruptura': _shadowColor = 'rgba(255,2,0,0.7)'; _color = '#FF0200'; break; default: _color = '#00fffc'; _shadowColor = 'rgba(5, 255, 250, 0.7) '; break; } //To decide style of the line. dotted or solid switch (option.style) { case 'dashed': _dash = [4, 2]; break; case 'solid': _dash = []; break; case 'dotted': _dash = [4, 2]; break; default: _dash = [4, 2]; break; } //If left_node is actually right side, following code will switch elements. //If left_node is actually over the right_node put the lines top $(option.right_node).each(function(index, value) { _left_node = $(option.left_node); _right_node = $(value); var _gap = option.horizantal_gap || 0; if (_left_node.position().top >= _right_node.position().top) { _tmp = _left_node _left_node = _right_node _right_node = _tmp; } //Get Left point and Right Point if(_left_node.position().top> _right_node.position().top-_left_node.height()-60 && _left_node.position().top<= _right_node.position().top+_right_node.height()+60){ if(_left_node.position().left <= _right_node.position().left){ _left.x = _left_node.position().left + _left_node.outerWidth(); _left.y = _left_node.position().top + (_left_node.outerHeight()/2); _right.x = _right_node.position().left; _right.y = _right_node.position().top + (_right_node.outerHeight()/2); _ctx.moveTo(_left.x, _left.y); if (_gap != 0) { _ctx.lineTo(_left.x + _gap, _left.y); _ctx.lineTo(_right.x - _gap, _right.y); } _ctx.lineTo(_right.x, _right.y); }else{ _left.x = _left_node.position().left; _left.y = _left_node.position().top + _left_node.outerHeight()/2; _right.x = _right_node.position().left + _right_node.outerWidth(); _right.y = _right_node.position().top + (_right_node.outerHeight() / 2); _ctx.moveTo(_left.x, _left.y); if (_gap != 0) { _ctx.lineTo(_left.x - _gap, _left.y); _ctx.lineTo(_right.x + _gap, _right.y); } _ctx.lineTo(_right.x, _right.y); } }else{ _left.x = _left_node.position().left + (_left_node.outerWidth()/2); _left.y = _left_node.position().top + (_left_node.outerHeight() ); _right.x = _right_node.position().left + (_right_node.outerWidth()/2); _right.y = _right_node.position().top; _ctx.moveTo(_left.x, _left.y); if (_gap != 0) { _ctx.lineTo(_left.x , _left.y+ _gap); _ctx.lineTo(_right.x , _right.y- _gap); } _ctx.lineTo(_right.x, _right.y); } //Create a group //var g = _canvas.group({strokeWidth: 2, strokeDashArray:_dash}); if (!_ctx.setLineDash) { _ctx.setLineDash = function() {} } else { _ctx.setLineDash(_dash); } _ctx.lineWidth = option.width || 2; _ctx.strokeStyle = _color; _ctx.shadowColor = _shadowColor; _ctx.shadowOffsetX = 0; _ctx.shadowOffsetY = 5; _ctx.stroke(); }); //option.resize = option.resize || false; } else { if (_error) alert('Mandatory Fields are missing or incorrect'); } } catch (err) { if (_error) alert('Mandatory Fields are missing or incorrect'); } }; //It will redraw all line when screen resizes $(window).resize(function() { _me.redrawLines(); }); this.redrawLines = function() { _ctx.clearRect(0, 0, $(_parent).width(), $(_parent).height()); _nodes.forEach(function(entry) { entry.resize = true; _me.connect(entry); }); }; return this; }; }(jQuery));
var port = 8123, http = require('http'), url = require('url'), fs = require('fs'), io = require('socket.io').listen(port), sys = require('sys'), numClients = 0; io.set('log level', 1); io.sockets.on('connection', function(client){ client.on('messageupdate', function(message){ client.broadcast.emit('messageupdate', {message: JSON.parse(message)}); }); numClients++; io.sockets.emit('announcement', {numberOfClients: numClients}); client.on('disconnect', function() { numClients--; io.sockets.emit('announcement', {numberOfClients: numClients}); }); });
var defaultPlayersAmount = 2; var amountOfPlayers = defaultPlayersAmount; var allFields = new Array(); var tips = null; $(function() { tips = $('#tipsPlayerSettings'); /** * dialog for the player settings */ $('#dialogPlayerSettings').dialog({ autoOpen : false, height : 510, width : 950, modal : true, draggable : false, resizable : false, buttons : { 'Start game' : function() { var isValid = true; //check if form has any errors and display them. allFields.forEach(function(item) { var element = $(item); element.removeClass('ui-state-error'); isValid = isValid && checkLength(element, 'firstname/lastname', 3, 20); }); // ajax call to start new game if(isValid == true) { $.ajax({ type: 'POST', url: '/startNewGame', data: $('#formPlayerSettings').serialize(), dataType: 'html', cache: false, async: false }).done(function(data) { //load gameboard to container $('#mainContainer').empty(); $('#mainContainer').html(data); }) $(this).dialog('close'); } }, Cancel : function() { $(this).dialog('close'); } }, close : function() { // reset slider for player amount sliderAmountPlayersReset(); //reset the diplay field for first and last name $(this).find('input:text').each(function(index, item) { $(item).val(''); }); //reset the diplay field for the number $(this).find("input[name^='player_age']").each(function(index, item) { $(item).val(0); }); // reset the age sliders $('.ageSlider').slider('value', 0); //remove displayed errors allFields.forEach(function(item) { $(item).removeClass('ui-state-error'); }) $('#tipsPlayerSettings').html('All form fields are required'); } }); /** * dialog for the player amount settings */ $('#dialogPlayerAmount').dialog({ autoOpen : false, height : 300, width : 350, modal : true, draggable : false, resizable : false, buttons : { 'Ok' : function() { //remove existing elements allFields = new Array(); // close current dialog and open next one $(this).dialog('close'); $('#dialogPlayerSettings').dialog('open'); // display needed amount of users $('.player').each(function(index, item) { var splitId = item.id.split('_'); var intId = parseInt(splitId[1]); //now add element to allFields for checking $(this).find('input:text').each(function(index, item) { if(intId <= amountOfPlayers) { allFields.push(item); } }); if (intId <= amountOfPlayers) { $(item).addClass('displayed').removeClass('notDisplayed'); } }); }, Cancel : function() { // close the dialog $(this).dialog('close'); } }, close : function() { // reset slider for player amount sliderAmountPlayersReset(); $('.player').each(function(index, item) { var splitId = item.id.split('_'); var intId = parseInt(splitId[1]); if (intId > 2) { $(item).removeClass('displayed').addClass('notDisplayed'); } }); } }); // add click event to start new game link $('#startNewGame').click(function() { $('#dialogPlayerAmount').dialog('open'); }); /** * the age sliders are inital created here */ $('.ageSlider').each(function() { var splitId = this.id.split('_') $(this).slider({ range : 'min', value : 0, min : 0, max : 99, slide : function(event, ui) { $('#age_' + splitId[1]).val(ui.value) } }) }) /** * Anonymous function creates slider */ $("#amountPlayersSlider").slider({ range : 'min', value : defaultPlayersAmount, min : 2, max : 4, slide : function(event, ui) { $('#amountPlayersDisplay').val(ui.value); $('#amountPlayersDisplay').change(); amountOfPlayers = ui.value; $('#amountOfPlayersSubmit').val(ui.value); } }) /** * Resets the slider for setting player amount */ var sliderAmountPlayersReset = function() { $('#amountPlayersSlider').slider('value', defaultPlayersAmount); $('#amountPlayersDisplay').val(defaultPlayersAmount); } /** * Validation function to check length */ function checkLength(o, n, min, max) { if (o.val().length > max || o.val().length < min) { o.addClass('ui-state-error'); updateTips('Length of ' + n + ' must be between ' + min + ' and ' + max + '.'); return false; } else { return true; } } /** * Function sets a tip to correct the field. */ function updateTips(t) { tips.text(t).addClass('ui-state-highlight'); setTimeout(function() { tips.removeClass('ui-state-highlight', 1500); }, 500 ); } /** * The about dialog */ $('#dialogAbout').dialog({ autoOpen : false, height : 350, width : 350, modal : true, draggable : false, resizable : false, buttons : { 'Ok' : function() { $(this).dialog('close'); } } }) // add click event to open about dialog $('#about').click(function() { $('#dialogAbout').dialog('open'); }); /** * The about dialog */ $('#dialogQuit').dialog({ autoOpen : false, height : 170, width : 350, modal : true, draggable : false, resizable : false, buttons : { 'Ok' : function() { $.ajax({ type: 'GET', url: '/quitGame', dataType: 'html', cache: false, async: false }).done(function(data) { console.log(data); //close the current window var newWindow = window.open('', '_self', ''); window.close(); }) }, Cancel : function() { // close the dialog $(this).dialog('close'); } } }) // add click event to open quit dialog $('#quit').click(function() { $('#dialogQuit').dialog('open'); }); });
const express = require('express'); const app = express(); import { players, player, createPlayer } from './players-db.js'; const bodyParser = require('body-parser'); app.use(bodyParser.json()); // support json encoded bodies app.get('/players', function (req, res) { const p = players(); p.then(players => res.send(players)); }); app.get('/players/:id', function (req, res) { const p = player(req.params.id); p.then(player => res.send(player[0])); }); app.post('/players', function (req, res) { const params = JSON.parse(JSON.stringify(req.body)); if(!params.name) { return res.status(422).send({ 'status': 'error', 'message': 'mandatory parameter "name" must exists' }); } const p = createPlayer(params.name); p.then(result => { res.json(`{ 'status': 'ok', 'message': ${params.name} added as a player }`); }); p.catch(err => { res.status(500).send({ 'status': 'error', 'message': 'Internal server error', 'details': JSON.stringify(err) }); }) }); module.exports = app;
const request = require("request"); const SnipCart = function(auth) { this.key = auth; this.callApi = function(call, params = {}, method = "GET") { return new Promise((fulfill, reject) => { method = method.toUpperCase(); call = encodeURI(call); if (method == "GET") { let urlParams = Object.keys(params).map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) ).join("&"); call += (urlParams ? "?" + urlParams : ""); } request( { baseUrl: "https://app.snipcart.com/api", url: call, body: (params ? params : null), json: true, headers: { "Accept": "application/json", "Content-Type": "application/json" }, auth: { user: this.key, pass: "" }, encoding: "utf8", method: method }, function(error, response, body) { if (error) reject(error); else if (typeof body === "string") fulfill(JSON.parse(body)); else fulfill(body); } ); }); }; // DISCOUNTS this.deleteDiscount = function(discount) { let id = ((typeof discount == "string") ? discount : discount.id); return this.callApi(`/discounts/${id}`, null, "DELETE"); }; this.editDiscount = function(discount) { return this.callApi(`/discounts/${discount.id}`, discount, "PUT"); }; this.getDiscountCode = function(code) { return new Promise((fulfill, reject) => { this.callApi("/discounts").then(discounts => fulfill(discounts.find(d => d.code == code)) ).catch(reject); }); }; this.getDiscounts = function() { return this.callApi("/discounts"); }; this.newDiscount = function(discount) { return this.callApi("/discounts", discount, "POST"); }; return this; }; module.exports = SnipCart;
import Colors from '@Colors/colors' import commonStyle from './style' import { Dimensions } from 'react-native' import { baselineDeltaForFonts } from './DefaultText' import { border, sectionHeight } from '../util/StyleUtils' import { isScreenSmall } from '../util/ScreenSizes' const style = { container: { justifyContent: 'space-between', height: Dimensions.get('window').height - sectionHeight }, innerContainer: { justifyContent: 'space-between' }, buttonContainer: { height: sectionHeight, justifyContent: 'center', alignItems: 'center', backgroundColor: Colors.primaryBlue }, buttonInnerContainer: { alignItems: 'center', flexDirection: 'row', backgroundColor: 'transparent' }, buttonText: { fontSize: 24, color: 'white', textAlign: 'center', width: Dimensions.get('window').width - 20 }, priceContainer: { flexDirection: 'row', justifyContent: 'center' }, pricePoundLogo: { height: 43, width: 38.1, marginBottom: baselineDeltaForFonts(80, 58) }, pricePoundLogoContainer: { alignSelf: 'flex-end', marginRight: 12, marginBottom: 11 }, priceBeforeDecimal: { fontFamily: commonStyle.font.museo500, fontSize: 80, alignSelf: 'flex-end', margin: 0, padding: 0, color: Colors.primaryBlue }, priceAfterDecimal: { fontFamily: commonStyle.font.museo300, fontSize: 58, color: Colors.primaryBlue, alignSelf: 'flex-end', marginBottom: baselineDeltaForFonts(80, 58), paddingBottom: 0, opacity: 0.6 }, separator: { ...border(['bottom'], Colors.gray5, 1), marginHorizontal: 24 }, detailsInnerContainer: { marginVertical: isScreenSmall ? 12 : 18 }, referenceContainer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: isScreenSmall ? 43 : 61, marginHorizontal: isScreenSmall ? 20 : 24, marginVertical: 2 }, rowContainer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginHorizontal: isScreenSmall ? 20 : 24, marginVertical: 2 }, rowTitle: { fontFamily: commonStyle.font.museo300, color: Colors.gray, fontSize: isScreenSmall ? 19 : 22 }, rowData: { fontFamily: commonStyle.font.museo300, color: Colors.offBlack, fontSize: isScreenSmall ? 19 : 22, paddingLeft: 20, maxWidth: Dimensions.get('window').width * 0.5 }, sectionHeader: commonStyle.sectionHeader } export default style
class Door { constructor(room1, room2) { this.room1 = room1; this.room2 = room2; } isOpen() { return this.isOpen; } open() { if (!this.isOpen) { this.isOpen = !isOpen; } } initialize(room1, room2) { this.room1 = room1; this.room2 = room2; } } module.exports = Door;
import React from 'react'; import { Switch, Route } from 'react-router-dom'; import HomePage from './components/HomePage' import SetState from './components/SetState' import ReduxSection from './components/ReduxSection' import ServerPage from './components/ServerPage' const Test = ({ test }) => ( <div> <h2>Home {test}</h2> </div> ) export default ( <Switch> <Route exact path='/' component={HomePage} /> <Route path='/setstate' component={SetState} /> <Route path='/reduxsection' component={ReduxSection} /> <Route path='/serverpage' component={ServerPage} /> <Route path='/:home' component={HomePage}/> <Route path='/there' render={(props) => { return <div>You are here</div> }} /> </Switch> )
var searchData= [ ['nanocanvas',['NanoCanvas',['../class_nano_canvas.html',1,'']]], ['nanocanvas1',['NanoCanvas1',['../class_nano_canvas1.html',1,'']]], ['nanocanvas16',['NanoCanvas16',['../class_nano_canvas16.html',1,'']]], ['nanocanvas1_5f16',['NanoCanvas1_16',['../class_nano_canvas1__16.html',1,'']]], ['nanocanvas1_5f4',['NanoCanvas1_4',['../class_nano_canvas1__4.html',1,'']]], ['nanocanvas1_5f8',['NanoCanvas1_8',['../class_nano_canvas1__8.html',1,'']]], ['nanocanvas8',['NanoCanvas8',['../class_nano_canvas8.html',1,'']]], ['nanocanvasbase',['NanoCanvasBase',['../class_nano_canvas_base.html',1,'']]], ['nanocanvasbase_3c_201_20_3e',['NanoCanvasBase&lt; 1 &gt;',['../class_nano_canvas_base.html',1,'']]], ['nanocanvasbase_3c_2016_20_3e',['NanoCanvasBase&lt; 16 &gt;',['../class_nano_canvas_base.html',1,'']]], ['nanocanvasbase_3c_204_20_3e',['NanoCanvasBase&lt; 4 &gt;',['../class_nano_canvas_base.html',1,'']]], ['nanocanvasbase_3c_208_20_3e',['NanoCanvasBase&lt; 8 &gt;',['../class_nano_canvas_base.html',1,'']]], ['nanocanvasops',['NanoCanvasOps',['../class_nano_canvas_ops.html',1,'']]], ['nanoengine',['NanoEngine',['../class_nano_engine.html',1,'']]], ['nanoengine1_5f8',['NanoEngine1_8',['../class_nano_engine1__8.html',1,'']]], ['nanoengine_3c_20tile_5f8x8_5fmono_5f8_20_3e',['NanoEngine&lt; TILE_8x8_MONO_8 &gt;',['../class_nano_engine.html',1,'']]], ['nanoenginecore',['NanoEngineCore',['../class_nano_engine_core.html',1,'']]], ['nanoengineinputs',['NanoEngineInputs',['../class_nano_engine_inputs.html',1,'']]], ['nanoenginetiler',['NanoEngineTiler',['../class_nano_engine_tiler.html',1,'']]], ['nanoenginetiler_3c_20tile_5f8x8_5fmono_5f8_2c_20w_2c_20h_2c_20b_20_3e',['NanoEngineTiler&lt; TILE_8x8_MONO_8, W, H, B &gt;',['../class_nano_engine_tiler.html',1,'']]], ['nanofixedsprite',['NanoFixedSprite',['../class_nano_fixed_sprite.html',1,'']]], ['nanosprite',['NanoSprite',['../class_nano_sprite.html',1,'']]] ];
const superagent = require('superagent'); const _ = require('lodash'); const xmlParse = require("xml-parse"); const config = { username: null, password: null, msisdn: null, message: null, timeout: 5000 } function create(obj) { const url = 'http://mysms.trueafrican.com/v1/api/esme/send'; const headers = { 'Content-Type': 'application/json' }; obj = Object.assign(config,obj); let username = obj.username, password = obj.password, msisdn = obj.msisdn, message = obj.message, timeout = obj.timeout; if (_.isEmpty(username)) { throw ("Invalid username"); } if (_.isEmpty(password)) { throw ("Invalid password"); } if (_.isEmpty(msisdn)) { throw ("Invalid msisdn"); } if (_.isEmpty(message)) { throw ("Invalid message"); } const data = {msisdn : [msisdn], message :message, username : username, password : password}; let response = {}; return new Promise((resolve, reject) => { superagent .post(url) .send(data) // query string .timeout({ response: timeout, // Wait 5 seconds for the server to start sending, deadline: 60000, // but allow 1 minute for the file to finish loading. }) .set(headers) .then((res) => { // Do something //console.log(res); resolve({'response': res}); }) .catch(err => reject(err)); }); } module.exports = create;
/** * External dependencies */ import classNames from 'classnames'; /** * Internal dependencies */ import GridGallery from './GridGallery.jsx'; class Grid extends React.Component { constructor(props) { super(props); } render() { const { blockGroupId, className, items, // from items moveItem, // from items gridSettings, // from atts // transitionTime, // from settings imageControlsSettings, // from atts imageCaptionSettings, // from atts imageHoverEffect, // from atts imageHoverEffectSettings, // from atts imageHighlightEffect, // from atts imageHighlightEffectSettings, // from atts ItemComponent, PlaceholderNoItems, } = this.props; return <> <div className={ classNames( className, 'cgb-block' ) }> { items.length > 0 && <div className="cgb-block-grid"> <GridGallery blockGroupId={ blockGroupId } items={ items } gridSettings={ gridSettings } imageControlsSettings={ imageControlsSettings } imageCaptionSettings={ imageCaptionSettings } imageHoverEffect={ imageHoverEffect } imageHoverEffectSettings={ imageHoverEffectSettings } imageHighlightEffect={ imageHighlightEffect } imageHighlightEffectSettings={ imageHighlightEffectSettings } axis={ 'xy' } useDragHandle={ true } onSortEnd={ ( { oldIndex, newIndex } ) => { moveItem( oldIndex, newIndex ) } } ItemComponent={ ItemComponent } /> </div> } { items.length === 0 && PlaceholderNoItems && <PlaceholderNoItems/> } { items.length === 0 && ! PlaceholderNoItems && <div></div> } </div> </>; } } export default Grid;
import scrollNoThrottle from '~/scroll-event-no-throttle'; import scrollWithThrottle from '~/scroll-event-with-throttle'; import requestAnimationFrame from '~/request-animation-frame'; import reactScrollEvent from '~/react-scroll-event-no-throttle'; import reactScrollEventThrottle from '~/react-scroll-event-with-throttle' import reactAnimationFrame from '~/react-request-animation-frame'; export const setup = () => { const rootNode = document.getElementById('root'); while (rootNode.firstChild) { rootNode.removeChild(rootNode.firstChild); } const topText = document.createElement('p'); topText.textContent = `Exploring different ways of triggering an animation based on the current scroll position of the page`; rootNode.appendChild(topText); const links = document.createElement('ul'); function addLink(label, handler) { const el = document.createElement('li'); const link = document.createElement('a'); const href = label.toLowerCase().replace(/\s/g, '-'); link.href = href; link.textContent = label; link.addEventListener('click', event => { event.preventDefault(); handler.call(null); history.pushState({}, label, href); return false; }); el.appendChild(link); links.appendChild(el); } addLink('Scroll event with no throttle', scrollNoThrottle); addLink('Scroll event with throttle', scrollWithThrottle); addLink('Request animation frame', requestAnimationFrame); addLink('React scroll event with no throttle', reactScrollEvent); addLink('React scroll event with throttle', reactScrollEventThrottle); addLink('React animation frame', reactAnimationFrame); rootNode.appendChild(links); const bottomText = document.createElement('p'); const bottomLink = document.createElement('a'); bottomLink.href = 'https://github.com/ivarni/animated-scroll'; bottomLink.textContent = 'Source on github'; bottomText.appendChild(bottomLink); rootNode.appendChild(bottomText); }
'use strict'; const webdocCli = require('..'); describe('webdoc-cli', () => { it('needs tests'); });
const yargs = require('yargs'); const axios = require('axios'); const argv = yargs .option({ a: { demand: true, alias: 'address', describe: 'Address to fetch the weather for', string: true, default: 'orbit apartment zirakpur' }, d: { demand: false, alias: 'detail', describe: 'Detailed Weather', string: true, choices: ['yes', 'no'] } }) .help() .alias('help', 'h') .argv; var encodedAddress = encodeURIComponent(argv.address); var geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=<GOOGLE-MAPS-API-KEY>`; axios.get(geocodeUrl) .then((response) => { if (response.data.status === "ZERO_RESULTS") { throw new Error('Invalid address'); } console.log(response.data.results[0].formatted_address); var lat = response.data.results[0].geometry.location.lat; var lng = response.data.results[0].geometry.location.lng;; var weatherUrl = `https://api.darksky.net/forecast/<DARKSKY-API-KEY>/${lat},${lng}?units=si`; return axios.get(weatherUrl); }).then((response) => { var temperature = response.data.currently.temperature; var apparentTemperature = response.data.currently.apparentTemperature; var weeklyPrediction = response.data.daily.summary; var currentSummary = response.data.currently.summary; var humidity = response.data.currently.humidity; if (argv.d === 'yes') { console.log(`It's curently: ${temperature} and ${currentSummary}`); console.log(`With a humidity of ${humidity * 100}%`) console.log(`The weekly prediction is ${weeklyPrediction}`); } else { console.log(`It's curently: ${temperature}`); console.log(`Feels like: ${apparentTemperature}`); } }) .catch((e) => { if (e.code === 'ENOTFOUND') { console.log('Unable to connect to API Servers'); } else { console.log(e.message); } });
(function(scope){ 'use strict'; function F(arity, fun, wrapper) { wrapper.a = arity; wrapper.f = fun; return wrapper; } function F2(fun) { return F(2, fun, function(a) { return function(b) { return fun(a,b); }; }) } function F3(fun) { return F(3, fun, function(a) { return function(b) { return function(c) { return fun(a, b, c); }; }; }); } function F4(fun) { return F(4, fun, function(a) { return function(b) { return function(c) { return function(d) { return fun(a, b, c, d); }; }; }; }); } function F5(fun) { return F(5, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return fun(a, b, c, d, e); }; }; }; }; }); } function F6(fun) { return F(6, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return fun(a, b, c, d, e, f); }; }; }; }; }; }); } function F7(fun) { return F(7, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return fun(a, b, c, d, e, f, g); }; }; }; }; }; }; }); } function F8(fun) { return F(8, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return fun(a, b, c, d, e, f, g, h); }; }; }; }; }; }; }; }); } function F9(fun) { return F(9, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return function(i) { return fun(a, b, c, d, e, f, g, h, i); }; }; }; }; }; }; }; }; }); } function A2(fun, a, b) { return fun.a === 2 ? fun.f(a, b) : fun(a)(b); } function A3(fun, a, b, c) { return fun.a === 3 ? fun.f(a, b, c) : fun(a)(b)(c); } function A4(fun, a, b, c, d) { return fun.a === 4 ? fun.f(a, b, c, d) : fun(a)(b)(c)(d); } function A5(fun, a, b, c, d, e) { return fun.a === 5 ? fun.f(a, b, c, d, e) : fun(a)(b)(c)(d)(e); } function A6(fun, a, b, c, d, e, f) { return fun.a === 6 ? fun.f(a, b, c, d, e, f) : fun(a)(b)(c)(d)(e)(f); } function A7(fun, a, b, c, d, e, f, g) { return fun.a === 7 ? fun.f(a, b, c, d, e, f, g) : fun(a)(b)(c)(d)(e)(f)(g); } function A8(fun, a, b, c, d, e, f, g, h) { return fun.a === 8 ? fun.f(a, b, c, d, e, f, g, h) : fun(a)(b)(c)(d)(e)(f)(g)(h); } function A9(fun, a, b, c, d, e, f, g, h, i) { return fun.a === 9 ? fun.f(a, b, c, d, e, f, g, h, i) : fun(a)(b)(c)(d)(e)(f)(g)(h)(i); } console.warn('Compiled in DEV mode. Follow the advice at https://elm-lang.org/0.19.1/optimize for better performance and smaller assets.'); // EQUALITY function _Utils_eq(x, y) { for ( var pair, stack = [], isEqual = _Utils_eqHelp(x, y, 0, stack); isEqual && (pair = stack.pop()); isEqual = _Utils_eqHelp(pair.a, pair.b, 0, stack) ) {} return isEqual; } function _Utils_eqHelp(x, y, depth, stack) { if (x === y) { return true; } if (typeof x !== 'object' || x === null || y === null) { typeof x === 'function' && _Debug_crash(5); return false; } if (depth > 100) { stack.push(_Utils_Tuple2(x,y)); return true; } /**/ if (x.$ === 'Set_elm_builtin') { x = $elm$core$Set$toList(x); y = $elm$core$Set$toList(y); } if (x.$ === 'RBNode_elm_builtin' || x.$ === 'RBEmpty_elm_builtin') { x = $elm$core$Dict$toList(x); y = $elm$core$Dict$toList(y); } //*/ /**_UNUSED/ if (x.$ < 0) { x = $elm$core$Dict$toList(x); y = $elm$core$Dict$toList(y); } //*/ for (var key in x) { if (!_Utils_eqHelp(x[key], y[key], depth + 1, stack)) { return false; } } return true; } var _Utils_equal = F2(_Utils_eq); var _Utils_notEqual = F2(function(a, b) { return !_Utils_eq(a,b); }); // COMPARISONS // Code in Generate/JavaScript.hs, Basics.js, and List.js depends on // the particular integer values assigned to LT, EQ, and GT. function _Utils_cmp(x, y, ord) { if (typeof x !== 'object') { return x === y ? /*EQ*/ 0 : x < y ? /*LT*/ -1 : /*GT*/ 1; } /**/ if (x instanceof String) { var a = x.valueOf(); var b = y.valueOf(); return a === b ? 0 : a < b ? -1 : 1; } //*/ /**_UNUSED/ if (typeof x.$ === 'undefined') //*/ /**/ if (x.$[0] === '#') //*/ { return (ord = _Utils_cmp(x.a, y.a)) ? ord : (ord = _Utils_cmp(x.b, y.b)) ? ord : _Utils_cmp(x.c, y.c); } // traverse conses until end of a list or a mismatch for (; x.b && y.b && !(ord = _Utils_cmp(x.a, y.a)); x = x.b, y = y.b) {} // WHILE_CONSES return ord || (x.b ? /*GT*/ 1 : y.b ? /*LT*/ -1 : /*EQ*/ 0); } var _Utils_lt = F2(function(a, b) { return _Utils_cmp(a, b) < 0; }); var _Utils_le = F2(function(a, b) { return _Utils_cmp(a, b) < 1; }); var _Utils_gt = F2(function(a, b) { return _Utils_cmp(a, b) > 0; }); var _Utils_ge = F2(function(a, b) { return _Utils_cmp(a, b) >= 0; }); var _Utils_compare = F2(function(x, y) { var n = _Utils_cmp(x, y); return n < 0 ? $elm$core$Basics$LT : n ? $elm$core$Basics$GT : $elm$core$Basics$EQ; }); // COMMON VALUES var _Utils_Tuple0_UNUSED = 0; var _Utils_Tuple0 = { $: '#0' }; function _Utils_Tuple2_UNUSED(a, b) { return { a: a, b: b }; } function _Utils_Tuple2(a, b) { return { $: '#2', a: a, b: b }; } function _Utils_Tuple3_UNUSED(a, b, c) { return { a: a, b: b, c: c }; } function _Utils_Tuple3(a, b, c) { return { $: '#3', a: a, b: b, c: c }; } function _Utils_chr_UNUSED(c) { return c; } function _Utils_chr(c) { return new String(c); } // RECORDS function _Utils_update(oldRecord, updatedFields) { var newRecord = {}; for (var key in oldRecord) { newRecord[key] = oldRecord[key]; } for (var key in updatedFields) { newRecord[key] = updatedFields[key]; } return newRecord; } // APPEND var _Utils_append = F2(_Utils_ap); function _Utils_ap(xs, ys) { // append Strings if (typeof xs === 'string') { return xs + ys; } // append Lists if (!xs.b) { return ys; } var root = _List_Cons(xs.a, ys); xs = xs.b for (var curr = root; xs.b; xs = xs.b) // WHILE_CONS { curr = curr.b = _List_Cons(xs.a, ys); } return root; } var _List_Nil_UNUSED = { $: 0 }; var _List_Nil = { $: '[]' }; function _List_Cons_UNUSED(hd, tl) { return { $: 1, a: hd, b: tl }; } function _List_Cons(hd, tl) { return { $: '::', a: hd, b: tl }; } var _List_cons = F2(_List_Cons); function _List_fromArray(arr) { var out = _List_Nil; for (var i = arr.length; i--; ) { out = _List_Cons(arr[i], out); } return out; } function _List_toArray(xs) { for (var out = []; xs.b; xs = xs.b) // WHILE_CONS { out.push(xs.a); } return out; } var _List_map2 = F3(function(f, xs, ys) { for (var arr = []; xs.b && ys.b; xs = xs.b, ys = ys.b) // WHILE_CONSES { arr.push(A2(f, xs.a, ys.a)); } return _List_fromArray(arr); }); var _List_map3 = F4(function(f, xs, ys, zs) { for (var arr = []; xs.b && ys.b && zs.b; xs = xs.b, ys = ys.b, zs = zs.b) // WHILE_CONSES { arr.push(A3(f, xs.a, ys.a, zs.a)); } return _List_fromArray(arr); }); var _List_map4 = F5(function(f, ws, xs, ys, zs) { for (var arr = []; ws.b && xs.b && ys.b && zs.b; ws = ws.b, xs = xs.b, ys = ys.b, zs = zs.b) // WHILE_CONSES { arr.push(A4(f, ws.a, xs.a, ys.a, zs.a)); } return _List_fromArray(arr); }); var _List_map5 = F6(function(f, vs, ws, xs, ys, zs) { for (var arr = []; vs.b && ws.b && xs.b && ys.b && zs.b; vs = vs.b, ws = ws.b, xs = xs.b, ys = ys.b, zs = zs.b) // WHILE_CONSES { arr.push(A5(f, vs.a, ws.a, xs.a, ys.a, zs.a)); } return _List_fromArray(arr); }); var _List_sortBy = F2(function(f, xs) { return _List_fromArray(_List_toArray(xs).sort(function(a, b) { return _Utils_cmp(f(a), f(b)); })); }); var _List_sortWith = F2(function(f, xs) { return _List_fromArray(_List_toArray(xs).sort(function(a, b) { var ord = A2(f, a, b); return ord === $elm$core$Basics$EQ ? 0 : ord === $elm$core$Basics$LT ? -1 : 1; })); }); var _JsArray_empty = []; function _JsArray_singleton(value) { return [value]; } function _JsArray_length(array) { return array.length; } var _JsArray_initialize = F3(function(size, offset, func) { var result = new Array(size); for (var i = 0; i < size; i++) { result[i] = func(offset + i); } return result; }); var _JsArray_initializeFromList = F2(function (max, ls) { var result = new Array(max); for (var i = 0; i < max && ls.b; i++) { result[i] = ls.a; ls = ls.b; } result.length = i; return _Utils_Tuple2(result, ls); }); var _JsArray_unsafeGet = F2(function(index, array) { return array[index]; }); var _JsArray_unsafeSet = F3(function(index, value, array) { var length = array.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = array[i]; } result[index] = value; return result; }); var _JsArray_push = F2(function(value, array) { var length = array.length; var result = new Array(length + 1); for (var i = 0; i < length; i++) { result[i] = array[i]; } result[length] = value; return result; }); var _JsArray_foldl = F3(function(func, acc, array) { var length = array.length; for (var i = 0; i < length; i++) { acc = A2(func, array[i], acc); } return acc; }); var _JsArray_foldr = F3(function(func, acc, array) { for (var i = array.length - 1; i >= 0; i--) { acc = A2(func, array[i], acc); } return acc; }); var _JsArray_map = F2(function(func, array) { var length = array.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = func(array[i]); } return result; }); var _JsArray_indexedMap = F3(function(func, offset, array) { var length = array.length; var result = new Array(length); for (var i = 0; i < length; i++) { result[i] = A2(func, offset + i, array[i]); } return result; }); var _JsArray_slice = F3(function(from, to, array) { return array.slice(from, to); }); var _JsArray_appendN = F3(function(n, dest, source) { var destLen = dest.length; var itemsToCopy = n - destLen; if (itemsToCopy > source.length) { itemsToCopy = source.length; } var size = destLen + itemsToCopy; var result = new Array(size); for (var i = 0; i < destLen; i++) { result[i] = dest[i]; } for (var i = 0; i < itemsToCopy; i++) { result[i + destLen] = source[i]; } return result; }); // LOG var _Debug_log_UNUSED = F2(function(tag, value) { return value; }); var _Debug_log = F2(function(tag, value) { console.log(tag + ': ' + _Debug_toString(value)); return value; }); // TODOS function _Debug_todo(moduleName, region) { return function(message) { _Debug_crash(8, moduleName, region, message); }; } function _Debug_todoCase(moduleName, region, value) { return function(message) { _Debug_crash(9, moduleName, region, value, message); }; } // TO STRING function _Debug_toString_UNUSED(value) { return '<internals>'; } function _Debug_toString(value) { return _Debug_toAnsiString(false, value); } function _Debug_toAnsiString(ansi, value) { if (typeof value === 'function') { return _Debug_internalColor(ansi, '<function>'); } if (typeof value === 'boolean') { return _Debug_ctorColor(ansi, value ? 'True' : 'False'); } if (typeof value === 'number') { return _Debug_numberColor(ansi, value + ''); } if (value instanceof String) { return _Debug_charColor(ansi, "'" + _Debug_addSlashes(value, true) + "'"); } if (typeof value === 'string') { return _Debug_stringColor(ansi, '"' + _Debug_addSlashes(value, false) + '"'); } if (typeof value === 'object' && '$' in value) { var tag = value.$; if (typeof tag === 'number') { return _Debug_internalColor(ansi, '<internals>'); } if (tag[0] === '#') { var output = []; for (var k in value) { if (k === '$') continue; output.push(_Debug_toAnsiString(ansi, value[k])); } return '(' + output.join(',') + ')'; } if (tag === 'Set_elm_builtin') { return _Debug_ctorColor(ansi, 'Set') + _Debug_fadeColor(ansi, '.fromList') + ' ' + _Debug_toAnsiString(ansi, $elm$core$Set$toList(value)); } if (tag === 'RBNode_elm_builtin' || tag === 'RBEmpty_elm_builtin') { return _Debug_ctorColor(ansi, 'Dict') + _Debug_fadeColor(ansi, '.fromList') + ' ' + _Debug_toAnsiString(ansi, $elm$core$Dict$toList(value)); } if (tag === 'Array_elm_builtin') { return _Debug_ctorColor(ansi, 'Array') + _Debug_fadeColor(ansi, '.fromList') + ' ' + _Debug_toAnsiString(ansi, $elm$core$Array$toList(value)); } if (tag === '::' || tag === '[]') { var output = '['; value.b && (output += _Debug_toAnsiString(ansi, value.a), value = value.b) for (; value.b; value = value.b) // WHILE_CONS { output += ',' + _Debug_toAnsiString(ansi, value.a); } return output + ']'; } var output = ''; for (var i in value) { if (i === '$') continue; var str = _Debug_toAnsiString(ansi, value[i]); var c0 = str[0]; var parenless = c0 === '{' || c0 === '(' || c0 === '[' || c0 === '<' || c0 === '"' || str.indexOf(' ') < 0; output += ' ' + (parenless ? str : '(' + str + ')'); } return _Debug_ctorColor(ansi, tag) + output; } if (typeof DataView === 'function' && value instanceof DataView) { return _Debug_stringColor(ansi, '<' + value.byteLength + ' bytes>'); } if (typeof File !== 'undefined' && value instanceof File) { return _Debug_internalColor(ansi, '<' + value.name + '>'); } if (typeof value === 'object') { var output = []; for (var key in value) { var field = key[0] === '_' ? key.slice(1) : key; output.push(_Debug_fadeColor(ansi, field) + ' = ' + _Debug_toAnsiString(ansi, value[key])); } if (output.length === 0) { return '{}'; } return '{ ' + output.join(', ') + ' }'; } return _Debug_internalColor(ansi, '<internals>'); } function _Debug_addSlashes(str, isChar) { var s = str .replace(/\\/g, '\\\\') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') .replace(/\r/g, '\\r') .replace(/\v/g, '\\v') .replace(/\0/g, '\\0'); if (isChar) { return s.replace(/\'/g, '\\\''); } else { return s.replace(/\"/g, '\\"'); } } function _Debug_ctorColor(ansi, string) { return ansi ? '\x1b[96m' + string + '\x1b[0m' : string; } function _Debug_numberColor(ansi, string) { return ansi ? '\x1b[95m' + string + '\x1b[0m' : string; } function _Debug_stringColor(ansi, string) { return ansi ? '\x1b[93m' + string + '\x1b[0m' : string; } function _Debug_charColor(ansi, string) { return ansi ? '\x1b[92m' + string + '\x1b[0m' : string; } function _Debug_fadeColor(ansi, string) { return ansi ? '\x1b[37m' + string + '\x1b[0m' : string; } function _Debug_internalColor(ansi, string) { return ansi ? '\x1b[36m' + string + '\x1b[0m' : string; } function _Debug_toHexDigit(n) { return String.fromCharCode(n < 10 ? 48 + n : 55 + n); } // CRASH function _Debug_crash_UNUSED(identifier) { throw new Error('https://github.com/elm/core/blob/1.0.0/hints/' + identifier + '.md'); } function _Debug_crash(identifier, fact1, fact2, fact3, fact4) { switch(identifier) { case 0: throw new Error('What node should I take over? In JavaScript I need something like:\n\n Elm.Main.init({\n node: document.getElementById("elm-node")\n })\n\nYou need to do this with any Browser.sandbox or Browser.element program.'); case 1: throw new Error('Browser.application programs cannot handle URLs like this:\n\n ' + document.location.href + '\n\nWhat is the root? The root of your file system? Try looking at this program with `elm reactor` or some other server.'); case 2: var jsonErrorString = fact1; throw new Error('Problem with the flags given to your Elm program on initialization.\n\n' + jsonErrorString); case 3: var portName = fact1; throw new Error('There can only be one port named `' + portName + '`, but your program has multiple.'); case 4: var portName = fact1; var problem = fact2; throw new Error('Trying to send an unexpected type of value through port `' + portName + '`:\n' + problem); case 5: throw new Error('Trying to use `(==)` on functions.\nThere is no way to know if functions are "the same" in the Elm sense.\nRead more about this at https://package.elm-lang.org/packages/elm/core/latest/Basics#== which describes why it is this way and what the better version will look like.'); case 6: var moduleName = fact1; throw new Error('Your page is loading multiple Elm scripts with a module named ' + moduleName + '. Maybe a duplicate script is getting loaded accidentally? If not, rename one of them so I know which is which!'); case 8: var moduleName = fact1; var region = fact2; var message = fact3; throw new Error('TODO in module `' + moduleName + '` ' + _Debug_regionToString(region) + '\n\n' + message); case 9: var moduleName = fact1; var region = fact2; var value = fact3; var message = fact4; throw new Error( 'TODO in module `' + moduleName + '` from the `case` expression ' + _Debug_regionToString(region) + '\n\nIt received the following value:\n\n ' + _Debug_toString(value).replace('\n', '\n ') + '\n\nBut the branch that handles it says:\n\n ' + message.replace('\n', '\n ') ); case 10: throw new Error('Bug in https://github.com/elm/virtual-dom/issues'); case 11: throw new Error('Cannot perform mod 0. Division by zero error.'); } } function _Debug_regionToString(region) { if (region.start.line === region.end.line) { return 'on line ' + region.start.line; } return 'on lines ' + region.start.line + ' through ' + region.end.line; } // MATH var _Basics_add = F2(function(a, b) { return a + b; }); var _Basics_sub = F2(function(a, b) { return a - b; }); var _Basics_mul = F2(function(a, b) { return a * b; }); var _Basics_fdiv = F2(function(a, b) { return a / b; }); var _Basics_idiv = F2(function(a, b) { return (a / b) | 0; }); var _Basics_pow = F2(Math.pow); var _Basics_remainderBy = F2(function(b, a) { return a % b; }); // https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf var _Basics_modBy = F2(function(modulus, x) { var answer = x % modulus; return modulus === 0 ? _Debug_crash(11) : ((answer > 0 && modulus < 0) || (answer < 0 && modulus > 0)) ? answer + modulus : answer; }); // TRIGONOMETRY var _Basics_pi = Math.PI; var _Basics_e = Math.E; var _Basics_cos = Math.cos; var _Basics_sin = Math.sin; var _Basics_tan = Math.tan; var _Basics_acos = Math.acos; var _Basics_asin = Math.asin; var _Basics_atan = Math.atan; var _Basics_atan2 = F2(Math.atan2); // MORE MATH function _Basics_toFloat(x) { return x; } function _Basics_truncate(n) { return n | 0; } function _Basics_isInfinite(n) { return n === Infinity || n === -Infinity; } var _Basics_ceiling = Math.ceil; var _Basics_floor = Math.floor; var _Basics_round = Math.round; var _Basics_sqrt = Math.sqrt; var _Basics_log = Math.log; var _Basics_isNaN = isNaN; // BOOLEANS function _Basics_not(bool) { return !bool; } var _Basics_and = F2(function(a, b) { return a && b; }); var _Basics_or = F2(function(a, b) { return a || b; }); var _Basics_xor = F2(function(a, b) { return a !== b; }); var _String_cons = F2(function(chr, str) { return chr + str; }); function _String_uncons(string) { var word = string.charCodeAt(0); return !isNaN(word) ? $elm$core$Maybe$Just( 0xD800 <= word && word <= 0xDBFF ? _Utils_Tuple2(_Utils_chr(string[0] + string[1]), string.slice(2)) : _Utils_Tuple2(_Utils_chr(string[0]), string.slice(1)) ) : $elm$core$Maybe$Nothing; } var _String_append = F2(function(a, b) { return a + b; }); function _String_length(str) { return str.length; } var _String_map = F2(function(func, string) { var len = string.length; var array = new Array(len); var i = 0; while (i < len) { var word = string.charCodeAt(i); if (0xD800 <= word && word <= 0xDBFF) { array[i] = func(_Utils_chr(string[i] + string[i+1])); i += 2; continue; } array[i] = func(_Utils_chr(string[i])); i++; } return array.join(''); }); var _String_filter = F2(function(isGood, str) { var arr = []; var len = str.length; var i = 0; while (i < len) { var char = str[i]; var word = str.charCodeAt(i); i++; if (0xD800 <= word && word <= 0xDBFF) { char += str[i]; i++; } if (isGood(_Utils_chr(char))) { arr.push(char); } } return arr.join(''); }); function _String_reverse(str) { var len = str.length; var arr = new Array(len); var i = 0; while (i < len) { var word = str.charCodeAt(i); if (0xD800 <= word && word <= 0xDBFF) { arr[len - i] = str[i + 1]; i++; arr[len - i] = str[i - 1]; i++; } else { arr[len - i] = str[i]; i++; } } return arr.join(''); } var _String_foldl = F3(function(func, state, string) { var len = string.length; var i = 0; while (i < len) { var char = string[i]; var word = string.charCodeAt(i); i++; if (0xD800 <= word && word <= 0xDBFF) { char += string[i]; i++; } state = A2(func, _Utils_chr(char), state); } return state; }); var _String_foldr = F3(function(func, state, string) { var i = string.length; while (i--) { var char = string[i]; var word = string.charCodeAt(i); if (0xDC00 <= word && word <= 0xDFFF) { i--; char = string[i] + char; } state = A2(func, _Utils_chr(char), state); } return state; }); var _String_split = F2(function(sep, str) { return str.split(sep); }); var _String_join = F2(function(sep, strs) { return strs.join(sep); }); var _String_slice = F3(function(start, end, str) { return str.slice(start, end); }); function _String_trim(str) { return str.trim(); } function _String_trimLeft(str) { return str.replace(/^\s+/, ''); } function _String_trimRight(str) { return str.replace(/\s+$/, ''); } function _String_words(str) { return _List_fromArray(str.trim().split(/\s+/g)); } function _String_lines(str) { return _List_fromArray(str.split(/\r\n|\r|\n/g)); } function _String_toUpper(str) { return str.toUpperCase(); } function _String_toLower(str) { return str.toLowerCase(); } var _String_any = F2(function(isGood, string) { var i = string.length; while (i--) { var char = string[i]; var word = string.charCodeAt(i); if (0xDC00 <= word && word <= 0xDFFF) { i--; char = string[i] + char; } if (isGood(_Utils_chr(char))) { return true; } } return false; }); var _String_all = F2(function(isGood, string) { var i = string.length; while (i--) { var char = string[i]; var word = string.charCodeAt(i); if (0xDC00 <= word && word <= 0xDFFF) { i--; char = string[i] + char; } if (!isGood(_Utils_chr(char))) { return false; } } return true; }); var _String_contains = F2(function(sub, str) { return str.indexOf(sub) > -1; }); var _String_startsWith = F2(function(sub, str) { return str.indexOf(sub) === 0; }); var _String_endsWith = F2(function(sub, str) { return str.length >= sub.length && str.lastIndexOf(sub) === str.length - sub.length; }); var _String_indexes = F2(function(sub, str) { var subLen = sub.length; if (subLen < 1) { return _List_Nil; } var i = 0; var is = []; while ((i = str.indexOf(sub, i)) > -1) { is.push(i); i = i + subLen; } return _List_fromArray(is); }); // TO STRING function _String_fromNumber(number) { return number + ''; } // INT CONVERSIONS function _String_toInt(str) { var total = 0; var code0 = str.charCodeAt(0); var start = code0 == 0x2B /* + */ || code0 == 0x2D /* - */ ? 1 : 0; for (var i = start; i < str.length; ++i) { var code = str.charCodeAt(i); if (code < 0x30 || 0x39 < code) { return $elm$core$Maybe$Nothing; } total = 10 * total + code - 0x30; } return i == start ? $elm$core$Maybe$Nothing : $elm$core$Maybe$Just(code0 == 0x2D ? -total : total); } // FLOAT CONVERSIONS function _String_toFloat(s) { // check if it is a hex, octal, or binary number if (s.length === 0 || /[\sxbo]/.test(s)) { return $elm$core$Maybe$Nothing; } var n = +s; // faster isNaN check return n === n ? $elm$core$Maybe$Just(n) : $elm$core$Maybe$Nothing; } function _String_fromList(chars) { return _List_toArray(chars).join(''); } function _Char_toCode(char) { var code = char.charCodeAt(0); if (0xD800 <= code && code <= 0xDBFF) { return (code - 0xD800) * 0x400 + char.charCodeAt(1) - 0xDC00 + 0x10000 } return code; } function _Char_fromCode(code) { return _Utils_chr( (code < 0 || 0x10FFFF < code) ? '\uFFFD' : (code <= 0xFFFF) ? String.fromCharCode(code) : (code -= 0x10000, String.fromCharCode(Math.floor(code / 0x400) + 0xD800, code % 0x400 + 0xDC00) ) ); } function _Char_toUpper(char) { return _Utils_chr(char.toUpperCase()); } function _Char_toLower(char) { return _Utils_chr(char.toLowerCase()); } function _Char_toLocaleUpper(char) { return _Utils_chr(char.toLocaleUpperCase()); } function _Char_toLocaleLower(char) { return _Utils_chr(char.toLocaleLowerCase()); } /**/ function _Json_errorToString(error) { return $elm$json$Json$Decode$errorToString(error); } //*/ // CORE DECODERS function _Json_succeed(msg) { return { $: 0, a: msg }; } function _Json_fail(msg) { return { $: 1, a: msg }; } function _Json_decodePrim(decoder) { return { $: 2, b: decoder }; } var _Json_decodeInt = _Json_decodePrim(function(value) { return (typeof value !== 'number') ? _Json_expecting('an INT', value) : (-2147483647 < value && value < 2147483647 && (value | 0) === value) ? $elm$core$Result$Ok(value) : (isFinite(value) && !(value % 1)) ? $elm$core$Result$Ok(value) : _Json_expecting('an INT', value); }); var _Json_decodeBool = _Json_decodePrim(function(value) { return (typeof value === 'boolean') ? $elm$core$Result$Ok(value) : _Json_expecting('a BOOL', value); }); var _Json_decodeFloat = _Json_decodePrim(function(value) { return (typeof value === 'number') ? $elm$core$Result$Ok(value) : _Json_expecting('a FLOAT', value); }); var _Json_decodeValue = _Json_decodePrim(function(value) { return $elm$core$Result$Ok(_Json_wrap(value)); }); var _Json_decodeString = _Json_decodePrim(function(value) { return (typeof value === 'string') ? $elm$core$Result$Ok(value) : (value instanceof String) ? $elm$core$Result$Ok(value + '') : _Json_expecting('a STRING', value); }); function _Json_decodeList(decoder) { return { $: 3, b: decoder }; } function _Json_decodeArray(decoder) { return { $: 4, b: decoder }; } function _Json_decodeNull(value) { return { $: 5, c: value }; } var _Json_decodeField = F2(function(field, decoder) { return { $: 6, d: field, b: decoder }; }); var _Json_decodeIndex = F2(function(index, decoder) { return { $: 7, e: index, b: decoder }; }); function _Json_decodeKeyValuePairs(decoder) { return { $: 8, b: decoder }; } function _Json_mapMany(f, decoders) { return { $: 9, f: f, g: decoders }; } var _Json_andThen = F2(function(callback, decoder) { return { $: 10, b: decoder, h: callback }; }); function _Json_oneOf(decoders) { return { $: 11, g: decoders }; } // DECODING OBJECTS var _Json_map1 = F2(function(f, d1) { return _Json_mapMany(f, [d1]); }); var _Json_map2 = F3(function(f, d1, d2) { return _Json_mapMany(f, [d1, d2]); }); var _Json_map3 = F4(function(f, d1, d2, d3) { return _Json_mapMany(f, [d1, d2, d3]); }); var _Json_map4 = F5(function(f, d1, d2, d3, d4) { return _Json_mapMany(f, [d1, d2, d3, d4]); }); var _Json_map5 = F6(function(f, d1, d2, d3, d4, d5) { return _Json_mapMany(f, [d1, d2, d3, d4, d5]); }); var _Json_map6 = F7(function(f, d1, d2, d3, d4, d5, d6) { return _Json_mapMany(f, [d1, d2, d3, d4, d5, d6]); }); var _Json_map7 = F8(function(f, d1, d2, d3, d4, d5, d6, d7) { return _Json_mapMany(f, [d1, d2, d3, d4, d5, d6, d7]); }); var _Json_map8 = F9(function(f, d1, d2, d3, d4, d5, d6, d7, d8) { return _Json_mapMany(f, [d1, d2, d3, d4, d5, d6, d7, d8]); }); // DECODE var _Json_runOnString = F2(function(decoder, string) { try { var value = JSON.parse(string); return _Json_runHelp(decoder, value); } catch (e) { return $elm$core$Result$Err(A2($elm$json$Json$Decode$Failure, 'This is not valid JSON! ' + e.message, _Json_wrap(string))); } }); var _Json_run = F2(function(decoder, value) { return _Json_runHelp(decoder, _Json_unwrap(value)); }); function _Json_runHelp(decoder, value) { switch (decoder.$) { case 2: return decoder.b(value); case 5: return (value === null) ? $elm$core$Result$Ok(decoder.c) : _Json_expecting('null', value); case 3: if (!_Json_isArray(value)) { return _Json_expecting('a LIST', value); } return _Json_runArrayDecoder(decoder.b, value, _List_fromArray); case 4: if (!_Json_isArray(value)) { return _Json_expecting('an ARRAY', value); } return _Json_runArrayDecoder(decoder.b, value, _Json_toElmArray); case 6: var field = decoder.d; if (typeof value !== 'object' || value === null || !(field in value)) { return _Json_expecting('an OBJECT with a field named `' + field + '`', value); } var result = _Json_runHelp(decoder.b, value[field]); return ($elm$core$Result$isOk(result)) ? result : $elm$core$Result$Err(A2($elm$json$Json$Decode$Field, field, result.a)); case 7: var index = decoder.e; if (!_Json_isArray(value)) { return _Json_expecting('an ARRAY', value); } if (index >= value.length) { return _Json_expecting('a LONGER array. Need index ' + index + ' but only see ' + value.length + ' entries', value); } var result = _Json_runHelp(decoder.b, value[index]); return ($elm$core$Result$isOk(result)) ? result : $elm$core$Result$Err(A2($elm$json$Json$Decode$Index, index, result.a)); case 8: if (typeof value !== 'object' || value === null || _Json_isArray(value)) { return _Json_expecting('an OBJECT', value); } var keyValuePairs = _List_Nil; // TODO test perf of Object.keys and switch when support is good enough for (var key in value) { if (value.hasOwnProperty(key)) { var result = _Json_runHelp(decoder.b, value[key]); if (!$elm$core$Result$isOk(result)) { return $elm$core$Result$Err(A2($elm$json$Json$Decode$Field, key, result.a)); } keyValuePairs = _List_Cons(_Utils_Tuple2(key, result.a), keyValuePairs); } } return $elm$core$Result$Ok($elm$core$List$reverse(keyValuePairs)); case 9: var answer = decoder.f; var decoders = decoder.g; for (var i = 0; i < decoders.length; i++) { var result = _Json_runHelp(decoders[i], value); if (!$elm$core$Result$isOk(result)) { return result; } answer = answer(result.a); } return $elm$core$Result$Ok(answer); case 10: var result = _Json_runHelp(decoder.b, value); return (!$elm$core$Result$isOk(result)) ? result : _Json_runHelp(decoder.h(result.a), value); case 11: var errors = _List_Nil; for (var temp = decoder.g; temp.b; temp = temp.b) // WHILE_CONS { var result = _Json_runHelp(temp.a, value); if ($elm$core$Result$isOk(result)) { return result; } errors = _List_Cons(result.a, errors); } return $elm$core$Result$Err($elm$json$Json$Decode$OneOf($elm$core$List$reverse(errors))); case 1: return $elm$core$Result$Err(A2($elm$json$Json$Decode$Failure, decoder.a, _Json_wrap(value))); case 0: return $elm$core$Result$Ok(decoder.a); } } function _Json_runArrayDecoder(decoder, value, toElmValue) { var len = value.length; var array = new Array(len); for (var i = 0; i < len; i++) { var result = _Json_runHelp(decoder, value[i]); if (!$elm$core$Result$isOk(result)) { return $elm$core$Result$Err(A2($elm$json$Json$Decode$Index, i, result.a)); } array[i] = result.a; } return $elm$core$Result$Ok(toElmValue(array)); } function _Json_isArray(value) { return Array.isArray(value) || (typeof FileList !== 'undefined' && value instanceof FileList); } function _Json_toElmArray(array) { return A2($elm$core$Array$initialize, array.length, function(i) { return array[i]; }); } function _Json_expecting(type, value) { return $elm$core$Result$Err(A2($elm$json$Json$Decode$Failure, 'Expecting ' + type, _Json_wrap(value))); } // EQUALITY function _Json_equality(x, y) { if (x === y) { return true; } if (x.$ !== y.$) { return false; } switch (x.$) { case 0: case 1: return x.a === y.a; case 2: return x.b === y.b; case 5: return x.c === y.c; case 3: case 4: case 8: return _Json_equality(x.b, y.b); case 6: return x.d === y.d && _Json_equality(x.b, y.b); case 7: return x.e === y.e && _Json_equality(x.b, y.b); case 9: return x.f === y.f && _Json_listEquality(x.g, y.g); case 10: return x.h === y.h && _Json_equality(x.b, y.b); case 11: return _Json_listEquality(x.g, y.g); } } function _Json_listEquality(aDecoders, bDecoders) { var len = aDecoders.length; if (len !== bDecoders.length) { return false; } for (var i = 0; i < len; i++) { if (!_Json_equality(aDecoders[i], bDecoders[i])) { return false; } } return true; } // ENCODE var _Json_encode = F2(function(indentLevel, value) { return JSON.stringify(_Json_unwrap(value), null, indentLevel) + ''; }); function _Json_wrap(value) { return { $: 0, a: value }; } function _Json_unwrap(value) { return value.a; } function _Json_wrap_UNUSED(value) { return value; } function _Json_unwrap_UNUSED(value) { return value; } function _Json_emptyArray() { return []; } function _Json_emptyObject() { return {}; } var _Json_addField = F3(function(key, value, object) { object[key] = _Json_unwrap(value); return object; }); function _Json_addEntry(func) { return F2(function(entry, array) { array.push(_Json_unwrap(func(entry))); return array; }); } var _Json_encodeNull = _Json_wrap(null); // TASKS function _Scheduler_succeed(value) { return { $: 0, a: value }; } function _Scheduler_fail(error) { return { $: 1, a: error }; } function _Scheduler_binding(callback) { return { $: 2, b: callback, c: null }; } var _Scheduler_andThen = F2(function(callback, task) { return { $: 3, b: callback, d: task }; }); var _Scheduler_onError = F2(function(callback, task) { return { $: 4, b: callback, d: task }; }); function _Scheduler_receive(callback) { return { $: 5, b: callback }; } // PROCESSES var _Scheduler_guid = 0; function _Scheduler_rawSpawn(task) { var proc = { $: 0, e: _Scheduler_guid++, f: task, g: null, h: [] }; _Scheduler_enqueue(proc); return proc; } function _Scheduler_spawn(task) { return _Scheduler_binding(function(callback) { callback(_Scheduler_succeed(_Scheduler_rawSpawn(task))); }); } function _Scheduler_rawSend(proc, msg) { proc.h.push(msg); _Scheduler_enqueue(proc); } var _Scheduler_send = F2(function(proc, msg) { return _Scheduler_binding(function(callback) { _Scheduler_rawSend(proc, msg); callback(_Scheduler_succeed(_Utils_Tuple0)); }); }); function _Scheduler_kill(proc) { return _Scheduler_binding(function(callback) { var task = proc.f; if (task.$ === 2 && task.c) { task.c(); } proc.f = null; callback(_Scheduler_succeed(_Utils_Tuple0)); }); } /* STEP PROCESSES type alias Process = { $ : tag , id : unique_id , root : Task , stack : null | { $: SUCCEED | FAIL, a: callback, b: stack } , mailbox : [msg] } */ var _Scheduler_working = false; var _Scheduler_queue = []; function _Scheduler_enqueue(proc) { _Scheduler_queue.push(proc); if (_Scheduler_working) { return; } _Scheduler_working = true; while (proc = _Scheduler_queue.shift()) { _Scheduler_step(proc); } _Scheduler_working = false; } function _Scheduler_step(proc) { while (proc.f) { var rootTag = proc.f.$; if (rootTag === 0 || rootTag === 1) { while (proc.g && proc.g.$ !== rootTag) { proc.g = proc.g.i; } if (!proc.g) { return; } proc.f = proc.g.b(proc.f.a); proc.g = proc.g.i; } else if (rootTag === 2) { proc.f.c = proc.f.b(function(newRoot) { proc.f = newRoot; _Scheduler_enqueue(proc); }); return; } else if (rootTag === 5) { if (proc.h.length === 0) { return; } proc.f = proc.f.b(proc.h.shift()); } else // if (rootTag === 3 || rootTag === 4) { proc.g = { $: rootTag === 3 ? 0 : 1, b: proc.f.b, i: proc.g }; proc.f = proc.f.d; } } } function _Process_sleep(time) { return _Scheduler_binding(function(callback) { var id = setTimeout(function() { callback(_Scheduler_succeed(_Utils_Tuple0)); }, time); return function() { clearTimeout(id); }; }); } // PROGRAMS var _Platform_worker = F4(function(impl, flagDecoder, debugMetadata, args) { return _Platform_initialize( flagDecoder, args, impl.init, impl.update, impl.subscriptions, function() { return function() {} } ); }); // INITIALIZE A PROGRAM function _Platform_initialize(flagDecoder, args, init, update, subscriptions, stepperBuilder) { var result = A2(_Json_run, flagDecoder, _Json_wrap(args ? args['flags'] : undefined)); $elm$core$Result$isOk(result) || _Debug_crash(2 /**/, _Json_errorToString(result.a) /**/); var managers = {}; var initPair = init(result.a); var model = initPair.a; var stepper = stepperBuilder(sendToApp, model); var ports = _Platform_setupEffects(managers, sendToApp); function sendToApp(msg, viewMetadata) { var pair = A2(update, msg, model); stepper(model = pair.a, viewMetadata); _Platform_enqueueEffects(managers, pair.b, subscriptions(model)); } _Platform_enqueueEffects(managers, initPair.b, subscriptions(model)); return ports ? { ports: ports } : {}; } // TRACK PRELOADS // // This is used by code in elm/browser and elm/http // to register any HTTP requests that are triggered by init. // var _Platform_preload; function _Platform_registerPreload(url) { _Platform_preload.add(url); } // EFFECT MANAGERS var _Platform_effectManagers = {}; function _Platform_setupEffects(managers, sendToApp) { var ports; // setup all necessary effect managers for (var key in _Platform_effectManagers) { var manager = _Platform_effectManagers[key]; if (manager.a) { ports = ports || {}; ports[key] = manager.a(key, sendToApp); } managers[key] = _Platform_instantiateManager(manager, sendToApp); } return ports; } function _Platform_createManager(init, onEffects, onSelfMsg, cmdMap, subMap) { return { b: init, c: onEffects, d: onSelfMsg, e: cmdMap, f: subMap }; } function _Platform_instantiateManager(info, sendToApp) { var router = { g: sendToApp, h: undefined }; var onEffects = info.c; var onSelfMsg = info.d; var cmdMap = info.e; var subMap = info.f; function loop(state) { return A2(_Scheduler_andThen, loop, _Scheduler_receive(function(msg) { var value = msg.a; if (msg.$ === 0) { return A3(onSelfMsg, router, value, state); } return cmdMap && subMap ? A4(onEffects, router, value.i, value.j, state) : A3(onEffects, router, cmdMap ? value.i : value.j, state); })); } return router.h = _Scheduler_rawSpawn(A2(_Scheduler_andThen, loop, info.b)); } // ROUTING var _Platform_sendToApp = F2(function(router, msg) { return _Scheduler_binding(function(callback) { router.g(msg); callback(_Scheduler_succeed(_Utils_Tuple0)); }); }); var _Platform_sendToSelf = F2(function(router, msg) { return A2(_Scheduler_send, router.h, { $: 0, a: msg }); }); // BAGS function _Platform_leaf(home) { return function(value) { return { $: 1, k: home, l: value }; }; } function _Platform_batch(list) { return { $: 2, m: list }; } var _Platform_map = F2(function(tagger, bag) { return { $: 3, n: tagger, o: bag } }); // PIPE BAGS INTO EFFECT MANAGERS // // Effects must be queued! // // Say your init contains a synchronous command, like Time.now or Time.here // // - This will produce a batch of effects (FX_1) // - The synchronous task triggers the subsequent `update` call // - This will produce a batch of effects (FX_2) // // If we just start dispatching FX_2, subscriptions from FX_2 can be processed // before subscriptions from FX_1. No good! Earlier versions of this code had // this problem, leading to these reports: // // https://github.com/elm/core/issues/980 // https://github.com/elm/core/pull/981 // https://github.com/elm/compiler/issues/1776 // // The queue is necessary to avoid ordering issues for synchronous commands. // Why use true/false here? Why not just check the length of the queue? // The goal is to detect "are we currently dispatching effects?" If we // are, we need to bail and let the ongoing while loop handle things. // // Now say the queue has 1 element. When we dequeue the final element, // the queue will be empty, but we are still actively dispatching effects. // So you could get queue jumping in a really tricky category of cases. // var _Platform_effectsQueue = []; var _Platform_effectsActive = false; function _Platform_enqueueEffects(managers, cmdBag, subBag) { _Platform_effectsQueue.push({ p: managers, q: cmdBag, r: subBag }); if (_Platform_effectsActive) return; _Platform_effectsActive = true; for (var fx; fx = _Platform_effectsQueue.shift(); ) { _Platform_dispatchEffects(fx.p, fx.q, fx.r); } _Platform_effectsActive = false; } function _Platform_dispatchEffects(managers, cmdBag, subBag) { var effectsDict = {}; _Platform_gatherEffects(true, cmdBag, effectsDict, null); _Platform_gatherEffects(false, subBag, effectsDict, null); for (var home in managers) { _Scheduler_rawSend(managers[home], { $: 'fx', a: effectsDict[home] || { i: _List_Nil, j: _List_Nil } }); } } function _Platform_gatherEffects(isCmd, bag, effectsDict, taggers) { switch (bag.$) { case 1: var home = bag.k; var effect = _Platform_toEffect(isCmd, home, taggers, bag.l); effectsDict[home] = _Platform_insert(isCmd, effect, effectsDict[home]); return; case 2: for (var list = bag.m; list.b; list = list.b) // WHILE_CONS { _Platform_gatherEffects(isCmd, list.a, effectsDict, taggers); } return; case 3: _Platform_gatherEffects(isCmd, bag.o, effectsDict, { s: bag.n, t: taggers }); return; } } function _Platform_toEffect(isCmd, home, taggers, value) { function applyTaggers(x) { for (var temp = taggers; temp; temp = temp.t) { x = temp.s(x); } return x; } var map = isCmd ? _Platform_effectManagers[home].e : _Platform_effectManagers[home].f; return A2(map, applyTaggers, value) } function _Platform_insert(isCmd, newEffect, effects) { effects = effects || { i: _List_Nil, j: _List_Nil }; isCmd ? (effects.i = _List_Cons(newEffect, effects.i)) : (effects.j = _List_Cons(newEffect, effects.j)); return effects; } // PORTS function _Platform_checkPortName(name) { if (_Platform_effectManagers[name]) { _Debug_crash(3, name) } } // OUTGOING PORTS function _Platform_outgoingPort(name, converter) { _Platform_checkPortName(name); _Platform_effectManagers[name] = { e: _Platform_outgoingPortMap, u: converter, a: _Platform_setupOutgoingPort }; return _Platform_leaf(name); } var _Platform_outgoingPortMap = F2(function(tagger, value) { return value; }); function _Platform_setupOutgoingPort(name) { var subs = []; var converter = _Platform_effectManagers[name].u; // CREATE MANAGER var init = _Process_sleep(0); _Platform_effectManagers[name].b = init; _Platform_effectManagers[name].c = F3(function(router, cmdList, state) { for ( ; cmdList.b; cmdList = cmdList.b) // WHILE_CONS { // grab a separate reference to subs in case unsubscribe is called var currentSubs = subs; var value = _Json_unwrap(converter(cmdList.a)); for (var i = 0; i < currentSubs.length; i++) { currentSubs[i](value); } } return init; }); // PUBLIC API function subscribe(callback) { subs.push(callback); } function unsubscribe(callback) { // copy subs into a new array in case unsubscribe is called within a // subscribed callback subs = subs.slice(); var index = subs.indexOf(callback); if (index >= 0) { subs.splice(index, 1); } } return { subscribe: subscribe, unsubscribe: unsubscribe }; } // INCOMING PORTS function _Platform_incomingPort(name, converter) { _Platform_checkPortName(name); _Platform_effectManagers[name] = { f: _Platform_incomingPortMap, u: converter, a: _Platform_setupIncomingPort }; return _Platform_leaf(name); } var _Platform_incomingPortMap = F2(function(tagger, finalTagger) { return function(value) { return tagger(finalTagger(value)); }; }); function _Platform_setupIncomingPort(name, sendToApp) { var subs = _List_Nil; var converter = _Platform_effectManagers[name].u; // CREATE MANAGER var init = _Scheduler_succeed(null); _Platform_effectManagers[name].b = init; _Platform_effectManagers[name].c = F3(function(router, subList, state) { subs = subList; return init; }); // PUBLIC API function send(incomingValue) { var result = A2(_Json_run, converter, _Json_wrap(incomingValue)); $elm$core$Result$isOk(result) || _Debug_crash(4, name, result.a); var value = result.a; for (var temp = subs; temp.b; temp = temp.b) // WHILE_CONS { sendToApp(temp.a(value)); } } return { send: send }; } // EXPORT ELM MODULES // // Have DEBUG and PROD versions so that we can (1) give nicer errors in // debug mode and (2) not pay for the bits needed for that in prod mode. // function _Platform_export_UNUSED(exports) { scope['Elm'] ? _Platform_mergeExportsProd(scope['Elm'], exports) : scope['Elm'] = exports; } function _Platform_mergeExportsProd(obj, exports) { for (var name in exports) { (name in obj) ? (name == 'init') ? _Debug_crash(6) : _Platform_mergeExportsProd(obj[name], exports[name]) : (obj[name] = exports[name]); } } function _Platform_export(exports) { scope['Elm'] ? _Platform_mergeExportsDebug('Elm', scope['Elm'], exports) : scope['Elm'] = exports; } function _Platform_mergeExportsDebug(moduleName, obj, exports) { for (var name in exports) { (name in obj) ? (name == 'init') ? _Debug_crash(6, moduleName) : _Platform_mergeExportsDebug(moduleName + '.' + name, obj[name], exports[name]) : (obj[name] = exports[name]); } } // HELPERS var _VirtualDom_divertHrefToApp; var _VirtualDom_doc = typeof document !== 'undefined' ? document : {}; function _VirtualDom_appendChild(parent, child) { parent.appendChild(child); } var _VirtualDom_init = F4(function(virtualNode, flagDecoder, debugMetadata, args) { // NOTE: this function needs _Platform_export available to work /**_UNUSED/ var node = args['node']; //*/ /**/ var node = args && args['node'] ? args['node'] : _Debug_crash(0); //*/ node.parentNode.replaceChild( _VirtualDom_render(virtualNode, function() {}), node ); return {}; }); // TEXT function _VirtualDom_text(string) { return { $: 0, a: string }; } // NODE var _VirtualDom_nodeNS = F2(function(namespace, tag) { return F2(function(factList, kidList) { for (var kids = [], descendantsCount = 0; kidList.b; kidList = kidList.b) // WHILE_CONS { var kid = kidList.a; descendantsCount += (kid.b || 0); kids.push(kid); } descendantsCount += kids.length; return { $: 1, c: tag, d: _VirtualDom_organizeFacts(factList), e: kids, f: namespace, b: descendantsCount }; }); }); var _VirtualDom_node = _VirtualDom_nodeNS(undefined); // KEYED NODE var _VirtualDom_keyedNodeNS = F2(function(namespace, tag) { return F2(function(factList, kidList) { for (var kids = [], descendantsCount = 0; kidList.b; kidList = kidList.b) // WHILE_CONS { var kid = kidList.a; descendantsCount += (kid.b.b || 0); kids.push(kid); } descendantsCount += kids.length; return { $: 2, c: tag, d: _VirtualDom_organizeFacts(factList), e: kids, f: namespace, b: descendantsCount }; }); }); var _VirtualDom_keyedNode = _VirtualDom_keyedNodeNS(undefined); // CUSTOM function _VirtualDom_custom(factList, model, render, diff) { return { $: 3, d: _VirtualDom_organizeFacts(factList), g: model, h: render, i: diff }; } // MAP var _VirtualDom_map = F2(function(tagger, node) { return { $: 4, j: tagger, k: node, b: 1 + (node.b || 0) }; }); // LAZY function _VirtualDom_thunk(refs, thunk) { return { $: 5, l: refs, m: thunk, k: undefined }; } var _VirtualDom_lazy = F2(function(func, a) { return _VirtualDom_thunk([func, a], function() { return func(a); }); }); var _VirtualDom_lazy2 = F3(function(func, a, b) { return _VirtualDom_thunk([func, a, b], function() { return A2(func, a, b); }); }); var _VirtualDom_lazy3 = F4(function(func, a, b, c) { return _VirtualDom_thunk([func, a, b, c], function() { return A3(func, a, b, c); }); }); var _VirtualDom_lazy4 = F5(function(func, a, b, c, d) { return _VirtualDom_thunk([func, a, b, c, d], function() { return A4(func, a, b, c, d); }); }); var _VirtualDom_lazy5 = F6(function(func, a, b, c, d, e) { return _VirtualDom_thunk([func, a, b, c, d, e], function() { return A5(func, a, b, c, d, e); }); }); var _VirtualDom_lazy6 = F7(function(func, a, b, c, d, e, f) { return _VirtualDom_thunk([func, a, b, c, d, e, f], function() { return A6(func, a, b, c, d, e, f); }); }); var _VirtualDom_lazy7 = F8(function(func, a, b, c, d, e, f, g) { return _VirtualDom_thunk([func, a, b, c, d, e, f, g], function() { return A7(func, a, b, c, d, e, f, g); }); }); var _VirtualDom_lazy8 = F9(function(func, a, b, c, d, e, f, g, h) { return _VirtualDom_thunk([func, a, b, c, d, e, f, g, h], function() { return A8(func, a, b, c, d, e, f, g, h); }); }); // FACTS var _VirtualDom_on = F2(function(key, handler) { return { $: 'a0', n: key, o: handler }; }); var _VirtualDom_style = F2(function(key, value) { return { $: 'a1', n: key, o: value }; }); var _VirtualDom_property = F2(function(key, value) { return { $: 'a2', n: key, o: value }; }); var _VirtualDom_attribute = F2(function(key, value) { return { $: 'a3', n: key, o: value }; }); var _VirtualDom_attributeNS = F3(function(namespace, key, value) { return { $: 'a4', n: key, o: { f: namespace, o: value } }; }); // XSS ATTACK VECTOR CHECKS function _VirtualDom_noScript(tag) { return tag == 'script' ? 'p' : tag; } function _VirtualDom_noOnOrFormAction(key) { return /^(on|formAction$)/i.test(key) ? 'data-' + key : key; } function _VirtualDom_noInnerHtmlOrFormAction(key) { return key == 'innerHTML' || key == 'formAction' ? 'data-' + key : key; } function _VirtualDom_noJavaScriptUri_UNUSED(value) { return /^javascript:/i.test(value.replace(/\s/g,'')) ? '' : value; } function _VirtualDom_noJavaScriptUri(value) { return /^javascript:/i.test(value.replace(/\s/g,'')) ? 'javascript:alert("This is an XSS vector. Please use ports or web components instead.")' : value; } function _VirtualDom_noJavaScriptOrHtmlUri_UNUSED(value) { return /^\s*(javascript:|data:text\/html)/i.test(value) ? '' : value; } function _VirtualDom_noJavaScriptOrHtmlUri(value) { return /^\s*(javascript:|data:text\/html)/i.test(value) ? 'javascript:alert("This is an XSS vector. Please use ports or web components instead.")' : value; } // MAP FACTS var _VirtualDom_mapAttribute = F2(function(func, attr) { return (attr.$ === 'a0') ? A2(_VirtualDom_on, attr.n, _VirtualDom_mapHandler(func, attr.o)) : attr; }); function _VirtualDom_mapHandler(func, handler) { var tag = $elm$virtual_dom$VirtualDom$toHandlerInt(handler); // 0 = Normal // 1 = MayStopPropagation // 2 = MayPreventDefault // 3 = Custom return { $: handler.$, a: !tag ? A2($elm$json$Json$Decode$map, func, handler.a) : A3($elm$json$Json$Decode$map2, tag < 3 ? _VirtualDom_mapEventTuple : _VirtualDom_mapEventRecord, $elm$json$Json$Decode$succeed(func), handler.a ) }; } var _VirtualDom_mapEventTuple = F2(function(func, tuple) { return _Utils_Tuple2(func(tuple.a), tuple.b); }); var _VirtualDom_mapEventRecord = F2(function(func, record) { return { message: func(record.message), stopPropagation: record.stopPropagation, preventDefault: record.preventDefault } }); // ORGANIZE FACTS function _VirtualDom_organizeFacts(factList) { for (var facts = {}; factList.b; factList = factList.b) // WHILE_CONS { var entry = factList.a; var tag = entry.$; var key = entry.n; var value = entry.o; if (tag === 'a2') { (key === 'className') ? _VirtualDom_addClass(facts, key, _Json_unwrap(value)) : facts[key] = _Json_unwrap(value); continue; } var subFacts = facts[tag] || (facts[tag] = {}); (tag === 'a3' && key === 'class') ? _VirtualDom_addClass(subFacts, key, value) : subFacts[key] = value; } return facts; } function _VirtualDom_addClass(object, key, newClass) { var classes = object[key]; object[key] = classes ? classes + ' ' + newClass : newClass; } // RENDER function _VirtualDom_render(vNode, eventNode) { var tag = vNode.$; if (tag === 5) { return _VirtualDom_render(vNode.k || (vNode.k = vNode.m()), eventNode); } if (tag === 0) { return _VirtualDom_doc.createTextNode(vNode.a); } if (tag === 4) { var subNode = vNode.k; var tagger = vNode.j; while (subNode.$ === 4) { typeof tagger !== 'object' ? tagger = [tagger, subNode.j] : tagger.push(subNode.j); subNode = subNode.k; } var subEventRoot = { j: tagger, p: eventNode }; var domNode = _VirtualDom_render(subNode, subEventRoot); domNode.elm_event_node_ref = subEventRoot; return domNode; } if (tag === 3) { var domNode = vNode.h(vNode.g); _VirtualDom_applyFacts(domNode, eventNode, vNode.d); return domNode; } // at this point `tag` must be 1 or 2 var domNode = vNode.f ? _VirtualDom_doc.createElementNS(vNode.f, vNode.c) : _VirtualDom_doc.createElement(vNode.c); if (_VirtualDom_divertHrefToApp && vNode.c == 'a') { domNode.addEventListener('click', _VirtualDom_divertHrefToApp(domNode)); } _VirtualDom_applyFacts(domNode, eventNode, vNode.d); for (var kids = vNode.e, i = 0; i < kids.length; i++) { _VirtualDom_appendChild(domNode, _VirtualDom_render(tag === 1 ? kids[i] : kids[i].b, eventNode)); } return domNode; } // APPLY FACTS function _VirtualDom_applyFacts(domNode, eventNode, facts) { for (var key in facts) { var value = facts[key]; key === 'a1' ? _VirtualDom_applyStyles(domNode, value) : key === 'a0' ? _VirtualDom_applyEvents(domNode, eventNode, value) : key === 'a3' ? _VirtualDom_applyAttrs(domNode, value) : key === 'a4' ? _VirtualDom_applyAttrsNS(domNode, value) : ((key !== 'value' && key !== 'checked') || domNode[key] !== value) && (domNode[key] = value); } } // APPLY STYLES function _VirtualDom_applyStyles(domNode, styles) { var domNodeStyle = domNode.style; for (var key in styles) { domNodeStyle[key] = styles[key]; } } // APPLY ATTRS function _VirtualDom_applyAttrs(domNode, attrs) { for (var key in attrs) { var value = attrs[key]; typeof value !== 'undefined' ? domNode.setAttribute(key, value) : domNode.removeAttribute(key); } } // APPLY NAMESPACED ATTRS function _VirtualDom_applyAttrsNS(domNode, nsAttrs) { for (var key in nsAttrs) { var pair = nsAttrs[key]; var namespace = pair.f; var value = pair.o; typeof value !== 'undefined' ? domNode.setAttributeNS(namespace, key, value) : domNode.removeAttributeNS(namespace, key); } } // APPLY EVENTS function _VirtualDom_applyEvents(domNode, eventNode, events) { var allCallbacks = domNode.elmFs || (domNode.elmFs = {}); for (var key in events) { var newHandler = events[key]; var oldCallback = allCallbacks[key]; if (!newHandler) { domNode.removeEventListener(key, oldCallback); allCallbacks[key] = undefined; continue; } if (oldCallback) { var oldHandler = oldCallback.q; if (oldHandler.$ === newHandler.$) { oldCallback.q = newHandler; continue; } domNode.removeEventListener(key, oldCallback); } oldCallback = _VirtualDom_makeCallback(eventNode, newHandler); domNode.addEventListener(key, oldCallback, _VirtualDom_passiveSupported && { passive: $elm$virtual_dom$VirtualDom$toHandlerInt(newHandler) < 2 } ); allCallbacks[key] = oldCallback; } } // PASSIVE EVENTS var _VirtualDom_passiveSupported; try { window.addEventListener('t', null, Object.defineProperty({}, 'passive', { get: function() { _VirtualDom_passiveSupported = true; } })); } catch(e) {} // EVENT HANDLERS function _VirtualDom_makeCallback(eventNode, initialHandler) { function callback(event) { var handler = callback.q; var result = _Json_runHelp(handler.a, event); if (!$elm$core$Result$isOk(result)) { return; } var tag = $elm$virtual_dom$VirtualDom$toHandlerInt(handler); // 0 = Normal // 1 = MayStopPropagation // 2 = MayPreventDefault // 3 = Custom var value = result.a; var message = !tag ? value : tag < 3 ? value.a : value.message; var stopPropagation = tag == 1 ? value.b : tag == 3 && value.stopPropagation; var currentEventNode = ( stopPropagation && event.stopPropagation(), (tag == 2 ? value.b : tag == 3 && value.preventDefault) && event.preventDefault(), eventNode ); var tagger; var i; while (tagger = currentEventNode.j) { if (typeof tagger == 'function') { message = tagger(message); } else { for (var i = tagger.length; i--; ) { message = tagger[i](message); } } currentEventNode = currentEventNode.p; } currentEventNode(message, stopPropagation); // stopPropagation implies isSync } callback.q = initialHandler; return callback; } function _VirtualDom_equalEvents(x, y) { return x.$ == y.$ && _Json_equality(x.a, y.a); } // DIFF // TODO: Should we do patches like in iOS? // // type Patch // = At Int Patch // | Batch (List Patch) // | Change ... // // How could it not be better? // function _VirtualDom_diff(x, y) { var patches = []; _VirtualDom_diffHelp(x, y, patches, 0); return patches; } function _VirtualDom_pushPatch(patches, type, index, data) { var patch = { $: type, r: index, s: data, t: undefined, u: undefined }; patches.push(patch); return patch; } function _VirtualDom_diffHelp(x, y, patches, index) { if (x === y) { return; } var xType = x.$; var yType = y.$; // Bail if you run into different types of nodes. Implies that the // structure has changed significantly and it's not worth a diff. if (xType !== yType) { if (xType === 1 && yType === 2) { y = _VirtualDom_dekey(y); yType = 1; } else { _VirtualDom_pushPatch(patches, 0, index, y); return; } } // Now we know that both nodes are the same $. switch (yType) { case 5: var xRefs = x.l; var yRefs = y.l; var i = xRefs.length; var same = i === yRefs.length; while (same && i--) { same = xRefs[i] === yRefs[i]; } if (same) { y.k = x.k; return; } y.k = y.m(); var subPatches = []; _VirtualDom_diffHelp(x.k, y.k, subPatches, 0); subPatches.length > 0 && _VirtualDom_pushPatch(patches, 1, index, subPatches); return; case 4: // gather nested taggers var xTaggers = x.j; var yTaggers = y.j; var nesting = false; var xSubNode = x.k; while (xSubNode.$ === 4) { nesting = true; typeof xTaggers !== 'object' ? xTaggers = [xTaggers, xSubNode.j] : xTaggers.push(xSubNode.j); xSubNode = xSubNode.k; } var ySubNode = y.k; while (ySubNode.$ === 4) { nesting = true; typeof yTaggers !== 'object' ? yTaggers = [yTaggers, ySubNode.j] : yTaggers.push(ySubNode.j); ySubNode = ySubNode.k; } // Just bail if different numbers of taggers. This implies the // structure of the virtual DOM has changed. if (nesting && xTaggers.length !== yTaggers.length) { _VirtualDom_pushPatch(patches, 0, index, y); return; } // check if taggers are "the same" if (nesting ? !_VirtualDom_pairwiseRefEqual(xTaggers, yTaggers) : xTaggers !== yTaggers) { _VirtualDom_pushPatch(patches, 2, index, yTaggers); } // diff everything below the taggers _VirtualDom_diffHelp(xSubNode, ySubNode, patches, index + 1); return; case 0: if (x.a !== y.a) { _VirtualDom_pushPatch(patches, 3, index, y.a); } return; case 1: _VirtualDom_diffNodes(x, y, patches, index, _VirtualDom_diffKids); return; case 2: _VirtualDom_diffNodes(x, y, patches, index, _VirtualDom_diffKeyedKids); return; case 3: if (x.h !== y.h) { _VirtualDom_pushPatch(patches, 0, index, y); return; } var factsDiff = _VirtualDom_diffFacts(x.d, y.d); factsDiff && _VirtualDom_pushPatch(patches, 4, index, factsDiff); var patch = y.i(x.g, y.g); patch && _VirtualDom_pushPatch(patches, 5, index, patch); return; } } // assumes the incoming arrays are the same length function _VirtualDom_pairwiseRefEqual(as, bs) { for (var i = 0; i < as.length; i++) { if (as[i] !== bs[i]) { return false; } } return true; } function _VirtualDom_diffNodes(x, y, patches, index, diffKids) { // Bail if obvious indicators have changed. Implies more serious // structural changes such that it's not worth it to diff. if (x.c !== y.c || x.f !== y.f) { _VirtualDom_pushPatch(patches, 0, index, y); return; } var factsDiff = _VirtualDom_diffFacts(x.d, y.d); factsDiff && _VirtualDom_pushPatch(patches, 4, index, factsDiff); diffKids(x, y, patches, index); } // DIFF FACTS // TODO Instead of creating a new diff object, it's possible to just test if // there *is* a diff. During the actual patch, do the diff again and make the // modifications directly. This way, there's no new allocations. Worth it? function _VirtualDom_diffFacts(x, y, category) { var diff; // look for changes and removals for (var xKey in x) { if (xKey === 'a1' || xKey === 'a0' || xKey === 'a3' || xKey === 'a4') { var subDiff = _VirtualDom_diffFacts(x[xKey], y[xKey] || {}, xKey); if (subDiff) { diff = diff || {}; diff[xKey] = subDiff; } continue; } // remove if not in the new facts if (!(xKey in y)) { diff = diff || {}; diff[xKey] = !category ? (typeof x[xKey] === 'string' ? '' : null) : (category === 'a1') ? '' : (category === 'a0' || category === 'a3') ? undefined : { f: x[xKey].f, o: undefined }; continue; } var xValue = x[xKey]; var yValue = y[xKey]; // reference equal, so don't worry about it if (xValue === yValue && xKey !== 'value' && xKey !== 'checked' || category === 'a0' && _VirtualDom_equalEvents(xValue, yValue)) { continue; } diff = diff || {}; diff[xKey] = yValue; } // add new stuff for (var yKey in y) { if (!(yKey in x)) { diff = diff || {}; diff[yKey] = y[yKey]; } } return diff; } // DIFF KIDS function _VirtualDom_diffKids(xParent, yParent, patches, index) { var xKids = xParent.e; var yKids = yParent.e; var xLen = xKids.length; var yLen = yKids.length; // FIGURE OUT IF THERE ARE INSERTS OR REMOVALS if (xLen > yLen) { _VirtualDom_pushPatch(patches, 6, index, { v: yLen, i: xLen - yLen }); } else if (xLen < yLen) { _VirtualDom_pushPatch(patches, 7, index, { v: xLen, e: yKids }); } // PAIRWISE DIFF EVERYTHING ELSE for (var minLen = xLen < yLen ? xLen : yLen, i = 0; i < minLen; i++) { var xKid = xKids[i]; _VirtualDom_diffHelp(xKid, yKids[i], patches, ++index); index += xKid.b || 0; } } // KEYED DIFF function _VirtualDom_diffKeyedKids(xParent, yParent, patches, rootIndex) { var localPatches = []; var changes = {}; // Dict String Entry var inserts = []; // Array { index : Int, entry : Entry } // type Entry = { tag : String, vnode : VNode, index : Int, data : _ } var xKids = xParent.e; var yKids = yParent.e; var xLen = xKids.length; var yLen = yKids.length; var xIndex = 0; var yIndex = 0; var index = rootIndex; while (xIndex < xLen && yIndex < yLen) { var x = xKids[xIndex]; var y = yKids[yIndex]; var xKey = x.a; var yKey = y.a; var xNode = x.b; var yNode = y.b; var newMatch = undefined; var oldMatch = undefined; // check if keys match if (xKey === yKey) { index++; _VirtualDom_diffHelp(xNode, yNode, localPatches, index); index += xNode.b || 0; xIndex++; yIndex++; continue; } // look ahead 1 to detect insertions and removals. var xNext = xKids[xIndex + 1]; var yNext = yKids[yIndex + 1]; if (xNext) { var xNextKey = xNext.a; var xNextNode = xNext.b; oldMatch = yKey === xNextKey; } if (yNext) { var yNextKey = yNext.a; var yNextNode = yNext.b; newMatch = xKey === yNextKey; } // swap x and y if (newMatch && oldMatch) { index++; _VirtualDom_diffHelp(xNode, yNextNode, localPatches, index); _VirtualDom_insertNode(changes, localPatches, xKey, yNode, yIndex, inserts); index += xNode.b || 0; index++; _VirtualDom_removeNode(changes, localPatches, xKey, xNextNode, index); index += xNextNode.b || 0; xIndex += 2; yIndex += 2; continue; } // insert y if (newMatch) { index++; _VirtualDom_insertNode(changes, localPatches, yKey, yNode, yIndex, inserts); _VirtualDom_diffHelp(xNode, yNextNode, localPatches, index); index += xNode.b || 0; xIndex += 1; yIndex += 2; continue; } // remove x if (oldMatch) { index++; _VirtualDom_removeNode(changes, localPatches, xKey, xNode, index); index += xNode.b || 0; index++; _VirtualDom_diffHelp(xNextNode, yNode, localPatches, index); index += xNextNode.b || 0; xIndex += 2; yIndex += 1; continue; } // remove x, insert y if (xNext && xNextKey === yNextKey) { index++; _VirtualDom_removeNode(changes, localPatches, xKey, xNode, index); _VirtualDom_insertNode(changes, localPatches, yKey, yNode, yIndex, inserts); index += xNode.b || 0; index++; _VirtualDom_diffHelp(xNextNode, yNextNode, localPatches, index); index += xNextNode.b || 0; xIndex += 2; yIndex += 2; continue; } break; } // eat up any remaining nodes with removeNode and insertNode while (xIndex < xLen) { index++; var x = xKids[xIndex]; var xNode = x.b; _VirtualDom_removeNode(changes, localPatches, x.a, xNode, index); index += xNode.b || 0; xIndex++; } while (yIndex < yLen) { var endInserts = endInserts || []; var y = yKids[yIndex]; _VirtualDom_insertNode(changes, localPatches, y.a, y.b, undefined, endInserts); yIndex++; } if (localPatches.length > 0 || inserts.length > 0 || endInserts) { _VirtualDom_pushPatch(patches, 8, rootIndex, { w: localPatches, x: inserts, y: endInserts }); } } // CHANGES FROM KEYED DIFF var _VirtualDom_POSTFIX = '_elmW6BL'; function _VirtualDom_insertNode(changes, localPatches, key, vnode, yIndex, inserts) { var entry = changes[key]; // never seen this key before if (!entry) { entry = { c: 0, z: vnode, r: yIndex, s: undefined }; inserts.push({ r: yIndex, A: entry }); changes[key] = entry; return; } // this key was removed earlier, a match! if (entry.c === 1) { inserts.push({ r: yIndex, A: entry }); entry.c = 2; var subPatches = []; _VirtualDom_diffHelp(entry.z, vnode, subPatches, entry.r); entry.r = yIndex; entry.s.s = { w: subPatches, A: entry }; return; } // this key has already been inserted or moved, a duplicate! _VirtualDom_insertNode(changes, localPatches, key + _VirtualDom_POSTFIX, vnode, yIndex, inserts); } function _VirtualDom_removeNode(changes, localPatches, key, vnode, index) { var entry = changes[key]; // never seen this key before if (!entry) { var patch = _VirtualDom_pushPatch(localPatches, 9, index, undefined); changes[key] = { c: 1, z: vnode, r: index, s: patch }; return; } // this key was inserted earlier, a match! if (entry.c === 0) { entry.c = 2; var subPatches = []; _VirtualDom_diffHelp(vnode, entry.z, subPatches, index); _VirtualDom_pushPatch(localPatches, 9, index, { w: subPatches, A: entry }); return; } // this key has already been removed or moved, a duplicate! _VirtualDom_removeNode(changes, localPatches, key + _VirtualDom_POSTFIX, vnode, index); } // ADD DOM NODES // // Each DOM node has an "index" assigned in order of traversal. It is important // to minimize our crawl over the actual DOM, so these indexes (along with the // descendantsCount of virtual nodes) let us skip touching entire subtrees of // the DOM if we know there are no patches there. function _VirtualDom_addDomNodes(domNode, vNode, patches, eventNode) { _VirtualDom_addDomNodesHelp(domNode, vNode, patches, 0, 0, vNode.b, eventNode); } // assumes `patches` is non-empty and indexes increase monotonically. function _VirtualDom_addDomNodesHelp(domNode, vNode, patches, i, low, high, eventNode) { var patch = patches[i]; var index = patch.r; while (index === low) { var patchType = patch.$; if (patchType === 1) { _VirtualDom_addDomNodes(domNode, vNode.k, patch.s, eventNode); } else if (patchType === 8) { patch.t = domNode; patch.u = eventNode; var subPatches = patch.s.w; if (subPatches.length > 0) { _VirtualDom_addDomNodesHelp(domNode, vNode, subPatches, 0, low, high, eventNode); } } else if (patchType === 9) { patch.t = domNode; patch.u = eventNode; var data = patch.s; if (data) { data.A.s = domNode; var subPatches = data.w; if (subPatches.length > 0) { _VirtualDom_addDomNodesHelp(domNode, vNode, subPatches, 0, low, high, eventNode); } } } else { patch.t = domNode; patch.u = eventNode; } i++; if (!(patch = patches[i]) || (index = patch.r) > high) { return i; } } var tag = vNode.$; if (tag === 4) { var subNode = vNode.k; while (subNode.$ === 4) { subNode = subNode.k; } return _VirtualDom_addDomNodesHelp(domNode, subNode, patches, i, low + 1, high, domNode.elm_event_node_ref); } // tag must be 1 or 2 at this point var vKids = vNode.e; var childNodes = domNode.childNodes; for (var j = 0; j < vKids.length; j++) { low++; var vKid = tag === 1 ? vKids[j] : vKids[j].b; var nextLow = low + (vKid.b || 0); if (low <= index && index <= nextLow) { i = _VirtualDom_addDomNodesHelp(childNodes[j], vKid, patches, i, low, nextLow, eventNode); if (!(patch = patches[i]) || (index = patch.r) > high) { return i; } } low = nextLow; } return i; } // APPLY PATCHES function _VirtualDom_applyPatches(rootDomNode, oldVirtualNode, patches, eventNode) { if (patches.length === 0) { return rootDomNode; } _VirtualDom_addDomNodes(rootDomNode, oldVirtualNode, patches, eventNode); return _VirtualDom_applyPatchesHelp(rootDomNode, patches); } function _VirtualDom_applyPatchesHelp(rootDomNode, patches) { for (var i = 0; i < patches.length; i++) { var patch = patches[i]; var localDomNode = patch.t var newNode = _VirtualDom_applyPatch(localDomNode, patch); if (localDomNode === rootDomNode) { rootDomNode = newNode; } } return rootDomNode; } function _VirtualDom_applyPatch(domNode, patch) { switch (patch.$) { case 0: return _VirtualDom_applyPatchRedraw(domNode, patch.s, patch.u); case 4: _VirtualDom_applyFacts(domNode, patch.u, patch.s); return domNode; case 3: domNode.replaceData(0, domNode.length, patch.s); return domNode; case 1: return _VirtualDom_applyPatchesHelp(domNode, patch.s); case 2: if (domNode.elm_event_node_ref) { domNode.elm_event_node_ref.j = patch.s; } else { domNode.elm_event_node_ref = { j: patch.s, p: patch.u }; } return domNode; case 6: var data = patch.s; for (var i = 0; i < data.i; i++) { domNode.removeChild(domNode.childNodes[data.v]); } return domNode; case 7: var data = patch.s; var kids = data.e; var i = data.v; var theEnd = domNode.childNodes[i]; for (; i < kids.length; i++) { domNode.insertBefore(_VirtualDom_render(kids[i], patch.u), theEnd); } return domNode; case 9: var data = patch.s; if (!data) { domNode.parentNode.removeChild(domNode); return domNode; } var entry = data.A; if (typeof entry.r !== 'undefined') { domNode.parentNode.removeChild(domNode); } entry.s = _VirtualDom_applyPatchesHelp(domNode, data.w); return domNode; case 8: return _VirtualDom_applyPatchReorder(domNode, patch); case 5: return patch.s(domNode); default: _Debug_crash(10); // 'Ran into an unknown patch!' } } function _VirtualDom_applyPatchRedraw(domNode, vNode, eventNode) { var parentNode = domNode.parentNode; var newNode = _VirtualDom_render(vNode, eventNode); if (!newNode.elm_event_node_ref) { newNode.elm_event_node_ref = domNode.elm_event_node_ref; } if (parentNode && newNode !== domNode) { parentNode.replaceChild(newNode, domNode); } return newNode; } function _VirtualDom_applyPatchReorder(domNode, patch) { var data = patch.s; // remove end inserts var frag = _VirtualDom_applyPatchReorderEndInsertsHelp(data.y, patch); // removals domNode = _VirtualDom_applyPatchesHelp(domNode, data.w); // inserts var inserts = data.x; for (var i = 0; i < inserts.length; i++) { var insert = inserts[i]; var entry = insert.A; var node = entry.c === 2 ? entry.s : _VirtualDom_render(entry.z, patch.u); domNode.insertBefore(node, domNode.childNodes[insert.r]); } // add end inserts if (frag) { _VirtualDom_appendChild(domNode, frag); } return domNode; } function _VirtualDom_applyPatchReorderEndInsertsHelp(endInserts, patch) { if (!endInserts) { return; } var frag = _VirtualDom_doc.createDocumentFragment(); for (var i = 0; i < endInserts.length; i++) { var insert = endInserts[i]; var entry = insert.A; _VirtualDom_appendChild(frag, entry.c === 2 ? entry.s : _VirtualDom_render(entry.z, patch.u) ); } return frag; } function _VirtualDom_virtualize(node) { // TEXT NODES if (node.nodeType === 3) { return _VirtualDom_text(node.textContent); } // WEIRD NODES if (node.nodeType !== 1) { return _VirtualDom_text(''); } // ELEMENT NODES var attrList = _List_Nil; var attrs = node.attributes; for (var i = attrs.length; i--; ) { var attr = attrs[i]; var name = attr.name; var value = attr.value; attrList = _List_Cons( A2(_VirtualDom_attribute, name, value), attrList ); } var tag = node.tagName.toLowerCase(); var kidList = _List_Nil; var kids = node.childNodes; for (var i = kids.length; i--; ) { kidList = _List_Cons(_VirtualDom_virtualize(kids[i]), kidList); } return A3(_VirtualDom_node, tag, attrList, kidList); } function _VirtualDom_dekey(keyedNode) { var keyedKids = keyedNode.e; var len = keyedKids.length; var kids = new Array(len); for (var i = 0; i < len; i++) { kids[i] = keyedKids[i].b; } return { $: 1, c: keyedNode.c, d: keyedNode.d, e: kids, f: keyedNode.f, b: keyedNode.b }; } // ELEMENT var _Debugger_element; var _Browser_element = _Debugger_element || F4(function(impl, flagDecoder, debugMetadata, args) { return _Platform_initialize( flagDecoder, args, impl.init, impl.update, impl.subscriptions, function(sendToApp, initialModel) { var view = impl.view; /**_UNUSED/ var domNode = args['node']; //*/ /**/ var domNode = args && args['node'] ? args['node'] : _Debug_crash(0); //*/ var currNode = _VirtualDom_virtualize(domNode); return _Browser_makeAnimator(initialModel, function(model) { var nextNode = view(model); var patches = _VirtualDom_diff(currNode, nextNode); domNode = _VirtualDom_applyPatches(domNode, currNode, patches, sendToApp); currNode = nextNode; }); } ); }); // DOCUMENT var _Debugger_document; var _Browser_document = _Debugger_document || F4(function(impl, flagDecoder, debugMetadata, args) { return _Platform_initialize( flagDecoder, args, impl.init, impl.update, impl.subscriptions, function(sendToApp, initialModel) { var divertHrefToApp = impl.setup && impl.setup(sendToApp) var view = impl.view; var title = _VirtualDom_doc.title; var bodyNode = _VirtualDom_doc.body; var currNode = _VirtualDom_virtualize(bodyNode); return _Browser_makeAnimator(initialModel, function(model) { _VirtualDom_divertHrefToApp = divertHrefToApp; var doc = view(model); var nextNode = _VirtualDom_node('body')(_List_Nil)(doc.body); var patches = _VirtualDom_diff(currNode, nextNode); bodyNode = _VirtualDom_applyPatches(bodyNode, currNode, patches, sendToApp); currNode = nextNode; _VirtualDom_divertHrefToApp = 0; (title !== doc.title) && (_VirtualDom_doc.title = title = doc.title); }); } ); }); // ANIMATION var _Browser_cancelAnimationFrame = typeof cancelAnimationFrame !== 'undefined' ? cancelAnimationFrame : function(id) { clearTimeout(id); }; var _Browser_requestAnimationFrame = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame : function(callback) { return setTimeout(callback, 1000 / 60); }; function _Browser_makeAnimator(model, draw) { draw(model); var state = 0; function updateIfNeeded() { state = state === 1 ? 0 : ( _Browser_requestAnimationFrame(updateIfNeeded), draw(model), 1 ); } return function(nextModel, isSync) { model = nextModel; isSync ? ( draw(model), state === 2 && (state = 1) ) : ( state === 0 && _Browser_requestAnimationFrame(updateIfNeeded), state = 2 ); }; } // APPLICATION function _Browser_application(impl) { var onUrlChange = impl.onUrlChange; var onUrlRequest = impl.onUrlRequest; var key = function() { key.a(onUrlChange(_Browser_getUrl())); }; return _Browser_document({ setup: function(sendToApp) { key.a = sendToApp; _Browser_window.addEventListener('popstate', key); _Browser_window.navigator.userAgent.indexOf('Trident') < 0 || _Browser_window.addEventListener('hashchange', key); return F2(function(domNode, event) { if (!event.ctrlKey && !event.metaKey && !event.shiftKey && event.button < 1 && !domNode.target && !domNode.hasAttribute('download')) { event.preventDefault(); var href = domNode.href; var curr = _Browser_getUrl(); var next = $elm$url$Url$fromString(href).a; sendToApp(onUrlRequest( (next && curr.protocol === next.protocol && curr.host === next.host && curr.port_.a === next.port_.a ) ? $elm$browser$Browser$Internal(next) : $elm$browser$Browser$External(href) )); } }); }, init: function(flags) { return A3(impl.init, flags, _Browser_getUrl(), key); }, view: impl.view, update: impl.update, subscriptions: impl.subscriptions }); } function _Browser_getUrl() { return $elm$url$Url$fromString(_VirtualDom_doc.location.href).a || _Debug_crash(1); } var _Browser_go = F2(function(key, n) { return A2($elm$core$Task$perform, $elm$core$Basics$never, _Scheduler_binding(function() { n && history.go(n); key(); })); }); var _Browser_pushUrl = F2(function(key, url) { return A2($elm$core$Task$perform, $elm$core$Basics$never, _Scheduler_binding(function() { history.pushState({}, '', url); key(); })); }); var _Browser_replaceUrl = F2(function(key, url) { return A2($elm$core$Task$perform, $elm$core$Basics$never, _Scheduler_binding(function() { history.replaceState({}, '', url); key(); })); }); // GLOBAL EVENTS var _Browser_fakeNode = { addEventListener: function() {}, removeEventListener: function() {} }; var _Browser_doc = typeof document !== 'undefined' ? document : _Browser_fakeNode; var _Browser_window = typeof window !== 'undefined' ? window : _Browser_fakeNode; var _Browser_on = F3(function(node, eventName, sendToSelf) { return _Scheduler_spawn(_Scheduler_binding(function(callback) { function handler(event) { _Scheduler_rawSpawn(sendToSelf(event)); } node.addEventListener(eventName, handler, _VirtualDom_passiveSupported && { passive: true }); return function() { node.removeEventListener(eventName, handler); }; })); }); var _Browser_decodeEvent = F2(function(decoder, event) { var result = _Json_runHelp(decoder, event); return $elm$core$Result$isOk(result) ? $elm$core$Maybe$Just(result.a) : $elm$core$Maybe$Nothing; }); // PAGE VISIBILITY function _Browser_visibilityInfo() { return (typeof _VirtualDom_doc.hidden !== 'undefined') ? { hidden: 'hidden', change: 'visibilitychange' } : (typeof _VirtualDom_doc.mozHidden !== 'undefined') ? { hidden: 'mozHidden', change: 'mozvisibilitychange' } : (typeof _VirtualDom_doc.msHidden !== 'undefined') ? { hidden: 'msHidden', change: 'msvisibilitychange' } : (typeof _VirtualDom_doc.webkitHidden !== 'undefined') ? { hidden: 'webkitHidden', change: 'webkitvisibilitychange' } : { hidden: 'hidden', change: 'visibilitychange' }; } // ANIMATION FRAMES function _Browser_rAF() { return _Scheduler_binding(function(callback) { var id = _Browser_requestAnimationFrame(function() { callback(_Scheduler_succeed(Date.now())); }); return function() { _Browser_cancelAnimationFrame(id); }; }); } function _Browser_now() { return _Scheduler_binding(function(callback) { callback(_Scheduler_succeed(Date.now())); }); } // DOM STUFF function _Browser_withNode(id, doStuff) { return _Scheduler_binding(function(callback) { _Browser_requestAnimationFrame(function() { var node = document.getElementById(id); callback(node ? _Scheduler_succeed(doStuff(node)) : _Scheduler_fail($elm$browser$Browser$Dom$NotFound(id)) ); }); }); } function _Browser_withWindow(doStuff) { return _Scheduler_binding(function(callback) { _Browser_requestAnimationFrame(function() { callback(_Scheduler_succeed(doStuff())); }); }); } // FOCUS and BLUR var _Browser_call = F2(function(functionName, id) { return _Browser_withNode(id, function(node) { node[functionName](); return _Utils_Tuple0; }); }); // WINDOW VIEWPORT function _Browser_getViewport() { return { scene: _Browser_getScene(), viewport: { x: _Browser_window.pageXOffset, y: _Browser_window.pageYOffset, width: _Browser_doc.documentElement.clientWidth, height: _Browser_doc.documentElement.clientHeight } }; } function _Browser_getScene() { var body = _Browser_doc.body; var elem = _Browser_doc.documentElement; return { width: Math.max(body.scrollWidth, body.offsetWidth, elem.scrollWidth, elem.offsetWidth, elem.clientWidth), height: Math.max(body.scrollHeight, body.offsetHeight, elem.scrollHeight, elem.offsetHeight, elem.clientHeight) }; } var _Browser_setViewport = F2(function(x, y) { return _Browser_withWindow(function() { _Browser_window.scroll(x, y); return _Utils_Tuple0; }); }); // ELEMENT VIEWPORT function _Browser_getViewportOf(id) { return _Browser_withNode(id, function(node) { return { scene: { width: node.scrollWidth, height: node.scrollHeight }, viewport: { x: node.scrollLeft, y: node.scrollTop, width: node.clientWidth, height: node.clientHeight } }; }); } var _Browser_setViewportOf = F3(function(id, x, y) { return _Browser_withNode(id, function(node) { node.scrollLeft = x; node.scrollTop = y; return _Utils_Tuple0; }); }); // ELEMENT function _Browser_getElement(id) { return _Browser_withNode(id, function(node) { var rect = node.getBoundingClientRect(); var x = _Browser_window.pageXOffset; var y = _Browser_window.pageYOffset; return { scene: _Browser_getScene(), viewport: { x: x, y: y, width: _Browser_doc.documentElement.clientWidth, height: _Browser_doc.documentElement.clientHeight }, element: { x: x + rect.left, y: y + rect.top, width: rect.width, height: rect.height } }; }); } // LOAD and RELOAD function _Browser_reload(skipCache) { return A2($elm$core$Task$perform, $elm$core$Basics$never, _Scheduler_binding(function(callback) { _VirtualDom_doc.location.reload(skipCache); })); } function _Browser_load(url) { return A2($elm$core$Task$perform, $elm$core$Basics$never, _Scheduler_binding(function(callback) { try { _Browser_window.location = url; } catch(err) { // Only Firefox can throw a NS_ERROR_MALFORMED_URI exception here. // Other browsers reload the page, so let's be consistent about that. _VirtualDom_doc.location.reload(false); } })); } var _Bitwise_and = F2(function(a, b) { return a & b; }); var _Bitwise_or = F2(function(a, b) { return a | b; }); var _Bitwise_xor = F2(function(a, b) { return a ^ b; }); function _Bitwise_complement(a) { return ~a; }; var _Bitwise_shiftLeftBy = F2(function(offset, a) { return a << offset; }); var _Bitwise_shiftRightBy = F2(function(offset, a) { return a >> offset; }); var _Bitwise_shiftRightZfBy = F2(function(offset, a) { return a >>> offset; }); function _Time_now(millisToPosix) { return _Scheduler_binding(function(callback) { callback(_Scheduler_succeed(millisToPosix(Date.now()))); }); } var _Time_setInterval = F2(function(interval, task) { return _Scheduler_binding(function(callback) { var id = setInterval(function() { _Scheduler_rawSpawn(task); }, interval); return function() { clearInterval(id); }; }); }); function _Time_here() { return _Scheduler_binding(function(callback) { callback(_Scheduler_succeed( A2($elm$time$Time$customZone, -(new Date().getTimezoneOffset()), _List_Nil) )); }); } function _Time_getZoneName() { return _Scheduler_binding(function(callback) { try { var name = $elm$time$Time$Name(Intl.DateTimeFormat().resolvedOptions().timeZone); } catch (e) { var name = $elm$time$Time$Offset(new Date().getTimezoneOffset()); } callback(_Scheduler_succeed(name)); }); } var $author$project$Main$LinkClicked = function (a) { return {$: 'LinkClicked', a: a}; }; var $author$project$Main$UrlChanged = function (a) { return {$: 'UrlChanged', a: a}; }; var $elm$core$Basics$EQ = {$: 'EQ'}; var $elm$core$Basics$GT = {$: 'GT'}; var $elm$core$Basics$LT = {$: 'LT'}; var $elm$core$List$cons = _List_cons; var $elm$core$Dict$foldr = F3( function (func, acc, t) { foldr: while (true) { if (t.$ === 'RBEmpty_elm_builtin') { return acc; } else { var key = t.b; var value = t.c; var left = t.d; var right = t.e; var $temp$func = func, $temp$acc = A3( func, key, value, A3($elm$core$Dict$foldr, func, acc, right)), $temp$t = left; func = $temp$func; acc = $temp$acc; t = $temp$t; continue foldr; } } }); var $elm$core$Dict$toList = function (dict) { return A3( $elm$core$Dict$foldr, F3( function (key, value, list) { return A2( $elm$core$List$cons, _Utils_Tuple2(key, value), list); }), _List_Nil, dict); }; var $elm$core$Dict$keys = function (dict) { return A3( $elm$core$Dict$foldr, F3( function (key, value, keyList) { return A2($elm$core$List$cons, key, keyList); }), _List_Nil, dict); }; var $elm$core$Set$toList = function (_v0) { var dict = _v0.a; return $elm$core$Dict$keys(dict); }; var $elm$core$Elm$JsArray$foldr = _JsArray_foldr; var $elm$core$Array$foldr = F3( function (func, baseCase, _v0) { var tree = _v0.c; var tail = _v0.d; var helper = F2( function (node, acc) { if (node.$ === 'SubTree') { var subTree = node.a; return A3($elm$core$Elm$JsArray$foldr, helper, acc, subTree); } else { var values = node.a; return A3($elm$core$Elm$JsArray$foldr, func, acc, values); } }); return A3( $elm$core$Elm$JsArray$foldr, helper, A3($elm$core$Elm$JsArray$foldr, func, baseCase, tail), tree); }); var $elm$core$Array$toList = function (array) { return A3($elm$core$Array$foldr, $elm$core$List$cons, _List_Nil, array); }; var $elm$core$Result$Err = function (a) { return {$: 'Err', a: a}; }; var $elm$json$Json$Decode$Failure = F2( function (a, b) { return {$: 'Failure', a: a, b: b}; }); var $elm$json$Json$Decode$Field = F2( function (a, b) { return {$: 'Field', a: a, b: b}; }); var $elm$json$Json$Decode$Index = F2( function (a, b) { return {$: 'Index', a: a, b: b}; }); var $elm$core$Result$Ok = function (a) { return {$: 'Ok', a: a}; }; var $elm$json$Json$Decode$OneOf = function (a) { return {$: 'OneOf', a: a}; }; var $elm$core$Basics$False = {$: 'False'}; var $elm$core$Basics$add = _Basics_add; var $elm$core$Maybe$Just = function (a) { return {$: 'Just', a: a}; }; var $elm$core$Maybe$Nothing = {$: 'Nothing'}; var $elm$core$String$all = _String_all; var $elm$core$Basics$and = _Basics_and; var $elm$core$Basics$append = _Utils_append; var $elm$json$Json$Encode$encode = _Json_encode; var $elm$core$String$fromInt = _String_fromNumber; var $elm$core$String$join = F2( function (sep, chunks) { return A2( _String_join, sep, _List_toArray(chunks)); }); var $elm$core$String$split = F2( function (sep, string) { return _List_fromArray( A2(_String_split, sep, string)); }); var $elm$json$Json$Decode$indent = function (str) { return A2( $elm$core$String$join, '\n ', A2($elm$core$String$split, '\n', str)); }; var $elm$core$List$foldl = F3( function (func, acc, list) { foldl: while (true) { if (!list.b) { return acc; } else { var x = list.a; var xs = list.b; var $temp$func = func, $temp$acc = A2(func, x, acc), $temp$list = xs; func = $temp$func; acc = $temp$acc; list = $temp$list; continue foldl; } } }); var $elm$core$List$length = function (xs) { return A3( $elm$core$List$foldl, F2( function (_v0, i) { return i + 1; }), 0, xs); }; var $elm$core$List$map2 = _List_map2; var $elm$core$Basics$le = _Utils_le; var $elm$core$Basics$sub = _Basics_sub; var $elm$core$List$rangeHelp = F3( function (lo, hi, list) { rangeHelp: while (true) { if (_Utils_cmp(lo, hi) < 1) { var $temp$lo = lo, $temp$hi = hi - 1, $temp$list = A2($elm$core$List$cons, hi, list); lo = $temp$lo; hi = $temp$hi; list = $temp$list; continue rangeHelp; } else { return list; } } }); var $elm$core$List$range = F2( function (lo, hi) { return A3($elm$core$List$rangeHelp, lo, hi, _List_Nil); }); var $elm$core$List$indexedMap = F2( function (f, xs) { return A3( $elm$core$List$map2, f, A2( $elm$core$List$range, 0, $elm$core$List$length(xs) - 1), xs); }); var $elm$core$Char$toCode = _Char_toCode; var $elm$core$Char$isLower = function (_char) { var code = $elm$core$Char$toCode(_char); return (97 <= code) && (code <= 122); }; var $elm$core$Char$isUpper = function (_char) { var code = $elm$core$Char$toCode(_char); return (code <= 90) && (65 <= code); }; var $elm$core$Basics$or = _Basics_or; var $elm$core$Char$isAlpha = function (_char) { return $elm$core$Char$isLower(_char) || $elm$core$Char$isUpper(_char); }; var $elm$core$Char$isDigit = function (_char) { var code = $elm$core$Char$toCode(_char); return (code <= 57) && (48 <= code); }; var $elm$core$Char$isAlphaNum = function (_char) { return $elm$core$Char$isLower(_char) || ($elm$core$Char$isUpper(_char) || $elm$core$Char$isDigit(_char)); }; var $elm$core$List$reverse = function (list) { return A3($elm$core$List$foldl, $elm$core$List$cons, _List_Nil, list); }; var $elm$core$String$uncons = _String_uncons; var $elm$json$Json$Decode$errorOneOf = F2( function (i, error) { return '\n\n(' + ($elm$core$String$fromInt(i + 1) + (') ' + $elm$json$Json$Decode$indent( $elm$json$Json$Decode$errorToString(error)))); }); var $elm$json$Json$Decode$errorToString = function (error) { return A2($elm$json$Json$Decode$errorToStringHelp, error, _List_Nil); }; var $elm$json$Json$Decode$errorToStringHelp = F2( function (error, context) { errorToStringHelp: while (true) { switch (error.$) { case 'Field': var f = error.a; var err = error.b; var isSimple = function () { var _v1 = $elm$core$String$uncons(f); if (_v1.$ === 'Nothing') { return false; } else { var _v2 = _v1.a; var _char = _v2.a; var rest = _v2.b; return $elm$core$Char$isAlpha(_char) && A2($elm$core$String$all, $elm$core$Char$isAlphaNum, rest); } }(); var fieldName = isSimple ? ('.' + f) : ('[\'' + (f + '\']')); var $temp$error = err, $temp$context = A2($elm$core$List$cons, fieldName, context); error = $temp$error; context = $temp$context; continue errorToStringHelp; case 'Index': var i = error.a; var err = error.b; var indexName = '[' + ($elm$core$String$fromInt(i) + ']'); var $temp$error = err, $temp$context = A2($elm$core$List$cons, indexName, context); error = $temp$error; context = $temp$context; continue errorToStringHelp; case 'OneOf': var errors = error.a; if (!errors.b) { return 'Ran into a Json.Decode.oneOf with no possibilities' + function () { if (!context.b) { return '!'; } else { return ' at json' + A2( $elm$core$String$join, '', $elm$core$List$reverse(context)); } }(); } else { if (!errors.b.b) { var err = errors.a; var $temp$error = err, $temp$context = context; error = $temp$error; context = $temp$context; continue errorToStringHelp; } else { var starter = function () { if (!context.b) { return 'Json.Decode.oneOf'; } else { return 'The Json.Decode.oneOf at json' + A2( $elm$core$String$join, '', $elm$core$List$reverse(context)); } }(); var introduction = starter + (' failed in the following ' + ($elm$core$String$fromInt( $elm$core$List$length(errors)) + ' ways:')); return A2( $elm$core$String$join, '\n\n', A2( $elm$core$List$cons, introduction, A2($elm$core$List$indexedMap, $elm$json$Json$Decode$errorOneOf, errors))); } } default: var msg = error.a; var json = error.b; var introduction = function () { if (!context.b) { return 'Problem with the given value:\n\n'; } else { return 'Problem with the value at json' + (A2( $elm$core$String$join, '', $elm$core$List$reverse(context)) + ':\n\n '); } }(); return introduction + ($elm$json$Json$Decode$indent( A2($elm$json$Json$Encode$encode, 4, json)) + ('\n\n' + msg)); } } }); var $elm$core$Array$branchFactor = 32; var $elm$core$Array$Array_elm_builtin = F4( function (a, b, c, d) { return {$: 'Array_elm_builtin', a: a, b: b, c: c, d: d}; }); var $elm$core$Elm$JsArray$empty = _JsArray_empty; var $elm$core$Basics$ceiling = _Basics_ceiling; var $elm$core$Basics$fdiv = _Basics_fdiv; var $elm$core$Basics$logBase = F2( function (base, number) { return _Basics_log(number) / _Basics_log(base); }); var $elm$core$Basics$toFloat = _Basics_toFloat; var $elm$core$Array$shiftStep = $elm$core$Basics$ceiling( A2($elm$core$Basics$logBase, 2, $elm$core$Array$branchFactor)); var $elm$core$Array$empty = A4($elm$core$Array$Array_elm_builtin, 0, $elm$core$Array$shiftStep, $elm$core$Elm$JsArray$empty, $elm$core$Elm$JsArray$empty); var $elm$core$Elm$JsArray$initialize = _JsArray_initialize; var $elm$core$Array$Leaf = function (a) { return {$: 'Leaf', a: a}; }; var $elm$core$Basics$apL = F2( function (f, x) { return f(x); }); var $elm$core$Basics$apR = F2( function (x, f) { return f(x); }); var $elm$core$Basics$eq = _Utils_equal; var $elm$core$Basics$floor = _Basics_floor; var $elm$core$Elm$JsArray$length = _JsArray_length; var $elm$core$Basics$gt = _Utils_gt; var $elm$core$Basics$max = F2( function (x, y) { return (_Utils_cmp(x, y) > 0) ? x : y; }); var $elm$core$Basics$mul = _Basics_mul; var $elm$core$Array$SubTree = function (a) { return {$: 'SubTree', a: a}; }; var $elm$core$Elm$JsArray$initializeFromList = _JsArray_initializeFromList; var $elm$core$Array$compressNodes = F2( function (nodes, acc) { compressNodes: while (true) { var _v0 = A2($elm$core$Elm$JsArray$initializeFromList, $elm$core$Array$branchFactor, nodes); var node = _v0.a; var remainingNodes = _v0.b; var newAcc = A2( $elm$core$List$cons, $elm$core$Array$SubTree(node), acc); if (!remainingNodes.b) { return $elm$core$List$reverse(newAcc); } else { var $temp$nodes = remainingNodes, $temp$acc = newAcc; nodes = $temp$nodes; acc = $temp$acc; continue compressNodes; } } }); var $elm$core$Tuple$first = function (_v0) { var x = _v0.a; return x; }; var $elm$core$Array$treeFromBuilder = F2( function (nodeList, nodeListSize) { treeFromBuilder: while (true) { var newNodeSize = $elm$core$Basics$ceiling(nodeListSize / $elm$core$Array$branchFactor); if (newNodeSize === 1) { return A2($elm$core$Elm$JsArray$initializeFromList, $elm$core$Array$branchFactor, nodeList).a; } else { var $temp$nodeList = A2($elm$core$Array$compressNodes, nodeList, _List_Nil), $temp$nodeListSize = newNodeSize; nodeList = $temp$nodeList; nodeListSize = $temp$nodeListSize; continue treeFromBuilder; } } }); var $elm$core$Array$builderToArray = F2( function (reverseNodeList, builder) { if (!builder.nodeListSize) { return A4( $elm$core$Array$Array_elm_builtin, $elm$core$Elm$JsArray$length(builder.tail), $elm$core$Array$shiftStep, $elm$core$Elm$JsArray$empty, builder.tail); } else { var treeLen = builder.nodeListSize * $elm$core$Array$branchFactor; var depth = $elm$core$Basics$floor( A2($elm$core$Basics$logBase, $elm$core$Array$branchFactor, treeLen - 1)); var correctNodeList = reverseNodeList ? $elm$core$List$reverse(builder.nodeList) : builder.nodeList; var tree = A2($elm$core$Array$treeFromBuilder, correctNodeList, builder.nodeListSize); return A4( $elm$core$Array$Array_elm_builtin, $elm$core$Elm$JsArray$length(builder.tail) + treeLen, A2($elm$core$Basics$max, 5, depth * $elm$core$Array$shiftStep), tree, builder.tail); } }); var $elm$core$Basics$idiv = _Basics_idiv; var $elm$core$Basics$lt = _Utils_lt; var $elm$core$Array$initializeHelp = F5( function (fn, fromIndex, len, nodeList, tail) { initializeHelp: while (true) { if (fromIndex < 0) { return A2( $elm$core$Array$builderToArray, false, {nodeList: nodeList, nodeListSize: (len / $elm$core$Array$branchFactor) | 0, tail: tail}); } else { var leaf = $elm$core$Array$Leaf( A3($elm$core$Elm$JsArray$initialize, $elm$core$Array$branchFactor, fromIndex, fn)); var $temp$fn = fn, $temp$fromIndex = fromIndex - $elm$core$Array$branchFactor, $temp$len = len, $temp$nodeList = A2($elm$core$List$cons, leaf, nodeList), $temp$tail = tail; fn = $temp$fn; fromIndex = $temp$fromIndex; len = $temp$len; nodeList = $temp$nodeList; tail = $temp$tail; continue initializeHelp; } } }); var $elm$core$Basics$remainderBy = _Basics_remainderBy; var $elm$core$Array$initialize = F2( function (len, fn) { if (len <= 0) { return $elm$core$Array$empty; } else { var tailLen = len % $elm$core$Array$branchFactor; var tail = A3($elm$core$Elm$JsArray$initialize, tailLen, len - tailLen, fn); var initialFromIndex = (len - tailLen) - $elm$core$Array$branchFactor; return A5($elm$core$Array$initializeHelp, fn, initialFromIndex, len, _List_Nil, tail); } }); var $elm$core$Basics$True = {$: 'True'}; var $elm$core$Result$isOk = function (result) { if (result.$ === 'Ok') { return true; } else { return false; } }; var $elm$json$Json$Decode$map = _Json_map1; var $elm$json$Json$Decode$map2 = _Json_map2; var $elm$json$Json$Decode$succeed = _Json_succeed; var $elm$virtual_dom$VirtualDom$toHandlerInt = function (handler) { switch (handler.$) { case 'Normal': return 0; case 'MayStopPropagation': return 1; case 'MayPreventDefault': return 2; default: return 3; } }; var $elm$browser$Browser$External = function (a) { return {$: 'External', a: a}; }; var $elm$browser$Browser$Internal = function (a) { return {$: 'Internal', a: a}; }; var $elm$core$Basics$identity = function (x) { return x; }; var $elm$browser$Browser$Dom$NotFound = function (a) { return {$: 'NotFound', a: a}; }; var $elm$url$Url$Http = {$: 'Http'}; var $elm$url$Url$Https = {$: 'Https'}; var $elm$url$Url$Url = F6( function (protocol, host, port_, path, query, fragment) { return {fragment: fragment, host: host, path: path, port_: port_, protocol: protocol, query: query}; }); var $elm$core$String$contains = _String_contains; var $elm$core$String$length = _String_length; var $elm$core$String$slice = _String_slice; var $elm$core$String$dropLeft = F2( function (n, string) { return (n < 1) ? string : A3( $elm$core$String$slice, n, $elm$core$String$length(string), string); }); var $elm$core$String$indexes = _String_indexes; var $elm$core$String$isEmpty = function (string) { return string === ''; }; var $elm$core$String$left = F2( function (n, string) { return (n < 1) ? '' : A3($elm$core$String$slice, 0, n, string); }); var $elm$core$String$toInt = _String_toInt; var $elm$url$Url$chompBeforePath = F5( function (protocol, path, params, frag, str) { if ($elm$core$String$isEmpty(str) || A2($elm$core$String$contains, '@', str)) { return $elm$core$Maybe$Nothing; } else { var _v0 = A2($elm$core$String$indexes, ':', str); if (!_v0.b) { return $elm$core$Maybe$Just( A6($elm$url$Url$Url, protocol, str, $elm$core$Maybe$Nothing, path, params, frag)); } else { if (!_v0.b.b) { var i = _v0.a; var _v1 = $elm$core$String$toInt( A2($elm$core$String$dropLeft, i + 1, str)); if (_v1.$ === 'Nothing') { return $elm$core$Maybe$Nothing; } else { var port_ = _v1; return $elm$core$Maybe$Just( A6( $elm$url$Url$Url, protocol, A2($elm$core$String$left, i, str), port_, path, params, frag)); } } else { return $elm$core$Maybe$Nothing; } } } }); var $elm$url$Url$chompBeforeQuery = F4( function (protocol, params, frag, str) { if ($elm$core$String$isEmpty(str)) { return $elm$core$Maybe$Nothing; } else { var _v0 = A2($elm$core$String$indexes, '/', str); if (!_v0.b) { return A5($elm$url$Url$chompBeforePath, protocol, '/', params, frag, str); } else { var i = _v0.a; return A5( $elm$url$Url$chompBeforePath, protocol, A2($elm$core$String$dropLeft, i, str), params, frag, A2($elm$core$String$left, i, str)); } } }); var $elm$url$Url$chompBeforeFragment = F3( function (protocol, frag, str) { if ($elm$core$String$isEmpty(str)) { return $elm$core$Maybe$Nothing; } else { var _v0 = A2($elm$core$String$indexes, '?', str); if (!_v0.b) { return A4($elm$url$Url$chompBeforeQuery, protocol, $elm$core$Maybe$Nothing, frag, str); } else { var i = _v0.a; return A4( $elm$url$Url$chompBeforeQuery, protocol, $elm$core$Maybe$Just( A2($elm$core$String$dropLeft, i + 1, str)), frag, A2($elm$core$String$left, i, str)); } } }); var $elm$url$Url$chompAfterProtocol = F2( function (protocol, str) { if ($elm$core$String$isEmpty(str)) { return $elm$core$Maybe$Nothing; } else { var _v0 = A2($elm$core$String$indexes, '#', str); if (!_v0.b) { return A3($elm$url$Url$chompBeforeFragment, protocol, $elm$core$Maybe$Nothing, str); } else { var i = _v0.a; return A3( $elm$url$Url$chompBeforeFragment, protocol, $elm$core$Maybe$Just( A2($elm$core$String$dropLeft, i + 1, str)), A2($elm$core$String$left, i, str)); } } }); var $elm$core$String$startsWith = _String_startsWith; var $elm$url$Url$fromString = function (str) { return A2($elm$core$String$startsWith, 'http://', str) ? A2( $elm$url$Url$chompAfterProtocol, $elm$url$Url$Http, A2($elm$core$String$dropLeft, 7, str)) : (A2($elm$core$String$startsWith, 'https://', str) ? A2( $elm$url$Url$chompAfterProtocol, $elm$url$Url$Https, A2($elm$core$String$dropLeft, 8, str)) : $elm$core$Maybe$Nothing); }; var $elm$core$Basics$never = function (_v0) { never: while (true) { var nvr = _v0.a; var $temp$_v0 = nvr; _v0 = $temp$_v0; continue never; } }; var $elm$core$Task$Perform = function (a) { return {$: 'Perform', a: a}; }; var $elm$core$Task$succeed = _Scheduler_succeed; var $elm$core$Task$init = $elm$core$Task$succeed(_Utils_Tuple0); var $elm$core$List$foldrHelper = F4( function (fn, acc, ctr, ls) { if (!ls.b) { return acc; } else { var a = ls.a; var r1 = ls.b; if (!r1.b) { return A2(fn, a, acc); } else { var b = r1.a; var r2 = r1.b; if (!r2.b) { return A2( fn, a, A2(fn, b, acc)); } else { var c = r2.a; var r3 = r2.b; if (!r3.b) { return A2( fn, a, A2( fn, b, A2(fn, c, acc))); } else { var d = r3.a; var r4 = r3.b; var res = (ctr > 500) ? A3( $elm$core$List$foldl, fn, acc, $elm$core$List$reverse(r4)) : A4($elm$core$List$foldrHelper, fn, acc, ctr + 1, r4); return A2( fn, a, A2( fn, b, A2( fn, c, A2(fn, d, res)))); } } } } }); var $elm$core$List$foldr = F3( function (fn, acc, ls) { return A4($elm$core$List$foldrHelper, fn, acc, 0, ls); }); var $elm$core$List$map = F2( function (f, xs) { return A3( $elm$core$List$foldr, F2( function (x, acc) { return A2( $elm$core$List$cons, f(x), acc); }), _List_Nil, xs); }); var $elm$core$Task$andThen = _Scheduler_andThen; var $elm$core$Task$map = F2( function (func, taskA) { return A2( $elm$core$Task$andThen, function (a) { return $elm$core$Task$succeed( func(a)); }, taskA); }); var $elm$core$Task$map2 = F3( function (func, taskA, taskB) { return A2( $elm$core$Task$andThen, function (a) { return A2( $elm$core$Task$andThen, function (b) { return $elm$core$Task$succeed( A2(func, a, b)); }, taskB); }, taskA); }); var $elm$core$Task$sequence = function (tasks) { return A3( $elm$core$List$foldr, $elm$core$Task$map2($elm$core$List$cons), $elm$core$Task$succeed(_List_Nil), tasks); }; var $elm$core$Platform$sendToApp = _Platform_sendToApp; var $elm$core$Task$spawnCmd = F2( function (router, _v0) { var task = _v0.a; return _Scheduler_spawn( A2( $elm$core$Task$andThen, $elm$core$Platform$sendToApp(router), task)); }); var $elm$core$Task$onEffects = F3( function (router, commands, state) { return A2( $elm$core$Task$map, function (_v0) { return _Utils_Tuple0; }, $elm$core$Task$sequence( A2( $elm$core$List$map, $elm$core$Task$spawnCmd(router), commands))); }); var $elm$core$Task$onSelfMsg = F3( function (_v0, _v1, _v2) { return $elm$core$Task$succeed(_Utils_Tuple0); }); var $elm$core$Task$cmdMap = F2( function (tagger, _v0) { var task = _v0.a; return $elm$core$Task$Perform( A2($elm$core$Task$map, tagger, task)); }); _Platform_effectManagers['Task'] = _Platform_createManager($elm$core$Task$init, $elm$core$Task$onEffects, $elm$core$Task$onSelfMsg, $elm$core$Task$cmdMap); var $elm$core$Task$command = _Platform_leaf('Task'); var $elm$core$Task$perform = F2( function (toMessage, task) { return $elm$core$Task$command( $elm$core$Task$Perform( A2($elm$core$Task$map, toMessage, task))); }); var $elm$browser$Browser$application = _Browser_application; var $author$project$Main$Model = function (key) { return function (url) { return function (status) { return function (gameId) { return function (amAdministrator) { return function (lastUpdate) { return function (players) { return function (myId) { return function (uuid) { return function (previousPackage) { return function (workloads) { return function (currentWorkload) { return function (showingGameoverSelf) { return function (gameKey) { return function (funnelState) { return function (formFields) { return function (pendingDialogs) { return function (nextDialogId) { return function (error) { return {amAdministrator: amAdministrator, currentWorkload: currentWorkload, error: error, formFields: formFields, funnelState: funnelState, gameId: gameId, gameKey: gameKey, key: key, lastUpdate: lastUpdate, myId: myId, nextDialogId: nextDialogId, pendingDialogs: pendingDialogs, players: players, previousPackage: previousPackage, showingGameoverSelf: showingGameoverSelf, status: status, url: url, uuid: uuid, workloads: workloads}; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; }; var $author$project$Protocol$NoGame = {$: 'NoGame'}; var $author$project$Main$SetField = F2( function (a, b) { return {$: 'SetField', a: a, b: b}; }); var $author$project$Main$Tick = function (a) { return {$: 'Tick', a: a}; }; var $author$project$Main$UsernamePlaceholder = {$: 'UsernamePlaceholder'}; var $elm$core$Platform$Cmd$batch = _Platform_batch; var $elm$core$Dict$RBEmpty_elm_builtin = {$: 'RBEmpty_elm_builtin'}; var $elm$core$Dict$empty = $elm$core$Dict$RBEmpty_elm_builtin; var $elm$random$Random$Generate = function (a) { return {$: 'Generate', a: a}; }; var $elm$random$Random$Seed = F2( function (a, b) { return {$: 'Seed', a: a, b: b}; }); var $elm$core$Bitwise$shiftRightZfBy = _Bitwise_shiftRightZfBy; var $elm$random$Random$next = function (_v0) { var state0 = _v0.a; var incr = _v0.b; return A2($elm$random$Random$Seed, ((state0 * 1664525) + incr) >>> 0, incr); }; var $elm$random$Random$initialSeed = function (x) { var _v0 = $elm$random$Random$next( A2($elm$random$Random$Seed, 0, 1013904223)); var state1 = _v0.a; var incr = _v0.b; var state2 = (state1 + x) >>> 0; return $elm$random$Random$next( A2($elm$random$Random$Seed, state2, incr)); }; var $elm$time$Time$Name = function (a) { return {$: 'Name', a: a}; }; var $elm$time$Time$Offset = function (a) { return {$: 'Offset', a: a}; }; var $elm$time$Time$Zone = F2( function (a, b) { return {$: 'Zone', a: a, b: b}; }); var $elm$time$Time$customZone = $elm$time$Time$Zone; var $elm$time$Time$Posix = function (a) { return {$: 'Posix', a: a}; }; var $elm$time$Time$millisToPosix = $elm$time$Time$Posix; var $elm$time$Time$now = _Time_now($elm$time$Time$millisToPosix); var $elm$time$Time$posixToMillis = function (_v0) { var millis = _v0.a; return millis; }; var $elm$random$Random$init = A2( $elm$core$Task$andThen, function (time) { return $elm$core$Task$succeed( $elm$random$Random$initialSeed( $elm$time$Time$posixToMillis(time))); }, $elm$time$Time$now); var $elm$random$Random$step = F2( function (_v0, seed) { var generator = _v0.a; return generator(seed); }); var $elm$random$Random$onEffects = F3( function (router, commands, seed) { if (!commands.b) { return $elm$core$Task$succeed(seed); } else { var generator = commands.a.a; var rest = commands.b; var _v1 = A2($elm$random$Random$step, generator, seed); var value = _v1.a; var newSeed = _v1.b; return A2( $elm$core$Task$andThen, function (_v2) { return A3($elm$random$Random$onEffects, router, rest, newSeed); }, A2($elm$core$Platform$sendToApp, router, value)); } }); var $elm$random$Random$onSelfMsg = F3( function (_v0, _v1, seed) { return $elm$core$Task$succeed(seed); }); var $elm$random$Random$Generator = function (a) { return {$: 'Generator', a: a}; }; var $elm$random$Random$map = F2( function (func, _v0) { var genA = _v0.a; return $elm$random$Random$Generator( function (seed0) { var _v1 = genA(seed0); var a = _v1.a; var seed1 = _v1.b; return _Utils_Tuple2( func(a), seed1); }); }); var $elm$random$Random$cmdMap = F2( function (func, _v0) { var generator = _v0.a; return $elm$random$Random$Generate( A2($elm$random$Random$map, func, generator)); }); _Platform_effectManagers['Random'] = _Platform_createManager($elm$random$Random$init, $elm$random$Random$onEffects, $elm$random$Random$onSelfMsg, $elm$random$Random$cmdMap); var $elm$random$Random$command = _Platform_leaf('Random'); var $elm$random$Random$generate = F2( function (tagger, generator) { return $elm$random$Random$command( $elm$random$Random$Generate( A2($elm$random$Random$map, tagger, generator))); }); var $elm$core$Bitwise$and = _Bitwise_and; var $elm$core$Array$bitMask = 4294967295 >>> (32 - $elm$core$Array$shiftStep); var $elm$core$Basics$ge = _Utils_ge; var $elm$core$Elm$JsArray$unsafeGet = _JsArray_unsafeGet; var $elm$core$Array$getHelp = F3( function (shift, index, tree) { getHelp: while (true) { var pos = $elm$core$Array$bitMask & (index >>> shift); var _v0 = A2($elm$core$Elm$JsArray$unsafeGet, pos, tree); if (_v0.$ === 'SubTree') { var subTree = _v0.a; var $temp$shift = shift - $elm$core$Array$shiftStep, $temp$index = index, $temp$tree = subTree; shift = $temp$shift; index = $temp$index; tree = $temp$tree; continue getHelp; } else { var values = _v0.a; return A2($elm$core$Elm$JsArray$unsafeGet, $elm$core$Array$bitMask & index, values); } } }); var $elm$core$Bitwise$shiftLeftBy = _Bitwise_shiftLeftBy; var $elm$core$Array$tailIndex = function (len) { return (len >>> 5) << 5; }; var $elm$core$Array$get = F2( function (index, _v0) { var len = _v0.a; var startShift = _v0.b; var tree = _v0.c; var tail = _v0.d; return ((index < 0) || (_Utils_cmp(index, len) > -1)) ? $elm$core$Maybe$Nothing : ((_Utils_cmp( index, $elm$core$Array$tailIndex(len)) > -1) ? $elm$core$Maybe$Just( A2($elm$core$Elm$JsArray$unsafeGet, $elm$core$Array$bitMask & index, tail)) : $elm$core$Maybe$Just( A3($elm$core$Array$getHelp, startShift, index, tree))); }); var $elm$core$Basics$negate = function (n) { return -n; }; var $elm$core$Bitwise$xor = _Bitwise_xor; var $elm$random$Random$peel = function (_v0) { var state = _v0.a; var word = (state ^ (state >>> ((state >>> 28) + 4))) * 277803737; return ((word >>> 22) ^ word) >>> 0; }; var $elm$random$Random$int = F2( function (a, b) { return $elm$random$Random$Generator( function (seed0) { var _v0 = (_Utils_cmp(a, b) < 0) ? _Utils_Tuple2(a, b) : _Utils_Tuple2(b, a); var lo = _v0.a; var hi = _v0.b; var range = (hi - lo) + 1; if (!((range - 1) & range)) { return _Utils_Tuple2( (((range - 1) & $elm$random$Random$peel(seed0)) >>> 0) + lo, $elm$random$Random$next(seed0)); } else { var threshhold = (((-range) >>> 0) % range) >>> 0; var accountForBias = function (seed) { accountForBias: while (true) { var x = $elm$random$Random$peel(seed); var seedN = $elm$random$Random$next(seed); if (_Utils_cmp(x, threshhold) < 0) { var $temp$seed = seedN; seed = $temp$seed; continue accountForBias; } else { return _Utils_Tuple2((x % range) + lo, seedN); } } }; return accountForBias(seed0); } }); }); var $elm$core$Array$length = function (_v0) { var len = _v0.a; return len; }; var $elm$core$Array$fromListHelp = F3( function (list, nodeList, nodeListSize) { fromListHelp: while (true) { var _v0 = A2($elm$core$Elm$JsArray$initializeFromList, $elm$core$Array$branchFactor, list); var jsArray = _v0.a; var remainingItems = _v0.b; if (_Utils_cmp( $elm$core$Elm$JsArray$length(jsArray), $elm$core$Array$branchFactor) < 0) { return A2( $elm$core$Array$builderToArray, true, {nodeList: nodeList, nodeListSize: nodeListSize, tail: jsArray}); } else { var $temp$list = remainingItems, $temp$nodeList = A2( $elm$core$List$cons, $elm$core$Array$Leaf(jsArray), nodeList), $temp$nodeListSize = nodeListSize + 1; list = $temp$list; nodeList = $temp$nodeList; nodeListSize = $temp$nodeListSize; continue fromListHelp; } } }); var $elm$core$Array$fromList = function (list) { if (!list.b) { return $elm$core$Array$empty; } else { return A3($elm$core$Array$fromListHelp, list, _List_Nil, 0); } }; var $author$project$Names$names = $elm$core$Array$fromList( _List_fromArray( ['Mary', 'John', 'Aliakmonas', 'Alkistis', 'alej', 'virr', 'dojo', 'doggo', 'hojo', 'baktu', 'James', 'Jamie', 'Alex', 'Antidisestablishmentarianism', 'Llanfair­pwllgwyngyll­gogery­chwyrn­drobwll­llan­tysilio­gogo­goch', 'L', 'Professor', 'admin', 'user', 'Nameless', 'Horan', 'Dolores', 'root', 'Picasso', 'Caesar', 'Gleich', 'Mash'])); var $elm$core$Maybe$withDefault = F2( function (_default, maybe) { if (maybe.$ === 'Just') { var value = maybe.a; return value; } else { return _default; } }); var $author$project$Names$generator = A2( $elm$random$Random$map, function (n) { return A2( $elm$core$Maybe$withDefault, 'Null', A2($elm$core$Array$get, n, $author$project$Names$names)); }, A2( $elm$random$Random$int, 0, $elm$core$Array$length($author$project$Names$names) - 1)); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Get = F2( function (a, b) { return {$: 'Get', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$get = $billstclair$elm_localstorage$PortFunnel$InternalTypes$Get($elm$core$Maybe$Nothing); var $author$project$Main$Receive = function (a) { return {$: 'Receive', a: a}; }; var $author$project$PortFunnels$cmdPort = _Platform_outgoingPort('cmdPort', $elm$core$Basics$identity); var $elm$core$Basics$compare = _Utils_compare; var $elm$core$Dict$get = F2( function (targetKey, dict) { get: while (true) { if (dict.$ === 'RBEmpty_elm_builtin') { return $elm$core$Maybe$Nothing; } else { var key = dict.b; var value = dict.c; var left = dict.d; var right = dict.e; var _v1 = A2($elm$core$Basics$compare, targetKey, key); switch (_v1.$) { case 'LT': var $temp$targetKey = targetKey, $temp$dict = left; targetKey = $temp$targetKey; dict = $temp$dict; continue get; case 'EQ': return $elm$core$Maybe$Just(value); default: var $temp$targetKey = targetKey, $temp$dict = right; targetKey = $temp$targetKey; dict = $temp$dict; continue get; } } } }); var $elm$core$Basics$not = _Basics_not; var $elm$core$Dict$Black = {$: 'Black'}; var $elm$core$Dict$RBNode_elm_builtin = F5( function (a, b, c, d, e) { return {$: 'RBNode_elm_builtin', a: a, b: b, c: c, d: d, e: e}; }); var $elm$core$Dict$Red = {$: 'Red'}; var $elm$core$Dict$balance = F5( function (color, key, value, left, right) { if ((right.$ === 'RBNode_elm_builtin') && (right.a.$ === 'Red')) { var _v1 = right.a; var rK = right.b; var rV = right.c; var rLeft = right.d; var rRight = right.e; if ((left.$ === 'RBNode_elm_builtin') && (left.a.$ === 'Red')) { var _v3 = left.a; var lK = left.b; var lV = left.c; var lLeft = left.d; var lRight = left.e; return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, key, value, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, lK, lV, lLeft, lRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, rK, rV, rLeft, rRight)); } else { return A5( $elm$core$Dict$RBNode_elm_builtin, color, rK, rV, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, key, value, left, rLeft), rRight); } } else { if ((((left.$ === 'RBNode_elm_builtin') && (left.a.$ === 'Red')) && (left.d.$ === 'RBNode_elm_builtin')) && (left.d.a.$ === 'Red')) { var _v5 = left.a; var lK = left.b; var lV = left.c; var _v6 = left.d; var _v7 = _v6.a; var llK = _v6.b; var llV = _v6.c; var llLeft = _v6.d; var llRight = _v6.e; var lRight = left.e; return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, llK, llV, llLeft, llRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, key, value, lRight, right)); } else { return A5($elm$core$Dict$RBNode_elm_builtin, color, key, value, left, right); } } }); var $elm$core$Dict$insertHelp = F3( function (key, value, dict) { if (dict.$ === 'RBEmpty_elm_builtin') { return A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, key, value, $elm$core$Dict$RBEmpty_elm_builtin, $elm$core$Dict$RBEmpty_elm_builtin); } else { var nColor = dict.a; var nKey = dict.b; var nValue = dict.c; var nLeft = dict.d; var nRight = dict.e; var _v1 = A2($elm$core$Basics$compare, key, nKey); switch (_v1.$) { case 'LT': return A5( $elm$core$Dict$balance, nColor, nKey, nValue, A3($elm$core$Dict$insertHelp, key, value, nLeft), nRight); case 'EQ': return A5($elm$core$Dict$RBNode_elm_builtin, nColor, nKey, value, nLeft, nRight); default: return A5( $elm$core$Dict$balance, nColor, nKey, nValue, nLeft, A3($elm$core$Dict$insertHelp, key, value, nRight)); } } }); var $elm$core$Dict$insert = F3( function (key, value, dict) { var _v0 = A3($elm$core$Dict$insertHelp, key, value, dict); if ((_v0.$ === 'RBNode_elm_builtin') && (_v0.a.$ === 'Red')) { var _v1 = _v0.a; var k = _v0.b; var v = _v0.c; var l = _v0.d; var r = _v0.e; return A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, l, r); } else { var x = _v0; return x; } }); var $elm$core$Dict$fromList = function (assocs) { return A3( $elm$core$List$foldl, F2( function (_v0, dict) { var key = _v0.a; var value = _v0.b; return A3($elm$core$Dict$insert, key, value, dict); }), $elm$core$Dict$empty, assocs); }; var $author$project$PortFunnels$simulatedPortDict = $elm$core$Dict$fromList(_List_Nil); var $author$project$PortFunnels$getCmdPort = F3( function (tagger, moduleName, useSimulator) { if (!useSimulator) { return $author$project$PortFunnels$cmdPort; } else { var _v0 = A2($elm$core$Dict$get, moduleName, $author$project$PortFunnels$simulatedPortDict); if (_v0.$ === 'Just') { var makeSimulatedCmdPort = _v0.a; return makeSimulatedCmdPort(tagger); } else { return $author$project$PortFunnels$cmdPort; } } }); var $author$project$Main$cmdPort = A3($author$project$PortFunnels$getCmdPort, $author$project$Main$Receive, '', false); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Clear = function (a) { return {$: 'Clear', a: a}; }; var $billstclair$elm_localstorage$PortFunnel$InternalTypes$ListKeys = F2( function (a, b) { return {$: 'ListKeys', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Put = F2( function (a, b) { return {$: 'Put', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$addPrefix = F2( function (prefix, key) { return (prefix === '') ? key : (prefix + ('.' + key)); }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Got = F3( function (a, b, c) { return {$: 'Got', a: a, b: b, c: c}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Keys = F3( function (a, b, c) { return {$: 'Keys', a: a, b: b, c: c}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateClear = function (a) { return {$: 'SimulateClear', a: a}; }; var $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateGet = F2( function (a, b) { return {$: 'SimulateGet', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateListKeys = F2( function (a, b) { return {$: 'SimulateListKeys', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulatePut = F2( function (a, b) { return {$: 'SimulatePut', a: a, b: b}; }); var $billstclair$elm_localstorage$PortFunnel$InternalTypes$Startup = {$: 'Startup'}; var $elm$json$Json$Decode$decodeValue = _Json_run; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$GotRecord = F3( function (label, key, value) { return {key: key, label: label, value: value}; }); var $elm$json$Json$Decode$field = _Json_decodeField; var $elm$json$Json$Decode$map3 = _Json_map3; var $elm$json$Json$Decode$null = _Json_decodeNull; var $elm$json$Json$Decode$oneOf = _Json_oneOf; var $elm$json$Json$Decode$nullable = function (decoder) { return $elm$json$Json$Decode$oneOf( _List_fromArray( [ $elm$json$Json$Decode$null($elm$core$Maybe$Nothing), A2($elm$json$Json$Decode$map, $elm$core$Maybe$Just, decoder) ])); }; var $elm$json$Json$Decode$string = _Json_decodeString; var $elm$json$Json$Decode$value = _Json_decodeValue; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$gotDecoder = A4( $elm$json$Json$Decode$map3, $billstclair$elm_localstorage$PortFunnel$LocalStorage$GotRecord, A2( $elm$json$Json$Decode$field, 'label', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string)), A2($elm$json$Json$Decode$field, 'key', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'value', $elm$json$Json$Decode$value)); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$KeysRecord = F3( function (label, prefix, keys) { return {keys: keys, label: label, prefix: prefix}; }); var $elm$json$Json$Decode$list = _Json_decodeList; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$keysDecoder = A4( $elm$json$Json$Decode$map3, $billstclair$elm_localstorage$PortFunnel$LocalStorage$KeysRecord, A2( $elm$json$Json$Decode$field, 'label', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string)), A2($elm$json$Json$Decode$field, 'prefix', $elm$json$Json$Decode$string), A2( $elm$json$Json$Decode$field, 'keys', $elm$json$Json$Decode$list($elm$json$Json$Decode$string))); var $elm$core$Tuple$pair = F2( function (a, b) { return _Utils_Tuple2(a, b); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$labeledStringDecoder = function (property) { return A3( $elm$json$Json$Decode$map2, $elm$core$Tuple$pair, A2( $elm$json$Json$Decode$field, 'label', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string)), A2($elm$json$Json$Decode$field, property, $elm$json$Json$Decode$string)); }; var $elm$json$Json$Encode$null = _Json_encodeNull; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$PutRecord = F2( function (key, value) { return {key: key, value: value}; }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$putDecoder = A3( $elm$json$Json$Decode$map2, $billstclair$elm_localstorage$PortFunnel$LocalStorage$PutRecord, A2($elm$json$Json$Decode$field, 'key', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'value', $elm$json$Json$Decode$value)); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$NOTAG = {$: 'NOTAG'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$ClearTag = {$: 'ClearTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$GetTag = {$: 'GetTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$GotTag = {$: 'GotTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$KeysTag = {$: 'KeysTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$ListKeysTag = {$: 'ListKeysTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$PutTag = {$: 'PutTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateClearTag = {$: 'SimulateClearTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateGetTag = {$: 'SimulateGetTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateListKeysTag = {$: 'SimulateListKeysTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulatePutTag = {$: 'SimulatePutTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$StartupTag = {$: 'StartupTag'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$clearTag = 'clear'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$getTag = 'get'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$gotTag = 'got'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$keysTag = 'keys'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$listKeysTag = 'listkeys'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$putTag = 'put'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateClearTag = 'simulateclear'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateGetTag = 'simulateget'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateListKeysTag = 'simulatelistkeys'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulatePutTag = 'simulateput'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$startupTag = 'startup'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$tagDict = $elm$core$Dict$fromList( _List_fromArray( [ _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$startupTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$StartupTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$getTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$GetTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$gotTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$GotTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$putTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$PutTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$listKeysTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$ListKeysTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$keysTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$KeysTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$clearTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$ClearTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateGetTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateGetTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$simulatePutTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulatePutTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateListKeysTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateListKeysTag), _Utils_Tuple2($billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateClearTag, $billstclair$elm_localstorage$PortFunnel$LocalStorage$SimulateClearTag) ])); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$strtag = function (str) { var _v0 = A2($elm$core$Dict$get, str, $billstclair$elm_localstorage$PortFunnel$LocalStorage$tagDict); if (_v0.$ === 'Just') { var tag = _v0.a; return tag; } else { return $billstclair$elm_localstorage$PortFunnel$LocalStorage$NOTAG; } }; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$decode = function (_v0) { var tag = _v0.tag; var args = _v0.args; var _v1 = $billstclair$elm_localstorage$PortFunnel$LocalStorage$strtag(tag); switch (_v1.$) { case 'GetTag': var _v2 = A2( $elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$labeledStringDecoder('key'), args); if (_v2.$ === 'Ok') { var _v3 = _v2.a; var label = _v3.a; var key = _v3.b; return $elm$core$Result$Ok( A2($billstclair$elm_localstorage$PortFunnel$InternalTypes$Get, label, key)); } else { return $elm$core$Result$Err( 'Get key not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'GotTag': var _v4 = A2($elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$gotDecoder, args); if (_v4.$ === 'Ok') { var label = _v4.a.label; var key = _v4.a.key; var value = _v4.a.value; return $elm$core$Result$Ok( A3( $billstclair$elm_localstorage$PortFunnel$InternalTypes$Got, label, key, _Utils_eq(value, $elm$json$Json$Encode$null) ? $elm$core$Maybe$Nothing : $elm$core$Maybe$Just(value))); } else { return $elm$core$Result$Err( 'Got not { label, key, value }: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'PutTag': var _v5 = A2($elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$putDecoder, args); if (_v5.$ === 'Ok') { var key = _v5.a.key; var value = _v5.a.value; return $elm$core$Result$Ok( A2( $billstclair$elm_localstorage$PortFunnel$InternalTypes$Put, key, _Utils_eq(value, $elm$json$Json$Encode$null) ? $elm$core$Maybe$Nothing : $elm$core$Maybe$Just(value))); } else { return $elm$core$Result$Err( 'Put not { key, value }: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'ListKeysTag': var _v6 = A2( $elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$labeledStringDecoder('prefix'), args); if (_v6.$ === 'Ok') { var _v7 = _v6.a; var label = _v7.a; var prefix = _v7.b; return $elm$core$Result$Ok( A2($billstclair$elm_localstorage$PortFunnel$InternalTypes$ListKeys, label, prefix)); } else { return $elm$core$Result$Err( 'ListKeys prefix not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'KeysTag': var _v8 = A2($elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$keysDecoder, args); if (_v8.$ === 'Ok') { var label = _v8.a.label; var prefix = _v8.a.prefix; var keys = _v8.a.keys; return $elm$core$Result$Ok( A3($billstclair$elm_localstorage$PortFunnel$InternalTypes$Keys, label, prefix, keys)); } else { return $elm$core$Result$Err( 'Keys not { prefix, keys }: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'ClearTag': var _v9 = A2($elm$json$Json$Decode$decodeValue, $elm$json$Json$Decode$string, args); if (_v9.$ === 'Ok') { var prefix = _v9.a; return $elm$core$Result$Ok( $billstclair$elm_localstorage$PortFunnel$InternalTypes$Clear(prefix)); } else { return $elm$core$Result$Err( 'Clear prefix not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'StartupTag': return $elm$core$Result$Ok($billstclair$elm_localstorage$PortFunnel$InternalTypes$Startup); case 'SimulateGetTag': var _v10 = A2( $elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$labeledStringDecoder('key'), args); if (_v10.$ === 'Ok') { var _v11 = _v10.a; var label = _v11.a; var key = _v11.b; return $elm$core$Result$Ok( A2($billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateGet, label, key)); } else { return $elm$core$Result$Err( 'Get key not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'SimulatePutTag': var _v12 = A2($elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$putDecoder, args); if (_v12.$ === 'Ok') { var key = _v12.a.key; var value = _v12.a.value; return $elm$core$Result$Ok( A2( $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulatePut, key, _Utils_eq(value, $elm$json$Json$Encode$null) ? $elm$core$Maybe$Nothing : $elm$core$Maybe$Just(value))); } else { return $elm$core$Result$Err( 'SimulatePut not { key, value }: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'SimulateListKeysTag': var _v13 = A2( $elm$json$Json$Decode$decodeValue, $billstclair$elm_localstorage$PortFunnel$LocalStorage$labeledStringDecoder('prefix'), args); if (_v13.$ === 'Ok') { var _v14 = _v13.a; var label = _v14.a; var prefix = _v14.b; return $elm$core$Result$Ok( A2($billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateListKeys, label, prefix)); } else { return $elm$core$Result$Err( 'SimulateListKeys prefix not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } case 'SimulateClearTag': var _v15 = A2($elm$json$Json$Decode$decodeValue, $elm$json$Json$Decode$string, args); if (_v15.$ === 'Ok') { var prefix = _v15.a; return $elm$core$Result$Ok( $billstclair$elm_localstorage$PortFunnel$InternalTypes$SimulateClear(prefix)); } else { return $elm$core$Result$Err( 'SimulateClear prefix not a string: ' + A2($elm$json$Json$Encode$encode, 0, args)); } default: return $elm$core$Result$Err('Unknown tag: ' + tag); } }; var $billstclair$elm_port_funnel$PortFunnel$GenericMessage = F3( function (moduleName, tag, args) { return {args: args, moduleName: moduleName, tag: tag}; }); var $elm$json$Json$Encode$object = function (pairs) { return _Json_wrap( A3( $elm$core$List$foldl, F2( function (_v0, obj) { var k = _v0.a; var v = _v0.b; return A3(_Json_addField, k, v, obj); }), _Json_emptyObject(_Utils_Tuple0), pairs)); }; var $elm$json$Json$Encode$string = _Json_wrap; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$encodeLabeledString = F3( function (label, string, property) { return $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'label', function () { if (label.$ === 'Just') { var lab = label.a; return $elm$json$Json$Encode$string(lab); } else { return $elm$json$Json$Encode$null; } }()), _Utils_Tuple2( property, $elm$json$Json$Encode$string(string)) ])); }); var $elm$json$Json$Encode$list = F2( function (func, entries) { return _Json_wrap( A3( $elm$core$List$foldl, _Json_addEntry(func), _Json_emptyArray(_Utils_Tuple0), entries)); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName = 'LocalStorage'; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$encode = function (message) { switch (message.$) { case 'Startup': return A3($billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$startupTag, $elm$json$Json$Encode$null); case 'Get': var label = message.a; var key = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$getTag, A3($billstclair$elm_localstorage$PortFunnel$LocalStorage$encodeLabeledString, label, key, 'key')); case 'Got': var label = message.a; var key = message.b; var value = message.c; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$gotTag, $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'label', function () { if (label.$ === 'Just') { var lab = label.a; return $elm$json$Json$Encode$string(lab); } else { return $elm$json$Json$Encode$null; } }()), _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'value', function () { if (value.$ === 'Nothing') { return $elm$json$Json$Encode$null; } else { var v = value.a; return v; } }()) ]))); case 'Put': var key = message.a; var value = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$putTag, $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'value', function () { if (value.$ === 'Nothing') { return $elm$json$Json$Encode$null; } else { var v = value.a; return v; } }()) ]))); case 'ListKeys': var label = message.a; var prefix = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$listKeysTag, A3($billstclair$elm_localstorage$PortFunnel$LocalStorage$encodeLabeledString, label, prefix, 'prefix')); case 'Keys': var label = message.a; var prefix = message.b; var keys = message.c; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$keysTag, $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'label', function () { if (label.$ === 'Just') { var lab = label.a; return $elm$json$Json$Encode$string(lab); } else { return $elm$json$Json$Encode$null; } }()), _Utils_Tuple2( 'prefix', $elm$json$Json$Encode$string(prefix)), _Utils_Tuple2( 'keys', A2($elm$json$Json$Encode$list, $elm$json$Json$Encode$string, keys)) ]))); case 'Clear': var prefix = message.a; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$clearTag, $elm$json$Json$Encode$string(prefix)); case 'SimulateGet': var label = message.a; var key = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateGetTag, A3($billstclair$elm_localstorage$PortFunnel$LocalStorage$encodeLabeledString, label, key, 'key')); case 'SimulatePut': var key = message.a; var value = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulatePutTag, $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'value', function () { if (value.$ === 'Nothing') { return $elm$json$Json$Encode$null; } else { var v = value.a; return v; } }()) ]))); case 'SimulateListKeys': var label = message.a; var prefix = message.b; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateListKeysTag, A3($billstclair$elm_localstorage$PortFunnel$LocalStorage$encodeLabeledString, label, prefix, 'prefix')); default: var prefix = message.a; return A3( $billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$simulateClearTag, $elm$json$Json$Encode$string(prefix)); } }; var $billstclair$elm_port_funnel$PortFunnel$ModuleDesc = function (a) { return {$: 'ModuleDesc', a: a}; }; var $billstclair$elm_port_funnel$PortFunnel$ModuleDescRecord = F4( function (moduleName, encoder, decoder, process) { return {decoder: decoder, encoder: encoder, moduleName: moduleName, process: process}; }); var $billstclair$elm_port_funnel$PortFunnel$makeModuleDesc = F4( function (name, encoder, decoder, processor) { return $billstclair$elm_port_funnel$PortFunnel$ModuleDesc( A4($billstclair$elm_port_funnel$PortFunnel$ModuleDescRecord, name, encoder, decoder, processor)); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$GetResponse = function (a) { return {$: 'GetResponse', a: a}; }; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$ListKeysResponse = function (a) { return {$: 'ListKeysResponse', a: a}; }; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$NoResponse = {$: 'NoResponse'}; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$State = function (a) { return {$: 'State', a: a}; }; var $elm$core$Dict$getMin = function (dict) { getMin: while (true) { if ((dict.$ === 'RBNode_elm_builtin') && (dict.d.$ === 'RBNode_elm_builtin')) { var left = dict.d; var $temp$dict = left; dict = $temp$dict; continue getMin; } else { return dict; } } }; var $elm$core$Dict$moveRedLeft = function (dict) { if (((dict.$ === 'RBNode_elm_builtin') && (dict.d.$ === 'RBNode_elm_builtin')) && (dict.e.$ === 'RBNode_elm_builtin')) { if ((dict.e.d.$ === 'RBNode_elm_builtin') && (dict.e.d.a.$ === 'Red')) { var clr = dict.a; var k = dict.b; var v = dict.c; var _v1 = dict.d; var lClr = _v1.a; var lK = _v1.b; var lV = _v1.c; var lLeft = _v1.d; var lRight = _v1.e; var _v2 = dict.e; var rClr = _v2.a; var rK = _v2.b; var rV = _v2.c; var rLeft = _v2.d; var _v3 = rLeft.a; var rlK = rLeft.b; var rlV = rLeft.c; var rlL = rLeft.d; var rlR = rLeft.e; var rRight = _v2.e; return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rlK, rlV, A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, lLeft, lRight), rlL), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, rK, rV, rlR, rRight)); } else { var clr = dict.a; var k = dict.b; var v = dict.c; var _v4 = dict.d; var lClr = _v4.a; var lK = _v4.b; var lV = _v4.c; var lLeft = _v4.d; var lRight = _v4.e; var _v5 = dict.e; var rClr = _v5.a; var rK = _v5.b; var rV = _v5.c; var rLeft = _v5.d; var rRight = _v5.e; if (clr.$ === 'Black') { return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, lLeft, lRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rK, rV, rLeft, rRight)); } else { return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, lLeft, lRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rK, rV, rLeft, rRight)); } } } else { return dict; } }; var $elm$core$Dict$moveRedRight = function (dict) { if (((dict.$ === 'RBNode_elm_builtin') && (dict.d.$ === 'RBNode_elm_builtin')) && (dict.e.$ === 'RBNode_elm_builtin')) { if ((dict.d.d.$ === 'RBNode_elm_builtin') && (dict.d.d.a.$ === 'Red')) { var clr = dict.a; var k = dict.b; var v = dict.c; var _v1 = dict.d; var lClr = _v1.a; var lK = _v1.b; var lV = _v1.c; var _v2 = _v1.d; var _v3 = _v2.a; var llK = _v2.b; var llV = _v2.c; var llLeft = _v2.d; var llRight = _v2.e; var lRight = _v1.e; var _v4 = dict.e; var rClr = _v4.a; var rK = _v4.b; var rV = _v4.c; var rLeft = _v4.d; var rRight = _v4.e; return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, llK, llV, llLeft, llRight), A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, lRight, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rK, rV, rLeft, rRight))); } else { var clr = dict.a; var k = dict.b; var v = dict.c; var _v5 = dict.d; var lClr = _v5.a; var lK = _v5.b; var lV = _v5.c; var lLeft = _v5.d; var lRight = _v5.e; var _v6 = dict.e; var rClr = _v6.a; var rK = _v6.b; var rV = _v6.c; var rLeft = _v6.d; var rRight = _v6.e; if (clr.$ === 'Black') { return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, lLeft, lRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rK, rV, rLeft, rRight)); } else { return A5( $elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, lK, lV, lLeft, lRight), A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, rK, rV, rLeft, rRight)); } } } else { return dict; } }; var $elm$core$Dict$removeHelpPrepEQGT = F7( function (targetKey, dict, color, key, value, left, right) { if ((left.$ === 'RBNode_elm_builtin') && (left.a.$ === 'Red')) { var _v1 = left.a; var lK = left.b; var lV = left.c; var lLeft = left.d; var lRight = left.e; return A5( $elm$core$Dict$RBNode_elm_builtin, color, lK, lV, lLeft, A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Red, key, value, lRight, right)); } else { _v2$2: while (true) { if ((right.$ === 'RBNode_elm_builtin') && (right.a.$ === 'Black')) { if (right.d.$ === 'RBNode_elm_builtin') { if (right.d.a.$ === 'Black') { var _v3 = right.a; var _v4 = right.d; var _v5 = _v4.a; return $elm$core$Dict$moveRedRight(dict); } else { break _v2$2; } } else { var _v6 = right.a; var _v7 = right.d; return $elm$core$Dict$moveRedRight(dict); } } else { break _v2$2; } } return dict; } }); var $elm$core$Dict$removeMin = function (dict) { if ((dict.$ === 'RBNode_elm_builtin') && (dict.d.$ === 'RBNode_elm_builtin')) { var color = dict.a; var key = dict.b; var value = dict.c; var left = dict.d; var lColor = left.a; var lLeft = left.d; var right = dict.e; if (lColor.$ === 'Black') { if ((lLeft.$ === 'RBNode_elm_builtin') && (lLeft.a.$ === 'Red')) { var _v3 = lLeft.a; return A5( $elm$core$Dict$RBNode_elm_builtin, color, key, value, $elm$core$Dict$removeMin(left), right); } else { var _v4 = $elm$core$Dict$moveRedLeft(dict); if (_v4.$ === 'RBNode_elm_builtin') { var nColor = _v4.a; var nKey = _v4.b; var nValue = _v4.c; var nLeft = _v4.d; var nRight = _v4.e; return A5( $elm$core$Dict$balance, nColor, nKey, nValue, $elm$core$Dict$removeMin(nLeft), nRight); } else { return $elm$core$Dict$RBEmpty_elm_builtin; } } } else { return A5( $elm$core$Dict$RBNode_elm_builtin, color, key, value, $elm$core$Dict$removeMin(left), right); } } else { return $elm$core$Dict$RBEmpty_elm_builtin; } }; var $elm$core$Dict$removeHelp = F2( function (targetKey, dict) { if (dict.$ === 'RBEmpty_elm_builtin') { return $elm$core$Dict$RBEmpty_elm_builtin; } else { var color = dict.a; var key = dict.b; var value = dict.c; var left = dict.d; var right = dict.e; if (_Utils_cmp(targetKey, key) < 0) { if ((left.$ === 'RBNode_elm_builtin') && (left.a.$ === 'Black')) { var _v4 = left.a; var lLeft = left.d; if ((lLeft.$ === 'RBNode_elm_builtin') && (lLeft.a.$ === 'Red')) { var _v6 = lLeft.a; return A5( $elm$core$Dict$RBNode_elm_builtin, color, key, value, A2($elm$core$Dict$removeHelp, targetKey, left), right); } else { var _v7 = $elm$core$Dict$moveRedLeft(dict); if (_v7.$ === 'RBNode_elm_builtin') { var nColor = _v7.a; var nKey = _v7.b; var nValue = _v7.c; var nLeft = _v7.d; var nRight = _v7.e; return A5( $elm$core$Dict$balance, nColor, nKey, nValue, A2($elm$core$Dict$removeHelp, targetKey, nLeft), nRight); } else { return $elm$core$Dict$RBEmpty_elm_builtin; } } } else { return A5( $elm$core$Dict$RBNode_elm_builtin, color, key, value, A2($elm$core$Dict$removeHelp, targetKey, left), right); } } else { return A2( $elm$core$Dict$removeHelpEQGT, targetKey, A7($elm$core$Dict$removeHelpPrepEQGT, targetKey, dict, color, key, value, left, right)); } } }); var $elm$core$Dict$removeHelpEQGT = F2( function (targetKey, dict) { if (dict.$ === 'RBNode_elm_builtin') { var color = dict.a; var key = dict.b; var value = dict.c; var left = dict.d; var right = dict.e; if (_Utils_eq(targetKey, key)) { var _v1 = $elm$core$Dict$getMin(right); if (_v1.$ === 'RBNode_elm_builtin') { var minKey = _v1.b; var minValue = _v1.c; return A5( $elm$core$Dict$balance, color, minKey, minValue, left, $elm$core$Dict$removeMin(right)); } else { return $elm$core$Dict$RBEmpty_elm_builtin; } } else { return A5( $elm$core$Dict$balance, color, key, value, left, A2($elm$core$Dict$removeHelp, targetKey, right)); } } else { return $elm$core$Dict$RBEmpty_elm_builtin; } }); var $elm$core$Dict$remove = F2( function (key, dict) { var _v0 = A2($elm$core$Dict$removeHelp, key, dict); if ((_v0.$ === 'RBNode_elm_builtin') && (_v0.a.$ === 'Red')) { var _v1 = _v0.a; var k = _v0.b; var v = _v0.c; var l = _v0.d; var r = _v0.e; return A5($elm$core$Dict$RBNode_elm_builtin, $elm$core$Dict$Black, k, v, l, r); } else { var x = _v0; return x; } }); var $elm$core$Dict$foldl = F3( function (func, acc, dict) { foldl: while (true) { if (dict.$ === 'RBEmpty_elm_builtin') { return acc; } else { var key = dict.b; var value = dict.c; var left = dict.d; var right = dict.e; var $temp$func = func, $temp$acc = A3( func, key, value, A3($elm$core$Dict$foldl, func, acc, left)), $temp$dict = right; func = $temp$func; acc = $temp$acc; dict = $temp$dict; continue foldl; } } }); var $elm$core$Dict$filter = F2( function (isGood, dict) { return A3( $elm$core$Dict$foldl, F3( function (k, v, d) { return A2(isGood, k, v) ? A3($elm$core$Dict$insert, k, v, d) : d; }), $elm$core$Dict$empty, dict); }); var $elm_community$dict_extra$Dict$Extra$removeWhen = F2( function (pred, dict) { return A2( $elm$core$Dict$filter, F2( function (k, v) { return !A2(pred, k, v); }), dict); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix = F2( function (prefix, key) { return (prefix === '') ? key : A2( $elm$core$String$dropLeft, 1 + $elm$core$String$length(prefix), key); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$process = F2( function (message, boxedState) { var state = boxedState.a; switch (message.$) { case 'Got': var label = message.a; var key = message.b; var value = message.c; return _Utils_Tuple2( boxedState, $billstclair$elm_localstorage$PortFunnel$LocalStorage$GetResponse( { key: A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix, state.prefix, key), label: label, value: value })); case 'Keys': var label = message.a; var prefix = message.b; var keys = message.c; return _Utils_Tuple2( boxedState, $billstclair$elm_localstorage$PortFunnel$LocalStorage$ListKeysResponse( { keys: A2( $elm$core$List$map, $billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix(state.prefix), keys), label: label, prefix: A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix, state.prefix, prefix) })); case 'Startup': return _Utils_Tuple2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$State( _Utils_update( state, {isLoaded: true})), $billstclair$elm_localstorage$PortFunnel$LocalStorage$NoResponse); case 'SimulateGet': var label = message.a; var key = message.b; return _Utils_Tuple2( boxedState, $billstclair$elm_localstorage$PortFunnel$LocalStorage$GetResponse( { key: A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix, state.prefix, key), label: label, value: A2($elm$core$Dict$get, key, state.simulationDict) })); case 'SimulatePut': var key = message.a; var value = message.b; return _Utils_Tuple2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$State( _Utils_update( state, { simulationDict: function () { if (value.$ === 'Nothing') { return A2($elm$core$Dict$remove, key, state.simulationDict); } else { var v = value.a; return A3($elm$core$Dict$insert, key, v, state.simulationDict); } }() })), $billstclair$elm_localstorage$PortFunnel$LocalStorage$NoResponse); case 'SimulateListKeys': var label = message.a; var prefix = message.b; return _Utils_Tuple2( boxedState, $billstclair$elm_localstorage$PortFunnel$LocalStorage$ListKeysResponse( { keys: A3( $elm$core$Dict$foldr, F3( function (k, _v2, res) { return A2($elm$core$String$startsWith, prefix, k) ? A2( $elm$core$List$cons, A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix, state.prefix, k), res) : res; }), _List_Nil, state.simulationDict), label: label, prefix: A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$stripPrefix, state.prefix, prefix) })); case 'SimulateClear': var prefix = message.a; return _Utils_Tuple2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$State( _Utils_update( state, { simulationDict: A2( $elm_community$dict_extra$Dict$Extra$removeWhen, F2( function (k, _v3) { return A2($elm$core$String$startsWith, prefix, k); }), state.simulationDict) })), $billstclair$elm_localstorage$PortFunnel$LocalStorage$NoResponse); default: return _Utils_Tuple2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$State(state), $billstclair$elm_localstorage$PortFunnel$LocalStorage$NoResponse); } }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleDesc = A4($billstclair$elm_port_funnel$PortFunnel$makeModuleDesc, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $billstclair$elm_localstorage$PortFunnel$LocalStorage$encode, $billstclair$elm_localstorage$PortFunnel$LocalStorage$decode, $billstclair$elm_localstorage$PortFunnel$LocalStorage$process); var $billstclair$elm_port_funnel$PortFunnel$encodeGenericMessage = function (message) { return $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'module', $elm$json$Json$Encode$string(message.moduleName)), _Utils_Tuple2( 'tag', $elm$json$Json$Encode$string(message.tag)), _Utils_Tuple2('args', message.args) ])); }; var $billstclair$elm_port_funnel$PortFunnel$messageToValue = F2( function (_v0, message) { var moduleDesc = _v0.a; return $billstclair$elm_port_funnel$PortFunnel$encodeGenericMessage( moduleDesc.encoder(message)); }); var $billstclair$elm_port_funnel$PortFunnel$sendMessage = F3( function (moduleDesc, cmdPort, message) { return cmdPort( A2($billstclair$elm_port_funnel$PortFunnel$messageToValue, moduleDesc, message)); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$send = F3( function (wrapper, message, _v0) { var state = _v0.a; var prefix = state.prefix; var mess = function () { switch (message.$) { case 'Get': var label = message.a; var key = message.b; return A2( $billstclair$elm_localstorage$PortFunnel$InternalTypes$Get, label, A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$addPrefix, prefix, key)); case 'Put': var key = message.a; var value = message.b; return A2( $billstclair$elm_localstorage$PortFunnel$InternalTypes$Put, A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$addPrefix, prefix, key), value); case 'ListKeys': var label = message.a; var pref = message.b; return A2( $billstclair$elm_localstorage$PortFunnel$InternalTypes$ListKeys, label, A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$addPrefix, prefix, pref)); case 'Clear': var pref = message.a; return $billstclair$elm_localstorage$PortFunnel$InternalTypes$Clear( A2($billstclair$elm_localstorage$PortFunnel$LocalStorage$addPrefix, prefix, pref)); default: return message; } }(); return A3($billstclair$elm_port_funnel$PortFunnel$sendMessage, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleDesc, wrapper, mess); }); var $author$project$Main$sendLocalStorage = F2( function (model, message) { return A3($billstclair$elm_localstorage$PortFunnel$LocalStorage$send, $author$project$Main$cmdPort, message, model.funnelState.storage); }); var $author$project$Main$getLocalStorageString = F2( function (model, key) { return A2( $author$project$Main$sendLocalStorage, model, $billstclair$elm_localstorage$PortFunnel$LocalStorage$get(key)); }); var $elm$core$Maybe$andThen = F2( function (callback, maybeValue) { if (maybeValue.$ === 'Just') { var value = maybeValue.a; return callback(value); } else { return $elm$core$Maybe$Nothing; } }); var $author$project$Main$getURLGameId = function (url) { return A2( $elm$core$Maybe$andThen, function (f) { return (f === '') ? $elm$core$Maybe$Nothing : $elm$core$Maybe$Just(f); }, url.fragment); }; var $billstclair$elm_localstorage$PortFunnel$LocalStorage$initialState = function (prefix) { return $billstclair$elm_localstorage$PortFunnel$LocalStorage$State( {isLoaded: false, prefix: prefix, simulationDict: $elm$core$Dict$empty}); }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$State = function (a) { return {$: 'State', a: a}; }; var $elm$core$Set$Set_elm_builtin = function (a) { return {$: 'Set_elm_builtin', a: a}; }; var $elm$core$Set$empty = $elm$core$Set$Set_elm_builtin($elm$core$Dict$empty); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$initialState = $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( {continuationCounter: 0, continuations: $elm$core$Dict$empty, isLoaded: false, noAutoReopenKeys: $elm$core$Set$empty, queues: $elm$core$Dict$empty, socketStates: $elm$core$Dict$empty}); var $author$project$PortFunnels$initialState = function (prefix) { return { storage: $billstclair$elm_localstorage$PortFunnel$LocalStorage$initialState(prefix), websocket: $billstclair$elm_websocket_client$PortFunnel$WebSocket$initialState }; }; var $author$project$Main$init = F3( function (flags, url, key) { var formFields = { gameId: function () { var _v0 = $author$project$Main$getURLGameId(url); if (_v0.$ === 'Just') { var f = _v0.a; return f; } else { return ''; } }(), text: '', username: '', usernamePlaceholder: '' }; var model = $author$project$Main$Model(key)(url)($author$project$Protocol$NoGame)($elm$core$Maybe$Nothing)(false)($elm$core$Maybe$Nothing)($elm$core$Array$empty)($elm$core$Maybe$Nothing)($elm$core$Maybe$Nothing)($elm$core$Maybe$Nothing)($elm$core$Maybe$Nothing)(0)(true)($elm$core$Maybe$Nothing)( $author$project$PortFunnels$initialState('drawtice'))(formFields)($elm$core$Dict$empty)(0)($elm$core$Maybe$Nothing); return _Utils_Tuple2( model, $elm$core$Platform$Cmd$batch( _List_fromArray( [ A2($elm$core$Task$perform, $author$project$Main$Tick, $elm$time$Time$now), A2( $elm$random$Random$generate, $author$project$Main$SetField($author$project$Main$UsernamePlaceholder), $author$project$Names$generator), A2($author$project$Main$getLocalStorageString, model, 'username') ]))); }); var $author$project$Main$AutoSubmit = function (a) { return {$: 'AutoSubmit', a: a}; }; var $author$project$Main$SendImage = F2( function (a, b) { return {$: 'SendImage', a: a, b: b}; }); var $author$project$Main$ShownConfirmDialog = function (a) { return {$: 'ShownConfirmDialog', a: a}; }; var $elm$core$Platform$Sub$batch = _Platform_batch; var $elm$json$Json$Decode$andThen = _Json_andThen; var $elm$json$Json$Decode$index = _Json_decodeIndex; var $author$project$Main$canvasReturnPort = _Platform_incomingPort( 'canvasReturnPort', A2( $elm$json$Json$Decode$andThen, function (_v0) { return A2( $elm$json$Json$Decode$andThen, function (_v1) { return $elm$json$Json$Decode$succeed( _Utils_Tuple2(_v0, _v1)); }, A2($elm$json$Json$Decode$index, 1, $elm$json$Json$Decode$string)); }, A2($elm$json$Json$Decode$index, 0, $elm$json$Json$Decode$string))); var $elm$json$Json$Decode$bool = _Json_decodeBool; var $elm$json$Json$Decode$int = _Json_decodeInt; var $author$project$Main$confirmReturnPort = _Platform_incomingPort( 'confirmReturnPort', A2( $elm$json$Json$Decode$andThen, function (_v0) { return A2( $elm$json$Json$Decode$andThen, function (_v1) { return $elm$json$Json$Decode$succeed( _Utils_Tuple2(_v0, _v1)); }, A2($elm$json$Json$Decode$index, 1, $elm$json$Json$Decode$int)); }, A2($elm$json$Json$Decode$index, 0, $elm$json$Json$Decode$bool))); var $elm$time$Time$Every = F2( function (a, b) { return {$: 'Every', a: a, b: b}; }); var $elm$time$Time$State = F2( function (taggers, processes) { return {processes: processes, taggers: taggers}; }); var $elm$time$Time$init = $elm$core$Task$succeed( A2($elm$time$Time$State, $elm$core$Dict$empty, $elm$core$Dict$empty)); var $elm$time$Time$addMySub = F2( function (_v0, state) { var interval = _v0.a; var tagger = _v0.b; var _v1 = A2($elm$core$Dict$get, interval, state); if (_v1.$ === 'Nothing') { return A3( $elm$core$Dict$insert, interval, _List_fromArray( [tagger]), state); } else { var taggers = _v1.a; return A3( $elm$core$Dict$insert, interval, A2($elm$core$List$cons, tagger, taggers), state); } }); var $elm$core$Process$kill = _Scheduler_kill; var $elm$core$Dict$merge = F6( function (leftStep, bothStep, rightStep, leftDict, rightDict, initialResult) { var stepState = F3( function (rKey, rValue, _v0) { stepState: while (true) { var list = _v0.a; var result = _v0.b; if (!list.b) { return _Utils_Tuple2( list, A3(rightStep, rKey, rValue, result)); } else { var _v2 = list.a; var lKey = _v2.a; var lValue = _v2.b; var rest = list.b; if (_Utils_cmp(lKey, rKey) < 0) { var $temp$rKey = rKey, $temp$rValue = rValue, $temp$_v0 = _Utils_Tuple2( rest, A3(leftStep, lKey, lValue, result)); rKey = $temp$rKey; rValue = $temp$rValue; _v0 = $temp$_v0; continue stepState; } else { if (_Utils_cmp(lKey, rKey) > 0) { return _Utils_Tuple2( list, A3(rightStep, rKey, rValue, result)); } else { return _Utils_Tuple2( rest, A4(bothStep, lKey, lValue, rValue, result)); } } } } }); var _v3 = A3( $elm$core$Dict$foldl, stepState, _Utils_Tuple2( $elm$core$Dict$toList(leftDict), initialResult), rightDict); var leftovers = _v3.a; var intermediateResult = _v3.b; return A3( $elm$core$List$foldl, F2( function (_v4, result) { var k = _v4.a; var v = _v4.b; return A3(leftStep, k, v, result); }), intermediateResult, leftovers); }); var $elm$core$Platform$sendToSelf = _Platform_sendToSelf; var $elm$time$Time$setInterval = _Time_setInterval; var $elm$core$Process$spawn = _Scheduler_spawn; var $elm$time$Time$spawnHelp = F3( function (router, intervals, processes) { if (!intervals.b) { return $elm$core$Task$succeed(processes); } else { var interval = intervals.a; var rest = intervals.b; var spawnTimer = $elm$core$Process$spawn( A2( $elm$time$Time$setInterval, interval, A2($elm$core$Platform$sendToSelf, router, interval))); var spawnRest = function (id) { return A3( $elm$time$Time$spawnHelp, router, rest, A3($elm$core$Dict$insert, interval, id, processes)); }; return A2($elm$core$Task$andThen, spawnRest, spawnTimer); } }); var $elm$time$Time$onEffects = F3( function (router, subs, _v0) { var processes = _v0.processes; var rightStep = F3( function (_v6, id, _v7) { var spawns = _v7.a; var existing = _v7.b; var kills = _v7.c; return _Utils_Tuple3( spawns, existing, A2( $elm$core$Task$andThen, function (_v5) { return kills; }, $elm$core$Process$kill(id))); }); var newTaggers = A3($elm$core$List$foldl, $elm$time$Time$addMySub, $elm$core$Dict$empty, subs); var leftStep = F3( function (interval, taggers, _v4) { var spawns = _v4.a; var existing = _v4.b; var kills = _v4.c; return _Utils_Tuple3( A2($elm$core$List$cons, interval, spawns), existing, kills); }); var bothStep = F4( function (interval, taggers, id, _v3) { var spawns = _v3.a; var existing = _v3.b; var kills = _v3.c; return _Utils_Tuple3( spawns, A3($elm$core$Dict$insert, interval, id, existing), kills); }); var _v1 = A6( $elm$core$Dict$merge, leftStep, bothStep, rightStep, newTaggers, processes, _Utils_Tuple3( _List_Nil, $elm$core$Dict$empty, $elm$core$Task$succeed(_Utils_Tuple0))); var spawnList = _v1.a; var existingDict = _v1.b; var killTask = _v1.c; return A2( $elm$core$Task$andThen, function (newProcesses) { return $elm$core$Task$succeed( A2($elm$time$Time$State, newTaggers, newProcesses)); }, A2( $elm$core$Task$andThen, function (_v2) { return A3($elm$time$Time$spawnHelp, router, spawnList, existingDict); }, killTask)); }); var $elm$time$Time$onSelfMsg = F3( function (router, interval, state) { var _v0 = A2($elm$core$Dict$get, interval, state.taggers); if (_v0.$ === 'Nothing') { return $elm$core$Task$succeed(state); } else { var taggers = _v0.a; var tellTaggers = function (time) { return $elm$core$Task$sequence( A2( $elm$core$List$map, function (tagger) { return A2( $elm$core$Platform$sendToApp, router, tagger(time)); }, taggers)); }; return A2( $elm$core$Task$andThen, function (_v1) { return $elm$core$Task$succeed(state); }, A2($elm$core$Task$andThen, tellTaggers, $elm$time$Time$now)); } }); var $elm$core$Basics$composeL = F3( function (g, f, x) { return g( f(x)); }); var $elm$time$Time$subMap = F2( function (f, _v0) { var interval = _v0.a; var tagger = _v0.b; return A2( $elm$time$Time$Every, interval, A2($elm$core$Basics$composeL, f, tagger)); }); _Platform_effectManagers['Time'] = _Platform_createManager($elm$time$Time$init, $elm$time$Time$onEffects, $elm$time$Time$onSelfMsg, 0, $elm$time$Time$subMap); var $elm$time$Time$subscription = _Platform_leaf('Time'); var $elm$time$Time$every = F2( function (interval, tagger) { return $elm$time$Time$subscription( A2($elm$time$Time$Every, interval, tagger)); }); var $author$project$Protocol$Manual = {$: 'Manual'}; var $author$project$Protocol$Periodic = {$: 'Periodic'}; var $author$project$Protocol$Rollcall = {$: 'Rollcall'}; var $author$project$Protocol$packageSourceFromString = function (string) { switch (string) { case 'Manual': return $author$project$Protocol$Manual; case 'Periodic': return $author$project$Protocol$Periodic; case 'Rollcall': return $author$project$Protocol$Rollcall; default: return $author$project$Protocol$Manual; } }; var $elm$core$Tuple$second = function (_v0) { var y = _v0.b; return y; }; var $author$project$PortFunnels$subPort = _Platform_incomingPort('subPort', $elm$json$Json$Decode$value); var $author$project$PortFunnels$subscriptions = F2( function (process, model) { return $author$project$PortFunnels$subPort(process); }); var $author$project$Main$subscriptions = function (model) { return $elm$core$Platform$Sub$batch( _List_fromArray( [ A2($elm$time$Time$every, 1000, $author$project$Main$Tick), A2($elm$time$Time$every, 7000, $author$project$Main$AutoSubmit), A2($author$project$PortFunnels$subscriptions, $author$project$Main$Receive, model), $author$project$Main$confirmReturnPort($author$project$Main$ShownConfirmDialog), $author$project$Main$canvasReturnPort( function (r) { return A2( $author$project$Main$SendImage, r.a, $author$project$Protocol$packageSourceFromString(r.b)); }) ])); }; var $author$project$Protocol$ErrorResponse = function (a) { return {$: 'ErrorResponse', a: a}; }; var $author$project$Protocol$ExtendDeadlineCommand = function (a) { return {$: 'ExtendDeadlineCommand', a: a}; }; var $author$project$Main$GameIdField = {$: 'GameIdField'}; var $author$project$Protocol$GameOver = {$: 'GameOver'}; var $author$project$Protocol$ImagePackage = function (a) { return {$: 'ImagePackage', a: a}; }; var $author$project$Protocol$ImagePackageCommand = F2( function (a, b) { return {$: 'ImagePackageCommand', a: a, b: b}; }); var $author$project$Protocol$JoinCommand = F2( function (a, b) { return {$: 'JoinCommand', a: a, b: b}; }); var $author$project$Protocol$KickCommand = function (a) { return {$: 'KickCommand', a: a}; }; var $author$project$Protocol$LeaveCommand = {$: 'LeaveCommand'}; var $author$project$Protocol$LeftGameResponse = {$: 'LeftGameResponse'}; var $author$project$PortFunnels$LocalStorageHandler = function (a) { return {$: 'LocalStorageHandler', a: a}; }; var $author$project$Protocol$NewGameCommand = function (a) { return {$: 'NewGameCommand', a: a}; }; var $author$project$Protocol$NextRoundCommand = {$: 'NextRoundCommand'}; var $author$project$Main$NoAction = {$: 'NoAction'}; var $author$project$Protocol$RestartGameCommand = {$: 'RestartGameCommand'}; var $author$project$Main$SocketReceive = function (a) { return {$: 'SocketReceive', a: a}; }; var $author$project$Protocol$StartCommand = {$: 'StartCommand'}; var $author$project$Main$StorageReceive = F2( function (a, b) { return {$: 'StorageReceive', a: a, b: b}; }); var $author$project$Protocol$Stuck = {$: 'Stuck'}; var $author$project$Protocol$TextPackage = function (a) { return {$: 'TextPackage', a: a}; }; var $author$project$Protocol$TextPackageCommand = F2( function (a, b) { return {$: 'TextPackageCommand', a: a, b: b}; }); var $author$project$Main$UsernameField = {$: 'UsernameField'}; var $author$project$Protocol$UuidCommand = function (a) { return {$: 'UuidCommand', a: a}; }; var $author$project$PortFunnels$WebSocketHandler = function (a) { return {$: 'WebSocketHandler', a: a}; }; var $author$project$Protocol$Working = function (a) { return {$: 'Working', a: a}; }; var $Janiczek$cmd_extra$Cmd$Extra$addCmd = F2( function (cmd, _v0) { var model = _v0.a; var oldCmd = _v0.b; return _Utils_Tuple2( model, $elm$core$Platform$Cmd$batch( _List_fromArray( [oldCmd, cmd]))); }); var $elm$core$Maybe$destruct = F3( function (_default, func, maybe) { if (maybe.$ === 'Just') { var a = maybe.a; return func(a); } else { return _default; } }); var $author$project$Main$canvasPort = _Platform_outgoingPort( 'canvasPort', function ($) { var a = $.a; var b = $.b; return A2( $elm$json$Json$Encode$list, $elm$core$Basics$identity, _List_fromArray( [ $elm$json$Json$Encode$string(a), function ($) { return A3($elm$core$Maybe$destruct, $elm$json$Json$Encode$null, $elm$json$Json$Encode$string, $); }(b) ])); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCodeToString = function (code) { switch (code.$) { case 'NormalClosure': return 'Normal'; case 'GoingAwayClosure': return 'GoingAway'; case 'ProtocolErrorClosure': return 'ProtocolError'; case 'UnsupportedDataClosure': return 'UnsupportedData'; case 'NoStatusRecvdClosure': return 'NoStatusRecvd'; case 'AbnormalClosure': return 'Abnormal'; case 'InvalidFramePayloadDataClosure': return 'InvalidFramePayloadData'; case 'PolicyViolationClosure': return 'PolicyViolation'; case 'MessageTooBigClosure': return 'MessageTooBig'; case 'MissingExtensionClosure': return 'MissingExtension'; case 'InternalErrorClosure': return 'InternalError'; case 'ServiceRestartClosure': return 'ServiceRestart'; case 'TryAgainLaterClosure': return 'TryAgainLater'; case 'BadGatewayClosure': return 'BadGateway'; case 'TLSHandshakeClosure': return 'TLSHandshake'; case 'TimedOutOnReconnect': return 'TimedOutOnReconnect'; default: return 'UnknownClosureCode'; } }; var $elm$json$Json$Encode$int = _Json_wrap; var $author$project$Main$confirmPort = _Platform_outgoingPort( 'confirmPort', function ($) { var a = $.a; var b = $.b; return A2( $elm$json$Json$Encode$list, $elm$core$Basics$identity, _List_fromArray( [ $elm$json$Json$Encode$string(a), $elm$json$Json$Encode$int(b) ])); }); var $elm$json$Json$Decode$decodeString = _Json_runOnString; var $author$project$Main$ShowError = function (a) { return {$: 'ShowError', a: a}; }; var $author$project$Main$errorPort = _Platform_outgoingPort('errorPort', $elm$json$Json$Encode$string); var $author$project$Main$errorLog = function (message) { return $elm$core$Platform$Cmd$batch( _List_fromArray( [ $author$project$Main$errorPort(message), A2( $elm$core$Task$perform, $author$project$Main$ShowError, $elm$core$Task$succeed(message)) ])); }; var $author$project$Protocol$errorParser = _Utils_Tuple2( $elm$json$Json$Decode$string, function (s) { return $author$project$Protocol$ErrorResponse(s); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeStringToString = function (string) { if (string.$ === 'Nothing') { return 'Nothing'; } else { var s = string.a; return 'Just \"' + (s + '\"'); } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeString = function (s) { if (s.$ === 'Nothing') { return 'Nothing'; } else { var string = s.a; return 'Just ' + string; } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$toString = function (mess) { switch (mess.$) { case 'Startup': return '<Startup>'; case 'PWillOpen': var key = mess.a.key; var url = mess.a.url; var keepAlive = mess.a.keepAlive; return 'PWillOpen { key = \"' + (key + ('\", url = \"' + (url + ('\", keepAlive = ' + (keepAlive ? 'True' : ('False' + '}')))))); case 'POOpen': var key = mess.a.key; var url = mess.a.url; return 'POOpen { key = \"' + (key + ('\", url = \"' + (url + '\"}'))); case 'PIConnected': var key = mess.a.key; var description = mess.a.description; return 'PIConnected { key = \"' + (key + ('\", description = \"' + (description + '\"}'))); case 'PWillSend': var key = mess.a.key; var message = mess.a.message; return 'PWillSend { key = \"' + (key + ('\", message = \"' + (message + '\"}'))); case 'POSend': var key = mess.a.key; var message = mess.a.message; return 'POSend { key = \"' + (key + ('\", message = \"' + (message + '\"}'))); case 'PIMessageReceived': var key = mess.a.key; var message = mess.a.message; return 'PIMessageReceived { key = \"' + (key + ('\", message = \"' + (message + '\"}'))); case 'PWillClose': var key = mess.a.key; var reason = mess.a.reason; return 'PWillClose { key = \"' + (key + ('\", reason = \"' + (reason + '\"}'))); case 'POClose': var key = mess.a.key; var reason = mess.a.reason; return 'POClose { key = \"' + (key + ('\", reason = \"' + (reason + '\"}'))); case 'PIClosed': var key = mess.a.key; var bytesQueued = mess.a.bytesQueued; var code = mess.a.code; var reason = mess.a.reason; var wasClean = mess.a.wasClean; return 'PIClosed { key = \"' + (key + ('\", bytesQueued = \"' + ($elm$core$String$fromInt(bytesQueued) + ('\", code = \"' + ($elm$core$String$fromInt(code) + ('\", reason = \"' + (reason + ('\", wasClean = \"' + (wasClean ? 'True' : ('False' + '\"}')))))))))); case 'POBytesQueued': var key = mess.a.key; return 'POBytesQueued { key = \"' + (key + '\"}'); case 'PIBytesQueued': var key = mess.a.key; var bufferedAmount = mess.a.bufferedAmount; return 'PIBytesQueued { key = \"' + (key + ('\", bufferedAmount = \"' + ($elm$core$String$fromInt(bufferedAmount) + '\"}'))); case 'PODelay': var millis = mess.a.millis; var id = mess.a.id; return 'PODelay { millis = \"' + ($elm$core$String$fromInt(millis) + ('\" id = \"' + (id + '\"}'))); case 'PIDelayed': var id = mess.a.id; return 'PIDelayed { id = \"' + (id + '\"}'); default: var key = mess.a.key; var code = mess.a.code; var description = mess.a.description; var name = mess.a.name; return 'PIError { key = \"' + ($billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeString(key) + ('\" code = \"' + (code + ('\" description = \"' + (description + ('\" name = \"' + ($billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeString(name) + '\"}'))))))); } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$errorToString = function (theError) { switch (theError.$) { case 'SocketAlreadyOpenError': var key = theError.a; return 'SocketAlreadyOpenError \"' + (key + '\"'); case 'SocketConnectingError': var key = theError.a; return 'SocketConnectingError \"' + (key + '\"'); case 'SocketClosingError': var key = theError.a; return 'SocketClosingError \"' + (key + '\"'); case 'SocketNotOpenError': var key = theError.a; return 'SocketNotOpenError \"' + (key + '\"'); case 'UnexpectedConnectedError': var key = theError.a.key; var description = theError.a.description; return 'UnexpectedConnectedError\n { key = \"' + (key + ('\", description = \"' + (description + '\" }'))); case 'UnexpectedMessageError': var key = theError.a.key; var message = theError.a.message; return 'UnexpectedMessageError { key = \"' + (key + ('\", message = \"' + (message + '\" }'))); case 'LowLevelError': var key = theError.a.key; var code = theError.a.code; var description = theError.a.description; var name = theError.a.name; return 'LowLevelError { key = \"' + ($billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeStringToString(key) + ('\", code = \"' + (code + ('\", description = \"' + (description + ('\", code = \"' + ($billstclair$elm_websocket_client$PortFunnel$WebSocket$maybeStringToString(name) + '\" }'))))))); default: var message = theError.a.message; return 'InvalidMessageError: ' + $billstclair$elm_websocket_client$PortFunnel$WebSocket$toString(message); } }; var $author$project$Protocol$GameDetails = F5( function (alias, status, players, uuid, currentStage) { return {alias: alias, currentStage: currentStage, players: players, status: status, uuid: uuid}; }); var $author$project$Protocol$GameDetailsResponse = function (a) { return {$: 'GameDetailsResponse', a: a}; }; var $author$project$Protocol$Drawing = {$: 'Drawing'}; var $author$project$Protocol$Lobby = {$: 'Lobby'}; var $author$project$Protocol$Starting = {$: 'Starting'}; var $author$project$Protocol$Understanding = {$: 'Understanding'}; var $author$project$Protocol$gameStatusFromString = function (string) { switch (string) { case 'Lobby': return $author$project$Protocol$Lobby; case 'Starting': return $author$project$Protocol$Starting; case 'Drawing': return $author$project$Protocol$Drawing; case 'Understanding': return $author$project$Protocol$Understanding; case 'GameOver': return $author$project$Protocol$GameOver; default: return $author$project$Protocol$Lobby; } }; var $elm$json$Json$Decode$map5 = _Json_map5; var $author$project$Protocol$PlayerDetails = F6( function (username, imageUrl, status, isAdmin, deadline, stuck) { return {deadline: deadline, imageUrl: imageUrl, isAdmin: isAdmin, status: status, stuck: stuck, username: username}; }); var $elm$json$Json$Decode$map6 = _Json_map6; var $author$project$Protocol$Done = {$: 'Done'}; var $author$project$Protocol$Uploading = function (a) { return {$: 'Uploading', a: a}; }; var $author$project$Protocol$playerStatusFromString = function (string) { switch (string) { case 'Done': return $author$project$Protocol$Done; case 'Working': return $author$project$Protocol$Working(0); case 'Uploading': return $author$project$Protocol$Uploading(50); default: return $author$project$Protocol$Stuck; } }; var $author$project$Protocol$playerDecoder = A7( $elm$json$Json$Decode$map6, $author$project$Protocol$PlayerDetails, A2($elm$json$Json$Decode$field, 'username', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'image_url', $elm$json$Json$Decode$string), A2( $elm$json$Json$Decode$field, 'status', A2($elm$json$Json$Decode$map, $author$project$Protocol$playerStatusFromString, $elm$json$Json$Decode$string)), A2($elm$json$Json$Decode$field, 'is_admin', $elm$json$Json$Decode$bool), A2($elm$json$Json$Decode$field, 'deadline', $elm$json$Json$Decode$int), A2($elm$json$Json$Decode$field, 'stuck', $elm$json$Json$Decode$bool)); var $author$project$Protocol$gameDetailsParser = _Utils_Tuple2( A6( $elm$json$Json$Decode$map5, $author$project$Protocol$GameDetails, A2($elm$json$Json$Decode$field, 'alias', $elm$json$Json$Decode$string), A2( $elm$json$Json$Decode$field, 'game_status', A2($elm$json$Json$Decode$map, $author$project$Protocol$gameStatusFromString, $elm$json$Json$Decode$string)), A2( $elm$json$Json$Decode$field, 'players', $elm$json$Json$Decode$list($author$project$Protocol$playerDecoder)), A2($elm$json$Json$Decode$field, 'uuid', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'current_stage', $elm$json$Json$Decode$int)), function (v) { return $author$project$Protocol$GameDetailsResponse(v); }); var $author$project$Main$getGameLink = function (model) { var url = model.url; var _v0 = model.gameId; if (_v0.$ === 'Just') { var gameId = _v0.a; return (gameId === '') ? url : _Utils_update( url, { fragment: $elm$core$Maybe$Just(gameId) }); } else { return url; } }; var $author$project$Main$imageUrl = 'http://localhost:3030/images/'; var $elm$core$Elm$JsArray$foldl = _JsArray_foldl; var $elm$core$Elm$JsArray$indexedMap = _JsArray_indexedMap; var $elm$core$Array$indexedMap = F2( function (func, _v0) { var len = _v0.a; var tree = _v0.c; var tail = _v0.d; var initialBuilder = { nodeList: _List_Nil, nodeListSize: 0, tail: A3( $elm$core$Elm$JsArray$indexedMap, func, $elm$core$Array$tailIndex(len), tail) }; var helper = F2( function (node, builder) { if (node.$ === 'SubTree') { var subTree = node.a; return A3($elm$core$Elm$JsArray$foldl, helper, builder, subTree); } else { var leaf = node.a; var offset = builder.nodeListSize * $elm$core$Array$branchFactor; var mappedLeaf = $elm$core$Array$Leaf( A3($elm$core$Elm$JsArray$indexedMap, func, offset, leaf)); return { nodeList: A2($elm$core$List$cons, mappedLeaf, builder.nodeList), nodeListSize: builder.nodeListSize + 1, tail: builder.tail }; } }); return A2( $elm$core$Array$builderToArray, true, A3($elm$core$Elm$JsArray$foldl, helper, initialBuilder, tree)); }); var $elm$core$Basics$neq = _Utils_notEqual; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$isConnected = F2( function (key, _v0) { var state = _v0.a; return !_Utils_eq( A2($elm$core$Dict$get, key, state.socketStates), $elm$core$Maybe$Nothing); }); var $author$project$Main$isGameRunning = function (model) { var _v0 = model.status; switch (_v0.$) { case 'NoGame': return false; case 'Lobby': return false; case 'GameOver': return false; case 'Starting': return true; case 'Drawing': return true; default: return true; } }; var $elm$browser$Browser$Navigation$pushUrl = _Browser_pushUrl; var $elm$url$Url$addPort = F2( function (maybePort, starter) { if (maybePort.$ === 'Nothing') { return starter; } else { var port_ = maybePort.a; return starter + (':' + $elm$core$String$fromInt(port_)); } }); var $elm$url$Url$addPrefixed = F3( function (prefix, maybeSegment, starter) { if (maybeSegment.$ === 'Nothing') { return starter; } else { var segment = maybeSegment.a; return _Utils_ap( starter, _Utils_ap(prefix, segment)); } }); var $elm$url$Url$toString = function (url) { var http = function () { var _v0 = url.protocol; if (_v0.$ === 'Http') { return 'http://'; } else { return 'https://'; } }(); return A3( $elm$url$Url$addPrefixed, '#', url.fragment, A3( $elm$url$Url$addPrefixed, '?', url.query, _Utils_ap( A2( $elm$url$Url$addPort, url.port_, _Utils_ap(http, url.host)), url.path))); }; var $author$project$Main$leaveGame = function (model) { var url0 = model.url; var url = _Utils_update( url0, {fragment: $elm$core$Maybe$Nothing}); return _Utils_Tuple2( _Utils_update( model, {currentWorkload: 0, gameId: $elm$core$Maybe$Nothing, gameKey: $elm$core$Maybe$Nothing, myId: $elm$core$Maybe$Nothing, players: $elm$core$Array$empty, previousPackage: $elm$core$Maybe$Nothing, showingGameoverSelf: false, status: $author$project$Protocol$NoGame, url: url, workloads: $elm$core$Maybe$Nothing}), A2( $elm$browser$Browser$Navigation$pushUrl, model.key, $elm$url$Url$toString(url))); }; var $elm$browser$Browser$Navigation$load = _Browser_load; var $billstclair$elm_port_funnel$PortFunnel$FunnelSpec = F4( function (accessors, moduleDesc, commander, handler) { return {accessors: accessors, commander: commander, handler: handler, moduleDesc: moduleDesc}; }); var $author$project$PortFunnels$LocalStorageFunnel = function (a) { return {$: 'LocalStorageFunnel', a: a}; }; var $author$project$PortFunnels$WebSocketFunnel = function (a) { return {$: 'WebSocketFunnel', a: a}; }; var $elm$core$Platform$Cmd$none = $elm$core$Platform$Cmd$batch(_List_Nil); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$commander = F2( function (_v0, _v1) { return $elm$core$Platform$Cmd$none; }); var $elm$core$Basics$composeR = F3( function (f, g, x) { return g( f(x)); }); var $elm$json$Json$Encode$bool = _Json_wrap; var $elm$core$List$append = F2( function (xs, ys) { if (!ys.b) { return xs; } else { return A3($elm$core$List$foldr, $elm$core$List$cons, ys, xs); } }); var $elm$core$List$concat = function (lists) { return A3($elm$core$List$foldr, $elm$core$List$append, _List_Nil, lists); }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleName = 'WebSocket'; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$encode = function (mess) { var gm = F2( function (tag, args) { return A3($billstclair$elm_port_funnel$PortFunnel$GenericMessage, $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleName, tag, args); }); switch (mess.$) { case 'Startup': return A2(gm, 'startup', $elm$json$Json$Encode$null); case 'POOpen': var key = mess.a.key; var url = mess.a.url; return A2( gm, 'open', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'url', $elm$json$Json$Encode$string(url)) ]))); case 'POSend': var key = mess.a.key; var message = mess.a.message; return A2( gm, 'send', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'message', $elm$json$Json$Encode$string(message)) ]))); case 'POClose': var key = mess.a.key; var reason = mess.a.reason; return A2( gm, 'close', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'reason', $elm$json$Json$Encode$string(reason)) ]))); case 'POBytesQueued': var key = mess.a.key; return A2( gm, 'getBytesQueued', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)) ]))); case 'PODelay': var millis = mess.a.millis; var id = mess.a.id; return A2( gm, 'delay', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'millis', $elm$json$Json$Encode$int(millis)), _Utils_Tuple2( 'id', $elm$json$Json$Encode$string(id)) ]))); case 'PWillOpen': var key = mess.a.key; var url = mess.a.url; var keepAlive = mess.a.keepAlive; return A2( gm, 'willopen', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'url', $elm$json$Json$Encode$string(url)), _Utils_Tuple2( 'keepAlive', $elm$json$Json$Encode$bool(keepAlive)) ]))); case 'PWillSend': var key = mess.a.key; var message = mess.a.message; return A2( gm, 'willsend', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'message', $elm$json$Json$Encode$string(message)) ]))); case 'PWillClose': var key = mess.a.key; var reason = mess.a.reason; return A2( gm, 'willclose', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'reason', $elm$json$Json$Encode$string(reason)) ]))); case 'PIConnected': var key = mess.a.key; var description = mess.a.description; return A2( gm, 'connected', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'description', $elm$json$Json$Encode$string(description)) ]))); case 'PIMessageReceived': var key = mess.a.key; var message = mess.a.message; return A2( gm, 'messageReceived', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'message', $elm$json$Json$Encode$string(message)) ]))); case 'PIClosed': var key = mess.a.key; var bytesQueued = mess.a.bytesQueued; var code = mess.a.code; var reason = mess.a.reason; var wasClean = mess.a.wasClean; return A2( gm, 'closed', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'bytesQueued', $elm$json$Json$Encode$int(bytesQueued)), _Utils_Tuple2( 'code', $elm$json$Json$Encode$int(code)), _Utils_Tuple2( 'reason', $elm$json$Json$Encode$string(reason)), _Utils_Tuple2( 'wasClean', $elm$json$Json$Encode$bool(wasClean)) ]))); case 'PIBytesQueued': var key = mess.a.key; var bufferedAmount = mess.a.bufferedAmount; return A2( gm, 'bytesQueued', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(key)), _Utils_Tuple2( 'bufferedAmount', $elm$json$Json$Encode$int(bufferedAmount)) ]))); case 'PIDelayed': var id = mess.a.id; return A2( gm, 'delayed', $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'id', $elm$json$Json$Encode$string(id)) ]))); default: var key = mess.a.key; var code = mess.a.code; var description = mess.a.description; var name = mess.a.name; var message = mess.a.message; return A2( gm, 'error', $elm$json$Json$Encode$object( $elm$core$List$concat( _List_fromArray( [ function () { if (key.$ === 'Just') { var k = key.a; return _List_fromArray( [ _Utils_Tuple2( 'key', $elm$json$Json$Encode$string(k)) ]); } else { return _List_Nil; } }(), _List_fromArray( [ _Utils_Tuple2( 'code', $elm$json$Json$Encode$string(code)), _Utils_Tuple2( 'description', $elm$json$Json$Encode$string(description)) ]), function () { if (name.$ === 'Just') { var n = name.a; return _List_fromArray( [ _Utils_Tuple2( 'name', $elm$json$Json$Encode$string(n)) ]); } else { return _List_Nil; } }(), function () { if (message.$ === 'Just') { var m = message.a; return _List_fromArray( [ _Utils_Tuple2( 'message', $elm$json$Json$Encode$string(m)) ]); } else { return _List_Nil; } }() ])))); } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$commander = F2( function (gfPort, response) { switch (response.$) { case 'CmdResponse': var message = response.a; return gfPort( $billstclair$elm_websocket_client$PortFunnel$WebSocket$encode(message)); case 'ListResponse': var responses = response.a; return $elm$core$Platform$Cmd$batch( A2( $elm$core$List$map, A2($elm$core$Basics$composeR, $billstclair$elm_websocket_client$PortFunnel$WebSocket$encode, gfPort), A3( $elm$core$List$foldl, F2( function (rsp, res) { if (rsp.$ === 'CmdResponse') { var message = rsp.a; return A2($elm$core$List$cons, message, res); } else { return res; } }), _List_Nil, responses))); default: return $elm$core$Platform$Cmd$none; } }); var $billstclair$elm_port_funnel$PortFunnel$StateAccessors = F2( function (get, set) { return {get: get, set: set}; }); var $author$project$PortFunnels$localStorageAccessors = A2( $billstclair$elm_port_funnel$PortFunnel$StateAccessors, function ($) { return $.storage; }, F2( function (substate, state) { return _Utils_update( state, {storage: substate}); })); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyBufferedAmount = F2( function (key, bufferedAmount) { return {bufferedAmount: bufferedAmount, key: key}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyDescription = F2( function (key, description) { return {description: description, key: key}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyMessage = F2( function (key, message) { return {key: key, message: message}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyReason = F2( function (key, reason) { return {key: key, reason: reason}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyUrl = F2( function (key, url) { return {key: key, url: url}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyUrlKeepAlive = F3( function (key, url, keepAlive) { return {keepAlive: keepAlive, key: key, url: url}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$MillisId = F2( function (millis, id) { return {id: id, millis: millis}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIBytesQueued = function (a) { return {$: 'PIBytesQueued', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIClosed = function (a) { return {$: 'PIClosed', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIClosedRecord = F5( function (key, bytesQueued, code, reason, wasClean) { return {bytesQueued: bytesQueued, code: code, key: key, reason: reason, wasClean: wasClean}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIConnected = function (a) { return {$: 'PIConnected', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIDelayed = function (a) { return {$: 'PIDelayed', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIError = function (a) { return {$: 'PIError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIErrorRecord = F5( function (key, code, description, name, message) { return {code: code, description: description, key: key, message: message, name: name}; }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIMessageReceived = function (a) { return {$: 'PIMessageReceived', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POBytesQueued = function (a) { return {$: 'POBytesQueued', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POClose = function (a) { return {$: 'POClose', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PODelay = function (a) { return {$: 'PODelay', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POOpen = function (a) { return {$: 'POOpen', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POSend = function (a) { return {$: 'POSend', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillClose = function (a) { return {$: 'PWillClose', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillOpen = function (a) { return {$: 'PWillOpen', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillSend = function (a) { return {$: 'PWillSend', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$Startup = {$: 'Startup'}; var $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$custom = $elm$json$Json$Decode$map2($elm$core$Basics$apR); var $elm$json$Json$Decode$fail = _Json_fail; var $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optionalDecoder = F3( function (pathDecoder, valDecoder, fallback) { var nullOr = function (decoder) { return $elm$json$Json$Decode$oneOf( _List_fromArray( [ decoder, $elm$json$Json$Decode$null(fallback) ])); }; var handleResult = function (input) { var _v0 = A2($elm$json$Json$Decode$decodeValue, pathDecoder, input); if (_v0.$ === 'Ok') { var rawValue = _v0.a; var _v1 = A2( $elm$json$Json$Decode$decodeValue, nullOr(valDecoder), rawValue); if (_v1.$ === 'Ok') { var finalResult = _v1.a; return $elm$json$Json$Decode$succeed(finalResult); } else { var finalErr = _v1.a; return $elm$json$Json$Decode$fail( $elm$json$Json$Decode$errorToString(finalErr)); } } else { return $elm$json$Json$Decode$succeed(fallback); } }; return A2($elm$json$Json$Decode$andThen, handleResult, $elm$json$Json$Decode$value); }); var $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optional = F4( function (key, valDecoder, fallback, decoder) { return A2( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$custom, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optionalDecoder, A2($elm$json$Json$Decode$field, key, $elm$json$Json$Decode$value), valDecoder, fallback), decoder); }); var $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required = F3( function (key, valDecoder, decoder) { return A2( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$custom, A2($elm$json$Json$Decode$field, key, valDecoder), decoder); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode = F2( function (value, decoder) { var _v0 = A2($elm$json$Json$Decode$decodeValue, decoder, value); if (_v0.$ === 'Ok') { var a = _v0.a; return $elm$core$Result$Ok(a); } else { var err = _v0.a; return $elm$core$Result$Err( $elm$json$Json$Decode$errorToString(err)); } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$decode = function (_v0) { var tag = _v0.tag; var args = _v0.args; switch (tag) { case 'startup': return $elm$core$Result$Ok($billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$Startup); case 'open': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POOpen, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'url', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyUrl))))); case 'send': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POSend, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'message', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyMessage))))); case 'close': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POClose, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'reason', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyReason))))); case 'getBytesQueued': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POBytesQueued, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed( function (key) { return {key: key}; })))); case 'delay': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PODelay, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'id', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'millis', $elm$json$Json$Decode$int, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$MillisId))))); case 'willopen': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillOpen, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'keepAlive', $elm$json$Json$Decode$bool, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'url', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyUrlKeepAlive)))))); case 'willsend': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillSend, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'message', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyMessage))))); case 'willclose': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillClose, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'reason', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyReason))))); case 'connected': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIConnected, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'description', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyDescription))))); case 'messageReceived': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIMessageReceived, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'message', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyMessage))))); case 'closed': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIClosed, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'wasClean', $elm$json$Json$Decode$bool, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'reason', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'code', $elm$json$Json$Decode$int, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'bytesQueued', $elm$json$Json$Decode$int, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIClosedRecord)))))))); case 'bytesQueued': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIBytesQueued, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'bufferedAmount', $elm$json$Json$Decode$int, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'key', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$KeyBufferedAmount))))); case 'delayed': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIDelayed, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'id', $elm$json$Json$Decode$string, $elm$json$Json$Decode$succeed( function (id) { return {id: id}; })))); case 'error': return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$valueDecode, args, A2( $elm$json$Json$Decode$map, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIError, A4( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optional, 'message', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string), $elm$core$Maybe$Nothing, A4( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optional, 'name', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string), $elm$core$Maybe$Nothing, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'description', $elm$json$Json$Decode$string, A3( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$required, 'code', $elm$json$Json$Decode$string, A4( $NoRedInk$elm_json_decode_pipeline$Json$Decode$Pipeline$optional, 'key', $elm$json$Json$Decode$nullable($elm$json$Json$Decode$string), $elm$core$Maybe$Nothing, $elm$json$Json$Decode$succeed($billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PIErrorRecord)))))))); default: return $elm$core$Result$Err('Unknown tag: ' + tag); } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$AbnormalClosure = {$: 'AbnormalClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosedResponse = function (a) { return {$: 'ClosedResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosingPhase = {$: 'ClosingPhase'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse = function (a) { return {$: 'CmdResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase = {$: 'ConnectedPhase'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedResponse = function (a) { return {$: 'ConnectedResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectingPhase = {$: 'ConnectingPhase'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse = function (a) { return {$: 'ErrorResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InvalidMessageError = function (a) { return {$: 'InvalidMessageError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$LowLevelError = function (a) { return {$: 'LowLevelError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$MessageReceivedResponse = function (a) { return {$: 'MessageReceivedResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse = {$: 'NoResponse'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ReconnectedResponse = function (a) { return {$: 'ReconnectedResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnexpectedConnectedError = function (a) { return {$: 'UnexpectedConnectedError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnexpectedMessageError = function (a) { return {$: 'UnexpectedMessageError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnknownClosure = {$: 'UnknownClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$BadGatewayClosure = {$: 'BadGatewayClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$GoingAwayClosure = {$: 'GoingAwayClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalErrorClosure = {$: 'InternalErrorClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$InvalidFramePayloadDataClosure = {$: 'InvalidFramePayloadDataClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$MessageTooBigClosure = {$: 'MessageTooBigClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$MissingExtensionClosure = {$: 'MissingExtensionClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoStatusRecvdClosure = {$: 'NoStatusRecvdClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$NormalClosure = {$: 'NormalClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$PolicyViolationClosure = {$: 'PolicyViolationClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ProtocolErrorClosure = {$: 'ProtocolErrorClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ServiceRestartClosure = {$: 'ServiceRestartClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$TLSHandshakeClosure = {$: 'TLSHandshakeClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$TimedOutOnReconnect = {$: 'TimedOutOnReconnect'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$TryAgainLaterClosure = {$: 'TryAgainLaterClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnsupportedDataClosure = {$: 'UnsupportedDataClosure'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$closurePairs = _List_fromArray( [ _Utils_Tuple2(1000, $billstclair$elm_websocket_client$PortFunnel$WebSocket$NormalClosure), _Utils_Tuple2(1001, $billstclair$elm_websocket_client$PortFunnel$WebSocket$GoingAwayClosure), _Utils_Tuple2(1002, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ProtocolErrorClosure), _Utils_Tuple2(1003, $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnsupportedDataClosure), _Utils_Tuple2(1005, $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoStatusRecvdClosure), _Utils_Tuple2(1006, $billstclair$elm_websocket_client$PortFunnel$WebSocket$AbnormalClosure), _Utils_Tuple2(1007, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InvalidFramePayloadDataClosure), _Utils_Tuple2(1008, $billstclair$elm_websocket_client$PortFunnel$WebSocket$PolicyViolationClosure), _Utils_Tuple2(1009, $billstclair$elm_websocket_client$PortFunnel$WebSocket$MessageTooBigClosure), _Utils_Tuple2(1010, $billstclair$elm_websocket_client$PortFunnel$WebSocket$MissingExtensionClosure), _Utils_Tuple2(1011, $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalErrorClosure), _Utils_Tuple2(1012, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ServiceRestartClosure), _Utils_Tuple2(1013, $billstclair$elm_websocket_client$PortFunnel$WebSocket$TryAgainLaterClosure), _Utils_Tuple2(1014, $billstclair$elm_websocket_client$PortFunnel$WebSocket$BadGatewayClosure), _Utils_Tuple2(1015, $billstclair$elm_websocket_client$PortFunnel$WebSocket$TLSHandshakeClosure), _Utils_Tuple2(4000, $billstclair$elm_websocket_client$PortFunnel$WebSocket$TimedOutOnReconnect) ]); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$closureDict = $elm$core$Dict$fromList($billstclair$elm_websocket_client$PortFunnel$WebSocket$closurePairs); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCode = function (code) { return A2( $elm$core$Maybe$withDefault, $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnknownClosure, A2($elm$core$Dict$get, code, $billstclair$elm_websocket_client$PortFunnel$WebSocket$closureDict)); }; var $elm_community$list_extra$List$Extra$find = F2( function (predicate, list) { find: while (true) { if (!list.b) { return $elm$core$Maybe$Nothing; } else { var first = list.a; var rest = list.b; if (predicate(first)) { return $elm$core$Maybe$Just(first); } else { var $temp$predicate = predicate, $temp$list = rest; predicate = $temp$predicate; list = $temp$list; continue find; } } } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCodeNumber = function (code) { var _v0 = A2( $elm_community$list_extra$List$Extra$find, function (_v1) { var c = _v1.b; return _Utils_eq(c, code); }, $billstclair$elm_websocket_client$PortFunnel$WebSocket$closurePairs); if (_v0.$ === 'Just') { var _v2 = _v0.a; var _int = _v2.a; return _int; } else { return 0; } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$IdlePhase = {$: 'IdlePhase'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$emptySocketState = {backoff: 0, continuationId: $elm$core$Maybe$Nothing, keepAlive: false, phase: $billstclair$elm_websocket_client$PortFunnel$WebSocket$IdlePhase, url: ''}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState = F2( function (key, state) { return A2( $elm$core$Maybe$withDefault, $billstclair$elm_websocket_client$PortFunnel$WebSocket$emptySocketState, A2($elm$core$Dict$get, key, state.socketStates)); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$doClose = F3( function (state, key, reason) { var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); return (!_Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase)) ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { continuations: function () { var _v0 = socketState.continuationId; if (_v0.$ === 'Nothing') { return state.continuations; } else { var id = _v0.a; return A2($elm$core$Dict$remove, id, state.continuations); } }(), socketStates: A2($elm$core$Dict$remove, key, state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse) : _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { socketStates: A3( $elm$core$Dict$insert, key, _Utils_update( socketState, {phase: $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosingPhase}), state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POClose( {key: key, reason: 'user request'}))); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketAlreadyOpenError = function (a) { return {$: 'SocketAlreadyOpenError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketClosingError = function (a) { return {$: 'SocketClosingError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketConnectingError = function (a) { return {$: 'SocketConnectingError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$checkUsedSocket = F2( function (state, key) { var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); var _v0 = socketState.phase; switch (_v0.$) { case 'IdlePhase': return $elm$core$Result$Ok(socketState); case 'ConnectedPhase': return $elm$core$Result$Err( _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketAlreadyOpenError(key)))); case 'ConnectingPhase': return $elm$core$Result$Err( _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketConnectingError(key)))); default: return $elm$core$Result$Err( _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketClosingError(key)))); } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$doOpen = F4( function (state, key, url, keepAlive) { var _v0 = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$checkUsedSocket, state, key); if (_v0.$ === 'Err') { var res = _v0.a; return res; } else { var socketState = _v0.a; return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { socketStates: A3( $elm$core$Dict$insert, key, _Utils_update( socketState, {keepAlive: keepAlive, phase: $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectingPhase, url: url}), state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POOpen( {key: key, url: url}))); } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketNotOpenError = function (a) { return {$: 'SocketNotOpenError', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$queueSend = F3( function (state, key, message) { var queues = state.queues; var current = A2( $elm$core$Maybe$withDefault, _List_Nil, A2($elm$core$Dict$get, key, queues)); var _new = A2( $elm$core$List$append, current, _List_fromArray( [message])); return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { queues: A3($elm$core$Dict$insert, key, _new, queues) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$doSend = F3( function (state, key, message) { var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); return (!_Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase)) ? ((!socketState.backoff) ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$SocketNotOpenError(key))) : A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$queueSend, state, key, message)) : (_Utils_eq( A2($elm$core$Dict$get, key, state.queues), $elm$core$Maybe$Nothing) ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POSend( {key: key, message: message}))) : A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$queueSend, state, key, message)); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$getContinuation = F2( function (id, state) { var _v0 = A2($elm$core$Dict$get, id, state.continuations); if (_v0.$ === 'Nothing') { return $elm$core$Maybe$Nothing; } else { var continuation = _v0.a; return $elm$core$Maybe$Just( _Utils_Tuple3( continuation.key, continuation.kind, _Utils_update( state, { continuations: A2($elm$core$Dict$remove, id, state.continuations) }))); } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$RetryConnection = {$: 'RetryConnection'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$allocateContinuation = F3( function (key, kind, state) { var counter = state.continuationCounter + 1; var id = $elm$core$String$fromInt(counter); var continuation = {key: key, kind: kind}; var _v0 = function () { var _v1 = A2($elm$core$Dict$get, key, state.socketStates); if (_v1.$ === 'Nothing') { return _Utils_Tuple2( state.continuations, A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state)); } else { var sockState = _v1.a; var _v2 = sockState.continuationId; if (_v2.$ === 'Nothing') { return _Utils_Tuple2( state.continuations, _Utils_update( sockState, { continuationId: $elm$core$Maybe$Just(id) })); } else { var oldid = _v2.a; return _Utils_Tuple2( A2($elm$core$Dict$remove, oldid, state.continuations), _Utils_update( sockState, { continuationId: $elm$core$Maybe$Just(id) })); } } }(); var continuations = _v0.a; var socketState = _v0.b; return _Utils_Tuple2( id, _Utils_update( state, { continuationCounter: counter, continuations: A3($elm$core$Dict$insert, id, continuation, continuations), socketStates: A3($elm$core$Dict$insert, key, socketState, state.socketStates) })); }); var $elm$core$Basics$pow = _Basics_pow; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$backoffMillis = function (backoff) { return 10 * A2($elm$core$Basics$pow, 2, backoff); }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$maxBackoff = 10; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$unexpectedClose = F2( function (state, _v0) { var key = _v0.key; var code = _v0.code; var reason = _v0.reason; var wasClean = _v0.wasClean; return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { socketStates: A2($elm$core$Dict$remove, key, state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosedResponse( { code: $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCode(code), expected: false, key: key, reason: reason, wasClean: wasClean })); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$handleUnexpectedClose = F2( function (state, closedRecord) { var key = closedRecord.key; var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); var backoff = 1 + socketState.backoff; if ((_Utils_cmp(backoff, $billstclair$elm_websocket_client$PortFunnel$WebSocket$maxBackoff) > 0) || (((backoff === 1) && (!_Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase))) || (closedRecord.bytesQueued > 0))) { return A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$unexpectedClose, state, _Utils_update( closedRecord, { code: (_Utils_cmp(backoff, $billstclair$elm_websocket_client$PortFunnel$WebSocket$maxBackoff) > 0) ? $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCodeNumber($billstclair$elm_websocket_client$PortFunnel$WebSocket$TimedOutOnReconnect) : closedRecord.code })); } else { if (socketState.url === '') { return A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$unexpectedClose, state, closedRecord); } else { var _v0 = A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$allocateContinuation, key, $billstclair$elm_websocket_client$PortFunnel$WebSocket$RetryConnection, state); var id = _v0.a; var state2 = _v0.b; var delay = $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PODelay( { id: id, millis: $billstclair$elm_websocket_client$PortFunnel$WebSocket$backoffMillis(backoff) }); return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state2, { socketStates: A3( $elm$core$Dict$insert, key, _Utils_update( socketState, {backoff: backoff}), state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse(delay)); } } }); var $elm$core$Dict$member = F2( function (key, dict) { var _v0 = A2($elm$core$Dict$get, key, dict); if (_v0.$ === 'Just') { return true; } else { return false; } }); var $elm$core$Set$member = F2( function (key, _v0) { var dict = _v0.a; return A2($elm$core$Dict$member, key, dict); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$DrainOutputQueue = {$: 'DrainOutputQueue'}; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$ListResponse = function (a) { return {$: 'ListResponse', a: a}; }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$processQueuedMessage = F3( function (state, key, reconnectedResponse) { var queues = state.queues; var _v0 = A2($elm$core$Dict$get, key, queues); if (_v0.$ === 'Nothing') { return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), reconnectedResponse); } else { if (!_v0.a.b) { return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { queues: A2($elm$core$Dict$remove, key, queues) })), reconnectedResponse); } else { var _v1 = _v0.a; var message = _v1.a; var tail = _v1.b; var posend = $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POSend( {key: key, message: message}); var _v2 = A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$allocateContinuation, key, $billstclair$elm_websocket_client$PortFunnel$WebSocket$DrainOutputQueue, state); var id = _v2.a; var state2 = _v2.b; var podelay = $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PODelay( {id: id, millis: 20}); var response = $billstclair$elm_websocket_client$PortFunnel$WebSocket$ListResponse( $elm$core$List$concat( _List_fromArray( [ function () { if (reconnectedResponse.$ === 'NoResponse') { return _List_Nil; } else { return _List_fromArray( [reconnectedResponse]); } }(), _List_fromArray( [ $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse(podelay), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse(posend) ]) ]))); return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state2, { queues: A3($elm$core$Dict$insert, key, tail, queues) })), response); } } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$process = F2( function (mess, unboxed) { var state = unboxed.a; switch (mess.$) { case 'Startup': return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, {isLoaded: true})), $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse); case 'PWillOpen': var key = mess.a.key; var url = mess.a.url; var keepAlive = mess.a.keepAlive; return A4($billstclair$elm_websocket_client$PortFunnel$WebSocket$doOpen, state, key, url, keepAlive); case 'PWillSend': var key = mess.a.key; var message = mess.a.message; return A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$doSend, state, key, message); case 'PWillClose': var key = mess.a.key; var reason = mess.a.reason; return A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$doClose, state, key, reason); case 'PIConnected': var key = mess.a.key; var description = mess.a.description; var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); if (!_Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectingPhase)) { return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnexpectedConnectedError( {description: description, key: key}))); } else { var newState = _Utils_update( state, { socketStates: A3( $elm$core$Dict$insert, key, _Utils_update( socketState, {backoff: 0, phase: $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase}), state.socketStates) }); return (!socketState.backoff) ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(newState), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedResponse( {description: description, key: key})) : A3( $billstclair$elm_websocket_client$PortFunnel$WebSocket$processQueuedMessage, newState, key, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ReconnectedResponse( {description: description, key: key})); } case 'PIMessageReceived': var key = mess.a.key; var message = mess.a.message; var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); return (!_Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectedPhase)) ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$UnexpectedMessageError( {key: key, message: message}))) : _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), socketState.keepAlive ? $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse : $billstclair$elm_websocket_client$PortFunnel$WebSocket$MessageReceivedResponse( {key: key, message: message})); case 'PIClosed': var closedRecord = mess.a; var key = closedRecord.key; var bytesQueued = closedRecord.bytesQueued; var code = closedRecord.code; var reason = closedRecord.reason; var wasClean = closedRecord.wasClean; var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); var expected = _Utils_eq(socketState.phase, $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosingPhase); return ((!expected) && (!A2($elm$core$Set$member, key, state.noAutoReopenKeys))) ? A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$handleUnexpectedClose, state, closedRecord) : _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state, { socketStates: A2($elm$core$Dict$remove, key, state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ClosedResponse( { code: $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCode(code), expected: expected, key: key, reason: reason, wasClean: wasClean })); case 'PIBytesQueued': var key = mess.a.key; var bufferedAmount = mess.a.bufferedAmount; return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse); case 'PIDelayed': var id = mess.a.id; var _v1 = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getContinuation, id, state); if (_v1.$ === 'Nothing') { return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse); } else { var _v2 = _v1.a; var key = _v2.a; var kind = _v2.b; var state2 = _v2.c; if (kind.$ === 'DrainOutputQueue') { return A3($billstclair$elm_websocket_client$PortFunnel$WebSocket$processQueuedMessage, state2, key, $billstclair$elm_websocket_client$PortFunnel$WebSocket$NoResponse); } else { var socketState = A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$getSocketState, key, state); var url = socketState.url; return (url !== '') ? _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State( _Utils_update( state2, { socketStates: A3( $elm$core$Dict$insert, key, _Utils_update( socketState, {phase: $billstclair$elm_websocket_client$PortFunnel$WebSocket$ConnectingPhase}), state.socketStates) })), $billstclair$elm_websocket_client$PortFunnel$WebSocket$CmdResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$POOpen( {key: key, url: url}))) : A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$unexpectedClose, state, { bytesQueued: 0, code: $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCodeNumber($billstclair$elm_websocket_client$PortFunnel$WebSocket$AbnormalClosure), key: key, reason: 'Missing URL for reconnect', wasClean: false }); } } case 'PIError': var key = mess.a.key; var code = mess.a.code; var description = mess.a.description; var name = mess.a.name; var message = mess.a.message; return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$LowLevelError( {code: code, description: description, key: key, message: message, name: name}))); default: return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$State(state), $billstclair$elm_websocket_client$PortFunnel$WebSocket$ErrorResponse( $billstclair$elm_websocket_client$PortFunnel$WebSocket$InvalidMessageError( {message: mess}))); } }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleDesc = A4($billstclair$elm_port_funnel$PortFunnel$makeModuleDesc, $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleName, $billstclair$elm_websocket_client$PortFunnel$WebSocket$encode, $billstclair$elm_websocket_client$PortFunnel$WebSocket$decode, $billstclair$elm_websocket_client$PortFunnel$WebSocket$process); var $author$project$PortFunnels$websocketAccessors = A2( $billstclair$elm_port_funnel$PortFunnel$StateAccessors, function ($) { return $.websocket; }, F2( function (substate, state) { return _Utils_update( state, {websocket: substate}); })); var $author$project$PortFunnels$handlerToFunnel = function (handler) { if (handler.$ === 'WebSocketHandler') { var websocketHandler = handler.a; return _Utils_Tuple2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleName, $author$project$PortFunnels$WebSocketFunnel( A4($billstclair$elm_port_funnel$PortFunnel$FunnelSpec, $author$project$PortFunnels$websocketAccessors, $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleDesc, $billstclair$elm_websocket_client$PortFunnel$WebSocket$commander, websocketHandler))); } else { var localStorageHandler = handler.a; return _Utils_Tuple2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, $author$project$PortFunnels$LocalStorageFunnel( A4($billstclair$elm_port_funnel$PortFunnel$FunnelSpec, $author$project$PortFunnels$localStorageAccessors, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleDesc, $billstclair$elm_localstorage$PortFunnel$LocalStorage$commander, localStorageHandler))); } }; var $author$project$PortFunnels$makeFunnelDict = F2( function (handlers, portGetter) { return _Utils_Tuple2( $elm$core$Dict$fromList( A2($elm$core$List$map, $author$project$PortFunnels$handlerToFunnel, handlers)), portGetter); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$makeOpenWithKey = F2( function (key, url) { return $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillOpen( {keepAlive: false, key: key, url: url}); }); var $elm$core$Elm$JsArray$map = _JsArray_map; var $elm$core$Array$map = F2( function (func, _v0) { var len = _v0.a; var startShift = _v0.b; var tree = _v0.c; var tail = _v0.d; var helper = function (node) { if (node.$ === 'SubTree') { var subTree = node.a; return $elm$core$Array$SubTree( A2($elm$core$Elm$JsArray$map, helper, subTree)); } else { var values = node.a; return $elm$core$Array$Leaf( A2($elm$core$Elm$JsArray$map, func, values)); } }; return A4( $elm$core$Array$Array_elm_builtin, len, startShift, A2($elm$core$Elm$JsArray$map, helper, tree), A2($elm$core$Elm$JsArray$map, func, tail)); }); var $elm$core$Maybe$map = F2( function (f, maybe) { if (maybe.$ === 'Just') { var value = maybe.a; return $elm$core$Maybe$Just( f(value)); } else { return $elm$core$Maybe$Nothing; } }); var $author$project$Main$setField = F3( function (field, value, model) { var oldForm = model.formFields; var newForm = function () { switch (field.$) { case 'GameIdField': return _Utils_update( oldForm, {gameId: value}); case 'UsernameField': return _Utils_update( oldForm, {username: value}); case 'UsernamePlaceholder': return _Utils_update( oldForm, {usernamePlaceholder: value}); default: return _Utils_update( oldForm, {text: value}); } }(); return _Utils_update( model, {formFields: newForm}); }); var $author$project$Main$maybeSetField = F2( function (field, value) { if (value.$ === 'Just') { var v = value.a; return A2($author$project$Main$setField, field, v); } else { return $elm$core$Basics$identity; } }); var $author$project$Protocol$packageSourceToString = function (source) { switch (source.$) { case 'Manual': return 'Manual'; case 'Periodic': return 'Periodic'; default: return 'Rollcall'; } }; var $author$project$Protocol$PersonalDetails = F2( function (myId, amAdministrator) { return {amAdministrator: amAdministrator, myId: myId}; }); var $author$project$Protocol$PersonalDetailsResponse = function (a) { return {$: 'PersonalDetailsResponse', a: a}; }; var $author$project$Protocol$personalDetailsParser = _Utils_Tuple2( A3( $elm$json$Json$Decode$map2, $author$project$Protocol$PersonalDetails, A2($elm$json$Json$Decode$field, 'my_id', $elm$json$Json$Decode$int), A2($elm$json$Json$Decode$field, 'am_administrator', $elm$json$Json$Decode$bool)), function (v) { return $author$project$Protocol$PersonalDetailsResponse(v); }); var $author$project$Protocol$PreviousImagePackageResponse = function (a) { return {$: 'PreviousImagePackageResponse', a: a}; }; var $author$project$Protocol$previousImagePackageParser = _Utils_Tuple2( A2($elm$json$Json$Decode$field, 'url', $elm$json$Json$Decode$string), function (v) { return $author$project$Protocol$PreviousImagePackageResponse(v); }); var $author$project$Protocol$PreviousTextPackageResponse = function (a) { return {$: 'PreviousTextPackageResponse', a: a}; }; var $author$project$Protocol$previousTextPackageParser = _Utils_Tuple2( A2($elm$json$Json$Decode$field, 'text', $elm$json$Json$Decode$string), function (v) { return $author$project$Protocol$PreviousTextPackageResponse(v); }); var $billstclair$elm_port_funnel$PortFunnel$process = F4( function (accessors, _v0, genericMessage, state) { var moduleDesc = _v0.a; var _v1 = moduleDesc.decoder(genericMessage); if (_v1.$ === 'Err') { var err = _v1.a; return $elm$core$Result$Err(err); } else { var message = _v1.a; var substate = accessors.get(state); var _v2 = A2(moduleDesc.process, message, substate); var substate2 = _v2.a; var response = _v2.b; return $elm$core$Result$Ok( _Utils_Tuple2( A2(accessors.set, substate2, state), response)); } }); var $Janiczek$cmd_extra$Cmd$Extra$withCmds = F2( function (cmds, model) { return _Utils_Tuple2( model, $elm$core$Platform$Cmd$batch(cmds)); }); var $billstclair$elm_port_funnel$PortFunnel$appProcess = F5( function (cmdPort, genericMessage, funnel, state, model) { var _v0 = A4($billstclair$elm_port_funnel$PortFunnel$process, funnel.accessors, funnel.moduleDesc, genericMessage, state); if (_v0.$ === 'Err') { var error = _v0.a; return $elm$core$Result$Err(error); } else { var _v1 = _v0.a; var state2 = _v1.a; var response = _v1.b; var gmToCmdPort = function (gm) { return cmdPort( $billstclair$elm_port_funnel$PortFunnel$encodeGenericMessage(gm)); }; var cmd = A2(funnel.commander, gmToCmdPort, response); var _v2 = A3(funnel.handler, response, state2, model); var model2 = _v2.a; var cmd2 = _v2.b; return $elm$core$Result$Ok( A2( $Janiczek$cmd_extra$Cmd$Extra$withCmds, _List_fromArray( [cmd, cmd2]), model2)); } }); var $author$project$PortFunnels$appTrampoline = F5( function (portGetter, genericMessage, funnel, state, model) { if (funnel.$ === 'WebSocketFunnel') { var appFunnel = funnel.a; return A5( $billstclair$elm_port_funnel$PortFunnel$appProcess, A2(portGetter, $billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleName, model), genericMessage, appFunnel, state, model); } else { var appFunnel = funnel.a; return A5( $billstclair$elm_port_funnel$PortFunnel$appProcess, A2(portGetter, $billstclair$elm_localstorage$PortFunnel$LocalStorage$moduleName, model), genericMessage, appFunnel, state, model); } }); var $billstclair$elm_port_funnel$PortFunnel$decodeValue = F2( function (decoder, value) { var _v0 = A2($elm$json$Json$Decode$decodeValue, decoder, value); if (_v0.$ === 'Ok') { var res = _v0.a; return $elm$core$Result$Ok(res); } else { var err = _v0.a; return $elm$core$Result$Err( $elm$json$Json$Decode$errorToString(err)); } }); var $billstclair$elm_port_funnel$PortFunnel$genericMessageDecoder = A4( $elm$json$Json$Decode$map3, $billstclair$elm_port_funnel$PortFunnel$GenericMessage, A2($elm$json$Json$Decode$field, 'module', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'tag', $elm$json$Json$Decode$string), A2($elm$json$Json$Decode$field, 'args', $elm$json$Json$Decode$value)); var $billstclair$elm_port_funnel$PortFunnel$decodeGenericMessage = function (value) { return A2($billstclair$elm_port_funnel$PortFunnel$decodeValue, $billstclair$elm_port_funnel$PortFunnel$genericMessageDecoder, value); }; var $billstclair$elm_port_funnel$PortFunnel$processValue = F5( function (funnels, appTrampoline, value, state, model) { var _v0 = $billstclair$elm_port_funnel$PortFunnel$decodeGenericMessage(value); if (_v0.$ === 'Err') { var error = _v0.a; return $elm$core$Result$Err(error); } else { var genericMessage = _v0.a; var moduleName = genericMessage.moduleName; var _v1 = A2($elm$core$Dict$get, moduleName, funnels); if (_v1.$ === 'Just') { var funnel = _v1.a; var _v2 = A4(appTrampoline, genericMessage, funnel, state, model); if (_v2.$ === 'Err') { var error = _v2.a; return $elm$core$Result$Err(error); } else { var _v3 = _v2.a; var model2 = _v3.a; var cmd = _v3.b; return $elm$core$Result$Ok( _Utils_Tuple2(model2, cmd)); } } else { return $elm$core$Result$Err('Unknown moduleName: ' + moduleName); } } }); var $author$project$PortFunnels$processValue = F4( function (_v0, value, state, model) { var funnelDict = _v0.a; var portGetter = _v0.b; return A5( $billstclair$elm_port_funnel$PortFunnel$processValue, funnelDict, $author$project$PortFunnels$appTrampoline(portGetter), value, state, model); }); var $billstclair$elm_localstorage$PortFunnel$LocalStorage$put = $billstclair$elm_localstorage$PortFunnel$InternalTypes$Put; var $author$project$Main$putLocalStorageString = F3( function (model, key, value) { return A2( $author$project$Main$sendLocalStorage, model, A2( $billstclair$elm_localstorage$PortFunnel$LocalStorage$put, key, $elm$core$Maybe$Just( $elm$json$Json$Encode$string(value)))); }); var $elm$core$List$filter = F2( function (isGood, list) { return A3( $elm$core$List$foldr, F2( function (x, xs) { return isGood(x) ? A2($elm$core$List$cons, x, xs) : xs; }), _List_Nil, list); }); var $billstclair$elm_websocket_client$PortFunnel$WebSocket$isReconnectedResponse = function (response) { if (response.$ === 'ReconnectedResponse') { return true; } else { return false; } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$reconnectedResponses = function (response) { switch (response.$) { case 'ReconnectedResponse': return _List_fromArray( [response]); case 'ListResponse': var list = response.a; return A2($elm$core$List$filter, $billstclair$elm_websocket_client$PortFunnel$WebSocket$isReconnectedResponse, list); default: return _List_Nil; } }; var $elm$core$Basics$round = _Basics_round; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$makeSend = F2( function (key, message) { return $billstclair$elm_websocket_client$PortFunnel$WebSocket$InternalMessage$PWillSend( {key: key, message: message}); }); var $author$project$Protocol$prepareSocketCommandJson = F2( function (commandType, data) { if (data.$ === 'Nothing') { return $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'type', $elm$json$Json$Encode$string(commandType)) ])); } else { var d = data.a; return $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'type', $elm$json$Json$Encode$string(commandType)), _Utils_Tuple2('data', d) ])); } }); var $author$project$Protocol$prepareSocketCommand = function (command) { switch (command.$) { case 'Ping': return A2($author$project$Protocol$prepareSocketCommandJson, 'ping', $elm$core$Maybe$Nothing); case 'NewGameCommand': var username = command.a; return A2( $author$project$Protocol$prepareSocketCommandJson, 'new_game', $elm$core$Maybe$Just( $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'username', $elm$json$Json$Encode$string(username)) ])))); case 'LeaveCommand': return A2($author$project$Protocol$prepareSocketCommandJson, 'leave_game', $elm$core$Maybe$Nothing); case 'JoinCommand': var gameId = command.a; var username = command.b; return A2( $author$project$Protocol$prepareSocketCommandJson, 'join_game', $elm$core$Maybe$Just( $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'game_id', $elm$json$Json$Encode$string(gameId)), _Utils_Tuple2( 'username', $elm$json$Json$Encode$string(username)) ])))); case 'StartCommand': return A2($author$project$Protocol$prepareSocketCommandJson, 'start_game', $elm$core$Maybe$Nothing); case 'KickCommand': var playerId = command.a; return A2( $author$project$Protocol$prepareSocketCommandJson, 'kick_player', $elm$core$Maybe$Just( $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'player_id', $elm$json$Json$Encode$int(playerId)) ])))); case 'UuidCommand': var uuid = command.a; return A2( $author$project$Protocol$prepareSocketCommandJson, 'my_uuid', $elm$core$Maybe$Just( $elm$json$Json$Encode$string(uuid))); case 'TextPackageCommand': var text = command.a; var source = command.b; return A2( $author$project$Protocol$prepareSocketCommandJson, 'text_package', $elm$core$Maybe$Just( $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'text', $elm$json$Json$Encode$string(text)), _Utils_Tuple2( 'source', $elm$json$Json$Encode$string( $author$project$Protocol$packageSourceToString(source))) ])))); case 'ImagePackageCommand': var image = command.a; var source = command.b; return A2( $author$project$Protocol$prepareSocketCommandJson, 'image_package', $elm$core$Maybe$Just( $elm$json$Json$Encode$object( _List_fromArray( [ _Utils_Tuple2( 'data', $elm$json$Json$Encode$string(image)), _Utils_Tuple2( 'source', $elm$json$Json$Encode$string( $author$project$Protocol$packageSourceToString(source))) ])))); case 'NextRoundCommand': return A2($author$project$Protocol$prepareSocketCommandJson, 'next_round', $elm$core$Maybe$Nothing); case 'ExtendDeadlineCommand': var secs = command.a; return A2( $author$project$Protocol$prepareSocketCommandJson, 'extend_deadline', $elm$core$Maybe$Just( $elm$json$Json$Encode$int(secs))); default: return A2($author$project$Protocol$prepareSocketCommandJson, 'restart_game', $elm$core$Maybe$Nothing); } }; var $billstclair$elm_websocket_client$PortFunnel$WebSocket$send = $billstclair$elm_port_funnel$PortFunnel$sendMessage($billstclair$elm_websocket_client$PortFunnel$WebSocket$moduleDesc); var $author$project$Main$sendWebSocket = function (message) { return A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$send, $author$project$Main$cmdPort, message); }; var $author$project$Main$wsKey = 'mainws'; var $author$project$Main$sendSocketCommand = function (command) { return $author$project$Main$sendWebSocket( A2( $billstclair$elm_websocket_client$PortFunnel$WebSocket$makeSend, $author$project$Main$wsKey, A2( $elm$json$Json$Encode$encode, 0, $author$project$Protocol$prepareSocketCommand(command)))); }; var $author$project$Main$SubmitImage = function (a) { return {$: 'SubmitImage', a: a}; }; var $author$project$Main$SubmitText = function (a) { return {$: 'SubmitText', a: a}; }; var $author$project$Main$submitPackage = function (model) { var _v0 = model.status; if (_v0.$ === 'Drawing') { return $author$project$Main$SubmitImage; } else { return $author$project$Main$SubmitText; } }; var $elm$core$Result$toMaybe = function (result) { if (result.$ === 'Ok') { var v = result.a; return $elm$core$Maybe$Just(v); } else { return $elm$core$Maybe$Nothing; } }; var $author$project$Main$posixPlusSeconds = F2( function (a, b) { return $elm$time$Time$millisToPosix( $elm$time$Time$posixToMillis(a) + ($elm$core$Basics$round(b) * 1000)); }); var $author$project$Main$posixTimeDifferenceSeconds = F2( function (a, b) { return ($elm$time$Time$posixToMillis(a) - $elm$time$Time$posixToMillis(b)) / 1000; }); var $author$project$Main$updatePlayerTime = F2( function (currentTime, player) { var _v0 = player.status; if (_v0.$ === 'Working') { var timeLeft = _v0.a; var _v1 = player.deadline; if (_v1.$ === 'Just') { var d = _v1.a; return _Utils_update( player, { status: $author$project$Protocol$Working( A2($author$project$Main$posixTimeDifferenceSeconds, d, currentTime)) }); } else { return _Utils_update( player, { deadline: $elm$core$Maybe$Just( A2($author$project$Main$posixPlusSeconds, currentTime, timeLeft)) }); } } else { return player; } }); var $author$project$Protocol$UuidResponse = function (a) { return {$: 'UuidResponse', a: a}; }; var $author$project$Protocol$uuidParser = _Utils_Tuple2( $elm$json$Json$Decode$string, function (s) { return $author$project$Protocol$UuidResponse(s); }); var $elm$core$Result$withDefault = F2( function (def, result) { if (result.$ === 'Ok') { var a = result.a; return a; } else { return def; } }); var $author$project$Protocol$AllWorkloadsResponse = function (a) { return {$: 'AllWorkloadsResponse', a: a}; }; var $elm$json$Json$Decode$array = _Json_decodeArray; var $author$project$Protocol$WorkPackageDetails = F2( function (playerId, data) { return {data: data, playerId: playerId}; }); var $author$project$Protocol$workpackageDecoder = $elm$json$Json$Decode$oneOf( _List_fromArray( [ A2( $elm$json$Json$Decode$map, $author$project$Protocol$TextPackage, A2($elm$json$Json$Decode$field, 'text', $elm$json$Json$Decode$string)), A2( $elm$json$Json$Decode$map, $author$project$Protocol$ImagePackage, A2($elm$json$Json$Decode$field, 'url', $elm$json$Json$Decode$string)) ])); var $author$project$Protocol$workpackageDetailsDecoder = A3( $elm$json$Json$Decode$map2, $author$project$Protocol$WorkPackageDetails, A2($elm$json$Json$Decode$field, 'player_id', $elm$json$Json$Decode$int), A2( $elm$json$Json$Decode$field, 'data', $elm$json$Json$Decode$nullable($author$project$Protocol$workpackageDecoder))); var $author$project$Protocol$workloadDecoder = A2( $elm$json$Json$Decode$field, 'packages', $elm$json$Json$Decode$list($author$project$Protocol$workpackageDetailsDecoder)); var $author$project$Protocol$workloadsParser = _Utils_Tuple2( $elm$json$Json$Decode$array($author$project$Protocol$workloadDecoder), function (v) { return $author$project$Protocol$AllWorkloadsResponse(v); }); var $author$project$Main$wsUrl = 'ws://localhost:3030/ws'; var $author$project$Main$socketHandler = F3( function (response, state, mdl) { var model = _Utils_update( mdl, {funnelState: state}); switch (response.$) { case 'MessageReceivedResponse': var message = response.a.message; var typeDecoder = A2($elm$json$Json$Decode$field, 'type', $elm$json$Json$Decode$string); var typeString = A2($elm$json$Json$Decode$decodeString, typeDecoder, message); var decodeData = function (decoder) { return A2( $elm$json$Json$Decode$decodeString, A2($elm$json$Json$Decode$field, 'data', decoder), message); }; var decodeDataUsingParser = function (parser) { var _v19 = decodeData(parser.a); if (_v19.$ === 'Err') { var e = _v19.a; return $author$project$Protocol$ErrorResponse( $elm$json$Json$Decode$errorToString(e)); } else { var v = _v19.a; return A2($elm$core$Tuple$second, parser, v); } }; var received = function () { if (typeString.$ === 'Err') { var e = typeString.a; return $author$project$Protocol$ErrorResponse( $elm$json$Json$Decode$errorToString(e)); } else { var s = typeString.a; switch (s) { case 'pong': return $author$project$Protocol$ErrorResponse('ping'); case 'error': return decodeDataUsingParser($author$project$Protocol$errorParser); case 'game_details': return decodeDataUsingParser($author$project$Protocol$gameDetailsParser); case 'personal_details': return decodeDataUsingParser($author$project$Protocol$personalDetailsParser); case 'your_uuid': return decodeDataUsingParser($author$project$Protocol$uuidParser); case 'left_game': return $author$project$Protocol$LeftGameResponse; case 'previous_text_package': return decodeDataUsingParser($author$project$Protocol$previousTextPackageParser); case 'previous_image_package': return decodeDataUsingParser($author$project$Protocol$previousImagePackageParser); case 'all_workloads': return decodeDataUsingParser($author$project$Protocol$workloadsParser); default: return $author$project$Protocol$ErrorResponse('Unknown response type received'); } } }(); return A2( $author$project$Main$update, $author$project$Main$SocketReceive(received), model); case 'ConnectedResponse': return _Utils_Tuple2( model, A2($author$project$Main$getLocalStorageString, model, 'uuid')); case 'ClosedResponse': var code = response.a.code; return _Utils_Tuple2( model, $author$project$Main$errorLog( 'Websocket connection closed: ' + $billstclair$elm_websocket_client$PortFunnel$WebSocket$closedCodeToString(code))); case 'ErrorResponse': var error = response.a; return _Utils_Tuple2( model, $author$project$Main$errorLog( $billstclair$elm_websocket_client$PortFunnel$WebSocket$errorToString(error))); default: var _v20 = $billstclair$elm_websocket_client$PortFunnel$WebSocket$reconnectedResponses(response); if (!_v20.b) { return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } else { if ((_v20.a.$ === 'ReconnectedResponse') && (!_v20.b.b)) { var r = _v20.a.a; return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } else { var list = _v20; return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } } } }); var $author$project$Main$storageHandler = F3( function (response, state, mdl) { var model = _Utils_update( mdl, {funnelState: state}); if (response.$ === 'GetResponse') { var label = response.a.label; var key = response.a.key; var value = response.a.value; var string = function () { if (value.$ === 'Nothing') { return $elm$core$Maybe$Nothing; } else { var v = value.a; return $elm$core$Result$toMaybe( A2($elm$json$Json$Decode$decodeValue, $elm$json$Json$Decode$string, v)); } }(); return A2( $author$project$Main$update, A2($author$project$Main$StorageReceive, key, string), model); } else { return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } }); var $author$project$Main$update = F2( function (msg, model) { update: while (true) { switch (msg.$) { case 'LinkClicked': var urlRequest = msg.a; if (urlRequest.$ === 'Internal') { var url = urlRequest.a; return _Utils_Tuple2( model, A2( $elm$browser$Browser$Navigation$pushUrl, model.key, $elm$url$Url$toString(url))); } else { var href = urlRequest.a; return _Utils_Tuple2( model, $elm$browser$Browser$Navigation$load(href)); } case 'UrlChanged': var url = msg.a; var mdl = function () { var _v2 = $author$project$Main$getURLGameId(url); if (_v2.$ === 'Just') { var f = _v2.a; return A3($author$project$Main$setField, $author$project$Main$GameIdField, f, model); } else { return model; } }(); return _Utils_Tuple2( _Utils_update( mdl, {url: url}), $elm$core$Platform$Cmd$none); case 'Tick': var newTime = msg.a; return _Utils_Tuple2( _Utils_update( model, { lastUpdate: $elm$core$Maybe$Just(newTime), players: function () { var _v3 = model.lastUpdate; if (_v3.$ === 'Nothing') { return model.players; } else { var lastUpdate = _v3.a; return A2( $elm$core$Array$map, $author$project$Main$updatePlayerTime(newTime), model.players); } }() }), A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$isConnected, $author$project$Main$wsKey, model.funnelState.websocket) ? $elm$core$Platform$Cmd$none : $elm$core$Platform$Cmd$none); case 'AutoSubmit': var newMsg = $author$project$Main$isGameRunning(model) ? A2($author$project$Main$submitPackage, model, $author$project$Protocol$Periodic) : $author$project$Main$NoAction; var $temp$msg = newMsg, $temp$model = model; msg = $temp$msg; model = $temp$model; continue update; case 'NoAction': return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); case 'NewGame': return _Utils_Tuple2( model, $elm$core$Platform$Cmd$batch( _List_fromArray( [ $author$project$Main$sendSocketCommand( $author$project$Protocol$NewGameCommand(model.formFields.username)), A3($author$project$Main$putLocalStorageString, model, 'username', model.formFields.username) ]))); case 'JoinGame': return _Utils_Tuple2( model, $elm$core$Platform$Cmd$batch( _List_fromArray( [ $author$project$Main$sendSocketCommand( A2($author$project$Protocol$JoinCommand, model.formFields.gameId, model.formFields.username)), A3($author$project$Main$putLocalStorageString, model, 'username', model.formFields.username) ]))); case 'StartGame': return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand($author$project$Protocol$StartCommand)); case 'LeaveGame': return A2( $Janiczek$cmd_extra$Cmd$Extra$addCmd, $author$project$Main$sendSocketCommand($author$project$Protocol$LeaveCommand), $author$project$Main$leaveGame(model)); case 'SubmitText': var source = msg.a; return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand( A2($author$project$Protocol$TextPackageCommand, model.formFields.text, source))); case 'SubmitImage': var source = msg.a; return _Utils_Tuple2( model, $author$project$Main$canvasPort( _Utils_Tuple2( 'snap', $elm$core$Maybe$Just( $author$project$Protocol$packageSourceToString(source))))); case 'KickPlayer': var value = msg.a; return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand( $author$project$Protocol$KickCommand(value))); case 'NextRound': return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand($author$project$Protocol$NextRoundCommand)); case 'ExtendDeadline': var value = msg.a; var secs = $elm$core$Basics$round(value * 60); return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand( $author$project$Protocol$ExtendDeadlineCommand(secs))); case 'SetField': var field = msg.a; var value = msg.b; return _Utils_Tuple2( A3($author$project$Main$setField, field, value, model), $elm$core$Platform$Cmd$none); case 'RestartGame': return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand($author$project$Protocol$RestartGameCommand)); case 'MoveWorkload': var dir = msg.a; var workload = function () { if (dir.$ === 'Forward') { return model.currentWorkload + 1; } else { return model.currentWorkload - 1; } }(); var workload2 = (workload < 0) ? 0 : workload; var maxWorkload = $elm$core$Array$length( A2($elm$core$Maybe$withDefault, $elm$core$Array$empty, model.workloads)) - 1; var workload3 = (_Utils_cmp(workload2, maxWorkload) > 0) ? maxWorkload : workload2; return _Utils_Tuple2( _Utils_update( model, {currentWorkload: workload3}), $elm$core$Platform$Cmd$none); case 'Send': var value = msg.a; return _Utils_Tuple2( model, $author$project$Main$cmdPort(value)); case 'Receive': var value = msg.a; var _v5 = A4( $author$project$PortFunnels$processValue, $author$project$Main$cyclic$funnelDict(), value, model.funnelState, model); if (_v5.$ === 'Err') { var error = _v5.a; return _Utils_Tuple2( model, $author$project$Main$errorLog(error)); } else { var res = _v5.a; var modul = A2( $elm$core$Result$withDefault, 'none', A2( $elm$json$Json$Decode$decodeValue, A2($elm$json$Json$Decode$field, 'module', $elm$json$Json$Decode$string), value)); if (modul === 'WebSocket') { var _v6 = A2( $elm$json$Json$Decode$decodeValue, A2($elm$json$Json$Decode$field, 'tag', $elm$json$Json$Decode$string), value); if ((_v6.$ === 'Ok') && (_v6.a === 'startup')) { return A2( $Janiczek$cmd_extra$Cmd$Extra$addCmd, $author$project$Main$sendWebSocket( A2($billstclair$elm_websocket_client$PortFunnel$WebSocket$makeOpenWithKey, $author$project$Main$wsKey, $author$project$Main$wsUrl)), res); } else { return res; } } else { return res; } } case 'StorageReceive': var key = msg.a; var value = msg.b; switch (key) { case 'username': return _Utils_Tuple2( A3( $author$project$Main$setField, $author$project$Main$UsernameField, A2($elm$core$Maybe$withDefault, '', value), model), $elm$core$Platform$Cmd$none); case 'uuid': if (value.$ === 'Just') { var uuid = value.a; return _Utils_Tuple2( _Utils_update( model, { uuid: $elm$core$Maybe$Just(uuid) }), $author$project$Main$sendSocketCommand( $author$project$Protocol$UuidCommand(uuid))); } else { return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } default: return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); } case 'SocketReceive': var value = msg.a; switch (value.$) { case 'GameDetailsResponse': var details = value.a; var showingGameoverSelf = model.showingGameoverSelf || (_Utils_eq(details.status, $author$project$Protocol$GameOver) && (!_Utils_eq(model.status, $author$project$Protocol$GameOver))); var playerCreator = F2( function (id, player) { var status = function () { if (player.stuck) { return $author$project$Protocol$Stuck; } else { var _v10 = player.status; if (_v10.$ === 'Working') { return $author$project$Protocol$Working(player.deadline); } else { return player.status; } } }(); return { deadline: $elm$core$Maybe$Nothing, image: player.imageUrl, isAdministrator: player.isAdmin, isMe: A2( $elm$core$Maybe$withDefault, false, A2( $elm$core$Maybe$map, function (i) { return _Utils_eq(i, id); }, model.myId)), status: status, username: player.username }; }); var players = A2( $elm$core$Array$indexedMap, playerCreator, $elm$core$Array$fromList(details.players)); var me = A2( $elm$core$Maybe$andThen, function (id) { return A2($elm$core$Array$get, id, players); }, model.myId); var username = A2( $elm$core$Maybe$map, function (p) { return p.username; }, me); var mdl = A3( $author$project$Main$maybeSetField, $author$project$Main$UsernameField, username, _Utils_update( model, { gameId: $elm$core$Maybe$Just(details.alias), gameKey: $elm$core$Maybe$Just( details.uuid + ('-' + $elm$core$String$fromInt(details.currentStage))), players: players, showingGameoverSelf: showingGameoverSelf, status: details.status })); return _Utils_Tuple2( mdl, $elm$core$Platform$Cmd$batch( _List_fromArray( [ A2( $elm$core$Maybe$withDefault, $elm$core$Platform$Cmd$none, A2( $elm$core$Maybe$map, function (p) { return A3($author$project$Main$putLocalStorageString, mdl, 'username', p.username); }, me)), _Utils_eq( mdl.url, $author$project$Main$getGameLink(mdl)) ? $elm$core$Platform$Cmd$none : A2( $elm$browser$Browser$Navigation$pushUrl, mdl.key, $elm$url$Url$toString( $author$project$Main$getGameLink(mdl))), A2($elm$core$Task$perform, $author$project$Main$Tick, $elm$time$Time$now) ]))); case 'ErrorResponse': var error = value.a; return _Utils_Tuple2( model, $author$project$Main$errorLog(error)); case 'PongResponse': return _Utils_Tuple2(model, $elm$core$Platform$Cmd$none); case 'PersonalDetailsResponse': var details = value.a; return _Utils_Tuple2( _Utils_update( model, { amAdministrator: details.amAdministrator, myId: $elm$core$Maybe$Just(details.myId), players: A2( $elm$core$Array$indexedMap, function (i) { return function (p) { return _Utils_update( p, { isMe: _Utils_eq(i, details.myId) }); }; }, model.players) }), $elm$core$Platform$Cmd$none); case 'UuidResponse': var uuid = value.a; return _Utils_Tuple2( _Utils_update( model, { uuid: $elm$core$Maybe$Just(uuid) }), A3($author$project$Main$putLocalStorageString, model, 'uuid', uuid)); case 'LeftGameResponse': return $author$project$Main$leaveGame(model); case 'PreviousTextPackageResponse': var text = value.a; return _Utils_Tuple2( _Utils_update( model, { previousPackage: $elm$core$Maybe$Just( $author$project$Protocol$TextPackage(text)) }), $elm$core$Platform$Cmd$none); case 'PreviousImagePackageResponse': var path = value.a; return _Utils_Tuple2( _Utils_update( model, { previousPackage: $elm$core$Maybe$Just( $author$project$Protocol$ImagePackage( _Utils_ap($author$project$Main$imageUrl, path))) }), $elm$core$Platform$Cmd$none); default: var workloads = value.a; var correctURL = function (data) { if ((data.$ === 'Just') && (data.a.$ === 'ImagePackage')) { var url = data.a.a; return $elm$core$Maybe$Just( $author$project$Protocol$ImagePackage( _Utils_ap($author$project$Main$imageUrl, url))); } else { return data; } }; var correctionInner = function (workpackage) { return _Utils_update( workpackage, { data: correctURL(workpackage.data) }); }; var correctionOuter = function (workload) { return A2($elm$core$List$map, correctionInner, workload); }; var correctURLs = function (workloads_) { return A2($elm$core$Array$map, correctionOuter, workloads_); }; return _Utils_Tuple2( _Utils_update( model, { workloads: $elm$core$Maybe$Just( correctURLs(workloads)) }), $elm$core$Platform$Cmd$none); } case 'ShowError': var value = msg.a; return _Utils_Tuple2( _Utils_update( model, { error: $elm$core$Maybe$Just(value) }), $elm$core$Platform$Cmd$none); case 'RemoveError': return _Utils_Tuple2( _Utils_update( model, {error: $elm$core$Maybe$Nothing}), $elm$core$Platform$Cmd$none); case 'ShowConfirmDialog': var message = msg.a; var newMsg = msg.b; var nextDialogId = model.nextDialogId; var dict = A3($elm$core$Dict$insert, nextDialogId, newMsg, model.pendingDialogs); return _Utils_Tuple2( _Utils_update( model, {nextDialogId: nextDialogId + 1, pendingDialogs: dict}), $author$project$Main$confirmPort( _Utils_Tuple2(message, nextDialogId))); case 'ShownConfirmDialog': var _v12 = msg.a; var pressed = _v12.a; var dialogId = _v12.b; var newMsg = A2($elm$core$Dict$get, dialogId, model.pendingDialogs); var dict = A2($elm$core$Dict$remove, dialogId, model.pendingDialogs); var mdl = _Utils_update( model, {pendingDialogs: dict}); if (pressed) { if (newMsg.$ === 'Just') { var m = newMsg.a; var $temp$msg = m, $temp$model = mdl; msg = $temp$msg; model = $temp$model; continue update; } else { return _Utils_Tuple2(mdl, $elm$core$Platform$Cmd$none); } } else { return _Utils_Tuple2(mdl, $elm$core$Platform$Cmd$none); } case 'SendImage': var value = msg.a; var source = msg.b; return _Utils_Tuple2( model, $author$project$Main$sendSocketCommand( A2($author$project$Protocol$ImagePackageCommand, value, source))); case 'ShowLightbox': var value = msg.a; return _Utils_Tuple2( model, $author$project$Main$canvasPort( _Utils_Tuple2( 'lightbox', $elm$core$Maybe$Just(value)))); case 'CloseSelfSummary': return _Utils_Tuple2( _Utils_update( model, {showingGameoverSelf: false}), $elm$core$Platform$Cmd$none); default: return _Utils_Tuple2( model, $author$project$Main$canvasPort( _Utils_Tuple2('store', $elm$core$Maybe$Nothing))); } } }); function $author$project$Main$cyclic$funnelDict() { return A2( $author$project$PortFunnels$makeFunnelDict, $author$project$Main$cyclic$handlers(), F2( function (_v21, _v22) { return $author$project$Main$cmdPort; })); } function $author$project$Main$cyclic$handlers() { return _List_fromArray( [ $author$project$PortFunnels$WebSocketHandler($author$project$Main$socketHandler), $author$project$PortFunnels$LocalStorageHandler($author$project$Main$storageHandler) ]); } try { var $author$project$Main$funnelDict = $author$project$Main$cyclic$funnelDict(); $author$project$Main$cyclic$funnelDict = function () { return $author$project$Main$funnelDict; }; var $author$project$Main$handlers = $author$project$Main$cyclic$handlers(); $author$project$Main$cyclic$handlers = function () { return $author$project$Main$handlers; }; } catch ($) { throw 'Some top-level definitions from `Main` are causing infinite recursion:\n\n ┌─────┐\n │ funnelDict\n │ ↓\n │ handlers\n │ ↓\n │ socketHandler\n │ ↓\n │ storageHandler\n │ ↓\n │ update\n └─────┘\n\nThese errors are very tricky, so read https://elm-lang.org/0.19.1/bad-recursion to learn how to fix it!';} var $elm$html$Html$Attributes$stringProperty = F2( function (key, string) { return A2( _VirtualDom_property, key, $elm$json$Json$Encode$string(string)); }); var $elm$html$Html$Attributes$class = $elm$html$Html$Attributes$stringProperty('className'); var $elm$html$Html$div = _VirtualDom_node('div'); var $elm$html$Html$main_ = _VirtualDom_node('main'); var $elm$virtual_dom$VirtualDom$attribute = F2( function (key, value) { return A2( _VirtualDom_attribute, _VirtualDom_noOnOrFormAction(key), _VirtualDom_noJavaScriptOrHtmlUri(value)); }); var $elm$html$Html$Attributes$attribute = $elm$virtual_dom$VirtualDom$attribute; var $elm$html$Html$button = _VirtualDom_node('button'); var $author$project$Main$getWorkPackageText = function (model) { var previousPackage = A2( $elm$core$Maybe$withDefault, $author$project$Protocol$TextPackage('an armadillo'), model.previousPackage); if (previousPackage.$ === 'TextPackage') { var t = previousPackage.a; return t; } else { return 'An error 500'; } }; var $elm$virtual_dom$VirtualDom$node = function (tag) { return _VirtualDom_node( _VirtualDom_noScript(tag)); }; var $elm$html$Html$node = $elm$virtual_dom$VirtualDom$node; var $elm$virtual_dom$VirtualDom$Normal = function (a) { return {$: 'Normal', a: a}; }; var $elm$virtual_dom$VirtualDom$on = _VirtualDom_on; var $elm$html$Html$Events$on = F2( function (event, decoder) { return A2( $elm$virtual_dom$VirtualDom$on, event, $elm$virtual_dom$VirtualDom$Normal(decoder)); }); var $elm$html$Html$Events$onClick = function (msg) { return A2( $elm$html$Html$Events$on, 'click', $elm$json$Json$Decode$succeed(msg)); }; var $elm$html$Html$section = _VirtualDom_node('section'); var $elm$virtual_dom$VirtualDom$text = _VirtualDom_text; var $elm$html$Html$text = $elm$virtual_dom$VirtualDom$text; var $author$project$Main$viewDrawing = function (model) { return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('drawing hall') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('drawing-prompt') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('drawing-prompt-intro') ]), _List_fromArray( [ $elm$html$Html$text('You must draw:') ])), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('drawing-subject') ]), _List_fromArray( [ $elm$html$Html$text( $author$project$Main$getWorkPackageText(model)) ])) ])), A3( $elm$html$Html$node, 'drawing-canvas', _List_fromArray( [ $elm$html$Html$Attributes$class('drawing-canvas'), A2( $elm$html$Html$Attributes$attribute, 'key', A2($elm$core$Maybe$withDefault, '', model.gameKey)) ]), _List_Nil), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-success landing-button'), $elm$html$Html$Events$onClick( $author$project$Main$SubmitImage($author$project$Protocol$Manual)) ]), _List_fromArray( [ $elm$html$Html$text('I\'m done!') ])) ])); }; var $author$project$Main$getMe = function (model) { return A2( $elm$core$Maybe$andThen, function (i) { return A2($elm$core$Array$get, i, model.players); }, model.myId); }; var $author$project$Main$amDone = function (model) { var _v0 = $author$project$Main$getMe(model); if (_v0.$ === 'Just') { var me = _v0.a; return $author$project$Main$isGameRunning(model) && _Utils_eq(me.status, $author$project$Protocol$Done); } else { return false; } }; var $elm$core$Basics$abs = function (n) { return (n < 0) ? (-n) : n; }; var $elm$core$String$cons = _String_cons; var $elm$core$String$fromChar = function (_char) { return A2($elm$core$String$cons, _char, ''); }; var $elm$core$Bitwise$shiftRightBy = _Bitwise_shiftRightBy; var $elm$core$String$repeatHelp = F3( function (n, chunk, result) { return (n <= 0) ? result : A3( $elm$core$String$repeatHelp, n >> 1, _Utils_ap(chunk, chunk), (!(n & 1)) ? result : _Utils_ap(result, chunk)); }); var $elm$core$String$repeat = F2( function (n, chunk) { return A3($elm$core$String$repeatHelp, n, chunk, ''); }); var $elm$core$String$padLeft = F3( function (n, _char, string) { return _Utils_ap( A2( $elm$core$String$repeat, n - $elm$core$String$length(string), $elm$core$String$fromChar(_char)), string); }); var $author$project$Main$formatTimeDifference = function (seconds) { return ((seconds < 0) ? '-' : '') + (A3( $elm$core$String$padLeft, 2, _Utils_chr('0'), $elm$core$String$fromInt( $elm$core$Basics$abs((seconds / 60) | 0))) + (':' + A3( $elm$core$String$padLeft, 2, _Utils_chr('0'), $elm$core$String$fromInt( $elm$core$Basics$abs(seconds % 60))))); }; var $elm$html$Html$header = _VirtualDom_node('header'); var $elm$html$Html$span = _VirtualDom_node('span'); var $elm$html$Html$Attributes$alt = $elm$html$Html$Attributes$stringProperty('alt'); var $elm$html$Html$img = _VirtualDom_node('img'); var $elm$html$Html$Attributes$src = function (url) { return A2( $elm$html$Html$Attributes$stringProperty, 'src', _VirtualDom_noJavaScriptOrHtmlUri(url)); }; var $author$project$Main$viewPlayerAvatar = function (player) { return A2( $elm$html$Html$img, _List_fromArray( [ $elm$html$Html$Attributes$class('avatar'), $elm$html$Html$Attributes$alt(player.username + ' Avatar'), $elm$html$Html$Attributes$src(player.image) ]), _List_Nil); }; var $author$project$Main$viewHeader = function (model) { return A2( $elm$html$Html$header, _List_fromArray( [ $elm$html$Html$Attributes$class( 'game-header' + ($author$project$Main$amDone(model) ? ' game-header-done' : '')) ]), _Utils_ap( function () { var _v0 = $author$project$Main$getMe(model); if (_v0.$ === 'Nothing') { return _List_Nil; } else { var me = _v0.a; return _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('game-header-me') ]), _List_fromArray( [ $author$project$Main$viewPlayerAvatar(me), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('my-username') ]), _List_fromArray( [ $elm$html$Html$text(me.username) ])) ])), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('my-status') ]), _List_fromArray( [ function () { var _v1 = me.status; switch (_v1.$) { case 'Done': return A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('status') ]), _List_fromArray( [ $elm$html$Html$text('Ready') ])); case 'Working': var timeLeft = _v1.a; return A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('big-scary-clock') ]), _List_fromArray( [ $elm$html$Html$text( $author$project$Main$formatTimeDifference( $elm$core$Basics$round(timeLeft))) ])); case 'Uploading': var percentage = _v1.a; return A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('status') ]), _List_fromArray( [ $elm$html$Html$text( $elm$core$String$fromInt( $elm$core$Basics$floor(percentage * 100)) + '%') ])); default: return A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('status') ]), _List_fromArray( [ $elm$html$Html$text('Stuck') ])); } }() ])) ]); } }(), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('game-status') ]), _List_fromArray( [ $elm$html$Html$text( function () { var _v2 = model.status; switch (_v2.$) { case 'NoGame': return 'Ready'; case 'Lobby': return 'Waiting for Players…'; case 'Starting': return 'Starting…'; case 'Drawing': return 'Drawing…'; case 'Understanding': return 'Understanding…'; default: return 'Game Over'; } }()) ])) ]))); }; var $author$project$Main$JoinGame = {$: 'JoinGame'}; var $author$project$Main$NewGame = {$: 'NewGame'}; var $elm$html$Html$a = _VirtualDom_node('a'); var $elm$html$Html$Attributes$autocomplete = function (bool) { return A2( $elm$html$Html$Attributes$stringProperty, 'autocomplete', bool ? 'on' : 'off'); }; var $elm$html$Html$Attributes$for = $elm$html$Html$Attributes$stringProperty('htmlFor'); var $elm$html$Html$form = _VirtualDom_node('form'); var $elm$html$Html$Attributes$href = function (url) { return A2( $elm$html$Html$Attributes$stringProperty, 'href', _VirtualDom_noJavaScriptUri(url)); }; var $elm$html$Html$i = _VirtualDom_node('i'); var $elm$html$Html$input = _VirtualDom_node('input'); var $elm$html$Html$label = _VirtualDom_node('label'); var $elm$html$Html$Attributes$name = $elm$html$Html$Attributes$stringProperty('name'); var $elm$html$Html$Events$alwaysStop = function (x) { return _Utils_Tuple2(x, true); }; var $elm$virtual_dom$VirtualDom$MayStopPropagation = function (a) { return {$: 'MayStopPropagation', a: a}; }; var $elm$html$Html$Events$stopPropagationOn = F2( function (event, decoder) { return A2( $elm$virtual_dom$VirtualDom$on, event, $elm$virtual_dom$VirtualDom$MayStopPropagation(decoder)); }); var $elm$json$Json$Decode$at = F2( function (fields, decoder) { return A3($elm$core$List$foldr, $elm$json$Json$Decode$field, decoder, fields); }); var $elm$html$Html$Events$targetValue = A2( $elm$json$Json$Decode$at, _List_fromArray( ['target', 'value']), $elm$json$Json$Decode$string); var $elm$html$Html$Events$onInput = function (tagger) { return A2( $elm$html$Html$Events$stopPropagationOn, 'input', A2( $elm$json$Json$Decode$map, $elm$html$Html$Events$alwaysStop, A2($elm$json$Json$Decode$map, tagger, $elm$html$Html$Events$targetValue))); }; var $elm$html$Html$Events$alwaysPreventDefault = function (msg) { return _Utils_Tuple2(msg, true); }; var $elm$virtual_dom$VirtualDom$MayPreventDefault = function (a) { return {$: 'MayPreventDefault', a: a}; }; var $elm$html$Html$Events$preventDefaultOn = F2( function (event, decoder) { return A2( $elm$virtual_dom$VirtualDom$on, event, $elm$virtual_dom$VirtualDom$MayPreventDefault(decoder)); }); var $elm$html$Html$Events$onSubmit = function (msg) { return A2( $elm$html$Html$Events$preventDefaultOn, 'submit', A2( $elm$json$Json$Decode$map, $elm$html$Html$Events$alwaysPreventDefault, $elm$json$Json$Decode$succeed(msg))); }; var $elm$html$Html$Attributes$placeholder = $elm$html$Html$Attributes$stringProperty('placeholder'); var $elm$html$Html$Attributes$boolProperty = F2( function (key, bool) { return A2( _VirtualDom_property, key, $elm$json$Json$Encode$bool(bool)); }); var $elm$html$Html$Attributes$required = $elm$html$Html$Attributes$boolProperty('required'); var $elm$html$Html$Attributes$type_ = $elm$html$Html$Attributes$stringProperty('type'); var $elm$html$Html$Attributes$value = $elm$html$Html$Attributes$stringProperty('value'); var $author$project$Main$viewLanding = function (model) { var url = model.url; var form = function () { var _v0 = $author$project$Main$getURLGameId(url); if (_v0.$ === 'Just') { return _List_fromArray( [ A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$type_('submit'), $elm$html$Html$Attributes$class('pure-button pure-button-primary landing-button'), $elm$html$Html$Events$onClick($author$project$Main$JoinGame) ]), _List_fromArray( [ $elm$html$Html$text('Join '), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('text-tt') ]), _List_fromArray( [ $elm$html$Html$text(model.formFields.gameId) ])), $elm$html$Html$text(' game') ])), A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Attributes$href( $elm$url$Url$toString( _Utils_update( url, {fragment: $elm$core$Maybe$Nothing}))) ]), _List_fromArray( [ $elm$html$Html$text('« Back') ])) ]); } else { return _List_fromArray( [ A2( $elm$html$Html$form, _List_fromArray( [ $elm$html$Html$Attributes$class('landing-join landing-join-gameid'), $elm$html$Html$Events$onSubmit($author$project$Main$JoinGame) ]), _List_fromArray( [ A2( $elm$html$Html$input, _List_fromArray( [ $elm$html$Html$Attributes$placeholder('GameId'), $elm$html$Html$Attributes$required(true), $elm$html$Html$Events$onInput( $author$project$Main$SetField($author$project$Main$GameIdField)), $elm$html$Html$Attributes$value(model.formFields.gameId), $elm$html$Html$Attributes$class('text-tt') ]), _List_Nil), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$type_('submit'), $elm$html$Html$Attributes$class('pure-button pure-button-primary landing-button') ]), _List_fromArray( [ $elm$html$Html$text('Join a running game') ])) ])), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-primary landing-button'), $elm$html$Html$Events$onClick($author$project$Main$NewGame) ]), _List_fromArray( [ $elm$html$Html$text('Start a New Game') ])) ]); } }(); return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('landing hall') ]), A2( $elm$core$List$cons, A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('landing-join landing-join-username') ]), _List_fromArray( [ A2( $elm$html$Html$label, _List_fromArray( [ $elm$html$Html$Attributes$for('username') ]), _List_fromArray( [ $elm$html$Html$text('People usually call me:') ])), A2( $elm$html$Html$div, _List_Nil, _List_fromArray( [ A2( $elm$html$Html$input, _List_fromArray( [ $elm$html$Html$Attributes$class('landing-username'), $elm$html$Html$Attributes$name('username'), $elm$html$Html$Attributes$placeholder(model.formFields.usernamePlaceholder), $elm$html$Html$Attributes$required(true), $elm$html$Html$Events$onInput( $author$project$Main$SetField($author$project$Main$UsernameField)), $elm$html$Html$Attributes$autocomplete(true), $elm$html$Html$Attributes$value(model.formFields.username) ]), _List_Nil), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('landing-username-icon'), A2($elm$html$Html$Attributes$attribute, 'aria-hidden', 'true') ]), _List_fromArray( [ A2( $elm$html$Html$i, _List_fromArray( [ $elm$html$Html$Attributes$class('fa fa-user-o') ]), _List_Nil) ])) ])) ])), form)); }; var $author$project$Main$LeaveGame = {$: 'LeaveGame'}; var $author$project$Main$StartGame = {$: 'StartGame'}; var $elm$html$Html$Attributes$disabled = $elm$html$Html$Attributes$boolProperty('disabled'); var $elm$html$Html$Attributes$rel = _VirtualDom_attribute('rel'); var $elm$html$Html$Attributes$target = $elm$html$Html$Attributes$stringProperty('target'); var $author$project$Main$viewLobby = function (model) { return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('lobby hall') ]), A2( $elm$core$List$cons, A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('game-link-presentation') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('text-muted') ]), _List_fromArray( [ $elm$html$Html$text('Share the following link to let other people join:') ])), function () { var url = $author$project$Main$getGameLink(model); return A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('game-link-large text-tt'), $elm$html$Html$Attributes$href( $elm$url$Url$toString(url)), $elm$html$Html$Attributes$target('_blank'), $elm$html$Html$Attributes$rel('noopener noreferrer') ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('game-link-protocol') ]), _List_fromArray( [ $elm$html$Html$text( function () { var _v0 = url.protocol; if (_v0.$ === 'Http') { return 'http://'; } else { return 'https://'; } }()) ])), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('game-link-host') ]), _List_fromArray( [ $elm$html$Html$text( _Utils_ap( url.host, _Utils_ap( A2( $elm$core$Maybe$withDefault, '', A2( $elm$core$Maybe$map, function (p) { return ':' + $elm$core$String$fromInt(p); }, url.port_)), url.path))) ])), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('game-link-path') ]), _List_fromArray( [ $elm$html$Html$text( '#' + A2($elm$core$Maybe$withDefault, '', url.fragment)) ])) ])); }() ])), model.amAdministrator ? _List_fromArray( [ A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button landing-button'), $elm$html$Html$Events$onClick($author$project$Main$LeaveGame) ]), _List_fromArray( [ $elm$html$Html$text('Cancel Game') ])), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-success landing-button'), $elm$html$Html$Attributes$disabled( $elm$core$Array$length(model.players) <= 1), $elm$html$Html$Events$onClick($author$project$Main$StartGame) ]), _List_fromArray( [ $elm$html$Html$text('Start Game') ])) ]) : _List_fromArray( [ A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-danger landing-button'), $elm$html$Html$Events$onClick($author$project$Main$LeaveGame) ]), _List_fromArray( [ $elm$html$Html$text('Leave Game') ])) ]))); }; var $author$project$Main$RemoveError = {$: 'RemoveError'}; var $author$project$Main$hasGameStarted = function (model) { var _v0 = model.gameId; if (_v0.$ === 'Nothing') { return false; } else { return true; } }; var $elm$html$Html$li = _VirtualDom_node('li'); var $elm$html$Html$nav = _VirtualDom_node('nav'); var $elm$html$Html$Attributes$title = $elm$html$Html$Attributes$stringProperty('title'); var $elm$html$Html$ul = _VirtualDom_node('ul'); var $author$project$Main$viewNav = function (model) { return A2( $elm$html$Html$nav, _List_fromArray( [ $elm$html$Html$Attributes$class('page-header pure-menu pure-menu-horizontal') ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-heading') ]), _List_fromArray( [ $elm$html$Html$text('Drawtice') ])), A2( $elm$html$Html$ul, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-list') ]), _Utils_ap( _List_fromArray( [ A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class( 'pure-menu-item pure-menu-useless' + ((!$author$project$Main$hasGameStarted(model)) ? ' pure-menu-selected' : '')) ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link') ]), _List_fromArray( [ $elm$html$Html$text('New Game') ])) ])), A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class( 'pure-menu-item pure-menu-useless' + ($author$project$Main$hasGameStarted(model) ? ' pure-menu-selected' : '')) ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link') ]), _List_fromArray( [ $elm$html$Html$text('Current Game') ])) ])) ]), _Utils_ap( function () { var _v0 = model.gameId; if (_v0.$ === 'Nothing') { return _List_Nil; } else { return _List_fromArray( [ A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item') ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link') ]), _List_fromArray( [ $elm$html$Html$text('Share this link to invite other people to join:') ])) ])), function () { var url = $elm$url$Url$toString( $author$project$Main$getGameLink(model)); return A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item pure-menu-selected') ]), _List_fromArray( [ A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link'), $elm$html$Html$Attributes$href(url), $elm$html$Html$Events$onClick($author$project$Main$NoAction) ]), _List_fromArray( [ $elm$html$Html$text(url) ])) ])); }() ]); } }(), function () { var _v1 = model.error; if (_v1.$ === 'Nothing') { return _List_Nil; } else { var err = _v1.a; return _List_fromArray( [ A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item') ]), _List_fromArray( [ A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link'), $elm$html$Html$Events$onClick($author$project$Main$RemoveError), $elm$html$Html$Attributes$href('#'), $elm$html$Html$Attributes$title('Hide error') ]), _List_fromArray( [ $elm$html$Html$text('❌') ])) ])), A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item') ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-heading') ]), _List_fromArray( [ $elm$html$Html$text('Error:') ])) ])), A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item') ]), _List_fromArray( [ A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link pure-menu-error') ]), _List_fromArray( [ $elm$html$Html$text(err) ])) ])) ]); } }()))), A2( $elm$html$Html$ul, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-list page-header-fin') ]), _List_fromArray( [ A2( $elm$html$Html$li, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-item') ]), _List_fromArray( [ A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-menu-link'), $elm$html$Html$Attributes$href('https://github.com/kongr45gpen/drawtice/'), $elm$html$Html$Attributes$target('_blank'), $elm$html$Html$Attributes$rel('noopener noreferrer') ]), _List_fromArray( [ $elm$html$Html$text('Github') ])) ])) ])) ])); }; var $author$project$Main$CloseSelfSummary = {$: 'CloseSelfSummary'}; var $elm$core$Array$filter = F2( function (isGood, array) { return $elm$core$Array$fromList( A3( $elm$core$Array$foldr, F2( function (x, xs) { return isGood(x) ? A2($elm$core$List$cons, x, xs) : xs; }), _List_Nil, array)); }); var $elm$core$List$head = function (list) { if (list.b) { var x = list.a; var xs = list.b; return $elm$core$Maybe$Just(x); } else { return $elm$core$Maybe$Nothing; } }; var $author$project$Main$lastElem = function (list) { lastElem: while (true) { if (!list.b) { return $elm$core$Maybe$Nothing; } else { if (!list.b.b) { var last = list.a; return $elm$core$Maybe$Just(last); } else { var head = list.a; var rest = list.b; var $temp$list = rest; list = $temp$list; continue lastElem; } } } }; var $author$project$Main$ShowLightbox = function (a) { return {$: 'ShowLightbox', a: a}; }; var $elm$html$Html$Attributes$download = function (fileName) { return A2($elm$html$Html$Attributes$stringProperty, 'download', fileName); }; var $elm$html$Html$Attributes$id = $elm$html$Html$Attributes$stringProperty('id'); var $author$project$Main$alwaysPreventDefault = function (msg) { return _Utils_Tuple2(msg, true); }; var $author$project$Main$onClickRaw = function (msg) { return A2( $elm$html$Html$Events$preventDefaultOn, 'input', A2( $elm$json$Json$Decode$map, $author$project$Main$alwaysPreventDefault, $elm$json$Json$Decode$succeed(msg))); }; var $elm$html$Html$p = _VirtualDom_node('p'); var $author$project$Main$viewWorkpackage = F4( function (model, loadId, packageId, _package) { var username = A2( $elm$core$Maybe$withDefault, '???', A2( $elm$core$Maybe$map, function (p) { return p.username; }, A2( $elm$core$Maybe$andThen, function (a) { return A2($elm$core$Array$get, _package.playerId, a); }, $elm$core$Maybe$Just(model.players)))); var uniqId = 'summary-image-' + ($elm$core$String$fromInt(loadId) + ('-' + $elm$core$String$fromInt(packageId))); var html = function () { var _v0 = _package.data; if (_v0.$ === 'Just') { if (_v0.a.$ === 'TextPackage') { var t = _v0.a.a; return A2( $elm$html$Html$p, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-package-text') ]), _List_fromArray( [ $elm$html$Html$text(t) ])); } else { var url = _v0.a.a; return A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$id(uniqId), $elm$html$Html$Attributes$href(url), A2($elm$html$Html$Attributes$attribute, 'data-lightbox', uniqId), $elm$html$Html$Attributes$download(''), $author$project$Main$onClickRaw( $author$project$Main$ShowLightbox(uniqId)) ]), _List_fromArray( [ A2( $elm$html$Html$img, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-package-image'), $elm$html$Html$Attributes$src(url), $elm$html$Html$Attributes$alt('Drawn image') ]), _List_Nil) ])); } } else { return A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-package-nothing'), $elm$html$Html$Attributes$title('The player didn\'t have time to complete this!') ]), _List_fromArray( [ $elm$html$Html$text('???') ])); } }(); return A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-package') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-package-prompt') ]), _List_fromArray( [ $elm$html$Html$text('by ' + (username + ':')) ])), html ])); }); var $author$project$Main$viewSelfSummary = function (model) { var workloadFinder = function (id) { return A2( $elm$core$Array$get, 0, A2( $elm$core$Array$filter, function (w) { return _Utils_eq( A2( $elm$core$Maybe$withDefault, -1, A2( $elm$core$Maybe$map, function (p) { return p.playerId; }, $elm$core$List$head(w))), id); }, A2($elm$core$Maybe$withDefault, $elm$core$Array$empty, model.workloads))); }; var workload = A2($elm$core$Maybe$andThen, workloadFinder, model.myId); var lastPackage = A2($elm$core$Maybe$andThen, $author$project$Main$lastElem, workload); var firstPackage = A2($elm$core$Maybe$andThen, $elm$core$List$head, workload); return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('self-reflection hall') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('self-reflection-intro') ]), _List_fromArray( [ $elm$html$Html$text('This is what you wrote:') ])), A2( $elm$core$Maybe$withDefault, $elm$html$Html$text('???'), A2( $elm$core$Maybe$map, A3($author$project$Main$viewWorkpackage, model, -1, -2), firstPackage)), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('self-reflection-intro') ]), _List_fromArray( [ $elm$html$Html$text('and this is what it turned into:') ])), A2( $elm$core$Maybe$withDefault, $elm$html$Html$text('???'), A2( $elm$core$Maybe$map, A3($author$project$Main$viewWorkpackage, model, -1, -2), lastPackage)), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-success landing-button'), $elm$html$Html$Events$onClick($author$project$Main$CloseSelfSummary) ]), _List_fromArray( [ $elm$html$Html$text('See more…') ])) ])); }; var $author$project$Main$DownloadGame = {$: 'DownloadGame'}; var $author$project$Main$ExtendDeadline = function (a) { return {$: 'ExtendDeadline', a: a}; }; var $author$project$Main$NextRound = {$: 'NextRound'}; var $author$project$Main$RestartGame = {$: 'RestartGame'}; var $author$project$Main$ShowConfirmDialog = F2( function (a, b) { return {$: 'ShowConfirmDialog', a: a, b: b}; }); var $elm$html$Html$aside = _VirtualDom_node('aside'); var $elm$html$Html$em = _VirtualDom_node('em'); var $elm$core$Array$isEmpty = function (_v0) { var len = _v0.a; return !len; }; var $author$project$Main$KickPlayer = function (a) { return {$: 'KickPlayer', a: a}; }; var $elm$core$String$fromFloat = _String_fromNumber; var $author$project$Main$viewPlayer = F3( function (model, id, player) { return A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class( 'player' + (player.isMe ? ' me' : '')) ]), _List_fromArray( [ $author$project$Main$viewPlayerAvatar(player), A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('username') ]), _List_fromArray( [ $elm$html$Html$text(player.username) ])), A2( $elm$html$Html$span, _List_Nil, A2( $elm$core$List$cons, function () { var _v0 = player.status; switch (_v0.$) { case 'Done': return $elm$html$Html$text('Done'); case 'Working': var timeLeft = _v0.a; return $elm$html$Html$text( 'Working, ' + ($author$project$Main$formatTimeDifference( $elm$core$Basics$round(timeLeft)) + ' left')); case 'Uploading': var fraction = _v0.a; return $elm$html$Html$text( 'Uploading (' + ($elm$core$String$fromFloat(fraction * 100) + '% done)')); default: return $elm$html$Html$text('Hit a wall'); } }(), model.amAdministrator ? _List_fromArray( [ A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class('kick-button'), $elm$html$Html$Attributes$href('#'), $elm$html$Html$Events$onClick( A2( $author$project$Main$ShowConfirmDialog, 'Are you sure you want to kick ' + (player.username + '?'), $author$project$Main$KickPlayer(id))) ]), _List_fromArray( [ $elm$html$Html$text('❌') ])) ]) : _List_Nil)) ])); }); var $author$project$Main$viewSidebar = function (model) { var playerList = $elm$core$Array$isEmpty(model.players) ? _List_Nil : _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('player-list') ]), $elm$core$Array$toList( A2( $elm$core$Array$indexedMap, $author$project$Main$viewPlayer(model), model.players))) ]); var gameoverActions = _Utils_eq(model.status, $author$project$Protocol$GameOver) ? _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('admin-actions') ]), _List_fromArray( [ model.amAdministrator ? A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Events$onClick($author$project$Main$RestartGame) ]), _List_fromArray( [ $elm$html$Html$text('Restart game') ])) : $elm$html$Html$text(''), (!model.showingGameoverSelf) ? A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Events$onClick($author$project$Main$DownloadGame) ]), _List_fromArray( [ $elm$html$Html$text('Download this') ])) : $elm$html$Html$text(''), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button pure-button-danger'), $elm$html$Html$Events$onClick( A2($author$project$Main$ShowConfirmDialog, 'Are you sure you want to leave this game?', $author$project$Main$LeaveGame)) ]), _List_fromArray( [ $elm$html$Html$text('Leave Game') ])) ])) ]) : _List_Nil; var gameId = A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('gameId') ]), _List_fromArray( [ function () { var _v0 = model.gameId; if (_v0.$ === 'Nothing') { return A2( $elm$html$Html$em, _List_fromArray( [ $elm$html$Html$Attributes$class('text-muted') ]), _List_fromArray( [ $elm$html$Html$text('Not Started') ])); } else { var id = _v0.a; return A2( $elm$html$Html$span, _List_fromArray( [ $elm$html$Html$Attributes$class('text-tt') ]), _List_fromArray( [ $elm$html$Html$text(id) ])); } }() ])); var adminActions = (model.amAdministrator && $author$project$Main$isGameRunning(model)) ? _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('admin-actions') ]), _List_fromArray( [ A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Events$onClick( $author$project$Main$ExtendDeadline(1)) ]), _List_fromArray( [ $elm$html$Html$text('Add more time') ])), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Events$onClick( A2($author$project$Main$ShowConfirmDialog, 'Are you sure you want to prematurely end this game for all players?', $author$project$Main$LeaveGame)) ]), _List_fromArray( [ $elm$html$Html$text('Cancel Game') ])), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button'), $elm$html$Html$Events$onClick( A2($author$project$Main$ShowConfirmDialog, 'Are you sure you want to quickly end this round?', $author$project$Main$NextRound)) ]), _List_fromArray( [ $elm$html$Html$text('End Round') ])) ])) ]) : _List_Nil; return A2( $elm$html$Html$aside, _List_fromArray( [ $elm$html$Html$Attributes$class('sidebar') ]), A2( $elm$core$List$cons, gameId, _Utils_ap( playerList, _Utils_ap(adminActions, gameoverActions)))); }; var $author$project$Main$TextField = {$: 'TextField'}; var $elm$html$Html$Attributes$action = function (uri) { return A2( $elm$html$Html$Attributes$stringProperty, 'action', _VirtualDom_noJavaScriptUri(uri)); }; var $author$project$Main$onSubmitRaw = function (msg) { return A2( $elm$html$Html$Events$preventDefaultOn, 'submit', A2( $elm$json$Json$Decode$map, $author$project$Main$alwaysPreventDefault, $elm$json$Json$Decode$succeed(msg))); }; var $elm$html$Html$textarea = _VirtualDom_node('textarea'); var $author$project$Main$viewStarting = function (model) { return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('starting') ]), _List_fromArray( [ A2( $elm$html$Html$form, _List_fromArray( [ $elm$html$Html$Attributes$class('text-starting hall'), $elm$html$Html$Attributes$action('#'), $author$project$Main$onSubmitRaw( $author$project$Main$SubmitText($author$project$Protocol$Manual)) ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('text-starting-prompt') ]), _List_fromArray( [ $elm$html$Html$text('What do you want people to draw?') ])), A2( $elm$html$Html$textarea, _List_fromArray( [ $elm$html$Html$Attributes$class('text-starting-input'), $elm$html$Html$Events$onInput( $author$project$Main$SetField($author$project$Main$TextField)) ]), _List_Nil), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button landing-button') ]), _List_fromArray( [ $elm$html$Html$text('Submit idea') ])) ])) ])); }; var $author$project$Main$Backward = {$: 'Backward'}; var $author$project$Main$Forward = {$: 'Forward'}; var $author$project$Main$MoveWorkload = function (a) { return {$: 'MoveWorkload', a: a}; }; var $elm$html$Html$h3 = _VirtualDom_node('h3'); var $author$project$Main$isAtWorkloadEnd = F2( function (model, dir) { return ((!model.currentWorkload) && _Utils_eq(dir, $author$project$Main$Backward)) ? true : (_Utils_eq( model.currentWorkload, $elm$core$Array$length( A2($elm$core$Maybe$withDefault, $elm$core$Array$empty, model.workloads)) - 1) && _Utils_eq(dir, $author$project$Main$Forward)); }); var $author$project$Main$viewSummary = function (model) { var workload = A2( $elm$core$Maybe$withDefault, _List_Nil, A2( $elm$core$Maybe$andThen, function (a) { return A2($elm$core$Array$get, model.currentWorkload, a); }, model.workloads)); return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('summary hall') ]), _List_fromArray( [ A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class( 'summary-arrow summary-arrow-left' + (A2($author$project$Main$isAtWorkloadEnd, model, $author$project$Main$Backward) ? ' summary-arrow-disabled' : '')), $elm$html$Html$Attributes$href('#'), $elm$html$Html$Events$onClick( $author$project$Main$MoveWorkload($author$project$Main$Backward)) ]), _List_fromArray( [ A2( $elm$html$Html$i, _List_fromArray( [ $elm$html$Html$Attributes$class('fa fa-chevron-left') ]), _List_Nil) ])), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-main') ]), _List_fromArray( [ A2( $elm$html$Html$h3, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-header') ]), _List_fromArray( [ $elm$html$Html$text( 'Series ' + $elm$core$String$fromInt(model.currentWorkload + 1)) ])), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('summary-container') ]), A2( $elm$core$List$indexedMap, A2($author$project$Main$viewWorkpackage, model, model.currentWorkload), workload)) ])), A2( $elm$html$Html$a, _List_fromArray( [ $elm$html$Html$Attributes$class( 'summary-arrow summary-arrow-right' + (A2($author$project$Main$isAtWorkloadEnd, model, $author$project$Main$Forward) ? ' summary-arrow-disabled' : '')), $elm$html$Html$Attributes$href('#'), $elm$html$Html$Events$onClick( $author$project$Main$MoveWorkload($author$project$Main$Forward)) ]), _List_fromArray( [ A2( $elm$html$Html$i, _List_fromArray( [ $elm$html$Html$Attributes$class('fa fa-chevron-right') ]), _List_Nil) ])) ])); }; var $author$project$Main$getWorkPackageImage = function (model) { var _default = $author$project$Main$imageUrl + 'dog.jpg'; var previousPackage = A2( $elm$core$Maybe$withDefault, $author$project$Protocol$ImagePackage(_default), model.previousPackage); if (previousPackage.$ === 'ImagePackage') { var p = previousPackage.a; return p; } else { return _default; } }; var $author$project$Main$viewUnderstanding = function (model) { return A2( $elm$html$Html$section, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding hall') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding-prompt') ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding-prompt-intro') ]), _List_fromArray( [ $elm$html$Html$text('Someone painted:') ])), A2( $elm$html$Html$img, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding-image'), $elm$html$Html$Attributes$src( $author$project$Main$getWorkPackageImage(model)), $elm$html$Html$Attributes$alt('What the previous player drew') ]), _List_Nil) ])), A2( $elm$html$Html$form, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding-write'), $elm$html$Html$Attributes$action('#'), $author$project$Main$onSubmitRaw( $author$project$Main$SubmitText($author$project$Protocol$Manual)) ]), _List_fromArray( [ A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('understanding-write-intro') ]), _List_fromArray( [ $elm$html$Html$text('What is that?') ])), A2( $elm$html$Html$textarea, _List_fromArray( [ $elm$html$Html$Attributes$class('text-understanding-input'), $elm$html$Html$Events$onInput( $author$project$Main$SetField($author$project$Main$TextField)) ]), _List_Nil), A2( $elm$html$Html$button, _List_fromArray( [ $elm$html$Html$Attributes$class('pure-button landing-button understanding-button') ]), _List_fromArray( [ $elm$html$Html$text('Submit explanation') ])) ])) ])); }; var $author$project$Main$view = function (model) { return { body: _List_fromArray( [ $author$project$Main$viewNav(model), $author$project$Main$viewHeader(model), A2( $elm$html$Html$div, _List_fromArray( [ $elm$html$Html$Attributes$class('page-container') ]), _List_fromArray( [ A2( $elm$html$Html$main_, _List_fromArray( [ $elm$html$Html$Attributes$class('page') ]), _List_fromArray( [ function () { var _v0 = model.status; switch (_v0.$) { case 'NoGame': return $author$project$Main$viewLanding(model); case 'Lobby': return $author$project$Main$viewLobby(model); case 'Starting': return $author$project$Main$viewStarting(model); case 'Drawing': return $author$project$Main$viewDrawing(model); case 'Understanding': return $author$project$Main$viewUnderstanding(model); default: return model.showingGameoverSelf ? $author$project$Main$viewSelfSummary(model) : $author$project$Main$viewSummary(model); } }() ])), $author$project$Main$viewSidebar(model) ])) ]), title: 'Drawtice' }; }; var $author$project$Main$main = $elm$browser$Browser$application( {init: $author$project$Main$init, onUrlChange: $author$project$Main$UrlChanged, onUrlRequest: $author$project$Main$LinkClicked, subscriptions: $author$project$Main$subscriptions, update: $author$project$Main$update, view: $author$project$Main$view}); _Platform_export({'Main':{'init':$author$project$Main$main( $elm$json$Json$Decode$succeed(_Utils_Tuple0))(0)}});}(this));
import React from 'react'; import 'antd/dist/antd.css'; import "./StyleMenu.css"; import { Route, Link, Redirect } from 'react-router-dom'; import { Layout, Menu } from 'antd'; import { logOut } from "../Api/auth" import useAuth from "../Hooks/useAuth"; export default function LayoutSistema(props) { const { Header , Content} = Layout; const { routes } = props; const logoutUser = () => { logOut() window.location.reload(); } const { user, isLoading } = useAuth(); console.log(user); if (!user && !isLoading) { return ( <> <Route path="/" /> <Redirect to="/" /> </> ) } if (user && !isLoading) { return ( <Layout className="color"> <Header className='head'> <Menu theme="dark" mode="horizontal"> <Menu.Item key="1"><Link to='/AdminSistema'>Home</Link></Menu.Item> <Menu.Item key="2"><Link to='/AdminSistema/ListComestibles' >Comestibles</Link></Menu.Item> <Menu.Item key="3"> <Link to='/AdminSistema/ListTecnologia'>Tecnologia</Link></Menu.Item> <Menu.Item key="4"><Link to='/AdminSistema/ListLimpHigiene'>Limpieza e Higiene</Link></Menu.Item> <Menu.Item key="5"><Link to='/AdminSistema/ListDesEmpaques' >Desechables y Empaques</Link></Menu.Item> <Menu.Item key="6"><Link to='/AdminSistema/ListEqUtencilios'>Equipos y Utencilios</Link></Menu.Item> <Menu.Item key="7"> <Link to='/AdminSistema/ListMarcas'>Marcas</Link></Menu.Item> <Menu.Item key="8"> <Link to='/AdminSistema/MenuProductos'>Productos</Link></Menu.Item> <Menu.Item key="9"> <Link to='/AdminSistema/ListProveedores'>Proveedores</Link></Menu.Item> <Menu.Item key="10"><a id='logoutButton' onClick={logoutUser}>Cerrar Sesión</a></Menu.Item> </Menu> </Header> <Content className='contenido'> <LoadRouters routes={routes} /> </Content> </Layout> ); } return null } function LoadRouters({ routes }) { return routes.map((route, index) => ( <Route key={index} path={route.path} exact={route.exact} component={route.component} /> )); }
export default [ [ { label: "Query", name: "query", type: "text", gridClass: "col s12 m5" }, { label: "Stars", name: "stars", type: "text", gridClass: "col s12 m5 offset-m2" } ], [ { label: "License", name: "license", type: "select", options: [ { value: "afl-3.0", label: "Academic Free License v3.0" }, { value: "apache-2.0", label: "Apache license 2.0" }, { value: "artistic-2.0", label: "Artistic license 2.0" }, { value: "bsl-1.0", label: "Boost Software License 1.0" }, { value: "bsd-2-clause", label: "BSD 2-clause 'Simplified' license" }, { value: "bsd-3-clause", label: "BSD 3-clause 'New' or 'Revised' license" }, { value: "bsd-3-clause-clear", label: "BSD 3-clause Clear license" }, { value: "cc", label: "Creative Commons license family" }, { value: "cc0-1.0", label: "Creative Commons Zero v1.0 Universal" }, { value: "cc-by-4.0", label: "Creative Commons Attribution 4.0" }, { value: "cc-by-sa-4.0", label: "Creative Commons Attribution Share Alike 4.0" }, { value: "ecl-2.0", label: "Educational Community License v2.0" }, { value: "epl-1.0", label: "Eclipse Public License 1.0" }, { value: "eupl-1.1", label: "European Union Public License 1.1" }, { value: "wtfpl", label: "Do What The F*ck You Want To Public License" }, { value: "agpl-3.0", label: "GNU Affero General Public License v3.0" }, { value: "gpl", label: "GNU General Public License family" }, { value: "gpl-2.0", label: "GNU General Public License v2.0" }, { value: "gpl-3.0", label: "GNU General Public License v3.0" }, { value: "unlicense", label: "The Unlicense" }, { value: "zlib", label: "zLib License" }, { value: "isc", label: "ISC" }, { value: "lgpl", label: "GNU Lesser General Public License family" }, { value: "mit", label: "MIT" } ], gridClass: "col s12 m5" }, { label: "Fork", name: "fork", type: "checkbox", gridClass: "col s12 m5 offset-m2" } ] ];
var _mSiteName = 'Google Local'; var _mZoomIn = 'Zoom In'; var _mZoomOut = 'Zoom Out'; var _mZoomSet = 'Click to set zoom level'; var _mZoomDrag = 'Drag to zoom'; var _mPanWest = 'Go left'; var _mPanEast = 'Go right'; var _mPanNorth = 'Go up'; var _mPanSouth = 'ÏòÏÂ'; var _mLastResult = 'Return to the last result'; var _mGoogleCopy = '&#169;2005 Google'; var _mDataCopy = 'Map data &#169;2005 '; var _mNavteq = 'NAVTEQ&#8482;'; var _mTeleAtlas = 'Tele Atlas'; var _mZenrin = 'ZENRIN'; var _mZenrinCopy = 'Map &#169;2005 '; var _mNormalMap = 'Map'; var _mNormalMapShort = 'Map'; var _mHybridMap = 'Hybrid'; var _mHybridMapShort = 'Hyb'; var _mNew = 'New!'; var _mTerms = 'Terms of Use'; var _mKeyholeMap = 'Satellite'; var _mKeyholeMapShort = 'Sat'; var _mKeyholeCopy = 'Imagery &#169;2005 '; var _mScale = 'Scale at the center of the map'; var _mKilometers = 'km'; var _mMiles = 'mi'; var _mMeters = 'm'; var _mFeet = 'ft'; var _mDecimalPoint = '.'; var _mThousandsSeparator = ','; var _mMapErrorTile = 'We are sorry, but we don\'t have maps at this zoom level for this region.<p>Try zooming out for a broader look.</p>'; var _mKeyholeErrorTile = 'We are sorry, but we don\'t have imagery at this zoom level for this region.<p>Try zooming out for a broader look.</p>'; var _mTermsURL = 'http://www.google.com/intl/en_ALL/help/terms_local.html'; var _mStaticPath = 'http://www.google.com/intl/en_ALL/mapfiles/'; var _mDomain = 'google.com'; var _apiHash = '5f87579ff86792cf982d095a4228e3de6cdaf562'; var _apiKey = 'ABQIAAAA7nPTPXCvzWYxyKdmbFQfTxRfh1ef-GeSz5gtCVpCKOPebNr1YhR23M_jRfeqAugNMsW3pZQJAwfCFw'; var _mApiBadKey = 'The Google Maps API key used on this web site was registered for a different web site. You can generate a new key for this web site at http://www.google.com/apis/maps/.'; function createMapSpecs() { var mt = 'http://mt%1$d.google.com/mt?n=404'; var mtd = '4'; var tv = 'w2.9'; var lrtv = 't2.2'; var apitv = 'ap.4'; var lrapitv = 'tap.2'; var hmt = 'http://mt%1$d.google.com/mt?n=404'; var hmtd = '4'; var htv = 'w2t.4'; var lrhtv = 't2t.2'; var apihtv = 'apt.3'; var lrapihtv = 'tapt.2'; var kmt = 'http://kh%1$d.google.com/kh?n=404'; var kmtd = '4'; var kdomain = 'google.com'; var ktv = '3'; var kdisable = false; var khauth = 'fzwq2tTFhLHFZ74U5ckS9FFkL2Y9qcJ7BtNUYQ'; var kjapandatumhack = false; var hybrid = (htv != ''); if (!arguments.callee.mapSpecs) { var mapSpecs = []; var tileVersion = window._apiKey ? apitv : tv; var lrTileVersion = window._apiKey ? lrapitv : lrtv; var hTileVersion = window._apiKey ? apihtv : htv; var lrHTileVersion = window._apiKey ? lrapihtv : lrhtv; var mapCopy = (tileVersion != tv) ? G_MAP_API_COPYRIGHTS :G_MAP_DEFAULT_COPYRIGHTS; var hybridCopy = (hTileVersion != htv) ? G_MAP_API_COPYRIGHTS :G_MAP_DEFAULT_COPYRIGHTS;_GOOGLE_MAP_TYPE = new _GoogleMapMercSpec(mt, mtd, tileVersion, mapCopy,lrTileVersion);mapSpecs.push(_GOOGLE_MAP_TYPE); if (!kdisable) { _SATELLITE_TYPE = new _KeyholeMapMercSpec(kmt, kmtd, kdomain, ktv,khauth, kjapandatumhack);mapSpecs.push(_SATELLITE_TYPE); if (hybrid) { _HYBRID_TYPE = new _HybridMapSpec(kmt, kmtd, kdomain, ktv, khauth,kjapandatumhack, hmt, hmtd,hTileVersion, hybridCopy,lrHTileVersion);mapSpecs.push(_HYBRID_TYPE); } } arguments.callee.mapSpecs = mapSpecs; } return arguments.callee.mapSpecs; } var _u = navigator.userAgent.toLowerCase(); function _ua(t) { return _u.indexOf(t) != -1; } function _uan(t) { if(!window.RegExp) { return 0; } var r = new RegExp(t+'([0-9]*)'); var s = r.exec(_u); var ret = 0; if (s.length >= 2) { ret = s[1]; } return ret; } function _noActiveX() { if(!_ua('msie') || !document.all || _ua('opera')) { return false; } var s = false; eval('try { new ActiveXObject("Microsoft.XMLDOM"); }'+'catch (e) { s = true; }'); return s; } function _compat() { return ((_ua('opera') &&parseInt(new RegExp("opera.(\\d+)").exec(_u)[1]) > 7 ) ||(_ua('safari') && _uan('safari/') >= 125) ||(_ua('msie') &&!_ua('msie 4') && !_ua('msie 5.0') && !_ua('msie 5.1') &&!_ua('msie 3') && !_ua('msie 5.5') && !_ua('powerpc')) ||(document.getElementById && window.XSLTProcessor &&window.XMLHttpRequest && !_ua('netscape6') &&!_ua('netscape/7.0'))); } _fc = false; _c = _fc || _compat(); function _browserIsCompatible() { return _c; } function GBrowserIsCompatible() { return _c; } function _havexslt() { if (typeof GetObject != 'undefined' ||(typeof XMLHttpRequest != 'undefined' &&typeof DOMParser != 'undefined' &&typeof XSLTProcessor != 'undefined')) { return true; } else { return false; } } function _script(src) { var src_name = src.split("/").pop();var aTimer = '<'+'script type="text/javascript">' +'if (typeof TS_load_timers == "object") ' +'TS_load_timers.start("load '+src_name+'", "glm_'+src_name+'");' +'<'+'/script>';document.write(aTimer);var ret='<'+'script src="'+src+'"'+' type="text/javascript"><'+'/script>';document.write(ret);aTimer = '<'+'script type="text/javascript">' +'if (typeof TS_load_timers == "object") TS_load_timers.end();' +'<'+'/script>';document.write(aTimer); } function GLoadMapsScript() { if (_havexslt()){_script("http://maps.google.com/mapfiles/maps.30a.js");} else if (_ua('safari')){_script("http://maps.google.com/mapfiles/maps.30a.safari.js");} else{_script("http://maps.google.com/mapfiles/maps.30a.xslt.js");} } if (_c && !_noActiveX()) { document.write('<style type="text/css" media="screen">.noscreen {display: none}</style>');document.write('<style type="text/css" media="print">.noprint {display: none}</style>');GLoadMapsScript(); }
import axios from 'axios'; import { BASE_URL } from '../config'; const baseURL = 'https://sindelantal-backend.herokuapp.com/'; const api = axios.create({ baseURL, headers: { 'Cache-Control': 'no-cache' }, timeout: 20000 }); const createUser = data => api.post('user/create', data); const loginUser = data => api.post('login', data); export default { createUser, loginUser };
import React, { Component, PropTypes } from 'react' import classname from 'classname' import '../scss/Toggle.scss' export default class Toggle extends Component { static propTypes = { children: PropTypes.node, checked: PropTypes.bool, onChange: PropTypes.func, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) } constructor (props) { super(props) const checked = !!props.checked this.state = { checked } } componentWillReceiveProps (props) { const checked = !!props.checked this.setState({ checked }) } handleChange (event) { const checked = !this.state.checked this.setState({ checked }) const { onChange, value } = this.props onChange && onChange({ checked, value }) } render () { const { checked } = this.state const cls = classname('Toggle', [ checked ? 'Toggle--enabled' : 'Toggle--disabled' ]) return ( <div className={cls} onClick={this.handleChange.bind(this)}> {this.props.children} <div className='Toggle-switch'> <i></i> </div> </div> ) } }
import axios from 'axios' const request = axios.create({ baseURL: "https://conduit.productionready.io" }) // 请求拦截器 // 相应拦截器 export default request
const { API_ROUTE } = process.env; const { STATIC_ROUTE } = process.env; module.exports = { API_ROUTE, STATIC_ROUTE, };
import React, { useEffect } from 'react' import { StyledHighScore } from './styles/StyledHighScore' const NO_OF_HIGH_SCORES = 10; const HIGH_SCORES = 'highScores'; const highScoreString = localStorage.getItem(HIGH_SCORES); const highScores = JSON.parse(highScoreString) ?? []; export function checkHighScore(score) { const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? []; const lowestScore = highScores[NO_OF_HIGH_SCORES - 1]?.score ?? 0; if (score > lowestScore) { saveHighScore(score, highScores); } } export function saveHighScore(score, highScores) { const name = prompt('You got a highscore! Enter name:'); const newScore = { score, name }; // 1. Add to list highScores.push(newScore); // 2. Sort the list highScores.sort((a, b) => b.score - a.score); // 3. Select new list highScores.splice(NO_OF_HIGH_SCORES); // 4. Save to local storage localStorage.setItem(HIGH_SCORES, JSON.stringify(highScores)); }; export function showHighScores() { const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ?? []; const highScoreList = document.getElementById(HIGH_SCORES); highScoreList.innerHTML = highScores .map((score) => `<li>${score.name} - ${score.score}`) .join(''); } const HighScore =() => { useEffect(()=>{ showHighScores() }, []) return( <StyledHighScore> <h2>HIGH SCORES</h2> <ol id='highScores'> </ol> </StyledHighScore> ) } export default HighScore
var idToke = 0; var contador = 0; var id = 0; firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. console.log("si esta registrado") console.log(user.displayName) idToke = user.uid console.log(idToke) } else { // No user is signed in. console.log("no esta registrado") } }); getIdDetail(); function getIdDetail() { var parameters = location.search.substring(1).split("&"); var temp = parameters[0].split("="); id = unescape(temp[1]); console.log(id); } loadCatalog(); //funcion para sacar todo lo que hay en catalogo function loadCatalog(){ var database = firebase.database().ref().child('catalog/' + id); database.remove(); database = firebase.database().ref().child('catalog/'); database.once('value', function(snapshot){ if(snapshot.exists()){ var content = ''; var column = 0; snapshot.forEach(function(data){ var name = data.val().name; var category= data.val().category; id = data.val().id; console.log(id) if(data.val().userCreator == idToke) { //content += '<div class="card"> <img class="card-img-top" src="..." alt="Card image cap"> <div class="card-body">'; content += '<div class="card"> <div class="card-body"> <h5 class="card-title">' + name + '</h5>'; //Title content += '<p class="card-text">' + category + '</p>';//Category content += '<a href="#" class="btn btn-primary">' + 'Edit' + '</a>'; content += '<a class="btn btn-danger" href="each.html?id='+id+'">' + 'Delete' + '</a>'; content += '</div> </div>'; } }); $('#createList').append(content); } }); } // var deleteEn = document.getElementById("deleteBtn").value; // deleteEn.value.addEventListener('click', e => { // var database = firebase.database().ref().child('catalog/' + id).remove // console.log("yes") // }); function logOut() { firebase.auth().signOut().then(function() { // Sign-out successful. console.log("yase fue") window.location.href = "login.html" }, function(error) { // An error happened. }); }
import React from "react"; import { connect } from "react-redux"; import { openModal, SUCCESS, CHALLENGE } from "ducks/Modals"; import Button from "components/Button"; import "./style.css"; import successIcon from "images/successG.png"; import challengeIcon from "images/challengeG.png"; import arrow from "images/ArrowB.png"; const SuccessesChallenges = props => ( <div className="successes-challenges"> <div className="box meeting-sidebar successes"> <div className="header"> <img src={successIcon} alt="" /> Successes </div> <ul> {props.successes.map(succ => ( <li key={succ.id}> {succ.title}{" "} <img src={arrow} alt="" onClick={() => { props.openExistingSuccessModal(succ.id, props.meeting); }} /> </li> ))} </ul> <Button click={() => { props.openNewSuccessModal(props.meeting); }} > New Success </Button> </div> <div className="box meeting-sidebar challenges"> <div className="header"> <img src={challengeIcon} alt="" /> Challenges </div> <ul> {props.challenges.map(chal => ( <li key={chal.id}> {chal.title}{" "} <img src={arrow} alt="" onClick={() => { props.openExistingChallengeModal(chal.id, props.meeting); }} /> </li> ))} </ul> <Button click={() => { props.openNewChallengeModal(props.meeting); }} > New Challenge </Button> </div> </div> ); const mapStateToProps = (state, ownProps) => ({ successes: state.successes.items.filter( ({ meeting }) => meeting === ownProps.meeting ), challenges: state.challenges.items.filter( ({ meeting }) => meeting === ownProps.meeting ) }); const mapDispatchToProps = dispatch => ({ openNewSuccessModal: meeting_id => { dispatch(openModal(SUCCESS, { new: true, meeting_id })); }, openExistingSuccessModal: (success_id, meeting_id) => { dispatch(openModal(SUCCESS, { new: false, success_id, meeting_id })); }, openNewChallengeModal: meeting_id => { dispatch(openModal(CHALLENGE, { new: true, meeting_id })); }, openExistingChallengeModal: (challenge_id, meeting_id) => { dispatch(openModal(CHALLENGE, { new: false, challenge_id, meeting_id })); } }); export default connect(mapStateToProps, mapDispatchToProps)( SuccessesChallenges );
const express = require('express'); const loginRouter = express.Router(); const jwt = require('jsonwebtoken'); const Userdata = require('../model/Userdata'); adminemail='admin@gmail.com' adminpassword='12345678' loginRouter.post('/',(req,res)=>{ res.header("Access-Control-Allow-Orgin","*") res.header('Access-Control-Allow-Methods: GET,POST, PATCH , PUT, DELETE,OPTIONS'); let password = req.body.password; let email = req.body.email; Userdata.findOne({"email":email}) .then(function(Userdat){ if ( ( email === adminemail && password === adminpassword ) || (email === Userdat?.email && password === Userdat?.password) ) { let payload = {subject: email+password} let token = jwt.sign(payload, 'secretKey') res.status(200).send({token}) } else { res.status(401).send('Invalid Password or Invalid Password') } }) }) module.exports = loginRouter;
class Wall{ index(req,res){ get_posts(function(post_data){ var js = [ "js/admin/wall/admin_wall.js" ]; res.render('wall/wall',{ title:'Bulletin',user:req.session.passport.user,posts:post_data,template_js:js }); }); } } function get_posts(cb){ pool.connect(function(err,client,done){ if(err){ return console.error("error fetching posts:",err); }else{ client.query("SELECT json_build_object('id', p.id, 'content', p.content, 'images',(SELECT json_agg(json_build_object('id', pi.id, 'img_orig_name', pi.img_orig_name))FROM posts_images pi WHERE p.id = pi.post_id))FROM posts p ORDER BY p.id DESC",function(err,result){ // client.query("SELECT posts.id, posts.content, array_agg(posts_images.img_orig_name) FROM posts_images INNER JOIN posts on posts_images.post_id = posts.id GROUP BY posts_images.post_id,posts.id",function(err,result){ if(err){ return console.error("error fetching posts:",err); }else{ cb(result.rows); } }); } }); } module.exports = new Wall();
export default 'global:effect'
import React from 'react'; import Header from './header/Header'; import {Route,Link,Switch} from 'react-router-dom'; require('../lib/showdown/showdown.js'); import Login from './login_regist/Login_register'; import Home from './home/Home'; import ArticleForm from './article/ArticleForm'; export default class Blog extends React.Component{ constructor(){ super(); } render(){ return ( <div className="blog_container"> <Switch> <Route exact path="/home" component={Home}/> <Route path="/login" component={Login}/> {/*<Route path="/newArticle" component={ArticleForm}/>*/} </Switch> </div> ); } }
/* * @lc app=leetcode.cn id=554 lang=javascript * * [554] 砖墙 */ // @lc code=start /** * @param {number[][]} wall * @return {number} */ var leastBricks = function(wall) { const cnt = new Map(); for (const widths of wall) { const n = widths.length - 1; let sum = 0; for (let i = 0; i < n; i++) { sum += widths[i]; cnt.set(sum, (cnt.get(sum) || 0) + 1) } } let maxcnt = 0; for (const [_, c] of cnt.entries()) { maxcnt = Math.max(maxcnt, c); } return wall.length - maxcnt; }; // @lc code=end
import React from "react"; import {List, ListItem, ListItemIcon, Checkbox, ListItemText} from "@material-ui/core"; const StudentList = ({filteredStudents, onTogglePresence}) => { return <> {filteredStudents ? <List style={{ width: "90%" }}> {filteredStudents.map(student => ( <ListItem key={student.id} dense button onClick={(e) => onTogglePresence(e, student.id, student.isPresent)} > <ListItemIcon> <Checkbox edge="start" checked={student.isPresent} /> </ListItemIcon> <ListItemText id={student.id} primary={student.name} /> </ListItem> ))} </List> : "carregando..."} </> } export default StudentList;
WhatTheTabStatic.Log({ sender: "popup.bundle.js", message: "Set popup javascript here." });
$(document).ready(function(){ function getUrlParam(name){ //构造一个含有目标参数的正则表达式对象 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //匹配目标参数 var r = window.location.search.substr(1).match(reg); //返回参数值 if (r!=null) return unescape(r[2]); return null; } //获取对应ID的商品内容 var id = getUrlParam('number'); $.getJSON('goodsData.json',function(result){ $.each(result,function(i,goods){ if(goods.id==id){ var zhekou=goods.price*10/goods.oldprice; $('.goodsname').text(goods.tittle); $('.middle_jiage strong').text('¥'+goods.price+'.00'); $('.middle_zhekou').text(zhekou.toFixed(1)+'折'); $('.bottom_jiage_numeber').text('¥'+goods.oldprice+'.00'); //判断是否是收藏商品,按钮需要高亮不 if(goods.shoucang==1){ $('.show').hide(); $('.hide').show(); } //该商品对应的口味信息 var zifuchuan=goods.kouwei; var attry=[]; attry=zifuchuan.split(','); var s=0; for(s;s<attry.length;s++){ var kouwei='<li><div class="editInfor-optTaste-ul-sku">'+attry[s]+'</div></li>'; $('.editInfor-optTaste-ul').append(kouwei); } //轮播图 var mySwiper = new Swiper('.swiper-container', { direction: 'horizontal', loop: true, pagination: '.swiper-pagination', autoplay:3000, autoplayDisableOnInteraction : false }) } }) //切换收藏 $(".shoucang").on("click",function(){ $(".shoucang>img").toggle(); }) //跳转到购物车页面 $(".gouwuchediv").on("click",function(){ window.location="shop.html"; }) //点击查看更多评价,跳转到更多评价页 $(".gengduodiv").on("click",function(){ window.location="moreRated.html"; }) //点击加入购物车跳出选择SKU弹窗 $('.jiarudiv').on('click',function(){ $('.editInfor').show(); }) //关闭选择SKU弹窗 $('.editInfor-cont-close').on('click',function(){ $('.editInfor').hide(); }) //SKU选择更换口味 $('.editInfor-optTaste-ul-sku').on('click',function(){ $('.editInfor-optTaste-ul-sku').removeClass('xuanzhong'); $(this).addClass('xuanzhong'); var value=$(this).text(); $('.editInfor-cont-taste').text(value); }) //减少购买数量 $('#editInfor-number-reduce').on('click',function(){ var value=$('#editInfor-number-text').val(); if(value<=1){ $(this).attr('disabled','disabled'); } else{ $('#editInfor-number-text').val(parseInt(parseInt(value)-1)); } }) //增加购买数量 $('#editInfor-number-add').on('click',function(){ $('#editInfor-number-reduce').removeAttr('disabled'); var value=$('#editInfor-number-text').val(); $('#editInfor-number-text').val(parseInt(parseInt(value)+1)); }) //点击确认 $('.editInfor-confirm').on('click',function(){ $('.editInfor').hide(); }) }) })
/*************************************************************************** * * Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved * $Id$ * **************************************************************************/ /** * @file Index.js * @extend bun.$_appname * react应用ssr demo */ class Action_Show_Example extends bun.class['$_appname'] { constructor() { super(); this.a = 1; } async execute(ctx) { let bsCommon = {}; let state = { home: '', pageone: '' }; // 获取各前端路由对应的model层入口 let dataClass = new Model_Services_DataStation().getClassName(ctx.path); let objServicePageData = new dataClass().execute(bsCommon); bsCommon['type'] = ctx.request.query.type || 'a'; state = Object.assign(state, objServicePageData); const initialState = state; await ctx.render('example',{ message: 'Bunjs is ready!', state: JSON.stringify(state) }); } } module.exports = Action_Show_Example;
import HTML from '../img/HTML.png' import CSS from '../img/CSS.png' import Bootstrap from '../img/bootstrap.svg' import Tailwind from '../img/Tailwind.png' import JS from '../img/JS.png' import react from '../img/React.png' import redux from '../img/redux.svg' import next from '../img/Next.png' import firebase from '../img/Firebase.png' import Webflow from '../img/Webflow.svg' import Figma from '../img/Figma.png' import '../style/techUsed.css' function Tech() { return ( <div className='flex justify-space-around'> <h2 className='tech__heading pb-3 py-3'> Technologies </h2> <div> <img className='tech__icons' height={70} width={75} src={Webflow} alt='Webflow' /> {/* - */} <img className='tech__icons' height={70} width={75} src={Figma} alt='Figma' /> <img className='tech__icons' height={80} width={75} src={HTML} alt='HTML5' /> {/* - */} <img className='tech__icons' height={80} width={65} src={CSS} alt='CSS3' /> {/* - */} <img className='tech__icons' height={80} width={65} src={JS} alt='JavaScript' /> {/* - */} <img className='tech__icons' height={75} width={75} src={Bootstrap} alt='Bootstrap4' /> {/* - */} <img className='tech__icons' height={70} width={75} src={Tailwind} alt='Tailwind CSS' /> {/* - */} <img className='tech__icons' height={85} width={95} src={react} alt='React' /> {/* - */} <img className='tech__icons' height={75} width={75} src={redux} alt='Redux' /> {/* - */} <img className='tech__icons' height={75} width={75} src={next} alt='Next.js' /> {/* - */} <img className='tech__icons' height={75} width={65} src={firebase} alt='Google Firebase' /> {/* - */} </div> </div> ) } export default Tech
// Your app should not require any pre-requisites. It should // run on any machine with latest LTS version of Node. // Alternatively you can create a Docker image. "use strict"; const express = require("express"); const app = express(); const jsonParser = require("body-parser").json; const fs = require("fs"); const logger = require("morgan"); // Data const data = fs.readFileSync("stats.json"); const stats = JSON.parse(data); // Routes const routes_stats = require("./routes/routes_stats"); const routes_convert = require("./routes/routes_convert"); // Parsing the req body as JSON // making it accessible from the req.body property app.use(jsonParser()); // Getting info about requests in the console app.use(logger("dev")); // Allowing Cross-Origin Resource Sharing app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); if (req.method === "OPTIONS") { res.header("Access-Control-Allow-Methods", "GET, PUT, POST"); return res.status(200).json({}); } next(); }); // The routes will try to apply one of the handlers app.use("/stats", routes_stats); app.use("/convert", routes_convert); // Catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error("Not Found"); err.status = 404; next(err); }); // Error handler app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ error: { message: err.message } }); }); // Setting the PORT for the API to run on const port = process.env.PORT || 3000; app.listen(port, () => { console.log("Listening on port:", port); }); //
import { useState } from '@hookstate/core' import store from '../store' const NotCompleted = () => { const { tasks } = useState(store) const notCompletedTasks = tasks.get().filter(task => !task.completed) const completeTask = task => { const taskIndex = tasks.get().indexOf(task) tasks.nested(taskIndex).completed.set(true) } return ( <div> <h4 className="text-muted mb-4">Todo</h4> {notCompletedTasks.map((task, index) => ( <div className="row row-cols-2 mb-3" key={index}> <div className="bg-light ms-2 lead p-2">{task.text}</div> <button className="btn btn-success btn-sm w-auto ms-3" onClick={() => completeTask(task)} > Complete </button> </div> ))} </div> ) } export default NotCompleted
var blossom = { main_size:0, invert:function(aug_path,G){ for(let i = 0; i<aug_path.length/2; i++){ G[aug_path[2*i]].partner = aug_path[2*i+1]; G[aug_path[2*i+1]].partner = aug_path[2*i]; } }, add_match_to_tree:function(G,v,w,wp){ G[w].mother = v; G[wp].mother = w; G[w].root = G[v].root; G[wp].root = G[v].root; G[w].distance = G[v].distance + 1; G[wp].distance = G[v].distance + 2; }, contract_graph:function(G,v,w){ var path_to_root_v = [v]; var path_to_root_w = [w]; while(G[v].mother !== -1){ path_to_root_v.push(G[v].mother); v = G[v].mother; } while(G[w].mother !== -1){ path_to_root_w.push(G[w].mother); w = G[w].mother; } var potential_stem_V; while((path_to_root_v.length>0)&&(path_to_root_w.length>0)){ if (path_to_root_v[path_to_root_v.length-1] === path_to_root_w[path_to_root_w.length-1]){ potential_stem_V = path_to_root_v[path_to_root_v.length-1]; path_to_root_v.pop(); path_to_root_w.pop(); } else { break; } } var blossom = [potential_stem_V].concat(path_to_root_w.reverse()); blossom = blossom.concat(path_to_root_v); blossom.push(potential_stem_V); var blossom_verteces = new Set(blossom); var G_size = G.length; var contracted_G = []; var blossom_vertex = {}; blossom_vertex.adj = []; blossom_vertex.partner = -1; blossom_vertex.blossom = -1; blossom_vertex.cycle = blossom; for(let i = 0; i<G_size; i++){ let vertex = {}; if(G[i].blossom === -1){ if(blossom_verteces.has(i)){ vertex.blossom = G_size; } else { vertex.blossom = -1; if(blossom_verteces.has(G[i].partner)){ vertex.partner = G_size; blossom_vertex.partner = i; } else { vertex.partner = G[i].partner; } vertex.adj = []; var points_to_blossom = false; for(let j = 0; j<G[i].adj.length; j++){ if(blossom_verteces.has(G[i].adj[j])){ points_to_blossom = true; } else { vertex.adj.push(G[i].adj[j]); } } if(points_to_blossom){ vertex.adj.push(G_size); blossom_vertex.adj.push(i); } } } else { vertex.blossom = G[i].blossom; } contracted_G.push(vertex); } contracted_G.push(blossom_vertex); return contracted_G; }, expand:function(G,G_prime,P_prime){ if(!P_prime.includes(G.length)){ return P_prime; } var cycle = G_prime[G.length].cycle; var pos = P_prime.indexOf(G.length); if (pos%2==0){ //looking for pos+1 var non_stem_neighbor = P_prime[pos+1]; if(G[non_stem_neighbor].adj.includes(cycle[0])){ P_prime[pos] = cycle[0]; return P_prime; } else { var first_half = P_prime.slice(0,pos); var second_half = P_prime.slice(pos+1,P_prime.length); var start; for(let i = 1; i<cycle.length-1; i++){ if(G[cycle[i]].adj.includes(non_stem_neighbor)){ start = i; break; } } var middle = []; if(G[cycle[start]].partner === cycle[start-1]){ for(let i = start; i >= 0; i--){ middle.push(cycle[i]); } } else { for(let i = start; i < cycle.length; i++){ middle.push(cycle[i]); } } var P = first_half; middle.reverse(); P = P.concat(middle); P = P.concat(second_half); return P; } } else { //looking for pos-1 var non_stem_neighbor = P_prime[pos-1]; if(G[non_stem_neighbor].adj.includes(cycle[0])){ P_prime[pos] = cycle[0]; return P_prime; } else { var first_half = P_prime.slice(0,pos); var second_half = P_prime.slice(pos+1,P_prime.length); var start; for(let i = 1; i<cycle.length-1; i++){ if(G[cycle[i]].adj.includes(non_stem_neighbor)){ start = i; break; } } var middle = []; if(G[cycle[start]].partner === cycle[start-1]){ for(let i = start; i >= 0; i--){ middle.push(cycle[i]); } } else { for(let i = start; i < cycle.length; i++){ middle.push(cycle[i]); } } var P = first_half; P = P.concat(middle); P = P.concat(second_half); return P; } } return []; }, setup:function(G, forest){ var G_size = G.length; for(let i = 0; i < G_size; i++){ if(G[i].blossom === -1){ G[i].mother = -1; if(G[i].partner === -1){ forest.push(i) G[i].distance = 0; G[i].root = i; } else { G[i].root = -1; G[i].distance = 100000; } } } }, bfs_check:function(G,root,queue){ v = queue.shift(); for(let j = 0; j < G[v].adj.length; j++){ w = G[v].adj[j]; if(G[w].partner === -1){ var P = [v,w]; while(G[v].mother !== -1){ P.unshift(G[v].mother); v = G[v].mother; } while(G[w].mother !== -1){ P.push(G[w].mother); w = G[w].mother; } return P; } } for(let j = 0; j < G[v].adj.length; j++){ w = G[v].adj[j]; //console.log(" w = " + w); if ( (G[w].partner !== -1) && (G[w].root === -1) ){ blossom.add_match_to_tree(G,v,w,G[w].partner); queue.push(G[w].partner); } else if(G[w].distance%2 === 1){ continue; } else if( (G[w].root === G[v].root)&&(G[w].distance%2 === 0) ){ var G_prime = blossom.contract_graph(G,v,w); var P_prime = blossom.find_aug_path_main(G_prime); var P = blossom.expand(G,G_prime,P_prime); return P; } else { var P = [v,w]; while(G[v].mother !== -1){ P.unshift(G[v].mother); v = G[v].mother; } while(G[w].mother !== -1){ P.push(G[w].mother); w = G[w].mother; } return P; } } return 'next'; }, bfs:function(G,root){ var queue = []; queue.push(root); while(queue.length > 0){ var aug_path = blossom.bfs_check(G,root,queue); if (aug_path !== 'next'){ return aug_path; } } return []; }, find_aug_path_main:function(G){ var forest = []; blossom.setup(G,forest); rtn = []; for(let i = 0; i<forest.length; i++){ let aug_path = blossom.bfs(G,forest[i]); if(aug_path.length !== 0){ rtn = aug_path; break; } } for(key in G){ delete G[key].root; } return rtn; }, } function solve(adj){ function find_path(){ let aug_path = blossom.find_aug_path_main(G); if(aug_path.length !== 0){ blossom.invert(aug_path,G); window.setTimeout(find_path,200); do_all(G); } else { var pairs = 0; for(let i = 0; i<G.length; i++){ if(G[i].partner !== -1){ pairs +=1; } } do_all(G); setTimeout(bc, 1500); return pairs/2; } } var G_size = adj.length; var G = []; for(let i = 0; i<G_size; i++){ let vertex = {}; vertex.partner = -1; vertex.blossom = -1; vertex.adj = []; for (let j = 0; j < adj[i].length; j++){ vertex.adj.push(adj[i][j]); } G.push(vertex); } find_path(); }
/* * Javascript genérico para carregar os modais: editar e adicionar. */ // Adicionar $('.loadModalInsert').live('click', function(action, grid){ loadModalCotnent($(this)); $('#dialog').dialog({ title: $(this).attr('title'), width: $(this).attr('width'), height: $(this).attr('height'), resizable: false, buttons: { 'Cancelar': function(){ $(this).html(""); $(this).dialog('destroy'); }, 'Adicionar': function () { $(this).find('form').submit(); $('.grid').flexReload(); } } }); return false; }); // Editar $('.loadModalUpdate').live('click', function(){ loadModalCotnent($(this)); $('#dialog').dialog({ title: $(this).attr('title'), width: $(this).attr('width'), height: $(this).attr('height'), resizable: false, buttons: { 'Cancelar': function(){ $(this).html(""); $(this).dialog('destroy'); }, 'Aplicar': function () { $(this).find('form').submit(); $('.grid').flexReload(); } } }); return false; }); // Função para carregar o conteúdo dentro de uma janela modal. // Recebe como parâmetro a referência do link ou botão clicado, para conseguir capturar seus atributos. function loadModalCotnent(obj) { $.ajax({ url: obj.attr('href'), type: 'GET', beforeSend: function() { $('#dialog').html(Ajax.loader); }, success: function(data) { $('#dialog').html(data); } }); }
//============================hash前端路由 /* * 夕空 flashme.cn 2020-4-19 //初始化 window.Router = new Router(); window.Router.init(); //方法 Router.route("/url", function, function); Router.route(url地址, 触发函数, 退出函数); 1.填写"hash"将会监听每次地址变更的触发 2.添加地址层级关系 例:Router.routes['/home'].subset=['/sub1','/sub2'] /home的子地址有/sub1、/sub2,打开子集地址/home将不执行退出函数 */ function Router() { this.routes = {}; this.currentUrl = ''; this.beforeUrl = ''; } Router.prototype.route = function(path, callback, removeback) { var obj={start:false,subset:[]}; obj.callback=callback || function(){}; if(removeback) obj.leave = removeback; this.routes[path] = obj; }; Router.prototype.refresh = function(ev) { this.routes["hash"] && this.routes["hash"](); this.currentUrl = location.hash.slice(1) || '/'; if(this.routes[this.currentUrl] && this.routes[this.currentUrl].start == false){ this.routes[this.currentUrl].callback(); this.routes[this.currentUrl].start = true; this.routes[this.currentUrl].before = this.beforeUrl;//记录上一个地址 } //将之前的地址判断是否执行退出 this.parentUrl(this.beforeUrl); //判断全部地址是否执行退出 for(var k in this.routes){ var than=this.routes[k]; if(than.start && this.currentUrl!=k){ //处在打开状态 & 当前地址不等于此地址 if(!this.forsub(than)){ than.start = false; than.leave && than.leave(); } } } this.beforeUrl=this.currentUrl; }; Router.prototype.forsub = function(than){ //for 子地址非打开状态 >> 执行退出函数 for(var i in than.subset){//判断子集是否打开状态 if(this.routes[than.subset[i]].start){ return true; } } return false; } Router.prototype.parentUrl = function (before) { if (before && this.currentUrl!=before && this.routes[before] && this.routes[before].start && !this.forsub(this.routes[before])) { this.routes[before].start = false; this.routes[before].leave && this.routes[before].leave(); var parent = this.routes[before].before; if (parent) { this.routes[before].before = null; this.parentUrl(parent); } } } Router.prototype.init = function() { window.addEventListener('load', this.refresh.bind(this), false); window.addEventListener('hashchange', this.refresh.bind(this), false); } //============================变量 dom 双向绑定 /* * 夕空 flashme.cn 2020-6-5 var obj={} var watch = new watchdata(); watch.inputevent(); //绑定input变化 watch.domevent(); //绑定dom变化 watch.setwatch(obj); obj.aaa="hello world!" <span ng-bind="aaa"></span> */ var watchdata = function () { //缓存 let watchscope = {}; let domeve=false; //绑定变量 return { setwatch: function (obj) { var than = this; let watchers = {}; watchscope = obj; const propertys = Object.keys(watchscope); propertys.forEach(function (prop) { //不处理函数属性 if ('function' == typeof watchscope[prop]) return; const propName = prop; // console.log(propName, watchscope[prop]); //监听对象属性 Object.defineProperty(watchscope, prop, { //value: watchscope[prop], configurable: true, get: function () { //console.log('get', prop, 'for', propName); return watchers[propName]; }, set: function (value) { //防止递归导致的栈溢出,先去掉监听的函数 domeve && document.removeEventListener('DOMCharacterDataModified', than.element); domeve && document.removeEventListener('DOMNodeInserted', than.element); watchers[prop] = value; var dom = document.querySelector("*[ng-bind='" + prop + "']") dom.innerText = watchers[prop]; dom.value = watchers[prop]; //重新监听 domeve && document.addEventListener('DOMCharacterDataModified', than.element, false); domeve && document.addEventListener('DOMNodeInserted', than.element, false); } }); }); }, element: function (e) { //dom的修改触发JS变量的修改 // console.log(e.newValue, e.prevValue, e.path); const attrs = e.target.parentElement.attributes; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if ('ng-bind' === attr.nodeName) { watchscope[attr.nodeValue] = e.target.nodeValue; } } }, domevent: function () { domeve=true; //绑定DOM的修改关联 document.addEventListener('DOMCharacterDataModified', this.element, false); document.addEventListener('DOMNodeInserted', this.element, false); }, inputevent: function () { //绑定input表单的修改关联 var input=document.querySelectorAll("input[ng-bind]") for(var k in input){ input[k].oninput = function (e) { watchscope[e.target.attributes["ng-bind"].nodeValue] = e.target.value; } } } } } //============================至底加载 function loading(target,fun){ var thisswitch=true; var loadico='<div class="loaderCircle"><div class="icono-spinner spin step"></div></div>'; target.bind('scroll', function onScroll() { if(!thisswitch){ return; } var toBottom = ($(this)[0].scrollTop + $(this).height() > $(this)[0].scrollHeight - 80); if(toBottom&&$(this).attr('loading')!='show') { $(this).attr('loading','show'); $(this).append(loadico); fun && fun(); } }); return { loadComplete:function(){ target.attr('loading','hide'); target.children('div.loaderCircle').remove(); }, switch:function (bol) { thisswitch=bol; } } } //回到顶部 function backtop($con) { var appTop = $con.height()*1.2 || $(window).height()*1.2; var scrTop; var backbtn=$con.siblings(".backtop"); $con.scroll(function(e){ scrTop = $con.scrollTop(); if(scrTop > appTop){ backbtn.show(); }else{ backbtn.hide(); } }) backbtn.click(function(){ $con.animate({scrollTop: 0}, 400); }) } //==========================================Tab按钮 function tabbox(tabtit,tab_conbox,mouseEvent) { $(tab_conbox).children().hide(); $(tabtit).children("label,.label").first().addClass("active"); $(tab_conbox).children().first().show(); $(tabtit).children("label,.label").bind(mouseEvent,function(){ $(this).addClass("active").siblings("label,.label").removeClass("active"); var activeindex = $(tabtit).children("label,.label").index(this); $(tab_conbox).children().eq(activeindex).show().siblings().hide(); return false; }); }; //将form表数据转Obj对象 postObj(form.serializeArray()) function postObj(params) { var values = {}; for (x in params) { if (!values[params[x].name]) { values[params[x].name] = params[x].value; }else if(values[params[x].name] instanceof Array==false){ values[params[x].name]=[values[params[x].name]]; values[params[x].name].push(params[x].value); }else{ values[params[x].name].push(params[x].value); } } return values; } // 对Date的扩展,将 Date 转化为指定格式的String // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) // 例子: // (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423 // (new Date()).Format("yyyy-M-d H:m:s.S") ==> 2006-7-2 8:9:4.18 Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "H+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } //Table固定表头 class=heightY执行固定表头 function tablehead($target) { $target.each(function () { //复制表格做置顶表头 var $this = $(this); if($this.hasClass('heightY')){ $this.find('.head').remove(); var tablehead = $this.find('table').clone(); tablehead.find('input,textarea,select').attr('name', ''); tablehead.find('input,textarea,select').attr('id', ''); tablehead.find('input.check').remove(); $this.append('<div class="head"></div>'); $this.find('.head').append(tablehead); $this.find('.head').height($this.find('.head thead').height()); $this.scroll(function () { $this.find('.head').css('top', $this.scrollTop()); }) } //全选按钮 $this.find('.check-all').click(function () { $this.find('tbody input[type=checkbox].check').prop('checked', $(this).prop('checked')); }) $this.on('click', 'input[type=checkbox].check', function(event) { if($this.find('input[type=checkbox].check:checked').length==$this.find('input[type=checkbox].check').length){ $this.find('.check-all').prop('checked',true); }else{ $this.find('.check-all').prop('checked',false); } }); }) }
/******************************************************************************* * * Copyright 2018 Adobe. All rights reserved. * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * ******************************************************************************/ const _ = require('lodash'); const fs = require('fs'); const handlebars = require('handlebars'); function generateModelClass(swagger, definition, classname) { let clazz = createClass(definition, classname, swagger); let modelTemplate = fs.readFileSync(__dirname + '/model.hbs', 'utf8'); let compiledTemplate = handlebars.compile(modelTemplate, {noEscape: true}); clazz.version = swagger.info.version; return compiledTemplate(clazz); } function createClass(definition, classname, swagger) { console.log('Creating class for ' + classname); let clazz = { class: classname, fields: [] }; let def = definition.allOf ? definition.allOf[1] : definition; clazz.imports = addImports(classname, def.properties, swagger); /* Support inheritance by making a class extend another one */ if (definition.allOf) { clazz.parentClass = getParentClass(definition.allOf[0]); } addProperties(definition.properties, definition.required, clazz); return clazz; } function objectWithSortedKeys(object) { let result = {}; _.forEach(Object.keys(object).sort(), function(key) { result[key] = object[key]; }); return result; } function addProperties(properties, requiredProperties, clazz) { let props = objectWithSortedKeys(properties); _.forEach(props, function(property, name) { let type = getType(property); if (type == 'array' && property.items) { type = getType(property.items) + '[]'; } let field = { name: name, nameUpperCase: _.upperFirst(name), description: property.description, required: requiredProperties ? requiredProperties.includes(name) : false, type: `{${type}}` } clazz.fields.push(field); }); } function addImports(classname, properties, swagger) { let types = new Set(); _.forEach(properties, function(property, name) { let type = getType(property); if (type == 'array' && property.items) { type = getType(property.items); } if (type != classname && swagger.definitions[type]) { types.add(type); } }); if (types.size) { return Array.from(types); } } function getParentClass(allOf) { let parts = allOf['$ref'].split('/'); return parts[parts.length - 1]; } function getType(object) { let type = object.type; if (!type && object['$ref']) { let parts = object['$ref'].split('/'); type = parts[parts.length - 1]; } return type; } module.exports.generateModelClass = generateModelClass;
const db = require("../module/db") const common = require("../module/common") const md5 = require("md5") module.exports.adminlogin = function (req, res) { var password = md5(req.body.password + "@ele.com") db.findOne("adminList", { adminName: req.body.adminName, password }, function (err, adminInfo) { if (adminInfo) { db.insertOne("adminLog", { adminId: adminInfo._id, logType: 4, detail: req.body.adminName + "在" + common.getNowTime() + "登录了饿了么管理系统", addTime: Date.now() }, function (err, results) { res.json({ ok: 1, adminName: adminInfo.adminName, adminId: adminInfo._id }) }) } else { res.json({ ok: 2, msg: "账号密码错误" }) } }) } module.exports.adminLog = function (req, res) { var pageIndex = req.query.pageIndex / 1 || 1 var pageNum = 2 db.count("adminLog", {}, function (count) { var pageSum = Math.ceil(count / pageNum) if (pageSum < 1) pageSum = 1 if (pageIndex > pageSum) pageIndex = pageSum if (pageIndex < 1) pageIndex = 1 db.getadminLog(pageNum, (pageIndex - 1) * pageNum, function (err, adminInfo) { if (err) { res.json({ ok: 2, msg: "网络连接错误" }) } else { res.json({ ok: 1, adminInfo, pageSum }) } }) }) } module.exports.addadmin = function (req, res) { var password = md5(req.body.password + '@ele.com') console.log(password) db.find("adminList", { where: { adminName: req.body.adminName } }, function (err, adminList) { console.log(adminList) if (adminList.length > 0) { res.json({ ok: 2, msg: "该用户名已经被占用" }) } else { db.insertOne("adminList", { adminName: req.body.adminName, password }, function (err, results) { if (err) { res.json({ ok: 2, msg: "网络连接错误" }) } else { db.find("adminList", { where: { adminName: req.body.adminName } }, function (err, adminList) { db.insertOne("adminLog", { adminId: adminList[0]._id, logType: 5, detail: req.body.adminName + "在" + common.getNowTime() + "添加了管理员", addTime: Date.now() }, function (err, results) { res.json({ ok: 1, msg: "添加成功" }) }) }) } }) } }) } module.exports.getadminlist = function (req, res) { db.find("adminList", {}, function (err, adminList) { if (err) { res.json({ ok: 2, msg: "网络连接错误" }) } else { res.json({ ok: 1, adminList }) } }) } module.exports.changepass = function (req, res) { db.findOne("adminList", { adminName: req.body.adminName, password: md5(req.body.password + "@ele.com") }, function (err, adminInfo) { if (adminInfo) { db.updateOne("adminList", { adminName: req.body.adminName, password: md5(req.body.password + "@ele.com") }, { $set: { password: md5(req.body.newpass + '@ele.com') } }, function (err, results) { if (err) { res.json({ ok: 2, msg: "网络连接失败" }) } else { res.json({ ok: 1, msg: "修改成功" }) } }) } else { res.json({ ok: 2, msg: "修改失败,请检查您的账号密码" }) } }) } module.exports.deleteadminlog = function (req, res) { db.deleteOneById("adminLog", req.query.id, function (err, results) { if (err) { res.json({ ok: 2, msg: "网络连接错误" }) } else { res.json({ ok: 1, msg: "删除成功" }) } }) }
import { models } from '../../models/' let User = models.User export const search = (req, res) => { User.findAll().then(data => { return res.status(200).json(data) }) } export const join = (req, res) => { const data = req.body let name = data.name let ps = data.ps User.create({ userName: name, password: ps }).then(data => { return res.status(201).json(data) }) } export const remove = (req, res) => { const data = req.params let name = data.id User.destroy({ where: { userName: name } }).then(data => { return res.status(200).json(data) }) }
/*Класс Animal*/ var Animal = function(name, isHungry){ /*Публичные свойства класа Animal*/ this.name = name || ''; this.isHungry = isHungry || false; } /*Методы прототипа*/ Animal.prototype.sound = function() { alert("Я животное!"); } /*Класс Cat*/ var Cat = function(name, isHungry){ Animal.apply(this, arguments) } /*Cat наследует Animal*/ /*Наследование*/ Cat.prototype = Object.create(Animal.prototype); Cat.prototype.constructor = Animal; Cat.prototype.sound = function(sound) { if (this.isHungry){ // Полиморфизм расширяем свойство Animal.prototype.sound.call(this) } else{ alert("Кот сыт и молчит") } } var vaska = new Cat('Васька', true); var murchik = new Cat('Мурчик', false); vaska.sound("Мяу") murchik.sound("Мяу")
import Select from './select.js'; const selectElement = document.querySelectorAll('[data-custom]'); selectElement.forEach((item) => { const select = new Select(item); select; }); // test