text
stringlengths
7
3.69M
import {request} from './request' export function getAgentList() { return request({ url:'/getAgentList' }); }
define([ "backbone", "modules/finger/finger-model" ], function (Backbone, FingerModel) { "use strict"; var Fingers = Backbone.Collection.extend({ model: FingerModel }); return Fingers; });
// format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] STSP_orange_main_stop_name = ["Park 17<br />商場","馨園<br />宿舍","南科<br />實中","民生<br />水塔","臺鐵<br />南科站","南科<br />實中","社區<br />中心","西拉雅<br />廣場","台積電","群創<br />B廠","聯電","Park 17<br />商場"]; STSP_orange_main_stop_time_consume = [0, 4, 11, 3, 7, 10, 13, 16, 19, 22, 23, 24]; STSP_orange_important_stop = [0, 4, 6, 8]; // Park 17商場, 臺鐵南科站, 社區中心, 台積電 var start_stop = 0; // Park 17商場 var stop_01 = 1; // 馨園宿舍 var stop_02 = 2; // 南科實中 var TRA_NK = 4; // 臺鐵南科站 var stop_1 = 5; // 南科實中 var stop_2 = 6; // 社區中心 var stop_3 = 7; // 西拉雅廣場 var InnoLux = 9; // 群創B廠 var park17_end = 11; // Park 17商場 STSP_orange_time_go = [["06:30",[stop_01,stop_02]],["07:15",[stop_01,stop_02,[stop_2,1,stop_3,1]]],["07:15",[[stop_02+1,11,stop_2,1,stop_3,1]]], ["07:46",[stop_01,stop_02]],["07:58",[stop_01,stop_02]],["08:17",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["09:06",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]], ["09:50",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["11:05",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["12:00",[stop_01,stop_02,'*',[TRA_NK,23,InnoLux,-1,park17_end,1]]],["12:49",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["13:45",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["14:19",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]], ["15:18",[stop_01,stop_02,[InnoLux,-1,park17_end,1]]],["16:08",[stop_01,[stop_02,-6,stop_02+1,11,InnoLux,-1,park17_end,1]]],["17:03",[stop_01,stop_02]],["17:00",start_stop,TRA_NK,[stop_01,[stop_02,-6,stop_02+1,11,TRA_NK,1]]],["17:00",start_stop,TRA_NK,[stop_01,[stop_02,-6,stop_02+1,11,TRA_NK,1]]],["17:18",stop_02,TRA_NK,[[stop_02+1,5,TRA_NK,6]]] ]; var return_stop_1 = 6; // 南科實中校門口 // The name of return stops are different STSP_orange_main_stop_name_return = ["Park 17<br />商場","聯電","霞客湖<br />停車場","南茂<br />科技","商務<br />會館","華園<br />宿舍","南科實中<br />校門口","民生<br />水塔","臺鐵<br />南科站","南科<br />實中","社區<br />中心","璞園<br />宿舍","Park 17<br />商場"]; STSP_orange_main_stop_time_consume_return = [0, 2, 4, 6, 9, 11, 15, 13, 17, 20, 22, 22, 26]; STSP_orange_important_stop_return = [0, 3, 5, 8]; // Park 17商場, 南茂科技, 華園宿舍, 臺鐵南科站 STSP_orange_time_return = [["17:15",[return_stop_1]],["17:41",[return_stop_1]],["17:51",[return_stop_1]],["18:10",[return_stop_1]],["18:45",[return_stop_1]],["20:00",[return_stop_1]],["20:33",[[return_stop_1+1,5]]],["21:05",[return_stop_1]]];
var Shortcodes = require('smiley-caret-data/shortcodes'); module.exports = (function () { var exports = {}; var _sets = getSets(Shortcodes); function getSets(list) { var sets = []; for (var code in list) { for (var i = 0; i < code.length; i++) { sets[i] = sets[i] || []; if (sets[i].indexOf(code[i]) === -1) { sets[i].push(code[i]); } } } return sets; } exports.isPart = function (str) { for (var i = str.length - 1; i >= 0; i--) { if (!_sets[i] || _sets[i].indexOf(str[i]) === -1) { return false; } } return true; }; exports.get = function (key) { if (Shortcodes[key]) { return Shortcodes[key]; } else { return null; } }; exports.getAll = function () { return Shortcodes; }; return exports; })();
/* * Origin Builder Project * * * * Must obtain permission before using this script in any other purpose * * or.tools.js * */ ( function($){ if( typeof( or ) == 'undefined' ) window.or = {}; $().extend( or.tools, { esc_slug : function (str){ if( str === undefined ) return 'origin-builder'; str = str.replace(/^\s+|\s+$/g, ''); str = str.toLowerCase(); var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;"; var to = "aaaaeeeeiiiioooouuuunc------"; for (var i=0, l=from.length ; i<l ; i++) { str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); } str = str.replace(/[^a-z0-9 -]/g, '') .replace(/\s+/g, '-') .replace(/-+/g, '-'); return str; }, esc_attr : function( str ) { if( !str ){ return ''; } return str.toString() .replace(/</g, ':lt:') .replace(/>/g, ':gt:') .replace(/\[/g, ':lsqb:') .replace(/\]/g, ':rsqb:') .replace(/"/g, ':quot:') .replace(/'/g, ':apos:'); }, unesc_attr : function( str ) { if( !str ){ return ''; } return str.toString() .replace(/:lt:/g, '<') .replace(/:gt:/g, '>') .replace(/:lsqb:/g, '[') .replace(/:rsqb:/g, ']') .replace(/:quot:/g, '"') .replace(/:apos:/g, '\''); }, esc : function( str ) { if( !str ){ return ''; } return str.toString().replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }, unesc : function(str) { if( str == undefined ){ return ''; } return str.toString().replace(/&amp;/g, '&') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"') .replace(/&apos;/g, '\''); }, rawdecode : function( input ){ return decodeURIComponent( input+'' ); }, rawencode : function( input ){ input = (input+'').toString(); return encodeURIComponent( input ). replace(/!/g,'%21'). replace(/'/g,'%27'). replace(/\(/g,'%28'). replace(/\)/g,'%29'). replace(/\*/g,'%2A'); }, decode_css : function( css ){ var css_code = ''; css = css.replace( /\s+/g, ' ' ) .replace(/\/\*[^\/\*]+\*\//g,'') .replace(/[^a-zA-Z0-9\-\_\. \:\(\)\%\+\~\;\#\'\{\}\@\/]+/g,'') .trim().split( '{' ); for( var n in css ){ if( css[n].indexOf('}') > -1 ) { css[n] = css[n].split('}'); css[n][0] = css[n][0].split(';'); for( var m in css[n][0] ) { if( css[n][0][m].trim() != '' ) css_code += " "+css[n][0][m]+";\n"; } if( css[n][1].trim() != '' ) css_code += "}\n"+css[n][1]+"{\n"; else css_code += "}\n"; if( css[n][2] != undefined ) css_code += "}\n"; } else if( css[n].trim() != '' ) { css_code += css[n]+"{\n" } } return css_code; }, encode_css : function( css ){ if( css == undefined ) css = ''; css = css.replace(/\/\*[^\/\*]+\*\//g,'') .replace( /\ \ /g, '' ) .replace(/[^a-zA-Z0-9\-\_\. \:\(\)\%\+\~\;\!\#\'\{\}\@\/]+/g,'').trim(); return css; }, nfloat : function( n, m ){ n = n.toString(); if( m === undefined ) m = 2; if( n.indexOf('.') > -1 ){ return parseFloat( n.substr( 0, n.indexOf('.')+m+1 ) ); }else return parseFloat( n ); }, getFormData : function( $form ){ var unindexed = $form.serializeArray(), indexed = {}, avoidRepeat = {}, name, obs, j, k; $.map( unindexed, function( n, i ){ if( n['name'].indexOf('[') == -1 ){ if( n['value'] != '' ){ if( indexed[ n['name'] ] == undefined || indexed[ n['name'] ] == '__empty__' ) indexed[ n['name'] ] = n['value']; else indexed[ n['name'] ] += ','+n['value']; }else if( indexed[ n['name'] ] === undefined ){ indexed[ n['name'] ] = ''; } }else{ n['name'] = "["+n['name'].replace('[',']['); name = n['name'].replace( /\[/g, "['" ).replace( /\]/g, "']" ); obs = []; [].forEach.call( n['name'].split(']['), function( sp ){ sp = sp.replace( /\[/g, '' ).replace( /\]/g, '' ).trim(); obs[ obs.length ] = sp; }); if( obs.length > 0 ){ k = ''; for( j=0; j<obs.length; j++){ k += "['"+obs[j]+"']"; eval("if( indexed"+k+"==undefined )indexed"+k+"={};"); } } var query = "if( typeof(indexed"+name+") != 'string' )indexed"+name+"=n['value'];else if(n['value']!=='') indexed"+name+"+=','+n['value'];"; eval( query ); } }); return indexed; }, basename : function( str ){ var base = str.split(/[\\/]/).pop(); if( base.lastIndexOf(".") != -1 ) base = base.substring( 0, base.lastIndexOf(".") ); return base; }, toClipboard : function( str ) { if (window.clipboardData) { window.clipboardData.setData ("Text"); }else { document.oncopy = function(event) { event.clipboardData.setData('text', str); event.preventDefault(); }; document.execCommand("Copy", false, null); document.oncopy = null; } }, rgb2hex : function( rgb ) { if( rgb.indexOf('rgb') == -1 ) return rgb; rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); function hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); }, hex2rgb : function(hex) { r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); if (r) { return r.slice(1,4).map(function(x) { return parseInt(x, 16); }); } // short version r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); if (r) { return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); }); } return hex; }, base64 : { codex : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode : function (input){ if( input == undefined ){ return ''; } var output = new this.stringBuffer(); var enumerator = new this.utf8EncodeEnumerator(input); while (enumerator.moveNext()){ var chr1 = enumerator.current; enumerator.moveNext(); var chr2 = enumerator.current; enumerator.moveNext(); var chr3 = enumerator.current; var enc1 = chr1 >> 2; var enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); var enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); var enc4 = chr3 & 63; if (isNaN(chr2)){ enc3 = enc4 = 64; } else if (isNaN(chr3)){ enc4 = 64; } output.append(this.codex.charAt(enc1) + this.codex.charAt(enc2) + this.codex.charAt(enc3) + this.codex.charAt(enc4)); } return output.toString(); }, decode : function (input){ if( input == undefined ){ return ''; } var output = new this.stringBuffer(); var enumerator = new this.decodeEnumerator(input); while (enumerator.moveNext()){ var charCode = enumerator.current; if (charCode < 128){ output.append(String.fromCharCode(charCode)); }else if ((charCode > 191) && (charCode < 224)){ enumerator.moveNext(); var charCode2 = enumerator.current; output.append(String.fromCharCode(((charCode & 31) << 6) | (charCode2 & 63))); }else{ enumerator.moveNext(); var charCode2 = enumerator.current; enumerator.moveNext(); var charCode3 = enumerator.current; output.append(String.fromCharCode(((charCode & 15) << 12) | ((charCode2 & 63) << 6) | (charCode3 & 63))); } } return output.toString(); }, stringBuffer : function() { this.buffer = [] }, utf8EncodeEnumerator : function(input) { this._input = input; this._index = -1; this._buffer = [] }, decodeEnumerator : function(input) { this._input = input; this._index = -1; this._buffer = [] } }, media : { el : null, callback : null, uploader : null, open : function( e ){ if( typeof e.preventDefault == 'function' ) e.preventDefault(); atts = $().extend( { frame: 'select', multiple: false, title: 'Choose Image', button: 'Choose Image', type: 'image' }, e.data.atts ); or.tools.media.el = this; if( typeof e.data.callback == 'function' ) or.tools.media.callback = e.data.callback; else or.tools.media.callback = null; if ( or.tools.media.uploader ) { return or.tools.media.uploader.open(); } var insertImage = wp.media.controller.Library.extend({ defaults : _.defaults({ id: 'insert-image', title: atts.title, button: { text: atts.button }, multiple: false, editing: true, allowLocalEdits: true, displaySettings: true, displayUserSettings: true, type : atts.type }, wp.media.controller.Library.prototype.defaults ) }); //Extend the wp.media object or.tools.media.uploader = wp.media.frames.file_frame = wp.media({ frame: atts.frame, state : 'insert-image', states : [ new insertImage() ] }); or.tools.media.uploader.on('select', function( e ) { var currentSize = $('.attachment-display-settings .size').val() var state = or.tools.media.uploader.state('insert-image'); var attachments = state.get('selection'); if( attachments.length === 0 ){ if( $('#embed-url-field').get(0) && $('#embed-url-field').val() != null ){ if( typeof or.tools.media.callback == 'function' ) or.tools.media.callback( { url: $('#embed-url-field').val(), sizes: {} }, $(or.tools.media.el) ); } }else{ attachments.map( function( attachment ) { var attachment = attachment.toJSON(); attachment.size = currentSize; if( typeof or.tools.media.callback == 'function' ) or.tools.media.callback( attachment, $(or.tools.media.el) ); }); } }); or.tools.media.uploader.on('open', function( e ) { var ids = $(or.tools.media.el).parent().find('.or-param').val(); if( ids === undefined || ids == null || ids == '' ) return; ids = ids.split(','); var selection = or.tools.media.uploader.state().get('selection'); var attachments = []; ids.forEach(function( id ){ attachments[ attachments.length ] = wp.media.attachment( id ); }); selection.add( attachments ); }); //Open the uploader dialog return or.tools.media.uploader.open(); }, els : null, callbacks : null, uploaders : null, opens : function( e ){ if( typeof e.preventDefault == 'function' ) e.preventDefault(); or.tools.media.els = this; if( typeof e.data == 'function' ) or.tools.media.callbacks = e.data; else or.tools.media.callbacks = null; if ( or.tools.media.uploaders ) { or.tools.media.uploaders.open(); return false; } //Extend the wp.media object or.tools.media.uploaders = wp.media.frames.file_frame = wp.media({ title: or.__.i46, button: { text: or.__.i46 }, multiple: true, editing: true, allowLocalEdits: true, displaySettings: true, displayUserSettings: true, }); or.tools.media.uploaders.on('select', function( e ) { var attachments = or.tools.media.uploaders.state().get('selection'); attachments.map( function( attachment ) { var attachment = attachment.toJSON(); if( typeof or.tools.media.callbacks == 'function' ) or.tools.media.callbacks( attachment, $(or.tools.media.els) ); }); }); or.tools.media.uploaders.on('open', function( e ) { // Maybe we dont need to active selected images return false; var ids = $(or.tools.media.els).parent().find('.or-param').val(); if( ids === undefined || ids == null || ids == '' ) return; ids = ids.split(','); var selection = or.tools.media.uploaders.state().get('selection'); var attachments = []; ids.forEach(function( id ){ attachments[ attachments.length ] = wp.media.attachment( id ); }); selection.add( attachments ); }); //Open the uploader dialog or.tools.media.uploaders.open(); return false; } }, popup : new or.backbone.views( 'no-model' ).extend({ margin_top : $('html').get(0).offsetTop, no_close : false, render : function( el, atts ){ var keepCurrent = false; if( atts != undefined ){ if( atts.keepCurrentPopups == true ){ keepCurrent = true; } } if( keepCurrent == false ) $('.or-params-popup .sl-close.sl-func').trigger('click'); $('.sys-colorPicker').remove(); $('.or-controls .more.active').removeClass('active'); var pop_width = 440; if( atts.width != undefined ) pop_width = atts.width; var coor = this.coordinates( el, pop_width, keepCurrent ); var atts = $().extend({ top: coor[0], left: coor[1], pos: coor[2], bottom: coor[3], tip: coor[4], width: pop_width, class: '', drag: true, content: '', title: 'Settings', help: '', footer: true, footer_text: '', scrollTo: true, save_text: or.__.save, cancel_text: or.__.cancel }, atts ); if( atts.footer === false && atts.class.indexOf('no-footer') == -1 ) atts.class += ' no-footer'; this.el = $( or.template( 'popup', atts ) ); this.el.data({ 'button' : el, 'keepCurrentPopups' : keepCurrent, 'tab_active' : 0 }); if( atts.tip != 0 ) this.el.find( '.wp-pointer-arrow' ).css({marginRight: -atts.tip+'px'}); if( atts.scrollBack == true ) this.el.data({ 'scrolltop' : $(window).scrollTop() }); $('body').append( this.el ); if( atts.drag == true ){ or.ui.draggable( this.el.get(0), 'h3.m-p-header' ); this.el.find('h3.m-p-header').addClass('or-ui-draggable'); } $( this.el ).css({opacity: 1}); if( atts.scrollTo === true ){ setTimeout( function( pop, atts ){ var wsct = $(window).scrollTop(), wh = $(window).height(), wheight = wsct+(wh*0.1); if( wh > 800 ) pop.find('.m-p-body').css({ 'max-height': (wh - 250)+'px' }); var pop_rect = pop.get(0).getBoundingClientRect(); if( atts.top > wheight && atts.bottom === 0 ){ if( pop_rect.height < wh - 50 ){ or.ui.scrollAssistive( atts.top - ((wh-pop_rect.height)/2) , false ); }else or.ui.scrollAssistive( (atts.top - 50), false ); }else if( pop_rect.top < 0 ) or.ui.scrollAssistive( (wsct+pop_rect.top) - 50, false ); }, 1, this.el, atts ); } return this.el; }, coordinates : function( el, pop_width, keepCurrent ){ var grids; if( $(el).closest('#or-container').get(0) ) grids = document.getElementById('or-container').getBoundingClientRect(); else if( document.getElementById('wpbody-content') !== null ) grids = document.getElementById('wpbody-content').getBoundingClientRect(); else if( document.getElementById('content') !== null ) grids = document.getElementById('content').getBoundingClientRect(); else grids = document.getElementsByTagName('body')[0].getBoundingClientRect(); if( el === undefined ) return [0,0,0,0]; var coor = el.getBoundingClientRect(), swidth = (grids.width/3), sleft = coor.left-grids.left, top = coor.top+$(window).scrollTop()+coor.height-this.margin_top, bottom = 0, left = coor.left+$(window).scrollLeft()+(coor.width/2), tip = 0, pos = '', wheight = $(document).height(), wwidth = $(document).width(); if( sleft < swidth ){ pos = 'left'; left -= 63; }else if( sleft > swidth && sleft < swidth*2 ){ pos = 'center'; left -= (pop_width/2); }else if( sleft > swidth*2 && sleft < swidth*3 ){ pos = 'right'; left -= (pop_width-63); } if( wheight - top < 200 && $(window).scrollTop() > 0 ){ bottom = wheight-top+(coor.height/2); $('html').height( wheight - parseInt( $('html').css('padding-top') ) ); }else if( keepCurrent !== true ){ $('html').height(''); } if( left < 50 ){ tip = left - 50; left = 50; } if( left+swidth > wwidth ){ left -= ( (left+swidth) - wwidth ) + 50; } return [ top, left, pos, bottom, tip ]; }, events : { '.m-p-controls>li>.cancel,.m-p-header .sl-close:click' : 'cancel', '.m-p-header:dblclick' : 'cancel', '.m-p-controls>li>.save,.m-p-header .sl-check:click' : 'save' }, cancel : function( e ){ // We will dont close the popup when in instant saving if( $('#instantSaving').length > 0 || or.tools.popup.no_close === true ){ or.tools.popup.no_close = false; return; } if( e.target.tagName == 'INPUT' ) return; var el = $(this).closest('.or-params-popup'), keepCurrent = el.data('keepCurrentPopups'), beforecalb, calb, aftercalb, i; if( typeof el.data('before_cancel') !== undefined ){ beforecalb = el.data('before_cancel'); if( typeof beforecalb == 'function' ){ if( beforecalb( el, e ) == 'prevent' ) return; }else if( beforecalb !== undefined && beforecalb.length > 0 ){ for( i = 0; i< beforecalb.length; i++ ){ if( typeof beforecalb[i] == 'function' ){ if( beforecalb[i]( el, e ) == 'prevent' ) return; } } } } if( typeof el.data('cancel') !== undefined ){ calb = el.data('cancel'); if( typeof calb == 'function' ){ calb( el ); }else if( calb !== undefined && calb.length > 0 ){ for( i = 0; i< calb.length; i++ ){ if( typeof calb[i] == 'function' ) calb[i]( el ); } } } if( typeof el.data('after_cancel') !== undefined ){ aftercalb = el.data('after_cancel'); if( typeof aftercalb == 'function' ){ aftercalb( el ); }else if( aftercalb !== undefined && aftercalb.length > 0 ){ for( i = 0; i< aftercalb.length; i++ ){ if( typeof aftercalb[i] == 'function' ) aftercalb[i]( el ); } } } if( el.data('scrolltop') != undefined ) e.data.scrollback( el.data('scrolltop'), el.data('button') ); if( el.data('keepCurrentPopups') !== true ) $('html').height(''); el.remove(); $('.sys-colorPicker').remove(); // remove date picker $('.pika-single').remove(); if( keepCurrent == false ) $('.or-params-popup .sl-close.sl-func').trigger('click'); $( ".backgound_color" ).remove(); $('.backgound_color').css('opacity','1'); $('.backgound_color').css('height','0'); $('.backgound_color').css('width','0'); }, save : function( e ){ var el = $(this).closest('.or-params-popup'), keepCurrent = el.data('keepCurrentPopups'), beforecalb, calb, aftercalb, i; e.data.el = el; if( typeof el.data('before_callback') !== undefined ){ beforecalb = el.data('before_callback'); if( typeof beforecalb == 'function' ){ beforecalb( el ); }else if( beforecalb !== undefined && beforecalb.length > 0 ){ for( i = 0; i< beforecalb.length; i++ ){ if( typeof beforecalb[i] == 'function' ) beforecalb[i]( el ); } } } if( typeof el.data('callback') !== undefined ){ calb = el.data('callback'); if( typeof calb == 'function' ){ calb( el ); }else if( calb !== undefined && calb.length > 0 ){ for( i = 0; i< calb.length; i++ ){ if( typeof calb[i] == 'function' ) calb[i]( el ); } } } if( typeof el.data('after_callback') !== undefined ){ aftercalb = el.data('after_callback'); if( typeof aftercalb == 'function' ){ aftercalb( el ); }else if( aftercalb !== undefined && aftercalb.length > 0 ){ for( i = 0; i< aftercalb.length; i++ ){ if( typeof aftercalb[i] == 'function' ) aftercalb[i]( el ); } } } if($(this).hasClass("sl-check") ){ el.find('.sl-close.sl-func').trigger('click'); } // We will dont close the popup when in instant saving if( $('#instantSaving').length > 0 || or.tools.popup.no_close === true ){ or.tools.popup.no_close = false; return; } if( el.data('scrolltop') != undefined ) e.data.scrollback( el.data('scrolltop'), el.data('button') ); //el.remove(); el.find('.sl-close.sl-func').trigger('click'); if( keepCurrent == false ){ $('.or-params-popup .sl-close.sl-func').trigger('click'); $('html').height(''); } }, scrollback : function( sctop, btn ){ var now = $(window).scrollTop(); if( Math.abs( sctop - now ) > 200 ){ or.ui.scrollAssistive( sctop ); } }, add_tab : function( pop, args ){ args = $().extend( { title: '', class: '', cfg: '', callback: function(){} }, args ); var ul = pop.find('.m-p-wrap ul.or-pop-tabs'), slug = 'or-tab-'+Math.abs(parseInt(Math.random()*1000)), li = $('<li data-tab="'+slug+'" data-cfg="'+args.cfg+'" class="'+args.class+'">'+args.title+'</li>'); if( !ul.get(0) ){ /* if this is first tab be added */ ul = $('<ul class="or-pop-tabs"></ul>'); if( pop.find('.fields-edit-form').length > 0 ){ var fli = $('<li data-tab="fields-edit-form" class="or-tab-general-title active"><i class="et-tools"></i> General</li>') ul.append( fli ); fli.on( 'click', function( e ){ var wrp = $(this).closest('.m-p-wrap'); wrp.find('>.or-pop-tabs li').removeClass('active'); $(this).addClass('active'); wrp.find('.m-p-body>.or-pop-tab').removeClass('form-active'); wrp.find('.m-p-body>.fields-edit-form').addClass('form-active'); if( e.originalEvent !== undefined ) $(this).closest('.or-params-popup'). data({ tab_active: $(this).parent().find('>li').index( this ) }); }); } pop.find('.m-p-header').after( ul ); } ul.append( li ); /* Add event for new tab which just be created */ li.on( 'click', args.callback, function(e){ var slug = $(this).data('tab'), wrp = $(this).closest('.m-p-wrap').find('>.m-p-body'); $(this).closest('.m-p-wrap').find('>.or-pop-tabs li').removeClass('active'); $(this).addClass('active'); wrp.find('>.or-pop-tab').removeClass('form-active'); var tab = wrp.find('>.'+slug), click_actived = false, this_index = $(this).parent().find('>li').index( this ); if( $(this).closest('.or-params-popup').data('tab_active') == this_index ) click_actived = true; if( e.originalEvent !== undefined ) $(this).closest('.or-params-popup').data({ tab_active: this_index }); if( tab.get(0) ){ tab.addClass('form-active'); /* * If the tab is actived and click on it * We don't need to run callback */ if( click_actived === true ) return; var callback = $(this).data('callback'); if( typeof callback == 'function' ) callback( this, tab ); return; } tab = $('<form class="or-pop-tab '+slug+' form-active"></form>'); wrp.append( tab ); tab.on( 'submit', function(){ $(this).closest('.or-params-popup').find('.m-p-footer .save').trigger('click'); return false; }); if( typeof e.data == 'function' ) tab.append( e.data( this , tab ) ); var callback = $(this).data('callback'); if( typeof callback == 'function' ) callback( this, tab ); }); }, callback : function( pop, args ){ var calls; for( var st in args ){ calls = []; if( pop.data( st ) !== undefined && typeof pop.data( st ).push == 'function' ) calls = pop.data( st ); calls.push( args[st] ); pop.data( st, calls ); } } }), editor : { insert : function( id, html ){ var editor, hasTinymce = typeof tinymce !== 'undefined', hasQuicktags = typeof QTags !== 'undefined'; wpActiveEditor = id; if ( hasTinymce ) { editor = tinymce.get( wpActiveEditor ); } if ( editor && ! editor.isHidden() ) { editor.execCommand( 'mceInsertContent', false, html ); } else if ( hasQuicktags ) { QTags.insertContent( html ); } else { document.getElementById( wpActiveEditor ).value = html; } }, init : function ( textarea ) { if ( $( '#wp-link' ).parent().hasClass( 'wp-dialog' ) ) { $( '#wp-link' ).wpdialog( 'destroy' ); } textarea.val( switchEditors.wpautop( textarea.val() ) ); var eid = textarea.attr( "id" ), tmi = window.tinyMCEPreInit, tmic = tmi.mceInit, tmiq = tmi.qtInit; try { if ( _.isUndefined( tinyMCEPreInit.qtInit[ eid ] ) ) { tmiq[ eid ] = _.extend( {}, tmiq[ window.wpActiveEditor ], { id: eid } ); } if ( tmi && tmic[ window.wpActiveEditor ] ) { tmic[ eid ] = _.extend( {}, tmic[ window.wpActiveEditor ], { resize: 'vertical', height: 250, id: eid, setup: function ( e ) { if ( typeof(e.on) != 'undefined' ) { e.on( 'init', function ( e ) { e.target.focus(); window.wpActiveEditor = eid; }); } else { e.onInit.add( function ( e ) { e.focus(); window.wpActiveEditor = eid; }); } } } ); tmic[ eid ].wp_autoresize_on = false; window.wpActiveEditor = eid; } quicktags( tmic[ eid ] ); QTags._buttonsInit(); if ( window.tinymce ) { window.switchEditors && window.switchEditors.go( eid, 'tmce' ); if ( tinymce.majorVersion === "4" ) { tinymce.execCommand( 'mceAddEditor', true, eid ); var pop = $('#'+eid).closest('.or-params-popup'); if( pop.length > 0 && typeof pop.data('on_editor_change') == 'function' ){ var action = function(e) { clearTimeout( document._or_editor_timer ); document._or_editor_timer = setTimeout( function(){ if( typeof pop.data('on_editor_change') == 'function' ) pop.data('on_editor_change')( tinyMCE.activeEditor.getContent({format : 'raw'}) ); }, 500 ); } tinyMCE.get( eid ).on('keyup', action ).on('mouseup', action ).on('change', action ); } } } } catch ( e ) { $( '#wp-' + eid + '-wrap' ).html('Tinymce Error!'); if ( console && console.error ) { console.error( e ); } } } }, get_icons : function(){ if( or.icons != undefined ) return or.icons; function css_text(x) { return x.cssText; } var files = document.querySelectorAll('*[id^="or-sys-icon-"]'), html = '', css; if( !files || files.length === 0 ) return ''; for( var i=0; i < files.length; i++ ){ css = Array.prototype.map.call( files[i].sheet.cssRules, css_text ).join('\n'); css = css.split('::before'); css.forEach(function( i ){ i = i.split('.')[1]; if( i !== undefined && i.indexOf('/') == -1 ) html += '<i title="'+i.replace(/[^a-z-0-9]/g, "")+'" class="'+i.replace(/[^a-z-0-9]/g, "")+'"></i>'; }); } or.icons = html; return html; } } ); or.tools.base64.stringBuffer.prototype.append = function append(string) { this.buffer.push(string); return this }; or.tools.base64.stringBuffer.prototype.toString = function toString() { return this.buffer.join("") }; or.tools.base64.utf8EncodeEnumerator.prototype = { current: Number.NaN, moveNext: function() { if (this._buffer.length > 0) { this.current = this._buffer.shift(); return true } else if (this._index >= (this._input.length - 1)) { this.current = Number.NaN; return false } else { var charCode = this._input.charCodeAt(++this._index); if ((charCode == 13) && (this._input.charCodeAt(this._index + 1) == 10)) { charCode = 10; this._index += 2 } if (charCode < 128) { this.current = charCode } else if ((charCode > 127) && (charCode < 2048)) { this.current = (charCode >> 6) | 192; this._buffer.push((charCode & 63) | 128) } else { this.current = (charCode >> 12) | 224; this._buffer.push(((charCode >> 6) & 63) | 128); this._buffer.push((charCode & 63) | 128) } return true } } }; or.tools.base64.decodeEnumerator.prototype = { current: 64, moveNext: function() { if (this._buffer.length > 0) { this.current = this._buffer.shift(); return true } else if (this._index >= (this._input.length - 1)) { this.current = 64; return false } else { var enc1 = or.tools.base64.codex.indexOf(this._input.charAt(++this._index)); var enc2 = or.tools.base64.codex.indexOf(this._input.charAt(++this._index)); var enc3 = or.tools.base64.codex.indexOf(this._input.charAt(++this._index)); var enc4 = or.tools.base64.codex.indexOf(this._input.charAt(++this._index)); var chr1 = (enc1 << 2) | (enc2 >> 4); var chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); var chr3 = ((enc3 & 3) << 6) | enc4; this.current = chr1; if (enc3 != 64) this._buffer.push(chr2); if (enc4 != 64) this._buffer.push(chr3); return true } } }; } )( jQuery );
/** * Created by John on 2015-10-02. */ var express = require('express'); var url = require('url'); var path=require('path'); var swig=require('swig'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static(path.join(__dirname, 'public'))); //设置模块引擎 app.engine('html',swig.renderFile); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); //引入body对象 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); /** * 1:模拟卡片的信息,cards * 2;定义获取某个具体的id的时候,返回的数据 * 3:定义返回所有的路径的时候返回的数据 * * */ var cards=[ { id:1, name:'建设银行', amount:0 }, { id:2, name:'中国银行', amount:0 }, { id:3, name:'上海银行', amount:0 } ]; //当为某一个具体的id的时候,返回该id对应的数据 app.get('/card/user/123/:id',function(req,res){ var data=cards[req.params.id-1]; res.send(data); }); //返回所有的数据 app.get('/card/user/123',function(req,res){ res.send(data); }); app.get('/',function(req,res){ res.render('index'); }); //存储修改的数据 app.post('/card/user/123/:id',function(req,res){ /** * 1:获取id的值, * 2:存取传递过来的参数 * 3:返回更新之后的结果 * */ var index=req.params.id-1; console.log(req.body); cards[index]=req.body; console.log(cards[index]); res.send(cards[index]); }); app.listen(3000); console.log("Server runing at port: " + '3000' + ".");
$(".dropdown").mouseover(function () { $(this).addClass("show").find(".dropdown-menu").addClass("show"); }); $(".dropdown .dropdown-menu").mouseout(function () { $(this).removeClass("show").parent(".dropdown").removeClass("show") }); function signout() { alert("您已退出登录"); window.location.href="/SkipServlet?skip=logout" } function change() { var from = document.getElementById("from").value; var to = document.getElementById("to").value; document.getElementById("from").value = to; document.getElementById("to").value = from; } $(function () { $('#go-off').datetimepicker({ format:'yyyy-mm-dd', language:'zh-CN', autoclose:'true', minView:'month' }); $('#go-off2').datetimepicker({ format:'yyyy-mm-dd', language:'zh-CN', autoclose:'true', minView:'month' }); }); function click() { } $().ready(function() { validate(); }) function validate(){ $("#register").validate({ errorElement:'span', errorPlacement: function(error, element) { error.appendTo(element.parent()); }, rules:{ usr:{ required:true, minlength:6, maxlength:20 }, name:{ required:true, minlength:2, maxlength:8 }, pwd:{ required:true, minlength:6, maxlength:20 }, cpwd:{ required:true, minlength:6, maxlength:20, equalTo:"#pwd" }, tel:{ required:true, minlength:11, maxlength:11 }, number:{ required:true, minlength:18, maxlength:18 }, site:{ required:true }, agree:"required" }, messages:{ usr:{ required:"请输入用户名", minlength:"用户名长度不能小于6位", maxlength:"用户名长度不能大于20位" }, name:{ required:"请输入姓名", minlength:"姓名长度不能小于2位", maxlength:"姓名长度不能大于15位" }, pwd:{ required:"请输入密码", minlength:"密码长度不能小于6位", maxlength:"密码长度不能大于20位" }, cpwd:{ required:"请确认密码", minlength:"密码长度不能小于6位", maxlength:"密码长度不能大于20位", equalTo:"两次密码输入不一致" }, tel:{ required:"请输入电话号码", minlength:"请输入正确的电话号码", maxlength:"请输入正确的电话号码" }, number:{ required:"请输入身份证号", minlength:"请输入正确的身份证号码", maxlength:"请输入正确的身份证号码" }, site:{ required:"请输入地址" }, agree:"" } }) }
import React from "react" import { connect } from "react-redux" import Link from "../../components/Link/index"; import CensorWord from "../CensoredWords/Index" import Image from "../Image/Index" import { renderToString } from 'react-dom/server' import Translate from "../../components/Translate/Index" class Season extends React.Component{ constructor(props){ super(props) this.state = { movie:props.movie, seasons:props.seasons } } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} } else if (nextProps.pageInfoData.movie != prevState.movie) { return { movie:nextProps.movie, seasons:nextProps.seasons } } else{ return null } } render(){ let items = this.state.seasons.map((item,_) => { return ( <div key={item.season_id} className="item"> <div className="ThumbBox-wrap"> <Link href="/season" customParam={`seasonId=${item.season}&videoId=${this.state.movie.custom_url}`} as={`/watch/${this.state.movie.custom_url}/season/${item.season}`}> <a className="ThumbBox-link"> <div className="ThumbBox-coverImg"> <span> <Image image={item.image} imageSuffix={this.props.pageInfoData.imageSuffix} /> </span> </div> <div className="ThumbBox-Title"> <div className="title ellipsize2Line"> <h4 className="m-0">{`Season ${item.season}`}{" "} <span className="material-icons">fiber_manual_record</span> {" "} {`${item.episodes_count} Episodes`}</h4> </div> </div> </a> </Link> </div> </div> ) }) return ( <div className="gridContainer gridSeason"> {items} </div> ) } } const mapStateToProps = state => { return { pageInfoData: state.general.pageInfoData }; }; export default connect(mapStateToProps, null)(Season);
module.exports = function(grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), watch: { ts: { files: ["src/\*\*/\*.ts"], tasks: ["newer:ts:src"] }, public: { files: ["public/js/\*\*/\*.ts"], tasks: ["newer:ts:public", "newer:uglify"] }, sass: { files: ["public/scss/\*\*/\*.scss"], tasks: ["newer:sass:public", "newer:postcss", "newer:cssmin"] } }, ts: { src: { files: [{ src: ["src/\*\*/\*.ts", "!src/.baseDir.ts"], dest: "./dist" }], options: { module: "commonjs", target: "es6", sourceMap: false, rootDir: "src" } }, public: { files: [{ src: ["public/js/\*\*/\*.ts"], dest: "public/js" }], options: { module: "commonjs", target: "es6", sourceMap: false, rootDir: "public/js" } } }, sass: { public: { options: { sourcemap: "none", style: "expanded" }, files: [{ expand: true, cwd: "public/scss/", src: ["\*\*/\*.scss"], dest: "public/css/", ext: ".css" }] } }, postcss: { // Begin Post CSS Plugin options: { map: false, processors: [ require("autoprefixer")({ browsers: ["last 2 versions"] }) ] }, public: { src: "public/css/style.css" } }, cssmin: { // Begin CSS Minify Plugin public: { files: [{ expand: true, cwd: "public/css", src: ["\*.css", "!\*.min.css"], dest: "public/css", ext: ".min.css" }] } }, uglify: { // Begin JS Uglify Plugin options: { banner: "/*! <%= pkg.name %> <%= grunt.template.today('yyyy-mm-dd') %> */\n" }, public: { files: [{ expand: true, cwd: "public/js", src: ["*.js", "!*.min.js"], dest: "public/js", rename: function (dst, src) { return dst + "/" + src.replace(".js", ".min.js"); } }] } }, }); grunt.loadNpmTasks("grunt-newer"); grunt.loadNpmTasks("grunt-ts"); grunt.loadNpmTasks("grunt-contrib-sass"); grunt.loadNpmTasks("grunt-postcss"); grunt.loadNpmTasks("grunt-contrib-cssmin"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.registerTask("default", [ "newer:ts:src", "newer:sass", "newer:postcss", "newer:cssmin", "newer:ts:public", "newer:uglify" ]); };
import {Value} from 'slate'; const questionDescription = JSON.stringify({ document: { nodes: [ { object: 'block', type: 'paragraph', nodes: [ { object: 'text', leaves: [ { text: '', }, ], }, ], }, ], }, }); const optionA= JSON.stringify({ document: { nodes: [ { object: 'block', type: 'paragraph', nodes: [ { object: 'text', leaves: [ { text: '', }, ], }, ], }, ], }, }); const optionB= JSON.stringify({ document: { nodes: [ { object: 'block', type: 'paragraph', nodes: [ { object: 'text', leaves: [ { text: '', }, ], }, ], }, ], }, }); const optionC= JSON.stringify({ document: { nodes: [ { object: 'block', type: 'paragraph', nodes: [ { object: 'text', leaves: [ { text: '', }, ], }, ], }, ], }, }); const optionD= JSON.stringify({ document: { nodes: [ { object: 'block', type: 'paragraph', nodes: [ { object: 'text', leaves: [ { text: '', }, ], }, ], }, ], }, }); export const defaultValues = { desc:Value.fromJSON(JSON.parse(questionDescription)), optionA:Value.fromJSON(JSON.parse(optionA)), optionB:Value.fromJSON(JSON.parse(optionB)), optionC:Value.fromJSON(JSON.parse(optionC)), optionD:Value.fromJSON(JSON.parse(optionD)), explanation:Value.fromJSON(JSON.parse(optionD)), answer:'', typeId:'', subjectId:'', chapterId:'', topicId:'', complexityLevel:'1', tags:[{name:'',value:''}] };
"use strict"; var twitter = require('ntwitter'); var when = require('when'); var _ = require('underscore'); var config = require('./config'); var processor = require('./process'); var TIME_BETWEEN_REQUESTS = 60*1000; // var TIME_BETWEEN_REQUESTS = 300;//TODO: change to once a minute var twit = new twitter(config.twitter); //mockups for testing // twit.getFriendsIds = function(id, cb){ // id = id || '' + ''; // setTimeout(function(){ // cb(null, [id+1,id+2,id+3,id+4,id+5]); // }, 100); // }; // twit.getFollowersIds = function(id, cb){ // id = id || '' + ''; // setTimeout(function(){ // cb(null, [id+6,id+7,id+8,id+9]); // }, 100); // }; // rate limit a function returning a promise. Calls are queued up and executed at the // rate specified function rateLimit(fn){ var lastAPICall = 0; var q = []; var processing = false; function process(){ processing = true; var timeout = Math.max(TIME_BETWEEN_REQUESTS - (Date.now() - lastAPICall), 0); setTimeout(function(){ var p = q[0]; if(p){ p().then(function(){ q.shift(); lastAPICall = Date.now(); process(); }); }else{ processing = false; } }, timeout); } return function(){ var args = Array.prototype.slice.call(arguments); var deferred = when.defer(); q.push(function(){ return fn.apply(null, args).then(function(result){ deferred.resolve(result); }); }); !processing && process(); return deferred.promise; }; } //helper functions function getFriendsIds(id){ console.log('Getting friends of '+id); var deferred = when.defer(); twit.getFriendsIds(id, function(err, friends){ if(err){ console.log(err); deferred.reject(err); }else{ deferred.resolve(friends); // deferred.resolve(_.take(friends, 5)); } }); return deferred.promise; } function getFollowersIds(id){ console.log('Getting followers of '+id); var deferred = when.defer(); twit.getFollowersIds(id, function(err, followers){ if(err){ deferred.reject(err); }else{ deferred.resolve(followers); // deferred.resolve(_.take(followers, 5)); } }); return deferred.promise; } getFollowersIds = rateLimit(getFollowersIds); getFriendsIds = rateLimit(getFriendsIds); function showUser(ids){ var deferred = when.defer(); twit.showUser(ids, function(err, users){ if(err){ deferred.reject(err); }else{ deferred.resolve(users); } }); return deferred.promise; } function follow(id){ var deferred = when.defer(); //reject if not suitable twit.createFriendship(id, { follow: true }, function(err, user){ if(err) deferred.reject(); else deferred.resolve(user); }); return deferred.promise; } function unfollow(id){ var deferred = when.defer(); twit.createFriendship(id, function(err, user){ if(err) deferred.reject(); else deferred.resolve(); }); return deferred.promise; } var ids = {}; function addFollowers(followers){ return processor.addFollowers(followers); // return when.map(followers, function(follower){ // ids[follower] = 'FolOfFr'; // return when.resolve(follower); // }); } function gather(){ return getFriendsIds().then(function(friends){ console.log('Direct friends: '+friends.length); return when.map(friends, function(friend){ return getFollowersIds(friend).then(function(followersOfFriend){ return addFollowers(followersOfFriend); }); /* // logic to get followers of friends of friends return getFriendsIds(friend).then(function(friendsOfFriend){ console.log('friend: '+friend); console.log(friendsOfFriend.length); return when.map(friendsOfFriend, function(friendOfFriend){ ids[friendOfFriend] = 'FoF'; console.log(friendOfFriend); return getFollowersIds(friendOfFriend).then(function(followersOfFriendOfFriend){ return when.map(followersOfFriendOfFriend, function(followerOfFriendOfFriend){ ids[followerOfFriendOfFriend] = 'FoFF'; return when.resolve(); }); }); }); }); */ }); }); } gather().then(function(){ console.log('Gathering finished'); console.log(ids); process.exit(0); });
import axios from 'axios' export default { // 保存接口 save (params) { return axios.post('/myTask/save', params) }, // 更新接口 update (params) { return axios.post('/myTask/update', params) }, // 保存接口 saveTaskToSelf (params) { return axios.post('/myTask/saveTaskToSelf', params) }, // 通过候选人id查询 findByRelativeCandidateId (params) { return axios.get('/myTask/findByRelativeCandidateId?relativeCandidateId=' + params) }, // 查询本人今日任务 queryTodayTaskForMe () { return axios.get('/myTask/queryTodayTaskForMe') }, // 查找后台数据 queryMyTaskPage (params) { return axios.post('/myTask/queryMyTaskPage', params) } }
var express = require("express"), router = express.Router({mergeParams: true}), Recipe = require("../models/recipe"), Comment = require("../models/comment"); middleware = require("../middleware"); //new comment form router.get("/new", middleware.isLoggedIn, function(req, res){ Recipe.findById(req.params.id, function(err, foundRecipe){ if(err){ console.log(err); } else { res.render("comments/new", {recipe: foundRecipe}); } }); }); //new comment logic router.post("/",middleware.isLoggedIn, function(req, res){ Recipe.findById(req.params.id, function(err, foundRecipe){ if(err){ console.log(err); } else { Comment.create(req.body.comment, function(err, comment){ if(err){ console.log(err); } else { comment.author.id = req.user._id; comment.author.username = req.user.username; comment.save(); foundRecipe.comments.push(comment); foundRecipe.save(); res.redirect("/recipes/" + foundRecipe._id); } }); } }); }); module.exports = router;
import React, { useState, useEffect } from 'react'; import { CSSTransitionGroup } from 'react-transition-group'; import { getDefaultState, getSets, isSet, getFormattedTime, getSetAnalysis, localStorageName } from './_util'; import SetHelp from './SetHelp'; import SetCard from './SetCard'; import SetsPossible from './SetsPossible'; export default () => { /* * */ const [state, setState] = useState(getDefaultState()) /* * */ const [gameOver, setGameOver] = useState(false); const resetGame = () => { localStorage.removeItem(localStorageName); setGameOver(false); setState(getDefaultState()); setInit(false); } /* * */ const [showPossibleSets, setShowPossibleSets] = useState(false); const toggleShowSets = (newState) => setShowPossibleSets(prevState => newState || !prevState); /* * */ const [timerIntervalId, setTimerIntervalId] = useState(null); const setTimer = () => { const id = setInterval(() => { setState(state => ({...state, timer: state.timer + 1})); }, 1000); setTimerIntervalId(id); } useEffect(() => { if (gameOver === true) { clearInterval(timerIntervalId); } }, [gameOver]) /* * */ const [isInit, setInit] = useState(false); useEffect(() => { if (isInit === false) { init(); } }, [isInit]); const init = () => { let n = 0; const addCardDelay = function () { if (n < 12) { addCard(); setTimeout(() => addCardDelay(), 100); } else { setInit(true); } n += 1; } addCardDelay(); setTimer(); } useEffect(() => { if (state.selected.length === 3) { if (isSet(state.selected)) { // alert('set found!') setFound(); } else { alert('not a set!') setState({...state, selected: [], wrong: state.wrong += 1}) } } }, [state.selected]) const toggleSelect = (card) => { let selected = [...state.selected]; const cardIndex = selected.findIndex((c) => c.id === card.id); if (cardIndex === -1) { selected.push(card); } else { selected.splice(cardIndex, 1); } setState(prevState => ({ ...prevState, selected})) } const setFound = () => { const { remainingCards, cards, selected, } = state; let cardIndex; let found = [...state.found] found.push(selected) selected.forEach((card, i) => { cardIndex = cards.findIndex((c) => c.id === card.id); if (cardIndex >= 12) { // remove extra cards from no set rounds cards.splice(cardIndex, 1); } else { cards.splice(cardIndex, 1, remainingCards.pop() || {id: '', placeholder: true}); } }) setState(prevState => ({...prevState, selected: [], remainingCards, cards, found})) setShowPossibleSets(false); // console.log(getSetAnalysis(getSets(getCards()))); console.log(getSetAnalysis(found)); } useEffect(() => { if (state.found.length > 0) { setStateInLocalStorage(); } }, [state.found, state.timer]) function setStateInLocalStorage() { localStorage.setItem(localStorageName, JSON.stringify(state)); } const addCard = () => { const { remainingCards, cards, } = state; if (remainingCards.length > 0) { cards.push(remainingCards.pop()) } setState(prevState => ({...prevState, remainingCards, cards})) } const sets = getSets(state.cards); if (sets.length === 0 && isInit === true) { if (state.remainingCards.length === 0) { // game over if (!gameOver) { setGameOver(true); } } else { // add extra card addCard(); } } return ( <div className='set' data-gameover={gameOver} data-found={state.found.length - 1}> <SetHelp toggleShowSets={toggleShowSets} showPossibleSets={showPossibleSets} sets={isInit ? sets : []} found={state.found} remainingCards={state.remainingCards} wrong={state.wrong} timer={state.timer} resetGame={resetGame} /> <div className='set__container'> <div className='set__container-inner'> <div className='set__in-play'> <div className='set__metadata'> <div className='set__metadata__remaining'> {state.remainingCards.slice(-4).map((card,i) => <div key={i} className='set-deck__card'></div> )} </div> <div className='set__found'> <CSSTransitionGroup transitionName='slide' transitionEnterTimeout={1700} transitionLeaveTimeout={0} > {state.found.map((set,i) => <div key={i} className='set-deck'> {set.map((card,j) => <div key={j} className='set-deck__card'></div> )} </div> )} </CSSTransitionGroup> </div> </div> <CSSTransitionGroup transitionName='deal' transitionEnterTimeout={1200} transitionLeaveTimeout={1200} transitionAppear={true} transitionAppearTimeout={1200} > {state.cards.map((card,i) => ( <div className='set-card__container' key={card.id} data-i={i} > <SetCard card={card} toggleSelect={toggleSelect} selected={state.selected.findIndex((c) => c.id === card.id) > -1} /> </div> ))} </CSSTransitionGroup> </div> </div> {showPossibleSets ? <SetsPossible sets={sets} /> : null } </div> {gameOver ? <button className='set__game-over' onClick={() => resetGame()}> <div>Game over! Click for new game</div> <div>{getFormattedTime(state.timer)}</div> </button> : null } </div> ) }
import React, {Component} from 'react'; import {Row, Col, Form} from 'antd'; import {QueryBar, FormElement} from '../../../index'; @Form.create() export default class Base extends Component { state = { collapsed: true }; handleCollapsedChange = (collapsed) => this.setState({collapsed}); render() { const {form} = this.props; const {collapsed} = this.state; const labelWidth = 80; return ( <div> <QueryBar showCollapsed collapsed={collapsed} onCollapsedChange={this.handleCollapsedChange} > <Row> <Col span={8}> <FormElement form={form} type="input" field="userName" label="用户名" labelWidth={labelWidth} /> </Col> <Col span={8}> <FormElement form={form} type="input" field="loginName" label="登录名" labelWidth={labelWidth} /> </Col> <Col span={8}> <FormElement form={form} type="input" field="job" label="工作" labelWidth={labelWidth} /> </Col> </Row> <Row style={{display: collapsed ? 'none' : 'block'}}> <Col span={8}> <FormElement form={form} type="input" field="age" label="年龄" labelWidth={labelWidth} /> </Col> <Col span={8}> <FormElement form={form} type="input" field="position" label="职位" labelWidth={labelWidth} /> </Col> <Col span={8}> <FormElement form={form} type="input" field="enjoy" label="爱好" labelWidth={labelWidth} /> </Col> </Row> </QueryBar> </div> ); } } export const title = '基础用法'; export const markdown = ` 基础用法 `;
/** * Created by ShriRam on 2/17/2017. */ //inc export function increment (index) { //noinspection JSAnnotator,JSAnnotator return { type: "INCREMENT_LIKES", index } } export function addComment(postId,author,comment){ return{ type:"ADD_COMMENT", postId, author, comment } } //remove comm export function removeComment(postId,i) { return { postId, i } }
$(function(){ //header里的微信二维码 $("#header .header .left .weixin").hover( function(){ $(this).find("img").show(); }, function(){ $(this).find("img").hide(); } ); //轮播图 var ord = 1; var myTimer = null; //下一张 function nextImg(){ ord++; if(ord>4){ $("#button li").eq(0).addClass("active").siblings().removeClass(); } $("#pic").stop(true,true).animate({"left":-(ord*$("#pic li").outerWidth())+"px"},function(){ if(ord>4){ $(this).css("left",-$("#pic li").outerWidth()+"px"); ord=1; } }); $("#button li").eq(ord-1).addClass("active").siblings().removeClass(); } //自动轮播 myTimer = setInterval(nextImg,4000); // 放上去停止轮播 $("#pic").mouseover(function(){ clearInterval(myTimer); }); // 离开自动轮播 $("#pic").mouseout(function(){ myTimer = setInterval(nextImg,1000); }); // 放上去调到对应图片 $("#button li").click(function(){ clearInterval(myTimer); ord = $(this).index(); nextImg(); }); //banner图上的副导航 $("#banner .banner .aside .asideLi").mouseover(function(){ $(this).find("ul").show(); }); $("#banner .banner .aside .asideLi").mouseout(function(){ $(this).find("ul").hide(); }); //banner下3个图片 $("#sort .threePic a").mouseover( function(){ $(this).stop(true,true).animate({"padding-top":"30px"},500); $(this).find("img").css({"box-shadow":"7px 6px 0 0 rgba(0,255,255,0.5)"}); } ); $("#sort .threePic a").mouseout( function(){ $(this).stop(true,true).animate({"padding-top":"40px"},500); $(this).find("img").css({"box-shadow":"6px 6px 0 0 rgba(0,0,0,0.2)"}); } ); //下方APP var index = 1; function nextApp(){ index++; $(".pic #outer").stop(true,true).animate({"left":-(index*$("#outer .outer").outerWidth())+"px"},function(){ if(index>2){ $(this).css("left",-$("#outer .outer").outerWidth()+"px"); index=1; } }); } function prevApp(){ index--; console.log(index); $(".pic #outer").stop(true,true).animate({left:-(index)*$("#outer .outer").outerWidth()+"px"},function(){ if(index<1){ $(this).css("left",-(4*$("#outer .outer").outerWidth())+"px"); index = 2; } }); } $(".pic #prev").click(function(){ prevApp(); });$(".pic #next").click(function(){ nextApp(); }); //登录后进入欢迎您 var userName = $.cookie("userName"); if(userName==null){ $(".header .right .login").show(); $(".header .right .register").show(); $(".header .right .welcome").hide(); }else{ $(".header .right .login").hide(); $(".header .right .register").hide(); $(".header .right .welcome").show(); $(".header .right .welcome").html("欢迎您~"+userName); $(".header .right .out").html("退出"); $(".header .right .out").css("cursor","pointer"); $(".header .right .out").click(function(){ $.cookie("userName",null); $(".header .right .login").show(); $(".header .right .register").show(); $(".header .right .welcome").hide(); }); } });
var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.render('home', { newPosts: [ { image: "images/a.jpg", title: "post1", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" },{ image: "images/a.jpg", title: "post2asdsdsadasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdada", href: "#" }] }); }); module.exports = router;
import React from "react" import { Switch, Route, Redirect } from "react-router" import Home from "./home/Home" import Classroom from "./Classroom/Classroom" import Exit from "./Exit/Exit" import Logo from "./templates/Logo" import Nav from "./templates/Nav" import Footer from "./templates/Footer" export default props => { const { name } = props return ( <> <Logo /> <Nav /> <Switch> <Route exact path="/" component={props => <Home name={name} />} /> <Route path="/salas" component={Classroom} /> <Route path="/sair" component={props => <Exit {...props} />} /> <Redirect to="/" /> </Switch> <Footer /> </> ) }
import React from 'react' import { View, Text, StyleSheet, Image } from 'react-native' import { colors } from '../utils/index' import Forecast from './Forecast' // import moment from 'moment' const { PRIMARY_COLOR, SECONDARY_COLOR } = colors function convertTime(unixTime){ let dt = new Date(unixTime * 1000) let h = dt.getHours() let m = "0" + dt.getMinutes() let t = h + ":" + m.substr(-2) return t } export default function WeatherInfo({ currentWeather,unitsSystem }) { const { main: {temp}, weather: [details], name, sys: {sunrise, sunset} } = currentWeather const { icon, main, description } = details const iconUrl = `https://openweathermap.org/img/wn/${icon}@4x.png` return ( <View style={styles.weatherInfo}> <Text style={styles.textSecondary}>{name}</Text> <Image style={styles.weatherIcon} source={{ url: iconUrl }} /> <Text style={styles.textPrimary}>{Math.floor(temp)}°</Text> <Text style={styles.weatherDescription}>{description}</Text> <Text style={styles.textSecondary}>{main}</Text> <Text style={styles.sunText}>Sunrise {convertTime(sunrise)} AM | Sunset {convertTime(sunset)} PM</Text> <Forecast unitsSystem={unitsSystem} /> </View> ) } const styles = StyleSheet.create({ weatherInfo: { alignItems: 'center', top: 40 }, weatherIcon: { width: 100, height: 100 }, weatherDescription: { textTransform: 'capitalize' }, textPrimary: { fontSize: 40, color: PRIMARY_COLOR, fontWeight: '600' }, textSecondary: { fontSize: 20, color: SECONDARY_COLOR, fontWeight: '500', marginTop: 10 }, sunText: { fontSize: 12, fontWeight: '600', color: 'white' } })
module.exports = { "env": { "node": true }, "extends": [ "eslint:recommended", ], "globals": { "Promise": 1 }, "parserOptions": { "ecmaVersion": 2018, "sourceType": "module" }, "rules": { "no-console":[ 0 ], "indent": [ 1, 2, {"SwitchCase": 1} ], "quotes": [ 1, "single" ], "semi": [ 2, "always" ], "no-var": ["error"], "prefer-arrow-callback": ["error"], "object-shorthand": ["error"], "no-duplicate-imports": ["error"], "no-iterator": ["error"], "dot-notation": ["error"], "no-plusplus": ["error"], "eqeqeq": ["error"], "no-nested-ternary": ["error"], "no-unneeded-ternary": ["error"], "brace-style": ["error"], "space-infix-ops": ["error"], "no-trailing-spaces": ["error"], "no-trailing-spaces": [ 2 ], "prefer-const": ["error", { "destructuring": "any", "ignoreReadBeforeAssign": false }], } };
/** * Eventually this handler will be responsible for * determining what features a user has access to */ export default async function handler(_req, res) { let flags = []; // if (process.env.VERCEL_ENV === "development") { // flags.push("next"); // } res.json(flags); }
/* initialize suggest counters */ cur_sel_index = 0 max_sel_itms = 0 last_search_str = 'undefined' /* keeping last search string in order to skip ajax calls */ cur_sel_item_legth = 0 /* the lenght of the selected suggested item */ cur_attr_num = 1 /* pos handler when editing html tag */ cur_max_attrs_num = 0 /* counter for currently edited html tag attributes */ cur_ap = 'v' /* track which part of the attribute we edit name/value */ last_action = '' /* track actions for better handling of actions while editing html tag */ multi_suggest = false /* sets a multivalue field input like for class attribute */ cur_sc_con = $('#dContent_con') /* current container cointaining selectable containers */ cur_sc = $('#dContent') /* currently marked selectable container for selecting */ cur_sc_index = 0 /* track selectable container siblings index */ wrap_selected_sc = false /* used on add smarty/html container selection to enable by pressing "r" key wraping selected container with the new one */ unwrap_selected_sc = false /* used on unwrap content by pressing "u" on "Del" functionality */ mouse_selection = true /* to enable/disable mouse selection when needed */ mouse_selection_handled = false /* to prevent double handling of middle mouse click */ enter_pressed = false /* to prevent double action with one press of enter key */ mouse_clicked = false /* track mouse click to check it when changing edited attribute/value */ tab_handled = false /* to prevent skipping adding new attribute with tab key */ buffer = '' /* initialize buffer for copy(cut)/paste operations */ preview_class = false /* flag wich tell us if we previewing class from suggest list */ cur_class = '' /* temp string to store current attribute class */ vars = [] /* current smarty template vars */ vars_db_info = [] /* store fetched info from db for creation of db queries */ suggest_vars = false /* flag to identify when to suggest smarty vars and when not */ cur_var_lvl = 0 /* used to keep current deepnes of multiarray */ cur_full_var = '' /* used when suggest multilevel variables to show only correct sub var suggest */ search_str = '' /* define search_str as global to have access to it in functions without need to pass it over */ skip_parse = false /* used to skip parsing smarty statements when such are included without html container */ db_tables = [] /* initialize empty db_tables collection */ /* initialize smarty modifiers (only the ones available in /node_modules/nsmarty/lib/nsmarty/parser.js) */ smarty_modifiers = [ 'capitalize', 'cat', 'count', 'count_characters', 'count_paragraphs', 'count_sentences', 'count_words', 'date_format', 'default', 'escape', 'indent', 'lower', 'nl2br', 'regex_replace', 'replace', 'spacify', 'string_format', 'strip', 'strip_tags', 'truncate', 'upper', 'wordwrap' ] styled_objs = [] /* keep references to objects that have hard coded styles */ new_classes = [] /* initialize epmty collection for moved hard coded styles to classes on save */ parents_stack = [] /* initialize epmty collection for saving currently scanned element (parent) */ index_stack = [] /* initialize epmty collection for saving current index before going deep in the rabit hole */ save_handled = false; /* preventing execution of saveTemplate twice in the same time */ function addHTMLorSS( event ) { resetBodyShortcuts(); suggestFor(event, 'html_tags', 'Type/Select HTML Tag', '', function( name ) { enter_pressed = true /* set this to true to indicate that enter press was handled and stop double action */ if (name !== '') { prepHtmlTag( name, function( html ) { clearMFE() $( '#dInfo' ).html('Select Container to Insert the HTML tag (hold shift to put it before or press "r" to wrap selected container)').removeClass("hide") $('#btn_n').click(function() { resetBodyShortcuts( function() { $( '.popover' ).remove(); resetDAField() /* remove (unbind) all current functionality on dAField */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ $('#selItmCon').remove() /* destroy selItmCon along with the content */ hideMF() /* hide the form and show the menu */ }) }) /* ask for insertion place */ conSelector( html, function() { $( '#btn_y' ).click( function() { checkAttrName() /* check if we need to update/remove attr */ if ( preview_class ) { /* when previewing class -> remove it */ removePreviewedClass() } tag_name = getCurTagName() /* get currently edited html tag name */ if ( !skip_parse && tag_name != 'TEXTAREA') { parse_smarty() /* parse smarty statements and html tags */ } else { skip_false = false /* reset the flag when used */ } /* unwrap the finished html tag from selItmCon */ kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).unwrap() /* destroy selItmCon leaving the content */ resetDAField() hideMF() /* hide the form and show the menu */ }) reset_scs() /* remove (unbind) all current functionality on all selectable containers */ resetBodyShortcuts() /* enable normal keyboard functioning */ if ( html.indexOf( 'nsmarty_code' ) != -1 ) { /* when smarty statement detected -> skip double parsing of smarty statements and finish adding */ skip_parse = true $('#btn_y').click() } else { /* otherwise -> enable smarty parsing and go to edit currently added html */ skip_parse = false editHTMLTag( html, function() { $('#btn_y').click() }) } }) /* show the buttons */ $('#btn_y, #btn_n').removeClass("hide") }) } else { hideMF() /* hide the form and show the menu */ } }) } function editHTMLorSS( event ) { resetBodyShortcuts(); hideSuggests(); showMF() /* clear form, hide menu, and show form container */ $( '#dInfo' ).html('Select Container to Edit').removeClass("hide") conSelector( '', function() { resetBodyShortcuts() /* enable normal keyboard functioning */ resetDAField() /* remove (unbind) all current functionality on dAField */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ var ee_html_str = $( cur_sc ).prop('outerHTML'); /* ee_html = edited element html string */ cur_sc_start_html = ee_html_str.substr( 0, ee_html_str.indexOf('>') + 1 ); /* get only the selected sc opening html */ if ( cur_sc_start_html.indexOf( 'nsmarty_code' ) == -1 ) { /* only when selected sc is not smarty code container */ $( '#btn_y' ).click( function() { checkAttrName() /* check if we need to update/remove attr */ if ( preview_class ) { /* when previewing class -> remove the class from thre real html tag */ removePreviewedClass() } kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).unwrap() /* destroy selItmCon leaving the content */ resetDAField() hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) $( '#btn_n' ).click( function() { if ( preview_class ) { /* when previewing class -> remove the class from thre real html tag */ removePreviewedClass() } kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).unwrap() /* destroy selItmCon leaving the content */ resetBodyShortcuts() /* enable normal keyboard functioning */ resetDAField() /* remove (unbind) all current functionality on dAField */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) editHTMLTag( cur_sc_start_html, function() { $('#btn_y').click() }) } else { $( '#btn_y' ).click( function() { checkAttrName() /* check if we need to update/remove attr */ if ( preview_class ) { /* when previewing class -> remove it */ removePreviewedClass() } /* unwrap the finished html tag from selItmCon */ kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).unwrap() /* destroy selItmCon leaving the content */ resetDAField() hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) $( '#btn_n' ).click( function() { /* unwrap the finished html tag from selItmCon */ kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).unwrap() /* destroy selItmCon leaving the content */ resetBodyShortcuts() /* enable normal keyboard functioning */ resetDAField() /* remove (unbind) all current functionality on dAField */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) editHTMLTag( ee_html_str, function() { $( '#btn_y' ).click() /* cancel operation when try to edit smarty code sc */ }) } }) $( '#btn_n' ).click( function() { resetBodyShortcuts() /* enable normal keyboard functioning */ resetDAField() /* remove (unbind) all current functionality on dAField */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) } function delHTMLorSS( event ) { resetBodyShortcuts(); hideSuggests() showMF() /* clear form, hide menu, and show form container */ $( '.popover' ).remove(); $( '#dInfo' ).html('Select Container to Delete (Press "u" to activate unwrap mode)').removeClass("hide") $( '#btn_n' ).click( function() { $( '.popover' ).remove(); /* clear all event listners on all selectable contents */ resetBodyShortcuts() /* enable normal keyboard functioning */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) conSelector( '', function() { reset_scs() resetBodyShortcuts( function() { if ( $( cur_sc ).attr( 'id' ) !== 'dContent' && $( cur_sc ).attr( 'id' ) !== 'dContent_con' ) { /* only delete when selected container is not dContent */ $( cur_sc ).unwrap() /* unwrap selected element before deleting it */ cur_sc.remove() /* the actual deleting of the element */ } $( '.popover' ).remove(); /* clear all event listners on all selectable contents */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ cur_sc_con = $('#dContent_con') /* reset cur_sc_con to initial state */ cur_sc = $('#dContent') /* reset cur_sc to initial state */ delHTMLorSS( event ); /* re invoke delHTMLorSS for continious deletion of elements */ }) }) } function editHTMLTag( html, callback ) { /* replace the brackets their equivalent entity names */ html = html.replace(/</g, '&lt').replace(/>/g, '&gt') /* remove special attribute sc (selectable container) */ html = html.replace('sc="true"', '') /* remove web editable atributes */ html = html.replace('contenteditable="true"', '') html = html.replace('spellcheck="true" ', '') /* add editable functionality to each attribute */ new_html = '' /* reset attr counters */ cur_attr_num = 1 cur_max_attrs_num = 0 if ( html.indexOf(" ") != -1 ) { /* when attributes found -> get the tag name */ var tag_start = html.substr( 0, html.indexOf( ' ' ) ) + ' '; if ( html.indexOf( '&gt&lt' ) != -1 ) { /* when not selfcontaining -> add the closing tag */ var tag_end = '&gt&lt/' + tag_start.substr( 3, ( tag_start.length - 4 ) ) + '&gt'; } else { /* otherwise -> just close the tag */ var tag_end = '&gt'; } } if ( html.indexOf( 'nsmarty_code' ) != -1 ) { /* when editing smarty statement */ if ( html.indexOf( '&gt&lt' ) != -1 ) { /* when no html ( smarty statement ) value */ $( '#btn_n' ).click(); /* simulate "cancel" button click */ } else { new_html = html.replace( /&gt(.*?)&lt\/code/g, '&gt<span id="htv" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { editHTV() }">$1</span>&lt\/code' ) $('#dInfo').html('<code>'+new_html+'</code>') editHTV() } } else { attr_arr = html.match(/ ([^"]*)=\"([^"]*)\"/g); if ( attr_arr != null ) { attr_arr.forEach(function( attr, i ) { attr_arr[i] = attr.substr( 1, attr.length ).replace(/"/g, ''); /* wrap each attrubute's value in contaniner which is used to access and edit the value */ if (attr.indexOf('&lt') == -1 && attr.indexOf('&gt') == -1) { /* skip < and > items - leaving only the actual attrubites of the html string */ attr_parts = attr.split("=") attr_parts[0] = attr_parts[0].replace(/ /g, ''); /* remove unwanterd spaces from attribute name */ attr_parts[1] = attr_parts[1].replace(/"/g, ''); /* remove the '"' from attribute value */ cur_max_attrs_num++ src_btn = '' /* initialize empty string which is used ( populated ) only for src attribute */ if ( attr_parts[ 0 ] == 'src' ) { /* when current attribute is src -> add browse button */ src_btn = '<span class="btn btn-info btn-file" id="dFileCon"><div id="fileuploader"></div></span><script>$("#fileuploader").uploadFile({ url:"/uploader", fileName:"srcFile", onSuccess:function(files,data,xhr,pd) { data = data.replace( /"/g, "" ); $("#eav_' + cur_max_attrs_num + '").html( data ); kids = $( "#selItmCon" ).children(); $( kids[0] ).attr( "src", data ) } })</script>' } attr = '<span class="eac" id="ean_' + cur_max_attrs_num + '" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { cur_attr_num = ' + cur_max_attrs_num + '; editAttr(' + cur_max_attrs_num + ', \'n\') }" last-val="' + attr_parts[ 0 ] + '">' + attr_parts[ 0 ] + '</span>="<span class="eac" id="eav_' + cur_max_attrs_num + '" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { cur_attr_num = ' + cur_max_attrs_num + '; editAttr(' + cur_max_attrs_num + ', \'v\') }">' + attr_parts[ 1 ].replace(/"(.*?)"/g, '$1') + '</span>"' + src_btn } new_html += attr+' ' /* if it's just before last element add option to add new attribute(s) */ if (i+1 == attr_arr.length) { new_html += ' <a class="btn btn-success btn_ana" id="btn_ana" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { addAttr() }">+</a> ' } }) } else { /* if there is no attributes add option to add new one */ new_html = ' <a class="btn btn-success btn_ana" id="btn_ana" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { addAttr() }">+</a> ' setTimeout(function() { /* slow addAttr a bit in order to have time to create btn_ana element */ addAttr( false ) }, 1 ) } new_html = tag_start + new_html + tag_end.replace(/&gt&lt/, '&gt<span id="htv" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { editHTV() }"></span>&lt') ;/* when the html tag is not selfcontaining (found '><' in the html string ) -> add value option */ $('#dInfo').html('<code>'+new_html+'</code>') editAttr( cur_attr_num, cur_ap ) } } function clearSelectedClass() { /* clear highlight class */ $('.eac').each(function() { $( this ).removeClass( 'tc-lg tc-gy' ) }) } function addAttr( update ) { last_search_str = 'undefinded' if ( typeof update === 'undefined' ) { /* when 'update' is not present */ update = true } if ( update ) { updateCurAttr( event ) } cur_max_attrs_num++ /* add empty attribute just before btn_ana */ $('#btn_ana').before('<span class="eac" id="ean_'+cur_max_attrs_num+'" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { cur_attr_num = '+cur_max_attrs_num+'; editAttr('+cur_max_attrs_num+', \'n\') }" last-val="last-val"></span>="<span class="eac" id="eav_'+cur_max_attrs_num+'" onclick="mouse_clicked = true; if ( checkAttrName() != \'exit\') { cur_attr_num = '+cur_max_attrs_num+'; editAttr('+cur_max_attrs_num+', \'v\') }"></span>" ') cur_attr_num = cur_max_attrs_num cur_ap = 'n' tab_handled = true editAttr( cur_attr_num, cur_ap ) } function editAttr( index, ap ) { suggest_type = 'attribute' mouse_clicked = false if ( last_action == 'editHTV' ) { /* when we was editing html tag value last -> remove the highlight class */ $('#htv').removeClass('tc-gy') } else { /* otherwise we assume we was editing either attr name or it's value so clear all highlighted attr part */ clearSelectedClass() } last_action = 'editAttr' /* update last action */ if ( preview_class && $( '#ean_' + cur_attr_num ).html() != 'class' ) { removePreviewedClass() } if ( typeof ap == 'undefined' ) { /* when ap not present -> set it to be value edit as default */ ap = 'v' } cur_ap = ap attr_val = $('#ea'+ ap +'_'+index).html() /* get attribute value as string */ dAField = $('#dAField').removeClass('hide').val( attr_val ) /* set attr val to dAField and unhide it */ multi_suggest = false /* reset to default */ if ( $('#ean_'+index).html() == 'class' && cur_ap == 'v' ) { /* when edit class value -> set multi suggeset = true */ multi_suggest = true } $('#dInfo').after(dAField) $('#dAField').unbind('keyup keydown focus blur change') /* detach events from previous use */ if ( cur_ap == 'v' ) { cur_tc = 'gy' /* different color for each attr part */ if ( $('#ean_'+index).html() == 'src' ) { placeholder = 'Broswse or Drag & Drop File on "Browse" button for "'+ $('#ean_'+index).html() +'"' } else { placeholder = 'Type/Select value for "'+ $('#ean_'+index).html() +'"' } } else { cur_tc = 'lg' /* different color for each attr part */ placeholder = "Type/Select attribute name" } $('#ea'+ ap +'_'+index).addClass( 'tc-' + cur_tc ) /* attach new events */ $('#dAField').addClass( 'input_ta' ) .html( attr_val ) /* add default value if defined */ .removeClass( "hide" ) /* show dAField */ .focus( function( event ) { updateTAHeight() suggest( event, suggest_type, 'dAField', 'dSuggests', 'ku', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest) }) .keyup(function(event) { /* setup on key up/down to catch what is writen and suggest items based on that */ if (event.keyCode == 27) { $('#btn_n').click() return } if ( event.shiftKey && event.keyCode == 72 && $('span#htv').length === 1 ) { /* when shift+h -> go directly to edit HTML value */ editHTV() return } if ( event.shiftKey && event.keyCode == 13 ) { /* when shift+enter execute callback */ $('#btn_y').click() return } if ($('#ean_'+index).html() == 'src' && cur_ap == 'v') { /* when editing src value */ event.preventDefault() /* disable editing src value */ } else { suggest( event, suggest_type, 'dAField', 'dSuggests', 'ku', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest) updateCurAttr( event ) if ( cur_ap == 'v') { /* only when editing attribute value */ updateRealAttr ( index ) } } }) .keydown(function(event) { if ($('#ean_'+index).html() == 'src' && cur_ap == 'v') { /* when editing src value -> enable only tab key */ attrTabHandler( event ) event.preventDefault() /* disable editing src value */ } else { suggest( event, suggest_type, 'dAField', 'dSuggests', 'kd', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest) attrTabHandler( event ) } }) .change(function(event) { hideSuggests() }) .blur(function(event) { setTimeout(function() { hideSuggests() }, 100 ); }) .focus() } function editHTV() { /* HTV = HTML Tag Value */ var mouse_clicked = false; var suggest_vars = false; var placeholder = 'Type/Select Content'; var suggest_type = 'smarty_statement'; /* set default suggest type */ var last_action = 'editHTV'; /* update last action */ if ( preview_class ) { removePreviewedClass() } hideSuggests() clearSelectedClass() cur_ap = 'n' var cur_val = $('#htv').html() /* get attribute value as string */ $('#htv').addClass('tc-gy') if ( cur_val == '&nbsp;' ) { /* when system space in place -> remove it */ cur_val = '' } var dAField = $('#dAField').val(cur_val) /* get dAField object */ $('#dAField').unbind('keyup keydown focus blur change').removeClass("hide") /* detach events from previous use */ /* attach new events */ $('#dAField').attr('placeholder', placeholder) .addClass('input_ta') /* input_ta make the textarea less wide and more input like looking */ .html(cur_val) /* add current va */ .removeClass("hide") /* show dAField */ .focus(function( event ) { updateTAHeight() }) .keyup(function( event ) { /* setup on key up/down to catch what is writen and suggest items based on that */ updateCurHTML( function() { suggest( event, suggest_type, 'dAField', 'dSuggests', 'ku', function( event ) { $('#btn_y').click() }, placeholder, true) updateRealHTML() updateTAHeight() if (event.keyCode == 27) { $('#btn_n').click() return } if ( event.keyCode == 13 ) { event.preventDefault(); } /* prevent default action of enter key */ if ( event.shiftKey && event.keyCode == 13 ) { /* when shift+enter execute callback */ $('#btn_y').click(); return } }) }) .keydown(function( event ) { if ( event.keyCode == 13 ) { event.preventDefault(); } /* prevent default action of enter key */ suggest( event, suggest_type, 'dAField', 'dSuggests', 'kd', function( event ) { $('#btn_y').click() }, placeholder, true) updateTAHeight() HTMLTabHandler( event ) if ( event.keyCode == 13 && typeof callback === 'function' ) { /* when shift+enter execute callback */ callback() } /* must suggest already catched smarty vars */ }) .change(function( event ) { updateRealHTML() hideSuggests() }) .blur(function(event) { setTimeout(function() { hideSuggests() }, 100 ); }) .focus() } function updateTAHeight() { contentHeight = $( '#dAField' ).textareaHelper( "height" ) if ( contentHeight < 28 ) { contentHeight = 28 } /* when is empty correct the height to match one line */ $( '#dAField' ).height( contentHeight ) } function updateCurAttr( event ) { if ( last_action != 'editHTV' ) { cur_val = $( '#dAField' ).val() /* get currently edited value */ if ( cur_val.substr( cur_val.length - 1, 1 ) == ' ' && event.keyCode == 9 ) { /* only when leaving editing and last char is space -> remove that space */ cur_val = cur_val.substr( 0, cur_val.length - 1 ) } if ( cur_ap == 'n' && cur_val == '' && event.keyCode == 9 && !tab_handled ) { /* when empty attribute name and tab pressed -> remove it */ last_attr_name = $( '#ean_' + cur_attr_num ).attr( 'last-val' ) /* get last attr name */ kids = $( '#selItmCon' ).children() $( kids[0] ).removeAttr( last_attr_name ) /* removing the attribute from the real html tag */ if ( handleReIndex( event ) == 'exit') { /* reindex attributes nums */ hideSuggests() return 'exit' } } else { /* update the visual code text */ tab_handled = false /* reset tab flag */ $( '#ea' + cur_ap + '_' + cur_attr_num ).html( cur_val ) /* put the value ot it's place (visual change only in editing form) */ scrollToLastCodeChange() } } } function updateCurHTML( callback ) { cur_val = $( '#dAField' ).val() /* get currently edited value */ $( '#htv' ).html( cur_val ) /* put the value ot it's place (visual change only in editing form) */ scrollToLastCodeChange() if ( typeof callback === 'function' ) { callback() } } function updateRealAttr( index ) { if ( !tab_handled ) { attr_name = $( '#ean_' + index ).html() /* get currently edited attribute name */ cur_val = $( '#eav_' + index ).html() /* get currently entered value */ kids = $( '#selItmCon' ).children() /* select the edited element by getting childs of the selItemCon container */ if ( typeof attr_name === 'undefined' ) { /* when ghost attr_name -> add new one */ cur_attr_num = 1 addAttr( false ) return } if ( !preview_class && attr_name.length > 0 ) { /* only when not previewing class */ $( kids[0] ).attr( attr_name, cur_val ) /* applying the changes to the current attribute */ } } } function updateRealHTML() { cur_val = $('#dAField').val() /* get currently entered value */ kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ $(kids[0]).html( cur_val ) /* applying the changes */ } function reIndexAttrs( event ) { realIndex = 0 /* set our index var */ ric = 2 /* set counter ric = Real Index Counter */ $('.eac').each(function ( index, item ) { /* iterate trough each eac (Editable Attribute Container) */ /* correct the index to match ours */ ric++ if (ric > 2) { ric = 1 realIndex++ } if ( ric == 1 ) { cur_part_char = 'n' } else { cur_part_char = 'v' } $( item ).attr('id', 'ea'+cur_part_char+'_'+realIndex) /* set real index on every attr helper element in order to correct missing ones */ $( item ).attr('onclick', 'if ( checkAttrName() != \'exit\') { cur_attr_num = '+realIndex+'; editAttr('+realIndex+', \''+cur_part_char+'\') }') /* correct onclick functionality with the real index */ }) cur_max_attrs_num = realIndex /* correct the num of the attributes counter */ if ( cur_max_attrs_num == 0 ) { /* when there is no attributes left -> Go To Next Selectable Item */ goToNextSelItm() } } function handleReIndex( event ) { if (cur_attr_num == cur_max_attrs_num) { /* when deleted the last (the rightest attribute in the list) -> move to Next Item */ if ( event.shiftKey ) { /* go to previous selectable item (previous attr value) */ updateRealAttr( cur_attr_num ) /* delete from DOM helper spans for this attribute */ $('#ean_'+cur_attr_num).remove() $('#eav_'+cur_attr_num).remove() $('#dInfo').html($('#dInfo').html().replace(' ="" ', " ")) /* remove the equal sign and quotes */ if ( cur_max_attrs_num > 1 ) { /* when not removing last standing attribute */ cur_ap = 'n' reIndexAttrs( event ) } else { /* otherwise -> go to next selectable item */ goToNextSelItm() return 'exit' } } else { /* go to next selectable item (html tag value or ok button)*/ cur_ap = 'v' goToNextSelItm() return 'exit' } } else { /* delete from DOM helper spans for this attribute */ $('#ean_'+cur_attr_num).remove() $('#eav_'+cur_attr_num).remove() $('#dInfo').html($('#dInfo').html().replace(' ="" ', " ")) /* remove the equal sign and quotes */ reIndexAttrs( event ) if ( !mouse_clicked ) { if ( event.shiftKey ) { /* when shift key -> go to previous attr */ cur_ap = 'v' cur_attr_num-- if (cur_attr_num == 0) { cur_attr_num = 1 } editAttr ( cur_attr_num, cur_ap ) return 'exit' } else { /* otherwise go to next editable item */ if ( cur_attr_num < cur_max_attrs_num ) { cur_ap = 'n' editAttr ( cur_attr_num, cur_ap ) return 'exit' } else { goToNextSelItm() return 'exit' } } } } } function HTMLTabHandler( event ) { if (event.keyCode == 9 && $( '#dInfo' ).html().indexOf( 'nsmarty_code' ) === -1 ) { event.preventDefault() updateCurHTML( function() { /* go to last attr which is actualy add new attribute option */ if ( event.shiftKey ) { editAttr( cur_attr_num, 'v' ) return } /* go to ok button if just tab */ else { $('#btn_y').focus() $('#dAField').unbind('keyup keydown focus blur change').addClass("hide") /* detach events from previous use */ } }) } } function attrTabHandler( event ) { if (event.keyCode == 9) { event.preventDefault() if ( checkAttrName() == 'exit' ) { /* before we move away of current attr name check if we had change it in order to update the real edited html tag attributes */ return 'exit' } if ( updateCurAttr( event ) == 'exit' ) { return 'exit' } /* go to previous attr if shit+tab */ if ( event.shiftKey ) { if ( cur_ap == 'v' ) { cur_ap = 'n' } else { if ( cur_attr_num > 1) { cur_ap = 'v' } cur_attr_num-- } if ( cur_attr_num == 0 ) { cur_attr_num = 1 } } /* go to next attr if just tab */ else { if ( cur_ap == 'n' ) { cur_ap = 'v' } else { if ( cur_attr_num < cur_max_attrs_num) { cur_ap = 'n' } cur_attr_num++ } if ( cur_attr_num > cur_max_attrs_num ) { goToNextSelItm() return } } if ( preview_class ) { removePreviewedClass(function() { editAttr( cur_attr_num, cur_ap ) }) } else { editAttr( cur_attr_num, cur_ap ) } } } function goToNextSelItm() { if ($('#ean_'+(cur_attr_num)).attr('last-val') == 'last-val' || cur_max_attrs_num == 0 || (cur_attr_num == cur_max_attrs_num)) { /* when last was adding new attr */ if ($('#dAField').val() == '') { /* when skipping adding attributes */ if ( $('span#htv').length === 1 ) { /* when the html tag is not selfcontaining -> edit the value */ /* delete from DOM helper spans for this attribute */ $('#ean_'+cur_attr_num).remove() $('#eav_'+cur_attr_num).remove() $('#dInfo').html($('#dInfo').html().replace(' ="" ', " ")) /* remove the equal sign and quotes */ cur_attr_num-- cur_max_attrs_num-- editHTV() } else { /* delete from DOM helper spans for this attribute */ $('#ean_'+cur_attr_num).remove() $('#eav_'+cur_attr_num).remove() $('#dInfo').html($('#dInfo').html().replace(' ="" ', " ")) /* remove the equal sign and quotes */ cur_attr_num-- cur_max_attrs_num-- $('#dAField').addClass("hide") $('#btn_y').focus() } } else { editHTV() } } else { /* add new attribute */ addAttr() } } function getCurTagName() { /* get currently edited html tag name */ kids = $( '#selItmCon' ).children() tag_name = $( kids[0] ).prop( 'tagName' ) return tag_name; } function scrollToLastCodeChange() { chars_offset = 0 /* init chars_offset counter */ curPos = $( '#dAField' ).prop( 'selectionStart' ) /* get current caret position */ tag_name = getCurTagName() /* get currently edited html tag name */ /* start calculating chars_offset */ chars_offset += tag_name.length + 2 /* add 2 more to count starting "<" and one space afther the tag name */ for ( i = 1 ; i <= cur_max_attrs_num; i++ ) { chars_offset += $( '#ean_' + i ).html().length /* add current attribute name */ chars_offset += $( '#eav_' + i ).html().length + 4 /* add current attribute value. The extra 4 are representing the ="" and one space char between each attribute */ if ( last_action != 'editHTV' ) { /* only when editing attributes -> check if we need to stop the loop */ if ( cur_attr_num == i ) { /* when we reach currently edited attribute */ /* reduce the chars_offset so the last entered char/suggested item shoud be center in view */ if ( cur_ap == 'n' ) { chars_offset -= $( '#eav_' + i ).html().length + $( '#ean_' + i ).html().length + 44 /* the extra 40 chars are to center the edited text in the middle of visible code in ( designed at 1366px wide ) */ chars_offset += curPos /* center view to curPos */ } else { chars_offset -= $( '#eav_' + i ).html().length + 44 /* 44 chars is about the middle of visible code in 1366px wide */ chars_offset += curPos /* center view to curPos */ } break } } } if ( last_action == 'editHTV' ) { /* only when editing html value */ chars_offset += 6 /* add extra space for btn_ana and > */ chars_offset += curPos /* center view to curPos */ chars_offset -= 40 /* 40 chars is about the half of visible chars ( in 1366px width resolution ) */ } $( '#dInfo' ).scrollLeft( ( chars_offset * 12 ) + 3 ) /* scroll the code to caret position : chars_offset is counted chars to caret position; 12 single char width; the extra 3 is for visual correction */ } function inteligent_paste( target, data ) { smarty_detected = false if ( $( target ).hasClass( 'lsc' ) ) { /* when LastSmartyChild selected */ smarty_detected = true } else if ( $( target ).hasClass( 'fsc' ) ) { /* when FirstSmartyChild selected */ smarty_detected = true target = $( target ).parent().children().last() /* get parent's child last one to select LastSmartyChild */ } else if ( $( target ).children().hasClass( 'lsc' ) ) { /* when current selectable container is parent of smarty block */ smarty_detected = true target = $( target ).children().last() /* select the last child which is LastSmartyChild */ } if ( wrap_selected_sc ) { /* when wrap selected sc with the new element is enabled */ var targetOutherHTML = target.prop('outerHTML'); /* get the target html */ wrap_selected_sc = false /* reset the flag to false */ data = data.replace('sc="true"><', 'sc="true">' + targetOutherHTML + '<') /* wrap selected sc with the new tag */ target.before( data ) /* add before selected target */ target.remove() /* remove the original target */ cur_sc_con = $('#dContent_con') /* reset cur_sc_con */ cur_sc = $('#dContent') /* reset cur_sc */ cur_sc_index = 0 /* reset cur_sc_index */ } else if ( unwrap_selected_sc ) { /* when unwrap functionality is enabled */ unwrap_selected_sc = false /* reset the flag to false */ unwrap_SS ( cur_sc ) cur_sc_con = $('#dContent_con') /* reset cur_sc_con */ cur_sc = $('#dContent') /* reset cur_sc */ cur_sc_index = 0 /* reset cur_sc_index */ } else if ( event.shiftKey || smarty_detected ) { /* when shift pressed -> paste the data before the currently selected target */ target.before( data ) } else if ( $( target ).hasClass( 'nsmarty_code' ) ) { /* when smarty code selected put the data after the container instead into it */ target.after( data ) } else { /* paste in currently selected target */ if ( target.html() == '&nbsp;' ) { /* when the content is only system non breaking space -> remove it */ target.html('') } if ( typeof target.attr( 'sc' ) === 'undefined' ) { /* when targeted element is not selectable container */ /* backtrace parents until dContent or sc="true" */ var finished = false var parents_str = '.parent()' while ( !finished ) { /* found ancestor which is selectable content */ if ( eval( '$( target )' + parents_str + '.attr( "sc" )') ) { /* first parent that is selectable container */ finished = true eval( '$( target )' + parents_str + '.append( \'' + data + '\' )') /* append content here */ } /* end up to begining of edited template without finding hovered selectable content */ if (eval( '$( target )' + parents_str + '.hasClass( "dContent" )')) { /* sc not found -> add in the main container */ finished = true eval( '$( target )' + parents_str + '.append( \'' + data + '\' )') } parents_str += '.parent()' /* go to upper parent */ } } else { target.append( data ) } } } function enableKeyboardElementSelect( html, callback ) { last_index_arr = [] /* initialize last known index collection */ $(document.body).keydown(function ( event ) { event.preventDefault(); }) .keyup(function( event ) { event.preventDefault(); if ( !enter_pressed ) { /* prevent double action with one hit of an enter */ event.preventDefault() /* for disabling page scrolling on up down keys */ cur_sc.removeClass( 'blueprint-grid' ) /* remove blueprint background */ if ( event.keyCode == 27 ) { /* Esc -> simulate click on cancel button */ reset_scs() $('#btn_n').click() return } else if ( event.keyCode == 9 ) { /* Tab Key -> Toggle between normal and clear visual arrangements */ if ( $( '.sc_bordered' ).hasClass( 'sc_bordered_full' ) ) { $( '.sc_bordered' ).removeClass( 'sc_bordered_full' ) scrollTo( cur_sc ) } else { $( '.sc_bordered' ).addClass( 'sc_bordered_full' ) scrollTo( cur_sc ) } } else if ( event.keyCode == 37 || event.keyCode == 100 || event.keyCode == 65) { /* Left Arrow or "a" -> Move to previous sibling selectable container */ if ( cur_sc_index > 0 ) { cur_sc_index-- siblings = cur_sc_con.children( '[sc="true"]' ) $( '.popover' ).remove(); /* hide currently marked selectable container popover */ cur_sc = $(siblings[cur_sc_index]) scrollTo( cur_sc ) } } else if ( event.keyCode == 39 || event.keyCode == 102 || event.keyCode == 68 ) { /* Right Arrow or "d"-> Move to next sibling selectable container */ siblings = cur_sc_con.children( '[sc="true"]' ) if ( cur_sc_index < ( siblings.length - 1 ) ) { cur_sc_index++ $( '.popover' ).remove(); /* hide currently marked selectable container popover */ cur_sc = $(siblings[cur_sc_index]) scrollTo( cur_sc ) } } else if ( event.keyCode == 38 || event.keyCode == 104 || event.keyCode == 87 ) { /* Up Arrow or "w" -> Move to parent selectable container */ if ( cur_sc_con.attr('id') != 'dBody' ) { $( '.popover' ).remove(); /* hide currently marked selectable container popover */ if ( last_index_arr.length > 0 ) { /* when we have stored indexes of previous levels -> restore the last known */ cur_sc_index = last_index_arr[ last_index_arr.length - 1 ] /* restore saved child index */ last_index_arr.pop() /* remove restored index from the stack */ } else { /* otherwise -> reset to zero */ cur_sc_index = 0 } cur_sc = cur_sc.parent() scrollTo( cur_sc ) cur_sc_con = cur_sc.parent() } } else if ( event.keyCode == 40 || event.keyCode == 98 || event.keyCode == 83 ) { /* Down Arrow or "s" -> Move to first children selectable container */ siblings = cur_sc.children( '[sc="true"]' ) if ( siblings.length > 0 ) { last_index_arr.push( cur_sc_index ) /* save current level child index */ $( '.popover' ).remove(); /* hide currently marked selectable container popover */ cur_sc_index = 0 cur_sc_con = cur_sc cur_sc = $(siblings[0]) scrollTo( cur_sc ) } } else if ( event.keyCode == 67 ) { /* "c" key -> copy currently selected sc to buffer */ $( '.popover' ).remove(); /* hide the popover if case it's visible */ buffer = cur_sc.prop('outerHTML') } else if ( event.keyCode == 88 ) { /* "x" key -> cut currently selected sc to buffer */ $( '.popover' ).remove(); /* hide the popover if case it's visible */ buffer = cur_sc } else if ( event.keyCode == 86 ) { /* "v" key -> paste buffer */ inteligent_paste( cur_sc, buffer ); } else if ( event.keyCode == 82 ) { /* "r" key -> activate mode wrap selected sc with the new element */ wrap_selected_sc = true; } else if ( event.keyCode == 85 ) { /* "u" key -> activate mode "unwrap selected sc content (only removing the selected sc leaving it's content)" */ unwrap_selected_sc = true; } else if ( event.keyCode == 13 ) { /* Enter -> Select currently selected selectable container */ if ( html != '' ) { /* only when html string is not empty (skip if it's edit or delete) */ html = '<div id="selItmCon">'+html+'</div>'; } else { $( cur_sc ).wrap('<div id="selItmCon"></div>'); } /* add the html @ this location */ inteligent_paste( cur_sc, html ) if ( typeof callback === 'function' ) { $( '.popover' ).remove(); /* hide currently marked selectable container popover */ reset_scs() /* remove (unbind) all current functionality on all selectable containers */ callback() return } } } else { enter_pressed = false } /* prepare the text for the popover */ tooltip_txt = '<' tooltip_txt += cur_sc.prop( "tagName" ).toLowerCase()+' ' /* add the tag name */ if ( typeof cur_sc.prop( "id" ) !== 'undefined' && cur_sc.prop( "id" ) !== '' ) { /* when id attr present */ tooltip_txt += 'id="'+ cur_sc.prop( "id" ) +'" ' /* add the id */ } if ( typeof cur_sc.prop( "class" ) !== 'undefined' ) { /* when class attr present */ class_txt = cur_sc.prop( "class" ) /* remove system classes */ class_txt = class_txt.replace( 'blueprint-grid', '' ) class_txt = class_txt.replace( 'sc_bordered', '' ) class_txt = class_txt.replace( 'sc_bordered_full', '' ) class_txt = class_txt.replace( 'nsmarty_code', '' ) class_txt = class_txt.replace( 'fsc', '' ) class_txt = class_txt.replace( 'lsc', '' ) /* check if it was only system classes */ only_spaces_left = true for ( i = 0; i < class_txt.length; i++ ) { if ( class_txt.substr( i, 1 ) != ' ' ) { only_spaces_left = false } } if ( only_spaces_left ) { class_txt = '' } if ( class_txt.length > 20 ) { /* when class string is bigger than 20 chars -> shrink it */ class_txt = class_txt.substr(0, 17)+'...' } if ( class_txt.length > 0 ) { /* only when not empty */ tooltip_txt += 'class="'+ class_txt +'" ' /* add the class */ } } tooltip_txt += '>' if ( tooltip_txt != '<code >' ) { /* only when not smarty statement container */ /* show visualy currently marked selectable container */ cur_sc.attr( 'data-toggle', 'popover' ) cur_sc.attr( 'data-placement', 'top' ) cur_sc.attr( 'data-original-title', '' ) cur_sc.attr( 'data-content', tooltip_txt ) cur_sc.popover( 'show' ) } $( '.popover-title' ).remove() /* set blueprint background */ cur_sc.addClass('blueprint-grid') }) /* prepare the text for the popover */ tooltip_txt = '<' tooltip_txt += cur_sc.prop( "tagName" ).toLowerCase()+' ' /* add the tag name */ if ( typeof cur_sc.prop( "id" ) !== 'undefined' && cur_sc.prop( "id" ) !== '' ) { /* when id attr present */ tooltip_txt += 'id="'+ cur_sc.prop( "id" ) +'" ' /* add the id */ } if ( typeof cur_sc.prop( "class" ) !== 'undefined' ) { /* when class attr present */ class_txt = cur_sc.prop( "class" ) /* remove system classes */ class_txt = class_txt.replace( 'blueprint-grid', '' ) class_txt = class_txt.replace( 'sc_bordered', '' ) class_txt = class_txt.replace( 'sc_bordered_full', '' ) class_txt = class_txt.replace( 'nsmarty_code', '' ) class_txt = class_txt.replace( 'fsc', '' ) class_txt = class_txt.replace( 'lsc', '' ) /* check if it was only system classes */ only_spaces_left = true for ( i = 0; i < class_txt.length; i++ ) { if ( class_txt.substr( i, 1 ) != ' ' ) { only_spaces_left = false } } if ( only_spaces_left ) { class_txt = '' } if ( class_txt.length > 20 ) { /* when class string is bigger than 20 chars -> shrink it */ class_txt = class_txt.substr(0, 17)+'...' } if ( class_txt.length > 0 ) { /* only when not empty */ tooltip_txt += 'class="'+ class_txt +'" ' /* add the class */ } } tooltip_txt += '>' if ( tooltip_txt != '<code >' ) { /* only when not smarty statement container */ /* show visualy currently marked selectable container */ cur_sc.attr( 'data-toggle', 'popover' ) cur_sc.attr( 'data-placement', 'top' ) cur_sc.attr( 'data-original-title', '' ) cur_sc.attr( 'data-title', '' ) cur_sc.attr( 'data-content', tooltip_txt ) cur_sc.popover( 'show' ) } $( '.popover-title' ).remove() /* set blueprint background */ cur_sc.addClass('blueprint-grid') } function conSelector( html, callback ) { enableKeyboardElementSelect( html, callback ) scrollTo( cur_sc ) $('#dContent').on( 'click', function( event ) { event.preventDefault(); if ( event.type === 'click' && event.which == 2 && !mouse_selection_handled ) { mouse_selection = !mouse_selection; } }) /* iterate trough all selectable containers sc="true" */ $('[sc="true"]').each(function() { /* sc = seleactable container */ $( this ).addClass( 'sc_bordered' ) /* show all selectable containers with adding dashed border on each */ $( this ).prop('contenteditable', 'false'); /* disabling content edit on selection to prevent random pasting or writing in content */ /* handle all events at once to use the vars in all events */ $(this).on('mouseover mouseout click', function ( event ) { if ( mouse_selection_handled ) { event.preventDefault() setTimeout(function() { mouse_selection_handled = false; }, 1000 ); } if ( mouse_selection ) { var found_sc = false, /* do we have selectable container below the mouse cursor */ is_child = false, /* if hovering on child element insert before else append */ target = $( event.target ) /* get hovered element */ /* check current element */ if ($(target).attr('sc')) { found_sc = true; $( '.popover' ).remove(); /* remove the popover tooltip */ $( '.blueprint-grid' ).removeClass( 'blueprint-grid' ); /* remove old blueprint-grid */ $( target ).addClass( 'blueprint-grid' ); /* add blueprint-grid to current selectable content */ /* prepare the tooltip */ if ( $( target ).attr( 'data-bkp-title' ) === 'undefined' ) { /* only when data-bkp-title is not set */ if ( typeof $( target ).prop( 'title' ) !== 'undefined' ) { /* when data-toggle ia already used backup the properties we will change in order to restore it later */ $( target ).attr( 'data-bkp-title', $( target ).attr( 'title' ) ) } else { $( target ).attr( 'data-bkp-title', '' ) } } /* prepare tooltip text */ tooltip_txt = '<' tooltip_txt += $( target ).prop( "tagName" ).toLowerCase()+' ' /* add the tag name */ if ( typeof $( target ).prop( "id" ) !== 'undefined' && $( target ).prop( "id" ) !== '' ) { /* when id attr present */ tooltip_txt += 'id="'+ $( target ).prop( "id" ) +'" ' /* add the id */ } if ( typeof $( target ).prop( "class" ) !== 'undefined' ) { /* when class attr present */ class_txt = $( target ).prop( "class" ) /* remove system classes */ class_txt = class_txt.replace( 'blueprint-grid', '' ) class_txt = class_txt.replace( 'sc_bordered', '' ) class_txt = class_txt.replace( 'sc_bordered_full', '' ) class_txt = class_txt.replace( 'nsmarty_code', '' ) class_txt = class_txt.replace( 'fsc', '' ) class_txt = class_txt.replace( 'lsc', '' ) /* check if it was only system classes */ only_spaces_left = true for ( i = 0; i < class_txt.length; i++ ) { if ( class_txt.substr( i, 1 ) != ' ' ) { only_spaces_left = false } } if ( only_spaces_left ) { class_txt = '' } if ( class_txt.length > 20 ) { /* when class string is bigger than 20 chars -> shrink it */ class_txt = class_txt.substr(0, 17)+'...' } if ( class_txt.length > 0 ) { /* only when not empty */ tooltip_txt += 'class="'+ class_txt +'" ' /* add the class */ } } tooltip_txt += '>' if ( tooltip_txt != '<code >' ) { /* only when not smarty statement container */ $( target ).attr( 'title', tooltip_txt ) } else { /* ohterwise -> hide title */ $( target ).attr( 'title', '' ) } cur_sc = $( target ); /* set current selectable container to be hovered one */ cur_sc_con = cur_sc.parent(); /* set the sc parrent as cur_sc_con */ kids = cur_sc_con.children(); cur_sc_index = kids.index( $( target ) ); /* set the correct child index to cur_sc_index */ } else { /* backtrace parents until dContent or sc="true" */ var finished = false var parents_str = '.parent()' while ( !finished ) { /* found ancestor which is selectable content */ if ( eval( '$( target )' + parents_str + '.attr( "sc" )') ) { finished = true found_sc = true is_child = true eval( '$( target )' + parents_str + '.addClass( "blueprint-grid" )') } /* end up to begining of edited template without finding hovered selectable content */ if (eval( '$( target )' + parents_str + '.hasClass( "dContent" )')) { finished = true } parents_str += '.parent()' /* go to upper parent */ } } /* onmouseout remove the marker from the DOM */ if (event.type === 'mouseout' && found_sc) { /* remove old blueprint-grid */ $('.blueprint-grid').removeClass('blueprint-grid') } /* onclick remove the marker and put the html in selected position */ if ( event.type === 'click' && found_sc && event.which == 1 ) { event.preventDefault(); /* remove old blueprint-grid */ $('.blueprint-grid').removeClass('blueprint-grid') /* wrap the html tag with container in order to know where to apply the changes since we don't yet have id on the new element */ if ( html != '' ) { /* only when html string is not empty (skip if it's edit or delete) */ html = '<div id="selItmCon">'+html+'</div>'; } else { $( cur_sc ).wrap('<div id="selItmCon"></div>'); } /* add the html @ this location */ inteligent_paste( $( target ), html ) reset_scs() /* remove (unbind) all current functionality on all selectable containers */ /* exit/return trough callback function */ if (typeof callback === "function") { callback() } } } }) }) } function reset_scs() { $( '.sc_bordered' ).removeClass( 'sc_bordered' ) $( '[sc="true"]' ).each(function() { $( this ).prop( 'contenteditable', 'true' ); /* enable content edit */ $(this).unbind( 'mouseover mouseout click' ).removeClass( 'blueprint-grid' ).removeClass( 'sc_bordered' ).removeClass( 'sc_bordered_full' ) /* restore original titles */ if ( typeof $( this ).attr( 'data-bkp-title' ) !== 'undefined' ) { if ( $( this ).attr( 'data-bkp-title' ).indexOf('<') === -1 ) { $( this ).attr( 'title', $( this ).attr( 'data-bkp-title' ) ) } else { $( this ).attr( 'title', '' ); } } else { $( this ).attr( 'title', '' ); } /* remove all system attributes */ $( this ).removeAttr( 'data-bkp-title' ) .removeAttr( 'data-title' ) .removeAttr( 'data-toggle' ) .removeAttr( 'data-placement' ) .removeAttr( 'data-original-title' ) .removeAttr( 'data-content' ) .removeAttr( 'aria-describedby' ) .removeClass( 'blueprint-grid' ) .removeClass( 'sc_bordered' ) .removeClass( 'sc_bordered_full' ) if ( $( this ).attr( 'title' ) == '' ) { /* when empty title -> remove that attribute too */ $( this ).removeAttr( 'title' ) } }) } function resetDAField() { /* remove the popover */ $( '.popover' ).remove(); /* remove all possible bindings */ $( '#dAField' ).unbind( 'keyup keydown keypress focus blur change' ); $( '#btn_y' ).unbind( 'click' ); $( '#btn_n' ).unbind( 'click' ); /* reset selection index */ cur_sel_index = 0; /* reset suggest items counter */ max_sel_itms = 0; /* reset multi suggest */ multi_suggest = false; /* reset index vars */ cur_attr_num = 1; cur_ap = 'v'; cur_max_attrs_num = 0; } function suggestFor( event, suggest_type, placeholder, default_val, callback ) { /* initialize flag for suggested items content */ var is_res_con_hidden = true /* move dAField affter the suggests container in case it was used elsewhere */ $( '#dSuggests' ).after( $( '#dAField' ).removeClass( 'input_ta' ) ) showMF() /* clear form, hide menu, and show form container */ /* set buttons actions */ $('#btn_y').click(function() { resetDAField() if (typeof callback === "function") { cur_val = $('#dAField').val() if ( typeof callback === "function" ) { callback( cur_val ) } } }) $('#btn_n').click(function() { hideMF() /* hide the form and show the menu */ resetDAField() if ( typeof callback === "function" ) { callback('') /* return empty result */ } }) /* prepare the textarea */ $('#dAField').prop('placeholder', placeholder) .html(default_val) .removeClass( 'hide' ) .focus(function(event) { suggest( event, suggest_type, 'dAField', 'dSuggests', 'ku', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest ) }) .keyup(function(event) { if ( event.keyCode == 27 ) { /* on esc key -> simulate click on cancel button */ $('#btn_n').click() return } if ( event.keyCode == 13 && event.shiftKey ) { /* when shift+enter -> simulate ok button click */ $( '#btn_y' ).click(); } suggest( event, suggest_type, 'dAField', 'dSuggests', 'ku', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest ) }) .keydown(function(event) { suggest( event, suggest_type, 'dAField', 'dSuggests', 'kd', function( event ) { $('#btn_y').click() }, placeholder, multi_suggest ) }) .blur(function(event) { setTimeout(function() { hideSuggests() }, 100 ); }) .focus() /* show the buttons */ $( '#btn_y, #btn_n' ).removeClass( 'hide' ) } function suggest( event, suggest_type, req_con, res_con, key_event, callback, placeholder, cur_multi_suggest ) { /* set the placeholder if present */ if (typeof placeholder !== 'undefined') { $('#'+req_con).prop('placeholder', placeholder) } /* disable multi_suggest if not present as param */ if (typeof cur_multi_suggest === 'undefined') { multi_suggest = false } else { multi_suggest = cur_multi_suggest } var data = $('#'+req_con).val() var curPos = $('#'+req_con).prop("selectionStart") var cur_char = String.fromCharCode(event.keyCode) var selected_name = '' var is_res_con_hidden = false if ($('#'+res_con).hasClass("hide")) { is_res_con_hidden = true } /* set array of keys as follows : 38 - up arrow, 104 - numpad up arrow, 40 - down arrow, 99 - numpad down arrow, 13 - enter */ var ar = new Array(38, 104, 40, 98, 13) var disableArrowKeys = function(e) { if ($.inArray(event.keyCode, ar)>=0) { /* disable normal functioning for each of ar keys */ event.preventDefault() } } /* if suggestions are visible and up or down arrow is pressed cicle trough suggested items, enter for selection */ if (!is_res_con_hidden && (event.keyCode == 38 || event.keyCode == 104 || event.keyCode == 40 || event.keyCode == 98 || event.keyCode == 13) && key_event == 'kd') { $(document).keydown(disableArrowKeys) /* Up Arrow */ if (event.keyCode == 38 || event.keyCode == 104) { if (cur_sel_index >= 2) { cur_sel_index-- } else { cur_sel_index = max_sel_itms+1 } if ( suggest_type == 'attribute' && cur_ap == 'v' && $('#ean_'+cur_attr_num).html() == 'class' ) { removePreviewedClass( function() { previewSelectedClass( $('#si_'+cur_sel_index).html() ) }) } } /* Down Arrow */ else if (event.keyCode == 40 || event.keyCode == 98) { if (cur_sel_index <= max_sel_itms) { cur_sel_index++ } else { cur_sel_index = 1 } if ( suggest_type == 'attribute' && cur_ap == 'v' && $('#ean_'+cur_attr_num).html() == 'class' ) { removePreviewedClass( function() { previewSelectedClass( $('#si_'+cur_sel_index).html() ) }) } } /* Enter */ else { event.preventDefault() kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ if ( !event.shiftKey ) { $( '#si_' + cur_sel_index ).click() /* call predefined onclick javascript */ } else { if ( preview_class ) { removePreviewedClass() } } } unselectAllSuggests() return } else { $(document).unbind('keydown', disableArrowKeys) /* enable arrow keys */ } if (!is_res_con_hidden) { unselectAllSuggests() $('#si_'+cur_sel_index).addClass('suggestItemActive') /* set selected class to currently selected suggested item */ suggestScrollTo(cur_sel_index) /* scroll to current suggested item */ } /* if left or right arrows pressed try to catch new search string */ if ((event.keyCode == 37 || event.keyCode == 39) && key_event == 'ku') { catchTxtNearCaret( curPos, data, req_con, res_con, suggest_type, callback ) return } /* on backspace reinvoke suggest list get */ if (event.keyCode == 8 && key_event == 'ku') { catchTxtNearCaret( curPos, data, req_con, res_con, suggest_type, callback ) return } /* starting catching name search sting */ if ( event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 98 && event.keyCode != 104 && key_event == 'ku' ) { str_replace_pos = curPos - 1 catchTxtNearCaret( curPos, data, req_con, res_con, suggest_type, callback ) updateTAHeight() return } /* on any keyCode different from arrows and backspace and started catching name search string */ if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 38 && event.keyCode != 39 && event.keyCode != 40 && event.keyCode != 98 && event.keyCode != 104 && key_event == 'ku') { if (key_event == 'ku') { catchTxtNearCaret( curPos, data, req_con, res_con, suggest_type, callback ) updateTAHeight() return } } } function catchTxtNearCaret( caretPos, data, req_con, res_con, suggest_type, callback ) { search_str = '' charsToGrab = 1 found_delimiter = false delimiters = [ '$', '\'', '"', '}', ' ', '|', '.', '=', '<', '>', '!', '(', ')', '[', ']' ] /* if empty field suggest all options */ if ( data == '' ) { suggest_vars = false cur_full_var = '' last_search_str = search_str getSuggestList( suggest_type, search_str, req_con, res_con, callback ) return } cur_var_lvl = 0 /* reset current var level ( used when suggesting smarty variables ) */ for ( pos = caretPos; pos >= 0; pos-- ) { if ( delimiters.indexOf( data.substr( pos - 1, 1 ) ) != -1 || pos == 0 ) { /* when found one of the delimiters -> get out of the loop and bring out the current search_str */ if ( data.substr( pos - 1, 1 ) == '.' ) { /* when previous char is '.' */ cur_var_lvl++ } found_delimiter = true if ( pos == 1 ) { pen = 1 } else { pen = 0 charsToGrab-- } /* pen = position exception number */ search_str = data.substr( pos - pen, charsToGrab ) str_replace_pos = pos - 1 break } else { charsToGrab++ } } if ( data.substr( pos - 1, 1 ) == '$' ) { /* when found smarty var -> reset cur_full_var */ cur_full_var = '$' } if ( cur_var_lvl > 0 ) { /* when we had stoped on '.' */ cur_var_lvl = 0 /* cur_var_lvl must be 1 at this point and we reset it in order to get proper count of '.' */ for ( pos = pos - 1; pos >= 0; pos-- ) { /* check if there is other levels by searching for the main var '$' or start of the string */ if ( data.substr( pos, 1 ) == '.' ) { /* when '.' found -> increase current var level */ cur_var_lvl++ } else if ( data.substr( pos, 1 ) == '$' ) { /* when start of var found -> exit loop */ cur_full_var = data.substr( pos, parseInt(parseInt(curPos) - pos - 1) ) break } } } cur_pos_ch = data.substr( pos, 1 ) prev_pos_ch = data.substr( pos - 1, 1 ) if ( cur_pos_ch == '$' || prev_pos_ch == '$' || cur_pos_ch == '.' || prev_pos_ch == '.' ) { /* when exit on '$' -> activate suggesting smarty vars */ suggest_vars = true } else { /* otherwise -> disable suggesting smarty vars */ suggest_vars = false } if ( suggest_vars ) { suggest_type = 'smarty_vars' } else if ( cur_pos_ch == '{' || prev_pos_ch == '{' ) { suggest_type = 'smarty_statement' } else if ( cur_pos_ch == '|' || prev_pos_ch == '|' ) { suggest_type = 'smarty_var_modifiers' } getSuggestList( suggest_type, search_str, req_con, res_con, callback ) } function setSelectionRange( input, selectionStart, selectionEnd ) { if ( input.setSelectionRange ) { input.focus() input.setSelectionRange( selectionStart, selectionEnd ) } else if ( input.createTextRange ) { range = input.createTextRange() range.collapse( true ) range.moveEnd( 'character', selectionEnd ) range.moveStart( 'character', selectionStart ) range.select() } } function setCaretPosition( elemId, caretPos ) { var elem = document.getElementById(elemId); if(elem != null) { if(elem.createTextRange) { var range = elem.createTextRange(); range.move('character', caretPos); range.select(); } else { if(elem.selectionStart) { elem.focus(); elem.setSelectionRange(caretPos, caretPos); } else elem.focus(); } } } function suggestScrollTo( index ) { /* calculate the top_offset we need to scroll to */ top_offset = 0 for (i = 1; i < parseInt(index); i++) { top_offset += parseInt( $( '#si_' + i ).height() ) } /* scroll to the computed top_offset */ $( '#dSuggests' ).scrollTop( top_offset ) } function scrollTo( obj ) { $( obj ).get( 0 ).scrollIntoView(); /* scroll to current sc */ window.scrollBy ( 0, -113 ); /* scroll up a bit because of the fixed menu */ } function hideSuggests() { $('#dSuggests').addClass("hide") cur_sel_index = 0 /* reset selection index */ max_sel_itms = 0 /* reset suggest items counter */ } function showSuggests() { var caret_pos = $('#dAField').textareaHelper('caretPos') /* used for horizontal positioning of the suggests */ var elem_pos = $('#dAField').offset() /* used for vertical positioning of the suggests */ /* re-position the suggest pop-up */ $('#dSuggests').css('top', elem_pos.top + caret_pos.top - 5 - $('body').scrollTop() + 'px') $('#dSuggests').css('left', caret_pos.left + elem_pos.left - 10 + 'px') $('#dSuggests').removeClass("hide") /* show suggests */ cur_sel_index = 1 top_suggests.forEach( function( suggest, index ) { $(' .suggestItem ').each( function() { if ( $(this).html() == suggest.item ) { /* when top suggest is in current suggests bring in on top */ $( '#sls' ).after( $(this) ) } }) }) reindexSuggests() /* reindex suggests ids */ suggestScrollTo( cur_sel_index ) /* scroll to current suggest */ unselectAllSuggests() /* remove active class on all suggest items */ $('#si_'+cur_sel_index).addClass('suggestItemActive') /* set active class to currently selected suggested item */ if ( cur_ap == 'v' && $('#ean_'+cur_attr_num).html() == 'class') { removePreviewedClass( function() { previewSelectedClass( $('#si_'+cur_sel_index).html() ) }) } } function reindexSuggests() { i = 1 $(' .suggestItem ').each( function() { $( this ).attr( 'id', 'si_' + i ) i++ }) } function getSuggestList( type, str, req_con, res_con, callback ) { /* get currently edited html tag name */ kids = $('#selItmCon').children() /* set counter for results */ id_num = 1 tag_name = $(kids[0]).prop("tagName") /* set empty attr_name in case we don't search for attribute values */ attr_name = '' /* set proper action based on suggest type */ switch (type) { case 'html_tags': req = 'get_html_tags_by_str' break case 'attribute': req = 'get_attr_posible_vals' if ( cur_ap == 'v') { /* get current attribute name */ attr_name = $('#ean_'+cur_attr_num).html() } else { req = 'get_attrs_by_html_tag' } /* if we have class attribute we change to the special method which returns all possible to use classes */ if (attr_name == 'class') { req = 'get_classes_by_str' } break case 'smarty_statement': req = 'get_smarty_statements_by_str' break default: req = '' } /* textareaHelper is used for it's ability to get/set carret position */ $('#'+req_con).textareaHelper() if ( type == 'smarty_vars' && suggest_vars ) { if ( vars.length > 0 ) { /* only when we have storred vars */ $('#'+res_con).html( '<span class="hide" id="sls"></span>' ) /* init suggest container */ vars.forEach( function( cur_var, cur_index ) { if ( cur_var.index == cur_var_lvl && cur_var.name.indexOf( str ) != -1 && cur_var.full_var.indexOf( cur_full_var ) != -1 ) { /* only suggest vars on same level and containing currently searched string */ $('#sls').after('<a class="suggestItem" id="si_'+id_num+'" onclick="mouse_clicked = true; selectSuggestedItem(\''+cur_var.name+'\', \''+cur_var.name+'\', \''+type+'\', '+callback+' )" >'+cur_var.name+'</a>') id_num++ } }) max_sel_itms = id_num-2 showSuggests() } } else if ( type == 'smarty_var_modifiers' ) { $('#'+res_con).html( '<span class="hide" id="sls"></span>' ) /* init suggest container */ smarty_modifiers.forEach( function( cur_modifier ) { if ( cur_modifier.indexOf( str ) != -1 ) { /* only when searched string is part of current smarty modifier */ $('#sls').after('<a class="suggestItem" id="si_'+id_num+'" onclick="mouse_clicked = true; selectSuggestedItem(\''+cur_modifier+'\', \''+cur_modifier+'\', \''+type+'\', '+callback+' )" >'+cur_modifier+'</a>') id_num++ } }) max_sel_itms = id_num-2 showSuggests() } else if ( type == 'dbs' ) { if ( dbs.length > 0 ) { /* only when we have available dbs */ $('#'+res_con).html( '<span class="hide" id="sls"></span>' ) /* init suggest container */ dbs.forEach( function( cur_db_name ) { if ( cur_db_name.indexOf( str ) != -1 ) { /* only when searched string is part of current db name */ $('#sls').after('<a class="suggestItem" id="si_'+id_num+'" onclick="mouse_clicked = true; selectSuggestedItem(\''+cur_db_name+'\', \''+cur_db_name+'\', \''+type+'\', '+callback+' )" >'+cur_db_name+'</a>') id_num++ } }) max_sel_itms = id_num-2 showSuggests() } } else if ( type == 'db_tables' ) { if ( db_tables.length > 0 ) { /* only when we have available db_tables */ $('#'+res_con).html( '<span class="hide" id="sls"></span>' ) /* init suggest container */ db_tables.forEach( function( cur_db_table_name ) { if ( cur_db_table_name.indexOf( str ) != -1 ) { /* only when searched string is part of current db name */ $('#sls').after('<a class="suggestItem" id="si_'+id_num+'" onclick="mouse_clicked = true; selectSuggestedItem(\''+cur_db_table_name+'\', \''+cur_db_table_name+'\', \''+type+'\', '+callback+' )" >'+cur_db_table_name+'</a>') id_num++ } }) max_sel_itms = id_num-2 showSuggests() } } else { /* send ajax query to server with required data */ $.ajax({ url: "/ajax", type: "POST", data: { dAction: 'ajaxHandler(req, res)', req: req, str: str, attr_name: attr_name, tag_name: tag_name }, success: function(data) { if ( data.length > 0 ) { /* when not empty result */ obj = jQuery.parseJSON( data ) $('#'+res_con).html( '<span class="hide" id="sls"></span>' ) /* init suggest container */ /* add result items */ for (i in obj) { /* initialize params */ var title = '' /* set title if not null */ if (obj[i].title !== null) { title = obj[i].title } /* set displayed content on enter */ if ( typeof obj[i].full_statement !== 'undefined' ) { /* when suggesting smarty statement */ content = obj[i].full_statement } else { /* for all other the name is the content */ content = obj[i].name } $('#sls').after('<a class="suggestItem" id="si_'+id_num+'" onclick="mouse_clicked = true; selectSuggestedItem(\''+obj[i].name+'\', \''+content+'\', \''+type+'\', '+callback+' )" title="'+title+'">'+obj[i].name+'</a>') id_num++ } max_sel_itms = id_num-2 if ( $( '#dSuggests' ).html() != '<span class="hide" id="sls"></span>' ) { showSuggests() } else { hideSuggests() } } else { hideSuggests() } }, error: function() { } }) } } function removePreviewedClass( callback ) { kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ if ( typeof $(kids[0]) !== 'undefined' ) { html_tag_obj = kids[0] if ( preview_class ) { setTimeout(function() { /* find class attribute and get it's value */ $( '.eac' ).each(function() { if ( $(this).html() == 'class' ) { this_id_arr = $( this ).attr( 'id' ).split('_') this_index = this_id_arr[1] cur_class = $( '#eav_' + this_index ).html() /* get full class text from attribute class because addClass to children rewrites the whole class string */ } }) if ( typeof $( kids[0] ) !== 'undefined' ) { $( kids[0] ).attr( 'class', cur_class ) preview_class = false } }, 1 ) } if ( typeof callback === 'function' ) { callback() } } } function previewSelectedClass( class_name ) { kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ setTimeout(function() { cur_class = $('#dAField').val() /* get full class text from and add class_name to it because addClass to children rewrites the whole class string */ if ( typeof $( kids[0] ) !== 'undefined' && typeof class_name !== 'undefined' ) { $( kids[0] ).addClass( cur_class+' '+class_name ) preview_class = true } }, 1 ) } function checkAttrName() { if ( last_action != 'editHTV' ) { /* skip if we edit html tag value */ if ( $( '#ean_' + cur_attr_num ).attr('last-val') != $( '#ean_' + cur_attr_num ).html() ) { /* when the attribute name is changed with new -> remove the attribute from real html tag */ kids = $( '#selItmCon' ).children() /* select the edited element by getting childs of the selItemCon container */ if ( $( '#ean_' + cur_attr_num ).html().length > 0 ) { /* only when not empty attribute name */ $( kids[0] ).removeAttr( $( '#ean_' + cur_attr_num ).attr( 'last-val' ) ) /* remove the real attribute which was replaced from the edited html tag */ $( '#ean_' + cur_attr_num ).attr( 'last-val', $( '#ean_' + cur_attr_num ).html() ) /* update 'last-val' with current one */ $( kids[0] ).attr( $( '#ean_' + cur_attr_num ).attr('last-val'), $( '#eav_' + cur_attr_num ).html() ) /* add the new attr to the edited html tag and */ } else { $( kids[0] ).removeAttr( $( '#ean_' + cur_attr_num ).attr( 'last-val' ) ) /* remove the real attribute from the edited html tag */ if ( handleReIndex( event ) == 'exit') { /* reindex attributes nums */ hideSuggests() return 'exit' } } } } } function selectSuggestedItem( item_name, item_data, suggest_type, callback ) { curPos = $('#dAField').prop("selectionStart") last_cur_pos = curPos data = $('#dAField').val() delimiters = [ '\'', '"', '}', ' ', '|', '.', '=', '<', '>', '!', '(', ')', '[', ']' ] /* that should be all possible end points of smarty variable */ if ( suggest_type != 'smarty_statement' ) { /* when not suggesting smarty statement -> add starting smarty tag '{' */ delimiters.push('{') } if ( suggest_type != 'smarty_vars' ) { /* when not suggesting smarty statement -> add starting smarty tag '{' */ delimiters.push('$') } suggest_vars = false /* reset suggest_vars */ hideSuggests() if ( !event.shiftKey ) { /* only when shft key is not pressed */ updateTopSuggests( item_name ) /* add/update current item to top suggests list */ } /* move left from current caret position until delimiter found or begining of the data */ for ( left_pos = curPos; left_pos > 0; left_pos-- ) { /* if we find delimiter get out of the loop and bring out the position after the entered item */ if ( delimiters.indexOf( data.substr( left_pos - 1, 1 ) ) != -1 ) { break } } /* move right from current caret position until suggest found or end of the data */ for ( right_pos = curPos - 1; right_pos < data.length; right_pos++ ) { /* if we find suggest get out of the loop and bring out the position after the entered item */ if ( delimiters.indexOf( data.substr( right_pos + 1, 1 ) ) != -1 ) { right_pos++ break } } if ( suggest_type == 'smarty_statement' && $('#dAField').prop('placeholder').indexOf('HTML') !== -1 ) { /* when suggested item is smarty statement and we are on HTML tag adding -> put item_name */ new_data = data.substr( 0, left_pos ) + item_name + data.substr( right_pos ) } else { /* otherwise -> put item_data */ new_data = data.substr( 0, left_pos ) + item_data + data.substr( right_pos ) } if ( multi_suggest && right_pos == data.length && suggest_type != 'smarty_vars' ) { new_data += ' ' } if ( new_data.indexOf('undefined') == -1 ) { /* only when enter pressed on suggested item */ $( '#dAField' ).val( new_data ) /* pupolate textarea with replaced string */ } if ( multi_suggest ) { /* when multi suggest -> stay editing same field just reposition the caret */ add_pos = 0 /* initialize zero additional pos var */ if ( suggest_type == 'smarty_statement' ) { /* when suggesting smarty statement -> stay on same place */ /* try to find first parameter value position */ fpv_pos = item_data.indexOf("''") /* fpv = First Param Value */ if ( fpv_pos != -1 ) { /* when found parameter */ add_pos = fpv_pos /* update add_pos */ } /* find fist space in the smarty statement */ else { space_pos = item_data.indexOf(" ") if ( space_pos != -1 ) { /* when found space */ add_pos = space_pos /* update add_pos */ } else { add_pos = item_data.length /* update add_pos */ } } last_cur_pos = last_cur_pos - ( search_str.length ) + 1 /* correct cursor position in front of searching string + 1 */ setCaretPosition( 'dAField', parseInt( parseInt( last_cur_pos + add_pos ) ) ) } else { /* otherwise -> go to currently added item end */ if ( item_data.substr( 0, 1 ) == '$' && right_pos < data.length ) { /* when smarty var and not at the and of the data correct add_pos */ add_pos = -1 } else if ( suggest_type == 'attribute' ) { /* when adding attribute -> go after the space char */ add_pos = 2 } last_cur_pos = last_cur_pos - ( search_str.length ) /* correct cursor position in front of searching string */ setCaretPosition( 'dAField', parseInt( parseInt( last_cur_pos ) + item_data.length + add_pos ) ) } return false } else { if (cur_attr_num < cur_max_attrs_num ) { /* when not in the end of the attributes list */ updateCurAttr( event ) /* update the visual part */ updateRealAttr( cur_attr_num ) /* update the real html tag attr */ } else { /* at the end of the attributes list or not editing attrubites at all */ if ( cur_ap == 'n' ) { updateCurAttr( event ) updateRealAttr( cur_attr_num ) checkAttrName() cur_ap = 'v' editAttr ( cur_attr_num, cur_ap ) /* go to edit current attribute value */ } else if ( $('span#htv').length === 1 ) { /* when the html tag is not selfcontaining */ updateCurAttr( event ) updateRealAttr( cur_attr_num ) editHTV() } else { $( '#btn_y' ).focus() } } } /* when detect 'html' in placeholder exit trough callback if present */ if ( ( $('#dAField').prop('placeholder').indexOf('HTML') !== -1 || $('#dAField').prop('placeholder').indexOf('DB ') !== -1 ) && typeof callback === 'function' ) { callback() } } function updateTopSuggests( item_name ) { found = false top_suggests.forEach( function( item, index ) { if ( item_name == item.item ) { /* when there is same suggest -> increase its count */ top_suggests[index].count++ found = true } }) if ( !found ) { /* when not found -> add it */ top_suggests.push( { item: item_name, count: 1 } ) } /* sort the top suggest by count asscending */ top_suggests = top_suggests.sort( function( a, b ) { return a.count > b.count ? 1 : a.count < b.count ? -1 : 0 }) } function unselectAllSuggests() { $('.suggestItem').each(function() { $(this).removeClass( "suggestItemActive" ) }) } function prepHtmlTag( name, callback ) { $.ajax({ url: "/ajax", type: "POST", data: { dAction: 'ajaxHandler(req, res)', req: 'get_default_attrubutes_by_tag_name', name: name }, success: function(data) { if (data) { /* return prepared html tag for edit */ callback(data) } else { /* if no result (wrong entered html tag name) just hide the form and show the menu */ hideMF() } }, error: function() { } }) } function fetchVarsFromDB() { resetBodyShortcuts() /* disable previous keyboard functionality */ suggestFor( event, 'dbs', 'Type/Select DB Name', '', function( db_name ) { /* do nothing when empty name entered */ if ( db_name === '' ) { return false } $.ajax({ url: "/ajax", type: "POST", data: { dAction: 'ajaxHandler(req, res)', req: 'get_all_tables_by_db_name', db_name: db_name }, success: function( data ) { if ( data ) { db_tables = [] /* reset db_tables collection */ data = jQuery.parseJSON( data ) /* convert from string to js collection ( array ) */ data.forEach( function( db_table ) { db_tables.push( db_table ) }) setTimeout(function() { /* delay next suggestFor call to prevent executing two actions with one press of enter key */ suggestFor( event, 'db_tables', 'Type/Select DB Table Name', '', function( db_table_name ) { /* do nothing when empty name entered */ if ( db_table_name === '' ) { return false } $.ajax({ url: "/ajax", type: "POST", data: { dAction: 'ajaxHandler(req, res)', req: 'get_all_fields_by_db_table_name', db_name: db_name, db_table_name: db_table_name }, success: function( data ) { if ( data ) { data = jQuery.parseJSON( data ) /* convert from string to js collection ( array ) */ fields = '' /* initialize fields html string */ fi = 3 data.forEach( function( field ) { fields += '<input tabindex="' + fi + '" class="ci dbtfcb" type="checkbox" id="dbtf_' + fi + '" onchange="toggleField( this )"/> <label id="dbtfl_' + fi + '" class="ci" for="dbtf_' + fi + '">' + field + '</label>&nbsp;&nbsp;&nbsp;' fi++ }) clearMFE() $( '#dInfo' ).html('<div class="pf">Select Field(s) for the Collection : <button tabindex="1" id="sadbf" type="button" class="navbar-btn btn btn-small btn-primary " onclick="selectAllFields()">All</button>&nbsp;&nbsp;&nbsp;<button tabindex="2" type="button" class="navbar-btn btn btn-small btn-default" onclick="unselectAllFields()">None</button></div><br/><br/>' + fields).removeClass("hide") .keyup( function ( event ) { if (event.keyCode == 27) { $( '#btn_n' ).click() return } if ( event.keyCode == 13 && event.shiftKey ) { /* when shift+enter -> simulate ok button click */ $( '#btn_y' ).click() } }) $( '#btn_y' ).click( function() { resetBodyShortcuts(); selected_fields = [] /* initialize fields collction ( array ) to store selected fields which later will be converted to smarty variables */ $('.dbtfcb').each( function() { /* iterate trough each Data Base Table Field check box */ if ( $( this ).is(":checked") ) { /* when current check box is checked -> add the field to the collection */ id_arr = $( this ).attr( 'id' ).split('_') /* split current id to get it's number */ label = $( '#dbtfl_' + id_arr[1] ) /* id_arr index 1 must be the current id number */ selected_fields.push( label.html() ) } }) if ( selected_fields.length > 0 ) { /* only when we have selected atleast one of the present fields */ multi_suggest = true suggestFor( event, 'smarty_vars', 'Type/Select Smarty Variable Name for the Selected Fields Collection', '', function( collection_name ) { multi_suggest = false if ( collection_name != '' ) { collection_arr = collection_name.split( '.' ) /* fill each part of the collection as separate var ( for better suggesting ) if not already present */ collection_arr.forEach( function( cur_col_var, cur_var_lvl ) { found_in_vars = false if ( vars.length > 0 ) { /* when we have stored smarty vars */ vars.forEach( function( cur_var, cur_index ) { if ( cur_var.index == cur_var_lvl && cur_var.name == cur_col_var && cur_var.main_var == collection_arr[0] ) { found_in_vars = true } }) if ( !found_in_vars ) { /* only when not found in current vars collection -> add current field as var */ vars.push({"full_var":collection_name,"main_var":collection_arr[0],"name":cur_col_var,"index":cur_var_lvl}) } } else { /* when first var -> just add it */ vars.push({"full_var":collection_name,"main_var":collection_arr[0],"name":cur_col_var,"index":cur_var_lvl}) } }) cur_var_lvl = collection_arr.length /* set the current var level depending on collection_arr length */ /* fill each selected field as separate var in vars collection if not already present */ selected_fields.forEach( function( cur_table_field ) { cur_full_var = collection_name + '.' + cur_table_field found_in_vars = false vars.forEach( function( cur_var, cur_index ) { if ( cur_var.index == cur_var_lvl && cur_var.name == cur_table_field && cur_var.main_var == collection_arr[0] ) { found_in_vars = true } }) if ( !found_in_vars ) { /* only when not found in current vars collection -> add current field as var */ vars.push({"full_var":collection_name,"main_var":collection_arr[0],"name":cur_table_field,"index":cur_var_lvl}) } }) vars_db_info.push({"db_name":db_name,"table_name":db_table_name,"var_name":collection_name}); hideMF() /* hide the form and show the menu */ } else { hideMF() /* hide the form and show the menu */ } }) } }).removeClass( 'hide' ) $('#btn_n').click(function() { hideMF() /* hide the form and show the menu */ }).removeClass( 'hide' ) $( '#sadbf' ).focus() } else { /* if no result (wrong entered or empty db name) just hide the form and show the menu */ hideMF() } } }) }) }, 100 ) } else { /* if no result (wrong entered or empty db name) just hide the form and show the menu */ hideMF() } } }) }) } function addStyledObj( obj ) { if ( styled_objs.length > 0 ) { /* when we had stored styled objects in the stack */ found_duplicate = false styled_objs.forEach( function( cur_obj, index ) { if ( cur_obj.stored_style == $( obj ).attr('style') ) { /* when duplicate style found */ found_duplicate = true styled_objs[ index ].objs.push( $( obj ) ) /* add only the object to existing styling */ } }) if ( !found_duplicate ) { /* when unique styling found -> add the object and it's styling to the stack */ styled_objs.push( { objs: [ $( obj ) ], stored_style: $( obj ).attr('style') } ) } } else { /* add first object to the stack */ styled_objs.push( { objs: [ $( obj ) ], stored_style: $( obj ).attr('style') } ) } } function scanForHardCodedStyles( start_con, callback ) { waiting_for_children = false; /* exit point flag */ i = 0; /* initialize index on each call */ kids = $( start_con ).children(); /* get all children of current container */ if ( kids.length > 0 ) { /* when we have children */ obj_handled = false; found_style = false; while ( i < kids.length ) { if ( $( kids[ i ] ).children().length == 0 ) { /* when current child is childless */ if ( typeof $( kids[ i ] ).attr( 'style' ) !== 'undefined' ) { /* when we have applied hard coded styles to current kid */ addStyledObj( $( kids[ i ] ) ) /* add/update stack with this kid */ } obj_handled = true /* set flag to move to next element */ } else { /* when current child have own kids */ if ( typeof $( kids[ i ] ).attr( 'style' ) !== 'undefined' ) { /* when we have applied hard coded styles to current kid */ addStyledObj( $( kids[ i ] ) )/* add/update stack with this kid */ } waiting_for_children = true; /* block second exit point */ parents_stack.push( $( start_con ) ) /* save curently scanned element (parent) to know what to continue to scan when returned from wonderland */ index_stack.push( i ) /* save current index before going even deeper */ if ( scanForHardCodedStyles( $( kids[ i ] ) ) == 'handled' ) { /* when finished with inner children loop (recurse) */ start_con = parents_stack[ parents_stack.length -1 ] /* restore previous deepnes level */ i = index_stack[ index_stack.length - 1 ] /* restore prevoius deepnes level index */ kids = $( start_con ).children(); /* get all children of current container */ parents_stack.pop() /* remove the last element from the stack */ index_stack.pop() /* remove the last element from the stack */ obj_handled = true /* set flag to go next item or exit if finished */ waiting_for_children = false /* set the second exit point flag */ } } if ( !waiting_for_children ) { obj_handled = true } /* prevent infinite loop */ if ( obj_handled ) { /* when we have handled current object */ i++ /* go to next object or quit */ obj_handled = false /* reset the flag */ } } if ( typeof callback === 'function' ) { /* when callback is present and it's function */ callback( styled_objs ) /* exit trough callback */ } else { return 'handled' /* exit trough return */ } } } function acts( cur_class_name, cur_obj ) { /* acts = Add Class to Stack */ new_class = { name: cur_class_name, style: $( cur_obj ).attr( "style" ) }; new_classes.push( new_class ); } function previewProject() { saveTemplate( true ); } function saveTemplate( is_preview ) { if ( typeof is_preview == 'undefined' ) { is_preview = false; } resetBodyShortcuts(); if ( !save_handled ) { save_handled = true; hideSuggests() /* just in case suggest are visible */ if ( !is_preview ) { var schcsRes = scanForHardCodedStyles( $( '#dContent_con' ), function ( styled_objs ) { /* scan content for hard coded styles */ if ( styled_objs.length > 0 ) { /* when hard coded styles found */ cte = ''; /* cte = Code To Execute */ /* Generating dynamic code section (for better handling of multiple askFor calls) */ for ( i = 0; i < styled_objs.length; i++ ) { /* iterate each styled objects adding to cte (Code To Execute) in way that each next is executed after the callback of the precious is called */ styled_obj = styled_objs[ i ] cte += '$( styled_objs[ ' + i + ' ].objs[ 0 ] ).addClass( "hard_shadow" ); ' /* add highlight class to first object */ cte += 'cur_sc = $( styled_objs[ ' + i + ' ].objs[ 0 ] ); ' /* udpdate cur_sc with current object */ cte += 'scrollTo( cur_sc ); '; /* scroll to highlighted object */ cte += 'askFor( "Enter a Class Name For Highlighted Element Styles", "", function ( cur_class_name ) { '; /* ask for name of the new class */ cte += 'styled_objs[ ' + i + ' ].objs.forEach( function( cur_obj, cur_index ) { '; /* iterate each object with same style and remove the styling updatating the element with the new class instead */ cte += 'if ( cur_index == 0 && cur_class_name != "exit") { '; /* when it's the highlighted object */ cte += 'acts( cur_class_name, $( cur_obj ) ); '; /* add the new class to the stack */ cte += '$( cur_obj ).addClass( cur_class_name ); '; /* add the created class instead of the styles */ cte += '}; '; cte += '$( cur_obj ).removeClass ( "hard_shadow" ); '; /* remove hightligh class */ cte += '$( cur_obj ).removeAttr( "style" ); '; /* remove style attribute */ cte += '}); '; } cte += ' prepHTMLandSave(); '; /* after all hard coded styles are named in classes -> continue saving the data */ for ( i = 0; i < styled_objs.length; i++ ) { cte += '}); '; /* add closing tags for each call of askFor() in cte (Code To Execute) */ } eval( cte ) /* Execute Generated Code */ } else { prepHTMLandSave(); } }) } else { prepHTMLandSave( true ); } } } function prepHTMLandSave( is_preview ) { if ( typeof is_preview == 'undefined' ) { is_preview = false; } $( '#dContent' ).html( $( '#dContent' ).html() .replace( /\r/g, '' ) .replace( /\n/g, '' ) .replace( /\t/g, '' ) ) /* .replace( /&nbsp;/g, '' ) remove all non-breaking spaces, new lines or tabs */ reverse_parse_HTML( $( '#dContent' ) ) /* remove ( BSCNWAD ) edit helping content from the HTML */ showMF() if ( is_preview ) { $( '#dInfo' ).html( 'Preparing Preview...' ).removeClass( 'hide' ) } else { $( '#dInfo' ).html( 'Saving Template...' ).removeClass( 'hide' ) } formated_html = $( '#dContent' ).html() /* move cleaned template html into js var */ /* SEND COLLECTED DATA TO SERVER TO BE SAVED */ $.ajax({ url: "/ajax", type: "POST", data: { dAction: 'ajaxHandler(req, res)', req: 'save_template', formated_html: formated_html, vars: JSON.stringify ( vars ), vars_db_info: JSON.stringify ( vars_db_info ), new_classes: JSON.stringify ( new_classes ), top_suggests: JSON.stringify ( top_suggests ), is_preview: is_preview }, success: function() { setTimeout(function() { /* wait quater of second just for user convinience (to see that "save template" text is showing and disapearing) */ if ( is_preview ) { window.location.href = '/project_preview/'+ cur_project +'/'+ cur_route + '/' + cur_template; } else { location.reload(); /* reload page to apply style/class changes (if had some) */ } }, 250 ) }, error: function( err ) { console.log('ERROR : ' + err) } }) } function unwrap_SS( obj ) { $( obj ).append('<span class="unwrap_helper"></span>') /* add unwrap helper element */ $( '.unwrap_helper' ).unwrap() /* unwrwap nsmarty_code container */ $( '.unwrap_helper' ).remove() /* remove the helper element */ } function reverse_parse_HTML( obj ) { kids = $( obj ).children() if ( kids.length > 0 ) { $( kids ).each( function( kid_index, cur_kid ) { has_kids = false /* remove all system (VAB) attributes from current html element */ $( cur_kid ).removeAttr( 'contenteditable' ) .removeAttr( 'spellcheck' ) .removeAttr( 'sc' ) attrs_to_remove = [] for (var i = 0; i < cur_kid.attributes.length; i++) { /* iterate trough all cur_kid attributes */ var attr = cur_kid.attributes[i] /* get current attribute in attr */ if ( attr.value.length == 0 ) { /* if the attr is specified and it's empty -> remove it attr.specified && */ attrs_to_remove.push( attr.name ) /* mark current attribute for removing */ } } if ( attrs_to_remove.length > 0 ) { /* when empty attributes found */ attrs_to_remove.forEach( function( cur_empty_attr ) { /* iterate trough each attr name */ $( cur_kid ).removeAttr( cur_empty_attr ) /* remove current empty attribute */ }) } if ( $( cur_kid ).children().length > 0 ) { /* when current child have childs */ reverse_parse_HTML( $( cur_kid ) ) /* (recurse) */ } else { /* otherwise -> check for smarty statement container and remove it */ if ( $( cur_kid ).hasClass( 'nsmarty_code' ) ) { unwrap_SS( cur_kid ) } } }) } if ( $( obj ).hasClass( 'nsmarty_code' ) ) { /* when current obj is nsmarty_code container */ unwrap_SS( obj ) } } function parse_smarty() { kids = $('#selItmCon').children() /* select the edited element by getting childs of the selItemCon container */ if ( $(kids[0]).html() != '' ) { data = $(kids[0]).html() /* get current html */ parsed_html = '' /* initialize parsed html */ capture_smarty = false /* initialize capture_smarty flag */ captured_smarty = '' /* we keep currently captured smarty statement here */ last_ch = '' smarty_closing_tags = [] /* posible values : {/block} , {/capture} , {/for} , {/foreach} , {/function} , {/javascript} , {/if} */ /* parsing begins here */ for (i = 0; i < data.length; i++ ) { /* walk trough data text char by char */ ch = data.substr( i, 1 ) /* get current char in ch */ if ( i > 0 ) { /* only when not first char */ last_ch = data.substr( ( i - 1 ), 1 ) /* keep last ch for later checks */ } if ( ch == '}' ) { /* when end of smarty detected -> finish capturing of smarty and applying proper html wraper around it */ is_open_or_closing_tag = false /* check if current smarty statement is opening smarty tag */ /* BLOCK */ if ( captured_smarty.substr(0, 6) == '{block' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/block' ) } /* CAPTURE */ else if ( captured_smarty.substr(0, 8) == '{capture' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/capture' ) } /* FOR */ else if ( captured_smarty.substr(0, 5) == '{for ' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/for' ) } /* FOREACH */ else if ( captured_smarty.substr(0, 9) == '{foreach ' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/foreach' ) } /* FUNCTION */ else if ( captured_smarty.substr(0, 9) == '{function' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/function' ) } /* JAVASCRIPT */ else if ( captured_smarty.substr(0, 11) == '{javascript' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/javascript' ) } /* IF */ else if ( captured_smarty.substr(0, 3) == '{if' ) { is_open_or_closing_tag = true smarty_closing_tags.push( '{/if' ) } /* OPENING TAG */ if ( is_open_or_closing_tag ) { /* when opening tag found ( we didn't check for closing yet, so it's opening ) */ parsed_html += '<code class="nsmarty_code" sc="true">' parsed_html += '<code class="fsc nsmarty_code" sc="true">'+captured_smarty+'}</code>' /* fsc = First Smarty Child */ capture_smarty = false /* reset the flag for capturing smarty */ captured_smarty = '' /* reset captured smarty code */ } /* CLOSING TAG */ else if ( smarty_closing_tags.length > 0 ) { /* when we are looking for closing smarty tags */ if ( smarty_closing_tags[ smarty_closing_tags.length - 1 ] == captured_smarty ) { /* when last closing tag match current captured_smarty */ is_open_or_closing_tag = true parsed_html += '<code class="lsc nsmarty_code" sc="true">'+captured_smarty+'}</code>' parsed_html += '</code>' smarty_closing_tags.pop() capture_smarty = false /* reset the flag for capturing smarty */ captured_smarty = '' /* reset captured smarty code */ } } /* NOT OPENING OR CLOSING TAG */ if ( !is_open_or_closing_tag ) { /* put capsulated with html smarty block */ parsed_html += '<code class="nsmarty_code" sc="true">' parsed_html += captured_smarty+'}' parsed_html += '</code>' capture_smarty = false /* reset the flag for capturing smarty */ captured_smarty = '' /* reset captured smarty code */ } } if ( ch == '{' ) { /* when "{" found -> start capturing of smarty code */ capture_smarty = true /* set capturing smarty code flag to skip adding it before it's finished and we wrap it properly as present fot the html parser */ } if ( capture_smarty ) { /* when smarty code capturing */ captured_smarty += ch } else { /* when not capturing smarty code -> populate parsed_html as plain text char by char */ if ( ch != '}' ) { /* otherwise -> add everthing except } which is added when created smarty code wraping */ parsed_html += ch } } } $(kids[0]).html( parsed_html ) /* replace current html with parsed one */ } } function toggleField( obj ) { id_arr = $( obj ).attr( 'id' ).split('_') label = $( '#dbtfl_' + id_arr[1] ) if ( $(label).hasClass( 'tc-gy' ) ) { /* when the current label has highligh class -> remove it */ $(label).removeClass( 'tc-gy' ) } else { /* otherwise -> add highligh class */ $(label).addClass( 'tc-gy' ) } } function selectAllFields() { /* dbtfcb = Data Base Table Field Check Box */ $('.dbtfcb').each( function() { /* iterate trough each check box and check it */ id_arr = $( this ).attr( 'id' ).split('_') /* split current id to get it's number */ label = $( '#dbtfl_' + id_arr[1] ) /* id_arr index 1 must be the current id number */ $( this ).prop("checked", true) /* select current field */ $(label).addClass( 'tc-gy' ) /* set highlight class to current label */ }) } function unselectAllFields() { /* dbtfcb = Data Base Table Field Check Box */ $('.dbtfcb').each( function() { /* iterate trough each check box and check it */ id_arr = $( this ).attr( 'id' ).split('_') /* split current id to get it's number */ label = $( '#dbtfl_' + id_arr[1] ) /* id_arr index 1 must be the current id number */ $( this ).prop("checked", false) /* unselect current field */ $(label).removeClass( 'tc-gy' ) /* remove highlight class to current label */ }) } function backToTemplates() { /* set the action : back to previous module (templates) */ $('#dAction').val('backToTemplates(req, res)') /* submit request */ window.document.getElementById('dForm').submit() }
import Decorations from './Decorations'; export default Decorations;
var video, player, events, filteredEvents, occurInOrder, count, attachListeners, contentUrl; filteredEvents = { contenttimeupdate: 1, contentprogress: 1, contentwaiting: 1, contentsuspend: 1, adtimeupdate: 1, adprogress: 1, adwaiting: 1, adsuspend: 1, timeupdate: 1, progress: 1, waiting: 1, suspend: 1 }; // Asserts that elements in the first array occur in the same order as // in the second array. It's okay to have duplicates or intermediate // elements in the first array that don't occur in the second. An // assertion will fail if all of the elements in the second array are // not present in the first. occurInOrder = function(actual, expected) { var i, j; for (i = j = 0; i < actual.length; i++) { if (actual[i] !== expected[j]) { continue; } equal(actual[i], expected[j], 'matched "' + expected[j] + '" to event number ' + i); j++; } equal(j, expected.length, expected.length !== j ? 'missing ' + expected.slice(j).join(', ') : 'all expected events occurred'); }; // returns then number of elements in an array that equal the specified element. count = function(array, element) { var i = array.length, result = 0; while (i--) { if (array[i] === element) { result++; } } return result; }; attachListeners = function(player) { // capture video element events during test runs player.on(videojs.Html5.Events.concat(videojs.Html5.Events.map(function(event) { return 'ad' + event; })).concat(videojs.Html5.Events.map(function(event) { return 'content' + event; })).concat([ // events emitted by ad plugin 'adtimeout', 'contentended', 'contentupdate', 'contentplayback', // events emitted by third party ad implementors 'adsready', 'adscanceled', 'adstart', // startLinearAdMode() 'adend' // endLinearAdMode() ]), function(event) { events.push(event.type); }); events = []; return player; }; // get the absolute URL to the video so that snapshot restores aren't // seen as content updates contentUrl = (function() { var a = document.createElement('a'); a.href = '../example/sintel-low.mp4'; return a.href; })(); module('Ad Events Tranformation', { setup: function() { var vjsOptions = { inactivityTimeout: 0 }; video = document.createElement('video'); video.className = 'video-js vjs-default-skin'; video.width = '640'; video.height = '272'; video.setAttribute('controls', ''); // add video element behavior to phantom's non-functioning version if (/phantom/i.test(window.navigator.userAgent)) { video.removeAttribute = function(attr) { video[attr] = ''; }; video.load = function() {}; video.play = function() {}; } document.getElementById('qunit-fixture').appendChild(video); if (QUnit.config.flash) { vjsOptions.techOrder = ['flash']; } player = videojs(video, vjsOptions); // load a video player.src({ src: contentUrl, type: 'video/mp4' }); } }); test('linear ads should not affect regular video playback events', function(assert) { var done = assert.async(); player.exampleAds({ midrollPoint: 2 }); attachListeners(player).on('ended', function() { events = events.filter(function(event) { return !(event in filteredEvents); }); ok(events.length > 0, 'fired video events'); // ad events should occur in a sensible order occurInOrder(events, [ 'adstart', 'adend', // play a preroll 'contentplayback', 'adstart', 'adend', // play a midroll 'contentplayback', 'adstart', 'contentended', 'adend', // play a postroll 'contentplayback', 'ended' // end the video ]); // content related events should occur in a sensible order occurInOrder(events, [ 'play', // start the video 'playing', // content begins playing 'ended' // end the video ]); occurInOrder(events, [ 'loadstart', 'playing' ]); equal(count(events, 'adsready'), 1, 'fired adsready exactly once'); equal(count(events, 'loadstart'), 1, 'fired loadstart exactly once'); equal(count(events, 'ended'), 1, 'fired ended exactly once'); ok(player.ended(), 'the video is still ended'); done(); }); player.ready(function() { player.play(); }); }); test('regular video playback is not affected', function(assert) { var done = assert.async(); // disable ads player.exampleAds({ adServerUrl: 'empty-inventory.json' }); attachListeners(player).on('ended', function() { events = events.filter(function(event) { return !(event in filteredEvents); }); ok(events.length > 0, 'fired video events'); occurInOrder(events, [ 'play', // start the video 'ended' // end the video ]); occurInOrder(events, [ 'loadstart', 'playing' ]); equal(count(events, 'adstart'), 0, 'did not fire adstart'); equal(count(events, 'adend'), 0, 'did not fire adend'); equal(count(events, 'loadstart'), 1, 'fired loadstart exactly once'); equal(count(events, 'ended'), 1, 'fired ended exactly once'); ok(player.ended(), 'the video is still ended'); done(); }); player.ready(function() { player.play(); }); });
import axios from 'axios' /** * Encode url for GET request * @param data * @returns {string} */ function encodeData (data) { return Object.keys(data) .map(key => [key, data[key]].map(encodeURIComponent).join('=')) .join('&') } /** * Utility to format a promise whatever the method is (support GET POST PUT PATCH ...etc) * @param params * @returns {Promise<R>|Promise.<T>} */ export const makePromise = (params) => { const { host, endpoint, method = 'get', data = {}, headers = {}, responseType = 'json' } = params let {url} = params if (!url) { url = `${host}/${endpoint}/?` } if (method === 'get') { url += encodeData(data) } return axios({ method, url, data, headers, responseType }) .then(response => Promise.resolve(response.data)) .catch(error => Promise.reject(error)) }
import auth from './auth'; import { merge } from 'lodash'; import models from '../db/models'; export default { typeDefs: [auth.typeDefs].join(' '), resolvers: merge({}, auth.resolvers), context: req => ({ ...req, models }) };
app.controller("orderUpdateStateModelController",['$scope','$http','$modalInstance','orderStateService','id','orderState',function($scope,$http,$modalInstance,orderStateService,id,orderState){ $scope.formData = {} ; $scope.state = orderStateService.getOrderState(orderState) ; $scope.submit = function(){ $http({ url:"opr/orderAction!updateOrderState.action", method:"POST", data:{ id:id, orderState:orderState, trackMemo:$scope.formData.trackMemo } }).then(function(resp){ if(resp.data.code == 1){ $modalInstance.close(); }else{ alert(resp.data.message); } $scope.isDoing = false ; }); } $scope.cancel = function() { $modalInstance.dismiss('cancel'); }; //结束controller }]);
import uuidv4 from 'uuid/v4'; import { ADD_POST, DELETE_POST } from './types'; //import { newBook, saveBook, fetchBook, updateBook } //from '../actions/book-actions'; import axios from "axios"; //import {backendurl} from './index'; const url = '/books' const BASE_URL = "http://localhost:8090"; export function savePost(post) { // console.log(book); return dispatch => { axios.post(BASE_URL+'/books/add',post) .then(function (response) { // console.log(response); dispatch({ type: 'ADD_POST', payload: response }) }) .catch(function (error) { console.log("error",error); dispatch({ type: 'SAVE_BOOK_REJECTED', payload: error }) }); } } /* export const createPost = ({ title, body }) => ({ type: ADD_POST, payload: { id: uuidv4(), title, body } }); */ export const deletePost = id => ({ type: DELETE_POST, payload: { id } });
import React from 'react'; import {Carousel} from "react-bootstrap"; import first from "../../assets/images/westbound-web-banner-1.jpg"; import second from "../../assets/images/harpoon-web-banner.jpg"; import third from "../../assets/images/Rider-hero-1-NEW-copy.jpg"; const CarouselHome = () => { return ( <div> <Carousel style={{marginTop: '-7px'}}> <Carousel.Item interval={1000}> <img className="d-block w-100" src={first} alt="First slide" /> <Carousel.Caption> <h3>Cheap</h3> <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={500}> <img className="d-block w-100" src={second} alt="Second slide" /> <Carousel.Caption> <h3>Best ski shop</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item> <img className="d-block w-100" src={third} alt="Third slide" /> <Carousel.Caption> <h3>Good quality</h3> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p> </Carousel.Caption> </Carousel.Item> </Carousel> </div> ); }; export default CarouselHome;
import { createStore, applyMiddleware } from 'redux'; import { createLogger } from 'redux-logger'; import createSagaMiddleware from 'redux-saga'; import { composeWithDevTools } from 'redux-devtools-extension'; import rootReducer from 'src/rootReducer'; import { initSagas } from 'src/rootSagas'; const sagaMiddleware = createSagaMiddleware(); const loggerMiddleware = createLogger(); const composeEnhancers = composeWithDevTools({ // options like actionSanitizer, stateSanitizer }); export function configureStore() { const store = createStore( rootReducer, composeEnhancers( applyMiddleware( sagaMiddleware, loggerMiddleware ) ) ); initSagas(sagaMiddleware); return store; }
angular.module('starter') .factory('Formulaire', ['storage', '$q','remoteStorage', 'storage', function(localStorage, $q, remoteStorage, storage) { var formsPromise = null; var formsProductsPromise = null; return { load: function () { //for debug formsProductsPromise = remoteStorage.get('formsProducts').then(function (formsProducts) { localStorage.set('formsProducts', formsProducts); return formsProducts; }); formsPromise = remoteStorage.get('forms').then(function(forms) { localStorage.set('forms', forms); return forms; }); }, getFormsProducts: function () { formsProductsPromise = formsProductsPromise || storage.get('formsProducts').then(function (formsProducts) { localStorage.set('formsProducts', formsProducts); return formsProducts; }); return formsProductsPromise; }, get: function (formName) { formsPromise = formsPromise || storage.get('forms').then(function (forms) { storage.set('forms', forms); //keep in local return forms; }); return formsPromise.then(function (forms) { return forms[formName]; }); } }; } ]);
"use strict"; const mods = [ "shellfish/low", "shellfish/mid", "shellfish/high", "shell/ui", "shell/files" ]; require(mods, function (low, mid, high, ui, files) { function formatTime(seconds) { var t = seconds; var hsecs = Math.floor(t * 100) % 100; var secs = Math.floor(t) % 60; t /= 60; var minutes = Math.floor(t) % 60; t /= 60; var hours = Math.floor(t); var h = hours.toFixed(0); var m = minutes.toFixed(0); var s = secs.toFixed(0); var hs = hsecs.toFixed(0); if (h.length === 1) { h = "0" + h; } if (m.length === 1) { m = "0" + m; } if (s.length === 1) { s = "0" + s; } if (hs.length === 1) { hs = "0" + hs; } return (hours > 0 ? h + ":" : "") + m + ":" + s + "." + hs; } function showCutDialog(uri, ranges) { var idx = uri.lastIndexOf("/"); var path = idx !== -1 ? uri.substr(0, idx) : ""; var filename = decodeURIComponent(idx !== -1 ? uri.substr(idx + 1) : uri); idx = filename.lastIndexOf("."); var name = idx !== -1 ? filename.substr(0, idx) : filename; var ext = idx !== -1 ? filename.substr(idx) : ""; var dlg = high.element(mid.Dialog); dlg .onClosed(dlg.discard) .title("Cut Video") .button( high.element(mid.Button).text("Cut") .onClicked(function () { var directions = { }; for (var i = 0; i < ranges.length; ++i) { var target = dlg.find("target." + (i + 1)).get().text; var targetUri = path + "/" + encodeURIComponent(target); if (! directions[targetUri]) { directions[targetUri] = []; } directions[targetUri].push(ranges[i]); } cutVideo(uri, directions); dlg.close_(); }) ) .button( high.element(mid.Button).text("Cancel") .onClicked(function () { dlg.close_(); }) ) .add( high.element(mid.Label) .text("You may combine multiple ranges in the same output file.") ); var counter = 1; ranges.forEach(function (range) { dlg.add( high.element(mid.Labeled) .text("Range " + counter + " <" + formatTime(range[0]) + " - " + formatTime(range[1]) + ">") .add( high.element(mid.TextInput).id("target." + counter) .text(name + "_" + counter + ext) ) ); ++counter; }); dlg.show_(); } function cutVideo(uri, directions) { var busyIndicator = high.element(mid.BusyPopup).text("Sending"); busyIndicator.show_(); var data = { uri: uri, directions: directions }; $.ajax({ type: "POST", url: "/::video-editor/cut", data: JSON.stringify(data) }) .done(function (data, status, xhr) { var statusItem = new ui.StatusItem(); statusItem.icon = "sh-icon-movie_creation"; statusItem.text = "Waiting..."; files.pushStatus(statusItem); getStatus(statusItem); }) .fail(function (xhr, status, err) { ui.showError("Could not submit to server: " + err); }) .always(function () { busyIndicator.hide_(); }) } function getStatus(statusItem) { $.ajax({ type: "GET", url: "/::video-editor/status", dataType: "json" }) .done(function (data, status, xhr) { if (data.name) { statusItem.text = "Cutting Video: " + data.name; statusItem.progress = data.seconds / data.total * 100; setTimeout(function () { getStatus(statusItem); }, 1000); } else { files.popStatus(statusItem); } }) .fail(function (xhr, status, err) { files.popStatus(statusItem); }) .always(function () { }); } function MarkersBar() { Object.defineProperties(this, { position: { set: setPosition, get: position, enumerable: true }, duration: { set: setDuration, get: duration, enumerable: true }, inverse: { set: setInverse, get: inverse, enumerable: true }, onSeeked: { set: setOnSeeked, get: onSeeked, enumerable: true }, onRangesChanged: { set: setOnRangesChanged, get: onRangesChanged, enumerable: true } }); var m_position = 0; var m_duration = 0; var m_markers = []; var m_inverse = false; var m_onSeeked = null; var m_onRangesChanged = null; var m_item = $( low.tag("div") .style("position", "relative") .style("height", "2rem") .style("line-height", "2rem") .content( low.tag("div") .style("position", "absolute") .style("top", "0") .style("left", "0") .style("width", "100%") .style("height", "100%") ) .html() ); m_item.on("click", function (event) { if (m_onSeeked && m_markers.length > 0) { var p = Math.max(0, Math.min(1, event.offsetX / $(this).width())); var seconds = p * m_duration; m_onSeeked(closestMarker(seconds)); } }); function closestMarker(seconds) { var markers = m_markers.map(function (m) { return [m, Math.abs(m - seconds)]; }) .sort(function (a, b) { return a[1] - b[1]; }); if (markers.length > 0) { return markers[0][0]; } else { return null; } } function setPosition(pos) { m_position = pos; } function position() { return m_position; } function setDuration(duration) { m_duration = duration; updateRanges(); } function duration() { return m_duration; } function setInverse(v) { m_inverse = v; updateRanges(); } function inverse() { return m_inverse; } function setOnSeeked(cb) { m_onSeeked = cb; } function onSeeked() { return m_onSeeked; } function setOnRangesChanged(cb) { m_onRangesChanged = cb; } function onRangesChanged() { return m_onRangesChanged; } function updateRanges() { if (m_duration === 0) { return; } var ranges = []; var markers = m_markers.slice(); if (! m_inverse) { markers.push(0); } markers.sort(function (a, b) { return a - b; }); for (var i = 0; i < markers.length; i += 2) { var begin = markers[i]; var end = i + 1 < markers.length ? markers[i + 1] : m_duration; ranges.push([begin, end]); } m_item.find("> div:nth-child(1)").each(function (i) { var box = $(this); while (box.find("> div").length > ranges.length) { box.find("> div").last().remove(); } while (box.find("> div").length < ranges.length) { box.append( low.tag("div") .style("position", "absolute") .style("background-color", "rgba(255, 255, 0, 0.3)") .style("border-left", "solid 2px var(--color-primary)") .style("border-right", "solid 2px var(--color-primary)") .style("top", "0") .style("bottom", "0") .style("pointer-events", "none") .style("touch-action", "none") .html() ); } var gauges = box.find("> div"); for (var i = 0; i < ranges.length; ++i) { console.log("range " + i + ": " + ranges[i][0] + " - " + ranges[i][1]); gauges.eq(i) .css("left", (ranges[i][0] / m_duration * 100) + "%") .css("right", (100 - ranges[i][1] / m_duration * 100) + "%"); } }); if (m_onRangesChanged) { m_onRangesChanged(ranges); } } this.get = function () { return m_item; }; this.addMarker = function () { m_markers.push(m_position); updateRanges(); }; this.removeMarker = function () { if (m_markers.length > 0) { var marker = closestMarker(m_position); m_markers = m_markers.filter(function (m) { return Math.abs(m - marker) > 0.01; }); updateRanges(); } } } exports.VideoEditor = function () { Object.defineProperties(this, { uri: { set: setUri, get: uri, enumerable: true }, position: { set: setPosition, get: position, enumerable: true }, duration: { set: setDuration, get: duration, enumerable: true }, onChanged: { set: setOnChanged, get: onChanged, enumerable: true }, onSeeked: { set: setOnSeeked, get: onSeeked, enumerable: true } }); var m_uri = ""; var m_position = 0; var m_duration = 0; var m_onChanged = null; var m_onSeeked = null; var m_ranges = []; mid.extend(this, new mid.Box()); var m_markersBar = new MarkersBar(); m_markersBar.onSeeked = function (seconds) { if (m_onSeeked) { m_onSeeked(seconds); } }; m_markersBar.onRangesChanged = function (ranges) { m_ranges = ranges; cutButton.enabled = (m_ranges.length > 0); } this.add(m_markersBar); var m_toolbar = new mid.Toolbar(); this.add(m_toolbar); var btn = new mid.Button(); btn.icon = "content_cut"; btn.onClicked = function () { m_markersBar.addMarker(); }; m_toolbar.add(btn); btn = new mid.Button(); btn.icon = "delete"; btn.onClicked = function () { m_markersBar.removeMarker(); }; m_toolbar.add(btn); var gap = new mid.Gap(); m_toolbar.add(gap); btn = new mid.Button(); btn.icon = "flip"; btn.onClicked = function () { m_markersBar.inverse = ! m_markersBar.inverse; }; m_toolbar.add(btn); gap = new mid.Gap(); m_toolbar.add(gap); btn = new mid.Button(); btn.icon = "exposure_minus_1"; btn.onClicked = function () { if (m_onSeeked) { m_onSeeked(Math.max(0, m_position - 1.0)); } }; m_toolbar.add(btn); btn = new mid.Button(); btn.icon = "fast_rewind"; btn.onClicked = function () { if (m_onSeeked) { m_onSeeked(Math.max(0, m_position - 1.0 / 30)); } }; m_toolbar.add(btn); btn = new mid.Button(); btn.icon = "fast_forward"; btn.onClicked = function () { if (m_onSeeked) { m_onSeeked(Math.min(m_duration, m_position + 1.0 / 30)); } }; m_toolbar.add(btn); btn = new mid.Button(); btn.icon = "exposure_plus_1"; btn.onClicked = function () { if (m_onSeeked) { m_onSeeked(Math.min(m_duration, m_position + 1.0)); } }; m_toolbar.add(btn); var cutButton = new mid.Button(); cutButton.icon = "check"; cutButton.enabled = false; cutButton.onClicked = function () { showCutDialog(m_uri, m_ranges); } m_toolbar.right = cutButton; function setUri(uri) { m_uri = uri; } function uri() { return m_uri; } function setPosition(seconds) { m_position = seconds; m_markersBar.position = seconds; } function position() { return m_position; } function setDuration(seconds) { m_duration = seconds; m_markersBar.duration = seconds; } function duration() { return m_duration; } function setOnChanged(cb) { m_onChanged = cb; } function onChanged() { return m_onChanged; } function setOnSeeked(cb) { m_onSeeked = cb; } function onSeeked() { return m_onSeeked; } }; });
import React from 'react'; import Button from './Button.jsx'; import Store from '../stores/Store.jsx'; import uiConfig from '../utils/uiConfig.jsx'; import Actions from '../actions/Actions.jsx'; function getState() { return { header: Store.getHeader(), footer: Store.getFooter(), section: Store.getSection(), sectionId : Store.getSectionId() }; } class Main extends React.Component { constructor() { super(); this.state = {}; this.onUIChange = this.onUIChange.bind(this); this.toggleSection = this.toggleSection.bind(this); } componentDidMount() { Store.addUIChangeListener(this.onUIChange); Actions.ui.set('song'); this.state = getState(); } componentWillUnmount() { Store.removeUIChangeListener(this.onUIChange); } onUIChange() { this.setState(getState()); } toggleSection(sectionId){ Actions.ui.set(sectionId); } render() { let Header = this.state.header ? <this.state.header sectionId={this.state.sectionId} toggleSection={this.toggleSection}/> : null; let Footer = this.state.footer ? <this.state.footer sectionId={this.state.sectionId} /> : null; let Section = this.state.section ? <this.state.section/> : null; return ( <main> {Header} {Section} {Footer} </main> ); } } export default Main;
/*Change LOG 10/10/16 - Added detection for certain UPS shipping methods and express = T for PTS orders. Auto-approve will be skipped. 3/2/17 - Added If Billto!=shipto and payment method != paypal auto approve 3/3/17 - Added if created from is estimate, then auto approve SO 5/19/17 - Added paymenteventresult != 'HOLD' 7/27/17 - Added to arrAutoApprovedPayTypes Changed UI auto approval from <$350 to <$1000 7/28/17 - Added check invalid SHIP TO 8/1/17 - Removed check for Paypal as their is one implemented on 7/28/17 3/15/18 - Added If 2 or 3 Xs, then do not auto approve Added var execContext 3/19/18 - Added nlapiSubmitField("salesorder", soId, ["custbody17"], ["Manually Approve Biofreeze Promotion"]); 3/27/18 - Changed to nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["Manually Approve Biofreeze Promotion","T"]); 4/4/18 - Moved Call-In Order approval to after PAYMENT HOLD check 4/25/18 - Moved PayPal approval to before CC approval changed checkEmail from ORDER CLOSED DUE TO INCORRECT CREDIT CARD INFORMATION to INCORRECT CREDIT CARD INFORMATION 5/10/18 - nlapiSubmitField("salesorder", soId, ["custbody32"], ["paymenteventresult="+paymenteventresult]); 6/20/18 - if(paymenteventresult == 'HOLD') 1/3/19 - Do not approve Game Ready Control Unit id=184110 2/1/19 - Added new biofreeze promotion items 3/1/19 - Added FREE 2ND DAY SHIPPING custitem405 condition 3/13/19 - FREE 2ND DAY SHIPPING shippingcost = 0.00 3/14/19 - FREE 2ND DAY SHIPPING message field 4/26/19 - REMOVED Approve CC orders under $50 if CSC=Y CHANGED Approve Canada orders under $50 with 3 Ys REMOVED Approve all PTS Orders under $1000 and billTo=shipTo and paymentevent!=HOLD 4/30/19 - change $1000 to Approve CC orders under $150 if 3 Ys and billTo=shipTo 6/4/19 - Do not approve if SHIP TO line2 not empty 7/9/19 - skip if item SKIP AUTO APPROVAL = T 9/25/19 - Do not approve if customer is SPECIAL SHIPPING = T 2/15/21 - Added auto approve for all Elastogels and Etsy orders 2/19/21 - Added auto approval for all Newegg Orders */ function afterSubmit_processSOApproval(type) { try { if (type == 'delete' || type == 'approve') return; var soId = nlapiGetRecordId(); var currSORec = nlapiLoadRecord('salesorder', nlapiGetRecordId()); var execContext = nlapiGetContext().getExecutionContext(); nlapiLogExecution("debug", "type: " + type + "; soId: " + soId, "-----------START "+execContext+"-----------"); var customer = currSORec.getFieldText("entity"); var customerID = currSORec.getFieldValue('entity'); var custRec = nlapiLoadRecord('customer', customerID); var currForm = currSORec.getFieldValue('customform'); if(currForm != 102) { //nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; currForm: " + currForm + ";" // , "IGNORE:form is not Sales Order Receipt"); return; } var currStatus = currSORec.getFieldValue('orderstatus'); if (currStatus != null && currStatus != "A") { //nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; currStatus: " + currStatus + ";" // , "IGNORE:status is not pending approval."); return; } var skipAutoApprove1 = currSORec.getFieldValue("custbody_skip_auto_approve"); if (skipAutoApprove1 == "T") { nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; currStatus: " + currStatus + ";" , "IGNORE:skip queue record creation (custbody_skip_auto_approve = T)."); return; } //Get Values var orderTotal = currSORec.getFieldValue('total'); var paymentMethod = currSORec.getFieldText('paymentmethod'); var shipmethod = currSORec.getFieldValue("shipmethod"); var shippingcost = currSORec.getFieldValue("shippingcost"); var storefront = currSORec.getFieldValue("custbodystorefront") || ''; var soStatus = 'A'; var queueSO = false; var free2Day = false; var arrBiofreeze = [18265,33829,33828,18263,18261,14426,33831,33830,14424,14422,271912,271911,271909,271910,271908,271858, 284728,284727,284726,284729,284730,,33828,18263,33829,18265,18261,284732,284733,284736,284735,284734]; //go through each line items var count = nlapiGetLineItemCount("item"); for(i = 1; i <= count; i++) { var itemName = nlapiGetNewRecord().getLineItemText("item","item",i); //Item Name var itemID = nlapiGetNewRecord().getLineItemValue("item","item",i); //Item ID var itemType = nlapiGetNewRecord().getLineItemValue("item","itemtype",i); var rate = currSORec.getLineItemValue("item", "rate", i); nlapiLogExecution("debug", "rate = " + rate); //calcWorth(itemType, itemID, rate); //nlapiLogExecution("debug",customer,"itemID: "+itemID); //Ignore if Order has Biofreeze Promotion item for(d in arrBiofreeze) { if(itemID == arrBiofreeze[d]) { nlapiLogExecution("debug","soId: "+nlapiGetNewRecord()+"; customer "+customer,"IGNORE: Contains Biofreeze Promotion item: "+itemID); nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["Manually Approve Biofreeze Promotion","T"]); return; } } //Ignore if Order has Open Box kit item and not ebay if(storefront != "eBay" || (storefront != "eBay-flamedical")) { if(itemType=="Kit") { var kit = nlapiLoadRecord("kititem",itemID); var kitItemID = kit.getLineItemValue("member","item",1); var kitLineItem = nlapiLoadRecord("inventoryitem",kitItemID); var kitbox = kitLineItem.getFieldValue("custitem_openbox"); if(kitbox == "T") { nlapiLogExecution("debug",customer,"IGNORE: Contains Open Box item"+"; soId "+soId); nlapiSubmitField("salesorder", soId, ["custbody17"], ["Contains Open Box item"]); return; } } /*if(itemType=="InvtPart") { //nlapiLogExecution("debug","Line Item: ",itemName); var lineItem = nlapiLoadRecord("inventoryitem",itemID); var box = lineItem.getFieldValue("custitem_openbox"); //nlapiLogExecution("debug","soId: " + soId,"Open Box Item "+box); if(box == "T") { //nlapiLogExecution("debug",customer,"IGNORE: Contains Open Box item"+"; soId "+soId); //nlapiSubmitField("salesorder", soId, ["custbody17"], ["Contains Open Box item"]); //return; } } */ } //do not approve Game Ready Control Unit id=184110 if(itemID == 184110) { nlapiLogExecution("debug","soId: "+nlapiGetNewRecord()+"; customer "+customer,"IGNORE: Game Ready Unit Requires Prescription itemID="+itemID); nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["Game Ready Unit Requires Prescription","T"]); return; } //Check if PTS order has FREE 2ND DAY SHIPPING custitem405 if(isEmpty(storefront)) { if(itemType=="InvtPart") { var lineItem = nlapiLoadRecord("inventoryitem",itemID); //dLog('Free 2Day Check','itemID='+itemID+' | free2Day='+lineItem.getFieldValue('custitem405')); if(lineItem.getFieldValue('custitem405') == 'T') { dLog('Free 2Day Check','Change Shipping to Free 2 Day soId='+soId); free2Day = true; } } } //skip if item SKIP AUTO APPROVAL = T var skipItem = nlapiLookupField(loadItem(itemID), itemID, 'custitem_skipautoapproval') || 'F'; if(skipItem == 'T') { nlapiLogExecution("debug","soId: "+nlapiGetNewRecord()+"; customer "+customer,"IGNORE: item SKIP AUTO APPROVAL = T itemID="+itemID); nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve","custbody_scriptnotes"], ["item SKIP AUTO APPROVAL = T","T","skip if item SKIP AUTO APPROVAL = T"]); return; } } //if(customerID == 154983) //{ //Change Ship Via to 101486 FedEx 2Day® if PTS order has FREE 2ND DAY SHIPPING custitem405 if(free2Day) { currSORec.setFieldValue("shipmethod", 101486); //FedEx 2Day® currSORec.setFieldValue("shippingcost", 0.00); currSORec.setFieldValue("custbody20", "Free FedEx 2Day Shipping Promotion"); //Special Message currSORec.setFieldValue("custbody_scriptnotes", "Free FedEx 2Day Shipping Promotion"); orderChanged = true; } //Ignore if PTS order has FREE 2ND DAY SHIPPING custitem405 with multiple item if(free2Day && count > 1) { //Contains FREE 2ND DAY SHIPPING with multiple items -> Need Manual Approval nlapiLogExecution("debug","soId: "+nlapiGetNewRecord()+"; customer "+customer,"IGNORE: FREE 2ND DAY SHIPPING with multiple item itemID="+itemID); nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve","custbody_scriptnotes"], ["Entire Order Not Approved for Free 2Day","T","FREE 2ND DAY SHIPPING with multiple item"]); return; } //} //Ignore if Order has no payment and not Sales Order Invoice Replacement var salesOrderIssue = currSORec.getFieldValue('custbody17') || ''; //Quick Notes if (isEmpty(paymentMethod) && (salesOrderIssue.indexOf('Replacement Order') < 0) && (salesOrderIssue.indexOf('Lost Replacement Package') < 0)) { var orderNumber = currSORec.getFieldValue('tranid'); var customerID = currSORec.getFieldValue('entity'); currSORec.setFieldValue("custbody_skip_auto_approve", "T"); currSORec.setFieldValue("memo", "No Payment"); orderChanged = true; } //If non-PTS customer paid extra for UPS Ground if(!addressBlock){ if(!isEmpty(storefront)){ if(shipmethod == 272 && shippingcost > 0 /*&& (storefront == "eBay" || storefront == "eBay-flamedical")*/) { currSORec.setFieldValue("memo", "MUST SHIP UPS GROUND"); nlapiLogExecution("debug","type: " + type + "; soId: " + soId, "ebay order, shipmethod == 272 && shippingcost > 0"); orderChanged = true; } } } //Ignore if invalid SHIP TO (if both shipaddr1 and shipaddr2 do not have a number) var shipaddr1 = currSORec.getFieldValue('shipaddr1') || ''; var shipaddr2 = currSORec.getFieldValue('shipaddr2') || ''; //dLog('check for invalid SHIP TO','shipaddr1='+shipaddr1+' | shipaddr2='+shipaddr2); var shipToCheck = containsNumber(shipaddr1) || containsNumber(shipaddr2); //dLog('check for invalid SHIP TO','shipToCheck shipaddr1 and shipaddr2 OK? '+shipToCheck); //if shipaddr1 and shipaddr2 both FALSE then no number = invalid address if(!shipToCheck) { nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["Invalid SHIP TO","T"]); queueSO = false; return; } //Do not approve if SHIP TO line2 not empty if(!isEmpty(shipaddr2)) { nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["SHIP TO line2 not empty","T"]); queueSO = false; return; } //Do not approve if customer is SPECIAL SHIPPING = T var specialShipping = custRec.getFieldValue('custentity_specialshipping'); if(specialShipping == 'T') { nlapiSubmitField("salesorder", soId, ["custbody17","custbody_skip_auto_approve"], ["Customer Special Shipping","T"]); queueSO = false; return; } //Checks SO, SO Items, and Customer to verify Free 2nd Day Air is not used by a Professional Level Customer var shipping = nlapiGetFieldValue('shipmethod'); //Ship Via var priceLevel = custRec.getFieldValue('pricelevel');//price level of customer var freeSecondDay = false;//itemLoad(); var sendDMEPacket = false, hasDMEPacket = false; var shipState = currSORec.getFieldValue('shipstate') || ''; var itemCount = nlapiGetLineItemCount('item'); for(var i = 1; i <= itemCount; i++) { var itemType = nlapiGetLineItemValue('item','itemtype',i); if (itemType == 'InvtPart') { var itemID = nlapiGetLineItemValue('item','item',i); //Item Name var item = nlapiLoadRecord('inventoryitem',itemID); var itemShipping = item.getFieldValue('custitem405'); var itemDME = item.getFieldValue('custitem_dmeitem'); if(itemShipping == 'T') { freeSecondDay = true; } if(itemDME == 'T') { sendDMEPacket = true; } if(itemID == 249282) { hasDMEPacket = true; } } } //Ignore if Professional using Free 2nd Day Express if(shipping == '101486' && freeSecondDay == true && priceLevel == 7) { nlapiSubmitField('salesorder', soId, 'memo', 'Professional using Free 2nd Day Express.');//set memo field return; //Do Not Approve } //Email DME Packet as PDF attachment to customer //dLog('DME check','PTS order='+isEmpty(storefront)+' | shipState='+shipState+' | sendDMEPacket='+sendDMEPacket+' | hasDMEPacket='+hasDMEPacket); if(isEmpty(storefront) && shipState == 'GA' && sendDMEPacket && !hasDMEPacket) { dLog('DME Packet','-----------START-----------'); //add PPACKET DME Patient Packet noninventory item if(sendDMEPacket) { currSORec.selectNewLineItem('item'); currSORec.setCurrentLineItemValue('item','item', 249282); currSORec.setCurrentLineItemValue('item', 'quantity', 0); currSORec.commitLineItem('item'); var custbody_scriptnotes = currSORec.getFieldValue('custbody_scriptnotes'); if(!isEmpty(custbody_scriptnotes)) { currSORec.setFieldValue('custbody_scriptnotes',custbody_scriptnotes+"; DME Packet Added for GA Order");} else { currSORec.setFieldValue('custbody_scriptnotes',"DME Packet Added for GA Order"); } soChanged = true; dLog('DME Packet','added'); } //email PTS Patient Packet - Retain for Record and PTS Patient Packet - Deliverable Check List var customerEmail = currSORec.getFieldValue("email"); if(!isEmpty(customerEmail)) { if(checkEmail(soId,'PACKET')){ return; } //Check if email already sent -> send email else { var records = new Object(); records['transaction'] = soId; records['entity'] = customerID; var newAttachment1 = nlapiLoadFile(4866957); //PTS Patient Packet - Retain for Record.pdf var newAttachment2 = nlapiLoadFile(4866958); //PTS Patient Packet - Deliverable Check List.pdf var attachment = [newAttachment1,newAttachment2]; var sbj = 'Pro Therapy Supplies Sales Order #'+currSORec.getFieldValue('tranid')+' DME Patient Packet'; var msg = "Thank you for choosing Pro Therapy Supplies to be your durable medical equipment (DME) provider. We trust you are satisfied with your product." +"\n\nEnclosed in this packet you will find the following documents: (*must sign and return)" +"Deliverable Check list\nPatient Feedback Survey\nCompany Info & Hours of Operation\nRights and Responsibilities\nComplaint Procedure\nEmergency Preparedness\nPrivacy (HIPAA) Notification\nWarranty Information\nEducational and Instructional Materials (supplied by manufacturer with item when available)" +"\n\nFor Medicare Customers\nCurrent Supplier Standards\nAssignment of Benefits" +"\n\nAll Patients must return SIGNED 'DELIVERABLE CHECK LIST'" +"\n\nIt is very important for our records that this proof of delivery is executed. The form(s) may be faxed back to 1-866-755-2705 or emailed to dme@protherapysupplies.com" +"\n\nWe strive to provide the best quality products and excellent customer service, so please do not hesitate to call with any questions regarding your purchase." +"\n\nThanks for your cooperation!\nPro Therapy Supplies DME Service" +"\n\nwww.ProTherapySupplies.com\np. 800-883-0368 / 770-441-9808\nf. 866-755-2705 / 678-680-5818"; dLog('DME Packet','sbj='+sbj); nlapiSendEmail(25164763, customerEmail, sbj, msg, null, null, records, attachment, true, false, 'dme@protherapysupplies.com'); dLog('DME Packet','emailed'); } } dLog('DME Packet','-----------DONE-----------'); } var shipToAddress = currSORec.getFieldValue("shipaddress"); var arrAddress = shipToAddress.split(" "); var addressBlock = false; var addressUSA = false; var addressCANADA = false; var orderChanged = false; var arrUSA = ['PR', 'AK', 'AL', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']; //Flag if AK/HI/PR for (a in arrAddress) { if ((arrAddress[a] == "AK") || (arrAddress[a] == "HI") || (arrAddress[a] == "PR")) { currSORec.setFieldValue("custbody17", "Shipping to AK/HI/PR"); nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; address: " + shipToAddress + ";" , "NOTICE: Shipping to AK/HI/PR"); addressBlock = true; orderChanged = true; break; } } //Check if USA Order for (b in arrAddress) { for (c in arrUSA){ if (arrAddress[b] == arrUSA[c]) { addressUSA = true; break; } } } //Check if Canada Order for (c in arrAddress) { if (arrAddress[c] == "Canada") { addressCANADA = true; break; } } //Flag if International Order if(!addressUSA){ currSORec.setFieldValue("custbody17", "Intl Order"); orderChanged = true; nlapiLogExecution("debug", "NOTICE: Intl Order", "type: " + type + "; soId: " + soId + "; address: " + shipToAddress); } //Approve all ebay and ebay2 orders if(storefront == "eBay" || storefront == "eBay-flamedical"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Approve all Etsy orders if(storefront == "Etsy"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Approve all Elastogels orders if(storefront == "Elastogels"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Approve all Bonanza orders if(storefront == "Bonanza"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Approve all NewEgg orders if(storefront == "Newegg"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Approve all Saunders orders if(storefront == "Saunders"){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], [""]); queueSO = false; return; } //Do Not Approve International Order, Allow Canada Order below 100 if ((!addressUSA && !addressCANADA) || (addressCANADA && (parseFloat(orderTotal) >= 100))) { //Mark order as skip so quick notes is not re-written after initial Intl Order alert currSORec.setFieldValue("custbody_skip_auto_approve", "T"); nlapiLogExecution("debug", "type: " + type + "; soId: " + soId , "NOTICE: Do Not Approve International Order or Canada Order above 100" + "; address: " + shipToAddress); } //Calculate total weight of Order if(addressBlock){ var itemsCount = currSORec.getLineItemCount("item"); //number of line items var totalWeight = 0; var under16oz = false; for (var i = 1; i <= itemsCount; i++) { //var itemName = currSORec.getLineItemText("item","item",i); //Item Name var itemID = currSORec.getLineItemValue("item","item",i); //Item ID var itemType = currSORec.getLineItemValue("item","itemtype",i); if(itemType=="Kit") { var weight = parseFloat(lineitem("kititem",itemID)); if(weight == 0){weight = 1;} //set weight to over 1 lb so auto script does not skip //nlapiLogExecution("debug",customer,i+": "+typeof weight+" "+weight); totalWeight = totalWeight+weight; } if(itemType=="InvtPart") { var qty = currSORec.getLineItemValue("item","quantity",i); var weight = parseFloat(lineitem("inventoryitem",itemID)) * qty; if(weight == 0){weight = 1;} //set weight to over 1 lb so auto script does not skip //nlapiLogExecution("debug",customer,i+": "+typeof weight+" "+weight); totalWeight = totalWeight+weight; } } //nlapiLogExecution("debug",itemsCount,"total: "+totalWeight.toFixed(2)); if(totalWeight < 1) { //nlapiLogExecution("debug",customer,"total weight under 1 lb: "+totalWeight); under16oz = true; } } //Approve if HI/AK/PR under 16oz var underHIAK = addressBlock && under16oz; if(underHIAK){ currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["HI/AK/PR under 16oz"]); queueSO = false; return; } //nlapiLogExecution("debug", "underHIAK", underHIAK); var discount = currSORec.getFieldValue("discounttotal"); var surcharge = false; if(discount > 0) { nlapiLogExecution('debug','fieldChanged','discount more than 0 - do not send task'); surcharge = true; } //Ignore if HI/AK/PR over 16oz or Intl with $0 shipping var overHIAK = addressBlock && (!under16oz); //nlapiLogExecution("debug", "overHIAK", overHIAK); var chargesINTL = !addressUSA && currSORec.getFieldValue("altshippingcost") == 0; //nlapiLogExecution("debug", "chargesINTL", chargesINTL); //if(((addressBlock && (!under16oz)) || (!addressUSA && currSORec.getFieldValue("altshippingcost") == 0))) { if(overHIAK || chargesINTL){ /* //close order to get shipping quote for HI/AK and international addresses var items = currSORec.getLineItemCount('item'); for(var i = 1; i <= items; i++) { var itemType = currSORec.getLineItemValue('item','itemtype',i); if(itemType == "InvtPart") { currSORec.selectLineItem('item',i); currSORec.setCurrentLineItemValue('item','isclosed','T'); currSORec.commitLineItem('item'); } } nlapiLogExecution("debug", soId, "CLOSED for additional shipping charges"); */orderChanged = true; if(!surcharge) { /* //send task to 9 (Adams, Timonthy M) newTask = nlapiCreateRecord('task'); newTask.setFieldValue('owner', 9); newTask.setFieldValue('title', 'Please contact customer in regards to shipping quote'); newTask.setFieldValue('assigned', 9); newTask.setFieldValue('company', customerID); newTask.setFieldValue('transaction', soId); nlapiSubmitRecord(newTask, true);*/ } currSORec.setFieldValue(["custbody_skip_auto_approve","custbody_approval_status"], ["T","May Need Extra Shipping Charges"]); nlapiLogExecution("debug", soId, "IGNORE: Order is Pending Approval for extra shipping charges"); } //Block Professional Orders using Promo Codes var pricelevel = custRec.getFieldValue('pricelevel'); if(pricelevel == 7){ //7 = Professional Price Level //nlapiLogExecution("debug", customer, 'pricelevel: ' + pricelevel); if(!isEmpty(currSORec.getFieldValue('couponcode')) && !isEmpty(currSORec.getFieldValue('promocode'))){ nlapiLogExecution("debug", "soId: " + soId +"; "+ customer, 'IGNORE: Professional order using promotions'); currSORec.setFieldValue("custbody_approval_status", "IGNORE: Professional order using promotions"); currSORec.setFieldValue("custbody17", "Professional order using promotions"); currSORec.setFieldValue("custbody_skip_auto_approve", "T"); orderChanged = true; } } //Quick Notes for ARX orders var orderTotalArx = parseInt(currSORec.getFieldValue('total')); //dLog('orderTotal= ', 'Order Total= ' + orderTotal); var storeFront = currSORec.getFieldValue('custbodystorefront'); //dLog('storefront: ', 'storeFront= '+storeFront); if(storeFront == 'Arx' || storeFront == 'ARX') { if(orderTotalArx > 100) { //dLog('Arx Order: ', 'Arx Order: ' + soId + ' Arx Order with total of '+ orderTotalArx +'exceeds $100. Could not auto approve at this time.'); currSoRec.setFieldValue('custbody72', 'SO Auto Approval: Total exceeds $100. Could not run auto approval on this SO.'); orderChanged = true; } else if(orderTotalArx <= 100) { //dLog('Arx Order: ', 'Arx Order: ' + soId + ' Arx Order with total of ' + orderTotalArx + '. Auto approved.'); currSoRec.setFieldValue('custbody72', 'SO Auto Approval: Total is less than $100. Auto approval ran on this SO.'); orderChanged = true; } } //Ignore PTS orders with Express or UPS Shipping var expressOrders = currSORec.getFieldValue('custbody_expressorder'); var shipVia = currSORec.getFieldValue('custbody_expressorder'); var shipMethods = [101486, 273, 101488,278,24362,101487,275,183396,254200,254199]; //Ship Methods: 101486 - UPS 2nd Day Air, 273 - UPS 2nd Day Air®, 101488 - UPS 3 Day Select, 278 - UPS 3 Day Select® //24362 - UPS Ground Shipping, 183396 - UPS® Ground, 101487 - UPS Next Day Air, 275 if(isEmpty(storefront)) { if(expressOrders == 'T' || (shipMethods.indexOf(shipVia) > 0)) { nlapiSubmitField("salesorder", soId, ["custbody_skip_auto_approve",'custbody50'], ["T",'Express or UPS shipping']); return; } } /*var googlefinancialstate = currSORec.getFieldText('gcofinancialstate'); if(!isEmpty(googlefinancialstate)) { if(googlefinancialstate == 'PAYMENT_DECLINED') { currSORec.setFieldValue('custbody17', 'Google Payment Declined'); orderChanged = true; //send task to self for testing purposes newTask = nlapiCreateRecord('task'); newTask.setFieldValue('owner', 264861); newTask.setFieldValue('title', 'Check Google Payment Declined Script'); newTask.setFieldValue('assigned', 264861); newTask.setFieldValue('company', customerID); newTask.setFieldValue('transaction', soId); nlapiSubmitRecord(newTask, true); } }*/ if(orderChanged){ var id = nlapiSubmitRecord(currSORec, true); return; } //Do not auto-approve if SO is already tagged as skip var skipAutoApprove = currSORec.getFieldValue("custbody_skip_auto_approve"); if (skipAutoApprove == "T") { nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; currStatus: " + currStatus + ";" , "IGNORE:skip queue record creation (custbody_skip_auto_approve = T)."); return; } //Do not auto-approve if SO was Pending Fulfillment and rolled back to Pending Approval if (type == "edit") { var oldSOREC = nlapiGetOldRecord(); var oldStatus = oldSOREC.getFieldValue("orderstatus"); if (oldStatus == "B" && currStatus == "A") { nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; oldStatus: " + oldStatus + "; currStatus: " + currStatus + ";" , "IGNORE:SO was already approved (Pending Fulfillment) and rolled back to Pending Approval. Tagging SO custbody_skip_auto_approve = T and delete SO in queue."); //remove SO approval status nlapiSubmitField("salesorder", soId, ["custbody_skip_auto_approve", "custbody_approval_status"], ["T", ""]); deleteQueue(soId); return; } } var arrCreditCards = ['Master Card', 'Visa', 'Discover', 'American Express']; var arrAutoApprovedPayTypes = ['PayPal', 'Medibod Paypal', 'Buy.com Payment', 'Sears Payment', 'Newegg Payment', 'Jet Payment', 'Walmart Payment', 'SHOP.COM Payment', 'Shopify Payment - ProHealth', 'Wish.com Payment', /*'GoogleCheckout', 'Authorize.net V/M', 'Authorize.net Discover'*/]; var isCCType = false; var isOtherType = false; var cleanPaymentMethod = paymentMethod.toLowerCase(); cleanPaymentMethod = cleanPaymentMethod.replace(/ /gi,""); //Check payment type is valid Credit Card for (x in arrCreditCards) { //clean string var cleanCreditCards = arrCreditCards[x].toLowerCase(); cleanCreditCards = cleanCreditCards.replace(/ /gi,""); if (cleanCreditCards.indexOf(cleanPaymentMethod) > -1) { isCCType = true; break; } } //Check payment type is valid non-Credit Card for (x in arrAutoApprovedPayTypes) { //clean string var cleanPayTypes = arrAutoApprovedPayTypes[x].toLowerCase(); cleanPayTypes = cleanPayTypes.replace(/ /gi,""); if (cleanPayTypes.indexOf(cleanPaymentMethod) > -1) { isOtherType = true; break; } } var logMsg = "customerID = " + customerID + "; " + "paymentMethod = " + paymentMethod + "; " + "isCCType = " + isCCType + "; " + "orderTotal = " + orderTotal + "; " + "isOtherType = " + isOtherType; var isCSCMatch = ""; var billTo = currSORec.getFieldValue("billaddress"); billTo = billTo.replace( /\s\s+/g, ' ' ); var shipTo = currSORec.getFieldValue("shipaddress"); shipTo = shipTo.replace( /\s\s+/g, ' ' ); var isAVSSTMatch = ""; var isAVSZipMatch = ""; //Auto approve all SO taken by phone with sales rep (if address match and under $150) /*var soCallIn = currSORec.getFieldText('salesrep'); if (!isEmpty(soCallIn)) { if ((parseFloat(orderTotal) < 150) && (billTo == shipTo)) { currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["Call-In Order"]); queueSO = false; return; } }*/ //Approve Canada orders under $50 with 3 Ys if(addressCANADA && parseFloat(orderTotal) < 50) { if(isCCType) { isCSCMatch = currSORec.getFieldValue('ccsecuritycodematch'); isAVSSTMatch = currSORec.getFieldValue('ccavsstreetmatch'); isAVSZipMatch = currSORec.getFieldValue('ccavszipmatch'); if (isAVSSTMatch == 'Y' && isAVSZipMatch == 'Y' && isCSCMatch == 'Y') queueSO = true; nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + "; orderTotal: " + orderTotal + ";" , "CANADA order approved"); } } //Approve all PayPal Orders (moved from line 623) if(paymentMethod == "PayPal") { currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["PayPal = Auto Approve"]); queueSO = false; return; } //Basic CC criteria to approve if(isCCType) { isCSCMatch = currSORec.getFieldValue('ccsecuritycodematch') isAVSSTMatch = currSORec.getFieldValue('ccavsstreetmatch'); isAVSZipMatch = currSORec.getFieldValue('ccavszipmatch'); //if (parseFloat(orderTotal) < 50) //Approve CC orders under $50 if CSC=Y //{ // if (isCSCMatch == 'Y' /*&& (billTo == shipTo)*/) queueSO = true; //} if (parseFloat(orderTotal) < 150) //Approve CC orders under $150 if 3 Ys and billTo=shipTo { if (isAVSSTMatch == 'Y' && isAVSZipMatch == 'Y' && isCSCMatch == 'Y' && (billTo == shipTo)) queueSO = true; } } else if(isOtherType) //Approve any nonCC payment type orders { queueSO = true; } else { if(paymentMethod.match(/amazon/gi) != null) queueSO = true; } logMsg += " queueSO="+queueSO+ " isCSCMatch = " + isCSCMatch + "; " + "billTo = " + billTo + "; " + "shipTo = " + shipTo + "; " + "isAVSSTMatch = " + isAVSSTMatch + "; " + "isAVSZipMatch = " + isAVSZipMatch; nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + ";", logMsg); //Ignore if CC is 3 Ns and sends customer email Incorrect Credit Card Information if (isAVSSTMatch == 'N' && isAVSZipMatch == 'N' && isCSCMatch =='N') { dLog('NON MATCH - ALL N'); //if (!isEmpty(currSORec.getFieldValue('source'))) //{ var customerEmail = currSORec.getFieldValue("email"); var sbj = 'Order Closed Due to Incorrect Credit Card Information - Pro Therapy Supplies'; var msg = "We at Pro Therapy Supplies are emailing you to inform you that your order, "+currSORec.getFieldValue('tranid')+" has been temporarily closed due to mismatch credit card information." +" If you feel we have mistakenly flagged your order please contact us at your earliest convenience." +"\n\nIf you have any further questions, please reply to this email or call us at 1-800-883-0368." +"\n\nThank you for choosing Pro Therapy Supplies, we appreciate your business." +"\n\nKind Regards," +"\nPro Therapy Supplies" +"\n800-883-0368" +"\n\nNotice: This electronic message and attachment(s), if any, contains information from Pro Therapy Supplies that may be privileged and confidential. The information is intended to be for the use of the addressee only. If you are not the addressee, note that any disclosure, copying, distribution or use of the contents of this message is prohibited. If you received this message in error, please notify the sender immediately."; if(!checkEmail(soId,'INCORRECT CREDIT CARD INFORMATION')) { nlapiSendEmail(15525639, customerEmail, sbj, msg, null,null, null, null, true); } nlapiSubmitField("salesorder", soId, ["custbody_skip_auto_approve", "custbody51", "custbody50"], ["T", 75, "All Incorrect Credit Card Information"]); return; //} } //Ignore if CC is 2 or 3 Xs var ccX = 0; if(isAVSSTMatch == 'X') { ccX += 1; } if(isAVSZipMatch == 'X') { ccX += 1; } if(isCSCMatch == 'X') { ccX += 1; } if(ccX >= 2) { dLog('NO INFO - 2 or 3 X'); nlapiSubmitField("salesorder", soId, ["custbody_skip_auto_approve", "custbody51", "custbody50"], ["T", 75, "Some Credit Card Information is Incorrect"]); return; } //Approve all SO created from Estimate var createdFrom = currSORec.getFieldText('createdfrom') || ''; if (!isEmpty(createdFrom) && createdFrom.indexOf('Estimate') > -1) { dLog('Auto Approve Estimate'); nlapiSubmitField("salesorder", soId, ["custbody_approval_status","orderstatus"], ["Created From = Estimate","B"]); queueSO = false; return; } //if(customerID == 6679428) //{ var paymenteventresult = currSORec.getFieldValue('paymenteventresult'); //dLog('paymenteventresult','paymenteventresult='+paymenteventresult); //nlapiSubmitField("salesorder", soId, ["custbody32"], ["paymenteventresult="+paymenteventresult]); if(paymenteventresult == 'HOLD') { currSORec.setFieldValue("custbody32", "paymenteventresult="+paymenteventresult); nlapiSubmitRecord(currSORec, true, true); queueSO = false; } //} //Approve all PTS Orders under $1000 and billTo=shipTo and paymentevent!=HOLD /*if (storefront == "" || storefront == "Magento-protherapysupplies") { if (((parseFloat(orderTotal) < 1000) && (billTo == shipTo) && paymenteventresult != 'HOLD' )) { currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["Under $1000 with Billing = Shipping"]); queueSO = false; return; } }*/ //Approve all Orders through UI under $1000 and billTo=shipTo - PLACE AFTER PAYMENT HOLD if(isEmpty(currSORec.getFieldValue('source'))) { if ((parseFloat(orderTotal) < 1000) && (billTo == shipTo)) { currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["Call-In Order"]); queueSO = false; return; } } //Approve all Orders through UI from any marketplace if(isEmpty(currSORec.getFieldValue('source'))) { if ((storefront != "") && (storefront.search("Magento") == -1)) { currSORec.setFieldValue("orderstatus", "B"); nlapiSubmitRecord(currSORec, true, true); nlapiSubmitField("salesorder", soId, ["custbody_approval_status"], ["Marketplace Order"]); queueSO = false; return; } } //Fraud Detect if(!queueSO){ var fraudMsg = ""; var fraudLvl = 0; if(billTo != shipTo){ fraudMsg += "Billing/Shipping not match\n"; fraudLvl += 25;} if(isEmpty(isAVSSTMatch)) { fraudMsg += "AVS Street blank\n"; fraudLvl += 10;} if(isAVSSTMatch == 'N'){ fraudMsg += "AVS Street match = N\n"; fraudLvl += 10;} if(isAVSSTMatch == 'X'){ fraudMsg += "AVS Street match = X\n"; fraudLvl += 10;} if(isEmpty(isAVSZipMatch)) { fraudMsg += "AVS Zip blank\n"; fraudLvl += 10;} if(isAVSZipMatch == 'N'){ fraudMsg += "AVS Zip match = N\n"; fraudLvl += 10;} if(isAVSZipMatch == 'X'){ fraudMsg += "AVS Zip match = X\n"; fraudLvl += 10;} if(isEmpty(isCSCMatch)) { fraudMsg += "CSC blank\n"; fraudLvl += 30;} if(isCSCMatch == 'N'){ fraudMsg += "CSC match = N\n"; fraudLvl += 30;} if(isCSCMatch == 'X'){ fraudMsg += "CSC match = X\n"; fraudLvl += 30;} if(parseFloat(orderTotal) >= 100) { fraudMsg += "Order more than $100\n"; fraudLvl += 10;} if(!addressUSA) { fraudMsg += "International Order\n"; fraudLvl += 15;} nlapiSubmitField("salesorder", soId, ["custbody_skip_auto_approve", "custbody50", "custbody51"], ["T", fraudMsg, fraudLvl]); nlapiLogExecution("debug", "Fraud Detection; soId: " + soId , "IGNORE:"+"Fraud Level %: "+fraudLvl+"; Potential Fraud: "+fraudMsg); return; } if(queueSO) { nlapiLogExecution("debug", "queued", "soId: " + soId); queueApproval(soId, currSORec.getFieldValue("entity"), shipTo) } else { nlapiLogExecution("debug", "type: " + type + "; soId: " + soId + ";" , "IGNORE:did all the test and queue record not created."); } } catch (err) { var stErrMsg = ''; if (err.getDetails != undefined) { stErrMsg = 'Script Error: ' + err.getCode() + '<br>' + err.getDetails() + '<br>' + err.getStackTrace(); } else { stErrMsg = 'Script Error: ' + err.toString(); } nlapiLogExecution("debug","Script Error", stErrMsg); } } function checkForBackorder(soRec) { var hasBackorder = false; var lineItemCount = soRec.getLineItemCount("item"); for(i = 1; i <= lineItemCount; i++) { var boQty = soRec.getLineItemValue("item", "quantitybackordered", i); if (!isEmpty(boQty)) { if (parseFloat(boQty) > 0) { hasBackorder = true; break; } } } return hasBackorder; } function deleteQueue(soId) { var filters = [ new nlobjSearchFilter("custrecord_sopaq_sales_order", null, "anyof", soId) , new nlobjSearchFilter("isinactive", null, "is", "F") ]; var searchResult = nlapiSearchRecord("customrecord_so_pendingapproval_queue", null, filters, null); if (searchResult != null && searchResult.length > 0) { for (var i = 0; i < searchResult.length; i++) { var queueId = searchResult[i].getId(); nlapiSubmitField("customrecord_so_pendingapproval_queue", queueId, ["isinactive", "custrecord_sopaq_remarks"] , ["T", "Skip this. SO reverted to Pending Fulfillment by user."] ) nlapiLogExecution("debug", "deleteQueue", "queueId " + queueId + " marked as deleted."); } } } function queueApproval(soId, customerId, shipTo) { var filters = [ new nlobjSearchFilter("custrecord_sopaq_sales_order", null, "anyof", soId) , new nlobjSearchFilter("isinactive", null, "is", "F") ]; var searchResult = nlapiSearchRecord("customrecord_so_pendingapproval_queue", null, filters, null); if (searchResult != null && searchResult.length > 0) { nlapiLogExecution("debug", "queueApproval", "SO " + soId + " already in the queue"); } else { var tranDate = getGMTServerDate(); var yyyy = tranDate.getFullYear(); var MM = tranDate.getMonth() + 1; var dd = tranDate.getDate(); var HH = tranDate.getHours(); var mm = tranDate.getMinutes(); var utc = Math.round(new Date().getTime()/1000.0); var batchNo = 1; if (mm >= 0 && mm <= 29) batchNo = 2; // check if customer is already in the queue var sequenceNo = customerId + "_" + yyyy + MM + dd + "_" + HH + "0" + batchNo; // should be customerid_yyyymmdd_HH0batch var hasDuplicate = getDuplicateQueue(sequenceNo, shipTo); var queueRec = nlapiCreateRecord("customrecord_so_pendingapproval_queue"); queueRec.setFieldValue("name", sequenceNo); queueRec.setFieldValue("custrecord_sopaq_sales_order", soId); queueRec.setFieldValue("custrecord_sopaq_creation_batch", batchNo); queueRec.setFieldValue("custrecord_sopaq_date_created_utc", utc); var queueId = nlapiSubmitRecord(queueRec, true); var soApprovalStatus = "In Queue"; if (hasDuplicate) soApprovalStatus = "Duplicate"; // tag SO approval status as IN QUEUE nlapiSubmitField("salesorder", soId, "custbody_approval_status", soApprovalStatus); nlapiLogExecution("debug", "queueApproval", "soId: " + soId + "; batchNo: " + batchNo + "; queueId: " + queueId + "; utc: " + utc + ";") } } function getDuplicateQueue(sequenceNo, shipTo) { try { var hasDuplicate = false; var filters = [ new nlobjSearchFilter("name", null, "is", sequenceNo) , new nlobjSearchFilter("custrecord_sopaq_processed", null, "is", "F") , new nlobjSearchFilter("mainline", "custrecord_sopaq_sales_order", "is", "T") ]; var columns = [ new nlobjSearchColumn("custrecord_sopaq_sales_order") , new nlobjSearchColumn("shipaddress", "custrecord_sopaq_sales_order") ]; var searchResult = nlapiSearchRecord("customrecord_so_pendingapproval_queue", null, filters, columns); if (searchResult != null && searchResult.length > 0) { for (var i = 0; i < searchResult.length; i++) { var soId = searchResult[i].getValue("custrecord_sopaq_sales_order"); var soShipTo = searchResult[i].getValue("shipaddress", "custrecord_sopaq_sales_order"); if (shipTo == soShipTo) { nlapiSubmitField("salesorder", soId, "custbody_approval_status", "Duplicate"); hasDuplicate = true; } } } return hasDuplicate; } catch (ex) { var message = (ex instanceof nlobjError) ? ex.getStackTrace() + ": " + ex.getCode() + " " + ex.getDetails() : ex.toString(); nlapiLogExecution("error", "getDuplicateQueue", message); throw ex; } } function lineitem(type,id) { if(type == "kititem") { var kit = nlapiLoadRecord("kititem",id); var kitItemID = kit.getLineItemValue("member","item",1); var kitqty = kit.getLineItemValue("member","quantity",1); var kitLineItem = nlapiLoadRecord("inventoryitem",kitItemID); var kitweight = kitLineItem.getFieldValue("weight")*kitqty; var kitunits = kitLineItem.getFieldText("weightunit"); if(kitunits == 'oz'){kitweight = kitweight/16; } if(isEmpty(kitweight)){nlapiLogExecution("debug",id,'Item has no weight'); return 0;} //nlapiLogExecution("debug",id,"kitweight: "+kitweight+" "+kitunits); return kitweight; } if(type == "inventoryitem") { var lineItem = nlapiLoadRecord(type,id); var weight = lineItem.getFieldValue("weight"); var units = lineItem.getFieldText("weightunit"); if(units == 'oz'){weight = weight/16;} if(isEmpty(weight)){nlapiLogExecution("debug",id,'Item has no weight'); return 0;} //nlapiLogExecution("debug",id,"weight: "+weight+" "+units); return weight; } } function isEmpty(fldValue) { if (fldValue == '') return true; if (fldValue == 'null') return true; if (fldValue == null) return true; if (fldValue == 'undefined') return true; if (fldValue == undefined) return true; return false; } function getGMTServerDate() { var nowDate = new Date(); var ts = nowDate.getTime(); var offsetSec = nowDate.getTimezoneOffset() * 60000; var gmtTs = ts + offsetSec; return(new Date(gmtTs)); } function sendTask(tranID,customerID,message,userID,title,assignedID,tasktype) { if(userID < 1) { dLog('sendTask userID='+userID+'; soID='+tranID,'Task Sent to Elizabeth Owen instead'); message = message + "\n\nFormer userID="+userID; userID = 264861; } newTask = nlapiCreateRecord('task'); newTask.setFieldValue('owner', userID); newTask.setFieldValue('title', title); newTask.setFieldValue('message', message); newTask.setFieldValue('custevent9', tasktype); newTask.setFieldValue('assigned', assignedID); newTask.setFieldValue('company', customerID); newTask.setFieldValue('transaction', tranID); nlapiSubmitRecord(newTask, true); } function checkEmail(tranID,keyword) { var filters = new Array(); filters[0] = new nlobjSearchFilter('mainline', null, 'is', 'T'); filters[1] = new nlobjSearchFilter('internalid', null, 'is', tranID); var columns = new Array(); columns[0] = new nlobjSearchColumn('subject', 'messages'); var searchresults = nlapiSearchRecord('salesorder', null, filters, columns); for ( var i = 0; searchresults != null && i < searchresults.length; i++ ) { var searchresult = searchresults[i]; var subject = searchresult.getValue('subject', 'messages'); if(subject.toUpperCase().search(keyword) != -1) { dLog('subjectEmail',keyword+' email already sent.'); return true; } //dLog('retrieveMessage',i+': '+subject); } return false; } function containsNumber(str) { var matches = str.match(/\d+/g); if (matches != null) { //has number return true; } else{ //all text return false; } } function loadItem(id) { var recType = nlapiLookupField('item', id, 'recordtype'); return recType; //returns the actual item record field name //lotnumberedinventoryitem //inventoryitem //kititem //serializedinventoryitem } function calcWorth(type, id, rate) { if(type == "kititem") { var kit = nlapiLoadRecord("kititem",id); var kitItemID = kit.getLineItemValue("member","item",1); var kitqty = kit.getLineItemValue("member","quantity",1); var item = nlapiLoadRecord("inventoryitem",kitItemID); } if(type == "inventoryitem") { var item = nlapiLoadRecord(type,id); } var cost = item.getLineItemValue('lastpurchaseprice'); var shiptopts = item.getFieldValue('custitem_vendorshipping'); var shipping = item.getFieldValue('shippingcos'); var threshold = ((cost+shipping+shiptopts)*1.03)*1.27; // cost of item + shipping cost + shipping to us cost + 3% for standard credit card costs and adds 27% profit if (rate <= threshold) // if the price sold is sell it for is less than the threshold dont auto approve and task (create person to task) // to change price, and suggest new price to change to { currSORec.setFieldValue("custbody_skip_auto_approve", "T"); var title = "Item value is too low"; var message = "" // newTask = nlapiCreateRecord('task'); // newTask.setFieldValue('title', title); // newTask.setFieldValue('message', message); // newTask.setFieldValue('assigned', assignedID); // newTask.setFieldValue('company', customerID); // newTask.setFieldValue('transaction', soId); // nlapiSubmitRecord(newTask, true); } return; } function dLog(logTitle, logDetails) { nlapiLogExecution('DEBUG', logTitle, logDetails); }
import React, { Component } from "react"; import SuspectDataService from "../../services/suspect.service"; import UserService from "../../services/user.service"; import Form from "react-validation/build/form"; import Input from "react-validation/build/input"; import TextArea from "react-validation/build/textarea"; import CheckButton from "react-validation/build/button"; import AuthService from "../../services/auth.service"; // import Navigation from "../navigation/navigation" import BurgerNavigation from "../navigation/burger-navigation" import suspect from "../images/suspect.png"; const required = value => { if (!value) { return ( <div className="alert alert-danger" role="alert"> This field is required! </div> ); } }; export default class AddSuspect extends Component { constructor(props) { super(props); this.onChangeSuspectname = this.onChangeSuspectname.bind(this); this.onChangeSuspectAddress = this.onChangeSuspectAddress.bind(this); this.onChangeSuspectContact = this.onChangeSuspectContact.bind(this); this.onChangeSuspectage = this.onChangeSuspectage.bind(this); this.onChangeContact = this.onChangeContact.bind(this); this.onChangeComplaintDescription = this.onChangeComplaintDescription.bind(this); this.onChangeCamefrom = this.onChangeCamefrom.bind(this); this.handleSuspect = this.handleSuspect.bind(this); this.state = { suspectname: "", suspectaddress: "", suspectcontact: "", suspectage: "", contact: "", complaintdescription: "", camefrom: "", errormessage: "", rightcontent: "", wrongcontent: "", successful: false, message: "", submitted: false, currentUser: AuthService.getCurrentUser(), }; } onChangeSuspectname(e) { this.setState({ suspectname: e.target.value }); } onChangeSuspectAddress(e) { this.setState({ suspectaddress: e.target.value }); } onChangeSuspectage(e) { this.setState({ suspectage: e.target.value }); } onChangeContact(e) { this.setState({ contact: e.target.value }); } onChangeSuspectContact(e) { this.setState({ suspectcontact: e.target.value }); } onChangeComplaintDescription(e) { this.setState({ complaintdescription: e.target.value }); } onChangeCamefrom(e) { this.setState({ camefrom: e.target.value }); } handleSuspect(e) { e.preventDefault(); this.setState({ message: "", successful: false }); this.form.validateAll(); if (this.checkBtn.context._errors.length === 0) { var data = { suspectname: this.state.suspectname, suspectage: this.state.suspectage, suspectcontact: this.state.suspectcontact, suspectaddress: this.state.suspectaddress, contact: this.state.contact, camefrom: this.state.camefrom, complaintdescription: this.state.complaintdescription, currentusername: this.state.currentUser.username, }; SuspectDataService.create(data) .then( response => { this.setState({ message: response.data.message, successful: true }); setTimeout(function () { window.location.reload() }, 3000); }, error => { const resMessage = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); this.setState({ successful: false, message: resMessage }); } ); } } componentDidMount() { UserService.getUserBoard().then( response => { this.setState({ rightcontent: response.data }); }, error => { this.setState({ wrongcontent: (error.response && error.response.data && error.response.data.message) || error.message || error.toString() }); } ); } render() { if (this.state.wrongcontent) { return <div> <BurgerNavigation /> <div className="container custom-container">{this.state.wrongcontent}</div></div> } else { return ( <div> <BurgerNavigation /> <div className="container custom-container"> <h2 className="text-center">Inform about any suspected person here.</h2> <img src={suspect} alt="suspect-one" className="rounded mx-auto d-block img-fluid" /> <div className="col-md-12 user_card"> <Form onSubmit={this.handleSuspect} ref={c => { this.form = c; }}> {!this.state.successful && ( <div> <div className="form-group"> <label htmlFor="suspectname">Full Name of Suspect</label> <Input type="text" className="form-control" id="suspectname" value={this.state.suspectname} onChange={this.onChangeSuspectname} name="suspectname" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="suspectage">Suspect Age(Approximate)</label> <Input type="number" className="form-control" id="suspectage" value={this.state.suspectage} onChange={this.onChangeSuspectage} name="suspectage" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="suspectaddress">Suspect Address</label> <Input type="text" className="form-control" id="suspectaddress" required value={this.state.suspectaddress} onChange={this.onChangeSuspectAddress} name="suspectaddress" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="suspectcontact">Suspect Contact Number</label> <Input type="text" className="form-control" id="suspectcontact" required value={this.state.suspectcontact} onChange={this.onChangeSuspectContact} name="suspectcontact" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="camefrom">Did suspect return from aboard or been residing in Nepal?</label> <Input type="text" className="form-control" id="camefrom" required value={this.state.camefrom} onChange={this.onChangeCamefrom} name="camefrom" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="contact">Your Contact Number</label> <Input type="text" className="form-control" id="contact" required value={this.state.contact} onChange={this.onChangeContact} name="contact" validations={[required]} /> </div> <div className="form-group"> <label htmlFor="complaintdescription">Additional Description</label> <TextArea type="text" className="form-control" id="complaintdescription" required value={this.state.complaintdescription} onChange={this.onChangeComplaintDescription} name="complaintdescription" validations={[required]}/> </div> <div className="form-group"> <button className="btn btn-success btn-block">Submit</button> </div> </div> )} {this.state.message && ( <div className="form-group"> <div className={ this.state.successful ? "alert alert-success" : "alert alert-danger" } role="alert" > {this.state.message} </div> </div> )} <CheckButton style={{ display: "none" }} ref={c => { this.checkBtn = c; }} /> </Form> </div> </div> </div> ); } } }
import { deletePalette } from './deletePalette'; import { hasError, setMessage } from '../actions'; describe('deletePalette', () => { let mockPalette let mockDispatch let mockMessage beforeEach(() => { mockMessage = 'Deleted palette with id 68' mockPalette = { palette_name: "one", palette_id: 68, project_id: 1, color_1: "#605976", color_2: "#3241f2", color_3: "#dc677", color_4: "#1c1eb5", color_5: "#c54e8b" } mockDispatch = jest.fn() }) it.skip('should dispatch setMessage if the response is okay', async () => { window.fetch = jest.fn().mockImplementation(() => Promise.resolve({ ok: true, json: () => Promise.resolve(mockMessage) })); const thunk = await deletePalette(mockPalette.palette_id) await thunk(mockDispatch) expect(mockDispatch).toHaveBeenCalledWith(setMessage('Deleted palette with id 68')) }) it('should dispatch hasError if the response is not okay', async () => { window.fetch = jest.fn().mockImplementation(() => Promise.resolve({ ok: false, statusText: 'Something went wrong' })); const thunk = await deletePalette(mockPalette.palette_id) await thunk(mockDispatch) expect(mockDispatch).toHaveBeenCalledWith(hasError('Something went wrong')) }) })
import React, { useState, Component, useEffect } from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { makeStyles } from '@material-ui/styles'; import { Card, CardHeader, CardContent, CardActions, Divider, Button, TextField } from '@material-ui/core'; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { loginUser } from "../../../redux/Join/actions"; import classnames from "classnames"; const useStyles = makeStyles(() => ({ root: {} })); const Login = props => { const { className,staticContext, ...rest } = props; const classes = useStyles(); const [errors, setErrors] = useState({}); const [userName, setUserName] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { // If logged in and user navigates to Login page, should redirect them to dashboard if (props.auth.isAuthenticated) { props.history.push("/dashboard"); } },[]) /* componentWillReceiveProps(nextProps) { if (nextProps.auth.isAuthenticated) { this.props.history.push("/dashboard"); // push user to dashboard when they login } if (nextProps.errors) { this.setState({ errors: nextProps.errors, }); } }*/ const onChange = (e) => { //setState({ [e.target.id]: e.target.value }); }; const onSubmit = (e) => { e.preventDefault(); const userData = { userName: userName, password: password, }; console.log(userData); this.props.loginUser(userData); // since we handle the redirect within our component, we don't need to pass in this.props.history as a parameter }; return ( <Card {...rest} className={clsx(classes.root, className)} > <form noValidate onSubmit={onSubmit}> <CardHeader subheader="Login" title="Login" /> <Divider /> <CardContent> <TextField fullWidth label="Username" name="Username" onChange={event => setUserName(event.target.value)} id="userName" type="text" value={userName} error={errors.userName} variant="outlined" helperText={errors.userName + ""+ errors.credentialsnotfound} className={classnames("", { invalid: errors.userName || errors.credentialsnotfound, })} /> <TextField fullWidth label="Password" name="password" style={{ marginTop: '1rem' }} variant="outlined" onChange={event => setPassword(event.target.value)} value={password} error={errors.password} id="password" type="password" className={classnames("", { invalid: errors.password || errors.passwordincorrect, })} helperText= {errors.password + " "+ errors.passwordincorrect} /> </CardContent> <Divider /> <CardActions> <Button color="primary" variant="outlined" > Login </Button> <Link to="/forgot"> Forgotten Password?</Link> </CardActions> </form> </Card> ); } Login.propTypes = { loginUser: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors, }); export default connect(mapStateToProps, { loginUser })(Login);
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'mydb'; // Database name const colName = 'products'; const client = new MongoClient(url); // Define a sequence of db operations const docArray = [ { id: 1, name: "Thor T-Shirt", description: "T-Shirt with Marvel's Thor's logo.", price: 29.99, units: 33 }, { id: 2, name: "Captain America T-Shirt", description: "T-Shirt with Marvel's Captain America's logo.", price: 24.99, units: 50 }, { id: 3, name: "Ironman T-Shirt", description: "T-Shirt with Marvel's Ironman's logo.", price: 19.99, units: 45 } ] const queryJSONf = {} const queryJSONup = { id: 2 }; const updateJSON = { id: 4 }; const queryJSONdel = { id: 3 }; const add = require('./add'); const update = require('./update'); const remove = require('./remove'); const read = require('./read'); const dbOperations = function(client, col) { add.insertDocuments(col, docArray, () => { update.updateDocument(col, queryJSONup, updateJSON, () => { remove.removeDocument(col, queryJSONdel, () => { read.findDocuments(col, queryJSONf, () => { client.close(); }) }) }) }); }; // Use connect method to connect to the Server client.connect(function(err) { console.log("Connected successfully to server"); const db = client.db(dbName); const collection = db.collection(colName); dbOperations(client, collection); });
import Sequelize from 'sequelize' import db from '../connect' const Story = db.define( 'story', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true }, title: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, description: { type: Sequelize.TEXT, allowNull: false, defaultValue: '' }, template: { type: Sequelize.ENUM, values: ['scroller', 'slider', 'original'], defaultValue: 'original' }, visibility: { type: Sequelize.ENUM, values: ['published', 'draft'], defaultValue: 'draft' }, creatorId: { type: Sequelize.UUID }, localId: { type: Sequelize.STRING, allowNull: false, defaultValue: '' }, slug: { type: Sequelize.STRING, allowNull: false } // organizationId:{ // type: Sequelize.UUID, // references: { // model: 'organization', // key: 'id' // }, // onDelete: 'CASCADE', // onUpdate: 'CASCADE' // // }, // previewImageId:{ // type: Sequelize.UUID, // references: { // model: 'image', // key: 'id' // }, // allowNull: true, // onDelete: 'SET NULL', // onUpdate: 'CASCADE' // } }, { freezeTableName: true } ) export default Story
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var color = "red" ctx.beginPath() ctx.strokeStyle=color ctx.lineWidth = 4 ctx.arc(300,200,40,0, 2*Math.PI) ctx.stroke() canvas.addEventListener("mousedown", my_mousedown) function my_mousedown (e) { mouse_x = e.clientX-canvas.offsetLeft; mouse_y = e.clientY-canvas.offsetTop; circle(mouse_x, mouse_y); color = document.getElementById("buttoncolor").value } function circle(mouse_x, mouse_y){ ctx.beginPath(); ctx.strokeStyle=color ctx.lineWidth = 4; ctx.arc(mouse_x, mouse_y,40,0, 2*Math.PI); ctx.stroke() }
const seaspec = require("../objects/abilitys/seaspec"); function seaspecuse(aobjids, entities, creator) { if (entities[creator] != undefined) { if (!entities[creator].isdead) { entities[creator].usingability = true var objids = aobjids.giveid(true); var a = new seaspec(entities, objids, entities[creator].id, entities[creator].x, entities[creator].y) entities[objids] = a; entities[objids].radius = entities[creator].radius * 3.5 } } } seaspecuse.prototype = {} module.exports = seaspecuse
 (function Component (id) {// @lock // Add the code that needs to be shared between components here function constructor (id) { // @region beginComponentDeclaration// @startlock var $comp = this; this.name = 'Manufacturer'; // @endregion// @endlock this.load = function (data) {// @lock // @region namespaceDeclaration// @startlock var modelsEvent = {}; // @dataSource var bModel_Add = {}; // @buttonImage var bModel_Delete = {}; // @buttonImage var bMan_Delete = {}; // @buttonImage var bMan_Add = {}; // @buttonImage var dataGrid1 = {}; // @dataGrid var bModel_OK = {}; // @button var bModel_Cancel = {}; // @button var bMan_Cancel = {}; // @button var bMan_OK = {}; // @button // @endregion// @endlock $('#'+getHtmlId('dataGrid2')+' .waf-dataGrid-body').css("overflow-x","hidden"); $('#'+getHtmlId('dialog1')+' .waf-dialog-header-buttons').hide(); $('#'+getHtmlId('dialog2')+' .waf-dialog-header-buttons').hide(); $comp.sourcesVar.arr_Sample = $comp.sources.p_Model.sampleToArray(); $comp.sources.arr_Sample.sync(); var prevManufacturerID; var prevModelID; // eventHandlers// @lock modelsEvent.onCollectionChange = function modelsEvent_onCollectionChange (event)// @startlock {// @endlock var result = $comp.sources.models.getEntityCollection(); $comp.sources.p_Model.setEntityCollection(result); };// @lock bModel_Add.click = function bModel_Add_click (event)// @startlock {// @endlock prevModelID = $comp.sources.p_Model.getKey(); $comp.widgets.t_Model_Warning.hide(); $comp.widgets.t_Model_Header.setValue('New Model '); $comp.sources.p_Model.newEntity(); $comp.widgets.dialog2.displayDialog(); };// @lock bModel_Delete.click = function bModel_Delete_click (event)// @startlock {// @endlock $comp.sources.p_Model.removeCurrent({ onError : function (event) { alert('Error encountered'); } }); };// @lock bMan_Delete.click = function bMan_Delete_click (event)// @startlock {// @endlock $comp.sources.p_Manufacturer.removeCurrent({ onError : function (event) { alert('Error encountered'); } }); };// @lock bMan_Add.click = function bMan_Add_click (event)// @startlock {// @endlock prevManufacturerID = $comp.sources.p_Manufacturer.getKey(); $comp.widgets.t_Man_Warning.hide(); $comp.widgets.dialog1.displayDialog(); $comp.widgets.t_Man_Header.setValue('New Manufacturer'); $comp.sources.p_Manufacturer.newEntity(); };// @lock dataGrid1.onRowDblClick = function dataGrid1_onRowDblClick (event)// @startlock {// @endlock $comp.widgets.dialog1.displayDialog(); };// @lock bModel_OK.click = function bModel_OK_click (event)// @startlock {// @endlock $comp.sources.p_Model.manufacturer.set ($comp.sources.p_Manufacturer); $comp.sources.p_Model.save({ onSuccess : function (event) { $comp.widgets.t_Model_Warning.hide(); $comp.sources.p_Model.addEntity($comp.sources.p_Model.getCurrentElement()); $comp.widgets.dialog2.closeDialog(); }, onError : function (event) { $comp.widgets.t_Model_Warning.setValue(event.error[0].message); $comp.widgets.t_Model_Warning.show(); } }); };// @lock bModel_Cancel.click = function bModel_Cancel_click (event)// @startlock {// @endlock $$(getHtmlId("dialog2")).closeDialog(); //cancel button $comp.sources.p_Model.selectByKey(prevModelID); };// @lock bMan_Cancel.click = function bMan_Cancel_click (event)// @startlock {// @endlock $$(getHtmlId("dialog1")).closeDialog(); //cancel button $comp.sources.p_Manufacturer.selectByKey(prevManufacturerID); };// @lock bMan_OK.click = function bMan_OK_click (event)// @startlock {// @endlock $comp.sources.p_Manufacturer.save({ onSuccess : function (event) { $comp.widgets.t_Man_Warning.hide(); $comp.sources.p_Manufacturer.addEntity($comp.sources.p_Manufacturer.getCurrentElement()); $comp.widgets.dialog1.closeDialog(); }, onError : function (event) { $comp.widgets.t_Man_Warning.show(); } }); //$$(getHtmlId("dialog1")).closeDialog(); //ok button };// @lock // @region eventManager// @startlock WAF.addListener(this.id + "_models", "onCollectionChange", modelsEvent.onCollectionChange, "WAF"); WAF.addListener(this.id + "_bModel_Add", "click", bModel_Add.click, "WAF"); WAF.addListener(this.id + "_bModel_Delete", "click", bModel_Delete.click, "WAF"); WAF.addListener(this.id + "_bMan_Delete", "click", bMan_Delete.click, "WAF"); WAF.addListener(this.id + "_bMan_Add", "click", bMan_Add.click, "WAF"); WAF.addListener(this.id + "_dataGrid1", "onRowDblClick", dataGrid1.onRowDblClick, "WAF"); WAF.addListener(this.id + "_bModel_OK", "click", bModel_OK.click, "WAF"); WAF.addListener(this.id + "_bModel_Cancel", "click", bModel_Cancel.click, "WAF"); WAF.addListener(this.id + "_bMan_Cancel", "click", bMan_Cancel.click, "WAF"); WAF.addListener(this.id + "_bMan_OK", "click", bMan_OK.click, "WAF"); // @endregion// @endlock };// @lock }// @startlock return constructor; })();// @endlock
const express = require('express') const bodyParser = require('body-parser') const router = express.Router() module.exports = router const db = require('../db') var csrf = require('csurf') const MIN_DESCRIPTION_LENGTH = 1 const MIN_NAME_LENGTH = 1 var csrfProtection = csrf() function getValidationErrorsForProject(name, description) { const validationError = [] if (name.length <= MIN_NAME_LENGTH) { validationError.push("Name should contain at least " + MIN_NAME_LENGTH + " character") } if (description.length <= MIN_DESCRIPTION_LENGTH) { validationError.push("Description should contain at least " + MIN_DESCRIPTION_LENGTH + " characters") } return validationError } router.get('/portfolio',csrfProtection, function (request, response) { const isLoggedIn = request.session.isLoggedIn db.getAllProjects(function (error, projects){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"}) console.log(error) } else { const model = { projects, isLoggedIn, title: "Portfolio page", csrfToken: request.csrfToken(), } response.render("portfolio.hbs", model) } }) }) router.post('/portfolio', csrfProtection,function (request, response) { const isLoggedIn = request.session.isLoggedIn const name = request.body.name const description = request.body.description const validationError = getValidationErrorsForProject(name, description); if(validationError.length == 0){ db.createProject(name, description, function(error){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not insert data into database, try again later"}) console.log(error) } else { response.redirect('/project/portfolio') } }) }else{ db.getAllProjects(function(error, projects){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"}) console.log(error) } else { const model = { validationError, projects, isLoggedIn, title: "Portfolio page" } response.render("portfolio.hbs", model) } }) } }) router.post('/delete/:id', function (request, response) { const id = request.params.id db.deleteProjectsById(id, function(error){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not delete data from database, try again later"}) console.log(error) } else { response.redirect('/project/portfolio') } }) }) router.get('/update/:id', csrfProtection,function (request, response) { /*if(request.session.isLoggedIn){ const model = { validationError: [], title: "Update guestbook page", } response.render('update-gpost.hbs', model) }else{ response.redirect("/login") } */ const id = request.params.id const isLoggedIn = request.session.isLoggedIn db.getProjectById(id, function(error, project){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"}) console.log(error) } else { const model = { project, title: "Update project page", isLoggedIn, csrfToken: request.csrfToken(), } response.render('update-project.hbs', model) } }) }) router.post('/update/:id',csrfProtection, function (request, response) { const id = request.params.id const newName = request.body.name const newDescription = request.body.description /*const validationError = getValidationErrorsForPost(newTitle, newContent) if (!request.session.isLoggedIn) { validationError.push("You have to login to update a project.") }*/ const validationError = getValidationErrorsForProject(newName, newDescription) if (!request.session.isLoggedIn) { validationError.push("You have to login to update a project post.") } if(validationError.length == 0){ db.updateProjects(newName, newDescription, id, function(error){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not update data into database, try again later"}) console.log(error) } else { response.redirect("/project/portfolio") } }) }else{ const model = { project: { id, name: newName, description: newDescription }, validationError, title: "Update portfolio post" } response.render('update-gpost.hbs', model) } }) router.get('/:id', function (request, response) { const id = request.params.id const isLoggedIn = request.session.isLoggedIn db.getProjectById(id, function(error, project){ if (error) { response.render('errorMessage.hbs', {errorMessage: "Could not select data from database, try again later"}) console.log(error) } else { const model = { project, title: "Details page", isLoggedIn, } response.render('project.hbs', model) } }) })
version="prealpha 3.4 - 0.1" baseRessList = [ "Hide", "Ore", "Stone", "Wood", "Meat", ] hideList=[ "Bear", "Cat", ] oreList=[ "Gold", "Silver", "Tin", "Copper", ] stoneList=[ "Alpha", "Beta", "Gamma", ] woodList=[ "Oak", "Birch", "Spruce", "Ash", "Yew", ] meatList=[ "Apple", "Worm", ] function getBaseList(name){ switch(name) { case "Hide": return hideList; case "Ore": return oreList; case "Stone": return stoneList; case "Wood": return woodList; case "Meat": return meatList; default: alert("no base list"); } } recipeList=[ { groupName:"Basic Runestools", draw:false, list:[ ] }, { groupName:"Basic Weapons", draw:false, list:[ ] }, { groupName:"Survivalist", draw:false, list:[ ] }, { groupName:"Runes", draw:false, list:[ { name:"Book Chapter", ingredient:[ {name:"Stitched Leather", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Stone", qte:3, obl:false}, ] }, { name:"Runestone: Advanced Harvesting Tools", ingredient:[ {name:"Sigil", qte:1, obl:true}, {name:"Wood Runestone Blank", qte:1, obl:true}, ] }, { name:"Runestone: Death", ingredient:[ {name:"Sigil: Death", qte:1, obl:true}, {name:"Stone Runestone Blank", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Runestone: Life", ingredient:[ {name:"Sigil: Life", qte:1, obl:true}, {name:"Stone Runestone Blank", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, ] }, { groupName:"Rune Components", draw:false, list:[ { name:"Sigil: Axe", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:1, obl:true}, ] }, { name:"Sigil: Death", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:3, obl:true}, ] }, { name:"Sigil: Hammer", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:1, obl:true}, ] }, { name:"Sigil: Knife", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:1, obl:true}, ] }, { name:"Sigil: Life", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:3, obl:true}, ] }, { name:"Sigil: Pick", ingredient:[ {name:"Parchment Paper", qte:1, obl:true}, {name:"Ore", qte:1, obl:true}, ] }, { name:"Specialty Seal", ingredient:[ {name:"Stone", qte:1, obl:true}, {name:"Ore", qte:1, obl:true}, ] }, { name:"Stone Runestone Blank", ingredient:[ {name:"Stone", qte:1, obl:true}, {name:"Stone", qte:1, obl:true}, {name:"Stone", qte:1, obl:true}, ] }, { name:"Stone Runestone Blank", ingredient:[ {name:"Wood", qte:1, obl:true}, {name:"Wood", qte:1, obl:true}, {name:"Wood", qte:1, obl:true}, ] }, ] }, { groupName:"Harvesting Potions", draw:false, list:[ ] }, { groupName:"Crafting Potions", draw:false, list:[ ] }, { groupName:"Potions and Flasks", draw:false, list:[ ] }, { groupName:"Fuel", draw:false, list:[ { name:"Carbon", ingredient:[ {name:"Meat", qte:5, obl:true}, ] }, { name:"Coal", ingredient:[ {name:"Wood", qte:1, obl:true}, ] }, ] }, { groupName:"Armor Components", draw:false, list:[ { name:"Armor Layer", ingredient:[ {name:"Ore", qte:2, obl:true}, {name:"Ore", qte:2, obl:true}, {name:"Hide", qte:2, obl:true}, {name:"Fluxing Stone", qte:1, obl:true}, ] }, { name:"Metal Rings", ingredient:[ {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Coal", qte:1, obl:true}, {name:"Specialty Seal", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, ] }, { name:"Metal Sheet", ingredient:[ {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Coal", qte:1, obl:true}, {name:"Specialty Seal", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, {name:"Armor Layer", qte:1, obl:false}, ] }, { name:"Treated Steel", ingredient:[ {name:"Iron", qte:3, obl:true}, {name:"Iron", qte:3, obl:true}, {name:"Carbon", qte:3, obl:true}, ] }, ] }, { groupName:"Weapons Components", draw:false, list:[ { name:"Arrowhead: Crushing", ingredient:[ {name:"Ore", qte:3, obl:true}, ] }, { name:"Arrowhead: Piercing", ingredient:[ {name:"Ore", qte:3, obl:true}, ] }, { name:"Arrowhead: Slashing", ingredient:[ {name:"Ore", qte:3, obl:true}, ] }, { name:"Book Clasp", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Bow Rest", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Bow Sight", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Metal Bar", ingredient:[ {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Ore", qte:3, obl:true}, {name:"Specialty Seal", qte:1, obl:false}, ] }, { name:"Pistol Barrel", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Pistol Body", ingredient:[ {name:"Weapon Grip", qte:1, obl:true}, {name:"Pistol Hammer and Frizzen", qte:1, obl:true}, {name:"Pistol Trigger", qte:1, obl:true}, ] }, { name:"Pistol Hammer and Frizzen", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Pistol Trigger", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Shield Covering", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Staff Heel", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Blade: Long", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Blade: Medium", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Blade: Short", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Blade: Thin", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Crossguard", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Grip", ingredient:[ {name:"Plank/Leather", qte:1, obl:true}, ] }, { name:"Weapon Head: Axe", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Head: Great Axe", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Head: Great Mace", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Head: Mace", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Hilt", ingredient:[ {name:"Weapon Grip", qte:1, obl:true}, {name:"Pommel", qte:1, obl:true}, {name:"Crossguard", qte:1, obl:true}, ] }, { name:"Weapon Hilt: Great", ingredient:[ {name:"Weapon Grip", qte:1, obl:true}, {name:"Pommel", qte:1, obl:true}, {name:"Crossguard", qte:1, obl:true}, ] }, { name:"Weapon Pommel", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Shaft: Long", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Shaft: Medium", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, { name:"Weapon Shaft: Short", ingredient:[ {name:"Metal Bar", qte:1, obl:true}, ] }, ] }, { groupName:"Armor", draw:true, list:[ { name:"Mail Boots", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, { name:"Mail Coif", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, { name:"Mail Gloves", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, { name:"Mail Hauberk", ingredient:[ {name:"Iron", qte:45, obl:true}, {name:"Tin", qte:10, obl:true}, {name:"Hide", qte:20, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Metal Rings", qte:1, obl:false}, {name:"Treated Steel", qte:4, obl:false}, ] }, { name:"Plate Boots", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, { name:"Plate Chest", ingredient:[ {name:"Iron", qte:45, obl:true}, {name:"Tin", qte:10, obl:true}, {name:"Hide", qte:20, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Treated Steel", qte:4, obl:false}, ] }, { name:"Plate Gloves", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, { name:"Plate Helmet", ingredient:[ {name:"Iron", qte:25, obl:true}, {name:"Tin", qte:5, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Reinforced Padding", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Metal Sheet", qte:1, obl:false}, {name:"Treated Steel", qte:2, obl:false}, ] }, ] }, { groupName:"Weapons", draw:true, list:[ { name:"One Handed Mace", ingredient:[ {name:"Weapon Hilt", qte:1, obl:true}, {name:"Weapon Head: Mace", qte:1, obl:true}, {name:"Weapon Shaft: Short", qte:1, obl:true}, ] }, { name:"One Handed Rapier", ingredient:[ {name:"Weapon Hilt", qte:1, obl:true}, {name:"Weapon Blade: Thin", qte:1, obl:true}, ] }, { name:"One Handed Sword", ingredient:[ {name:"Weapon Hilt", qte:1, obl:true}, {name:"Weapon Blade: Long", qte:1, obl:true}, ] }, { name:"Paired Axes", ingredient:[ {name:"Weapon Hilt", qte:2, obl:true}, {name:"Weapon Blade: Axe", qte:2, obl:true}, {name:"Weapon Shaft: Short", qte:2, obl:true}, ] }, { name:"Paired Long Daggers", ingredient:[ {name:"Weapon Hilt", qte:2, obl:true}, {name:"Weapon Blade: Short", qte:2, obl:true}, ] }, { name:"Paired Maces", ingredient:[ {name:"Weapon Hilt", qte:2, obl:true}, {name:"Weapon Head: Mace", qte:2, obl:true}, {name:"Weapon Shaft: Short", qte:2, obl:true}, ] }, { name:"Pistol", ingredient:[ {name:"Pistol Body", qte:1, obl:true}, {name:"Pistol Barrel", qte:1, obl:true}, ] }, { name:"Shield", ingredient:[ {name:"Shield Covering", qte:1, obl:true}, {name:"Shield Base", qte:1, obl:true}, {name:"Enarmes", qte:1, obl:true}, ] }, { name:"Two Handed Axe", ingredient:[ {name:"Weapon Hilt: Great", qte:1, obl:true}, {name:"Weapon Head: Great Axe", qte:1, obl:true}, {name:"Weapon Shaft: Medium", qte:1, obl:true}, ] }, { name:"Two Handed Mace", ingredient:[ {name:"Weapon Hilt: Great", qte:1, obl:true}, {name:"Weapon Head: Great Mace", qte:1, obl:true}, {name:"Weapon Shaft: Medium", qte:1, obl:true}, ] }, { name:"Two Handed Polearm", ingredient:[ {name:"Weapon Hilt: Great", qte:1, obl:true}, {name:"Weapon Head: Great Axe", qte:1, obl:true}, {name:"Weapon Shaft: Long", qte:1, obl:true}, ] }, { name:"Two Handed Polemace", ingredient:[ {name:"Weapon Hilt: Great", qte:1, obl:true}, {name:"Weapon Head: Great Mace", qte:1, obl:true}, {name:"Weapon Shaft: Long", qte:1, obl:true}, ] }, ] }, { groupName:"Woodworking Components", draw:false, list:[ { name:"Arrow Shaft", ingredient:[ {name:"Wood", qte:3, obl:true}, ] }, { name:"Book Binding", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, {name:"Stitched Leather", qte:1, obl:true}, ] }, { name:"Book Bound Chapter", ingredient:[ {name:"Book Chapter", qte:1, obl:true}, {name:"Book Chapter", qte:1, obl:true}, {name:"Book Chapter", qte:1, obl:true}, {name:"Book Chapter", qte:1, obl:true}, {name:"Lacing Sinew", qte:1, obl:true}, ] }, { name:"Bow Riser", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Bow Grip", qte:1, obl:true}, {name:"Bow Rest", qte:1, obl:true}, {name:"Bow Sight", qte:1, obl:true}, ] }, { name:"Bow Stave Limb", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, ] }, { name:"Parchment Paper", ingredient:[ {name:"Wood", qte:1, obl:true}, ] }, { name:"Parchment Vellum", ingredient:[ {name:"Wood", qte:2, obl:true}, {name:"Stitched Leather", qte:1, obl:true}, ] }, { name:"Plank", ingredient:[ {name:"Wood", qte:3, obl:true}, ] }, { name:"Shield Base: Medium", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, ] }, { name:"Shield Base: Small", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, ] }, { name:"Staff Head", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Runestone: Life", qte:1, obl:true}, {name:"Runestone: Death", qte:1, obl:true}, ] }, { name:"Staff Limb", ingredient:[ {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, {name:"Plank", qte:1, obl:true}, ] }, ] }, { groupName:"Woodworking Weapons", draw:true, list:[ { name:"Bow: Recurve", ingredient:[ {name:"Bow Stave Limb", qte:1, obl:true}, {name:"Bow Stave Limb", qte:1, obl:true}, {name:"Bow String", qte:1, obl:true}, {name:"Bow Riser", qte:1, obl:true}, ] }, { name:"Mystical Staff", ingredient:[ {name:"Staff Limb", qte:1, obl:true}, {name:"Staff Head", qte:1, obl:true}, {name:"Staff Heel", qte:1, obl:true}, ] }, { name:"one Handed Book", ingredient:[ {name:"Book Binding", qte:1, obl:true}, {name:"Book Chapters", qte:1, obl:true}, {name:"Book Clasp", qte:1, obl:true}, ] }, ], }, { groupName:"Wood Crafts", draw:false, list:[ { name:"Arrow", ingredient:[ {name:"Arrowhead", qte:10, obl:true}, {name:"Arrow Shaft", qte:10, obl:true}, ] }, { name:"Basic Arrow", ingredient:[ {name:"Wood", qte:1, obl:true}, ] }, ] }, { groupName:"Leatherworking Components", draw:false, list:[ { name:"Bow Grip", ingredient:[ {name:"Stitched Leather", qte:1, obl:true}, {name:"Stitched Leather", qte:1, obl:true}, ] }, { name:"Bow String", ingredient:[ {name:"Stitched Leather", qte:1, obl:true}, ] }, { name:"Enarmes", ingredient:[ {name:"Stitched Leather", qte:2, obl:true}, ] }, { name:"Hardened Leather", ingredient:[ {name:"Hide", qte:2, obl:true}, {name:"Hide", qte:2, obl:true}, {name:"Hide", qte:2, obl:true}, {name:"Lacing Sinew", qte:1, obl:true}, {name:"Leather Armor Layer", qte:1, obl:false}, {name:"Leather Armor Layer", qte:1, obl:false}, {name:"Leather Armor Layer", qte:1, obl:false}, {name:"Specialty Seal", qte:1, obl:false}, ] }, { name:"Lacing Sinew", ingredient:[ {name:"Meat", qte:2, obl:true}, ] }, { name:"Leather Armor Layer", ingredient:[ {name:"Ore", qte:2, obl:true}, {name:"Ore", qte:2, obl:true}, {name:"Hide", qte:5, obl:true}, ] }, { name:"Reinforced Padding", ingredient:[ {name:"Hide", qte:3, obl:true}, {name:"Hide", qte:3, obl:true}, {name:"Hide", qte:3, obl:true}, {name:"Ore", qte:1, obl:true}, {name:"Specialty Seal", qte:1, obl:false}, ] }, { name:"Stitched Leather", ingredient:[ {name:"Hide", qte:1, obl:true}, {name:"Hide", qte:1, obl:true}, {name:"Hide", qte:1, obl:true}, {name:"Specialty Seal", qte:1, obl:false}, ] }, ] }, { groupName:"Leather Armor", draw:true, list:[ { name:"Leather Boots", ingredient:[ {name:"Ore", qte:4, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, ] }, { name:"Leather Chest", ingredient:[ {name:"Ore", qte:8, obl:true}, {name:"Hide", qte:25, obl:true}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, ] }, { name:"Leather Gloves", ingredient:[ {name:"Ore", qte:4, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, ] }, { name:"Leather Helmet", ingredient:[ {name:"Ore", qte:4, obl:true}, {name:"Hide", qte:15, obl:true}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Hardened Leather", qte:1, obl:false}, {name:"Reinforced Padding", qte:1, obl:false}, ] }, ] }, ]
import Types from "../actionTypes"; const loadProducerDetailsRequest = (payload) => ({ type: Types.LOAD_PRODUCER_DETAILS_REQUEST, payload, }); const loadProducerDetailsSuccess = (payload) => ({ type: Types.LOAD_PRODUCER_DETAILS_SUCCESS, payload, }); const loadProducerDetailsFailure = (payload) => ({ type: Types.LOAD_PRODUCER_DETAILS_FAILURE, payload, }); export default { loadProducerDetailsRequest, loadProducerDetailsSuccess, loadProducerDetailsFailure, };
/* UI build-up: main leftpanel leftpane panel panel-heading meterlist rightpanel panel panel-heading graphbody Data moves from 'main' into both panels and the state is maintained on 'main' Clicking a meter in the left panel will affect the data shown in the right panel. The two panels are stateless. */ //ReactDOM.render(<NavBar navItems={['Home', 'About', 'My Account', 'Contact']}/>, document.getElementById("navbar")); var meters = [{meter:'1', name:'Vand', value:'2344' , unit:'m3'}, {meter:'2', name:'Gas', value:'12344' , unit:'m3'}, {meter:'3', name:'El', value:'232421' , unit:'kWh'} ]; var timedata = [ ]; // Maintain state here. var Main = React.createClass({ // Set initial state getInitialState: function() { return { selectedMeter: 1 }; }, // Mount socket and wait for "meter update" events. componentDidMount: function() { var that = this; this.socket = io(); this.socket.on('meter update', function (data) { console.log("Main-componentDidMount-JSON recv:", data); that.addMeterUpdate(data); }); }, addMeterUpdate: function(update) { var data = this.props.meterList; var len = data.length; console.log("props.data:", data); // Find the right meter and overwrite with the update. for (var i = 0; i < len; i++) { if(data[i].meter == update.meter) { data[i] = update; } } this.setState(data); }, /* Handler for selection of Meters in the left panel */ /* This is passed React style through the hierarchy to the individual buttons so that the state can live in the top component. */ meterSelectionHandler: function(meter) { console.log("main-meterSelectionHandler: ", meter); this.setState({ selectedMeter : meter}); }, render: function() { console.log("Main-render"); return ( <div> <LeftPanel meterList={this.props.meterList} onUpdate={this.meterSelectionHandler}/> <RightPanel meterID={this.state.selectedMeter} /> </div> ); } }); /* // create HiThere component var HiThere = React.createClass({ render: function () { return ( <h1>Graphs go here</h1> ); } }); ReactDOM.render(<HiThere />, document.getElementById('main')); */ /* // Bootstrap React example var ButtonGroup = ReactBootstrap.ButtonGroup; var Button = ReactBootstrap.Button; var MenuItem = ReactBootstrap.MenuItem; var DropdownButton = ReactBootstrap.DropdownButton; var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); ReactDOM.render(buttonGroupInstance, document.getElementById("main")); */ // Seed the initial state of the webpage. The remaining of the time socket.io does the work. $.getJSON( "/api/currentabsolutevalues", function( meters ) { ReactDOM.render(<Main meterList={meters}/>, document.getElementById("main")); });
var roleMissionary = { /** @param {Creep} creep **/ run: function(creep, village) { if (creep.spawning) { return; } if (creep.memory.getBoosted.length > 0) { if (creep.memory.lab) { let myLab = Game.getObjectById(creep.memory.lab); let status = myLab.boostCreep(creep); switch (status) { case ERR_NOT_IN_RANGE: creep.moveTo(myLab); return; case OK: creep.memory.getBoosted.shift(); delete creep.memory.lab return; case ERR_NOT_ENOUGH_RESOURCES: // Failed cause not enough minerals or energy // TODO: create request to fill it up //delete creep.memory.getBoosted; return; } } else { let labs = village.labs.reagentLabs; for (l in labs) { if (labs[l] == creep.memory.getBoosted[0]) { creep.memory.lab = l; creep.moveTo(Game.getObjectById(l)); return; } } // no lab found delete creep.memory.getBoosted; } } if (creep.memory.harvesting) { if (creep.carry.energy == creep.carryCapacity) { creep.memory.harvesting = false; return; } if (!creep.memory.sourceId) { creep.memory.sourceId = creep.pos.findClosestByRange(FIND_SOURCES_ACTIVE).id; } const source = Game.getObjectById(creep.memory.sourceId); if (source) { let status = creep.harvest(source); switch (status) { case ERR_NOT_IN_RANGE: creep.moveTo(source); break; case ERR_NOT_ENOUGH_RESOURCES: delete creep.memory.sourceId; break; } return; } } if (creep.carry.energy==0) { if (creep.room.storage && creep.room.storage.store[RESOURCE_ENERGY] >= creep.carryCapacity) { creep.withdrawMove(creep.room.storage) return } if (creep.memory.cattle && creep.memory.cattle.length > 0) { let cattle = creep.memory.cattle[creep.memory.cattle.length - 1]; if (cattle) { let cattleObj = Game.creeps[cattle]; this.harvestCattle(creep, cattleObj); } } else { creep.memory.harvesting = true; } } let flag = Game.flags[village.colonization.civFlag]; if (!flag.room || creep.room != flag.room) { creep.emote('missionary',CREEP_SPEECH.REMOTEMOVING); creep.moveTo(flag); return; } if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) { creep.moveTo(creep.room.controller); } }, harvestCattle(creep, cattleObj) { if (!creep.pos.isNearTo(cattleObj.pos)) { cattleObj.moveTo(creep.pos); return; } let pos = cattleObj.pos; cattleObj.drop(RESOURCE_ENERGY); let droppedEnergy = creep.room.lookForAt(LOOK_RESOURCES, pos)[0]; let status = creep.pickup(droppedEnergy); switch(status) { case 0: creep.memory.cattle.pop(); delete cattleObj.memory.herder; break; } } }; module.exports = roleMissionary;
import React, {Component} from 'react' import {ImagePickerIOS, TouchableOpacity, Image, Modal, View, Text, LayoutAnimation, ActionSheetIOS, Alert, ImageEditor} from 'react-native' import styles from './styles' import ImageCropModal from './ImageCropModal' // style= {styles.modal} class ProfileImage extends Component { constructor(props){ super(props) this.state = { modalVisible: false, cropVisible: false, cropImg: "", image: props.userImg || null, } this.handlePostImage = this.handlePostImage.bind(this) } componentWillReceiveProps(newProps){ if(newProps.userImg !== this.props.userImg){ this.setState({image: newProps.userImg}) } } handleChooseImage = (openType) => { ImagePickerIOS[openType]( //config {}, //successCB (imageUri) => { this.setState({ cropVisible: true, cropImg: imageUri }) }, //failedCB cancle => false); } showActionSheet = () => { var BUTTONS = [ '사진첩', '카메라', '취소']; ActionSheetIOS.showActionSheetWithOptions({ options: BUTTONS, cancelButtonIndex: 2, title: '프로필 사진 설정', }, (buttonIndex) => { if(buttonIndex === 2){ return false } let selectType = buttonIndex === 0 ? "openSelectDialog" : "openCameraDialog" this.handleChooseImage(selectType) }); } handlePostImage(cropData, imageUri) { // debugger console.log("handlePostImage",cropData, imageUri); ImageEditor.cropImage( imageUri, cropData, (successURI) => { this.setState({ image : successURI, cropVisible: false }) }, (errURI) => {console.log(errURI)} ) } render(){ //["register", "setting", "profile", "feed", "search"] const ImageStyle = { width: this.props.imageSize, height: this.props.imageSize, borderRadius: this.props.imageSize*0.5, borderWidth: 0.5, borderColor: '#5e5e5e', marginBottom: 10, } return( <TouchableOpacity onPress={this.showActionSheet}> <ImageCropModal visible={this.state.cropVisible} imageUri={this.state.cropImg} handlePostImage={this.handlePostImage}/> <Image style={ImageStyle} source={this.state.image ? {uri: this.state.image} : require('../../../assets/defaultUser.jpg')}/> </TouchableOpacity> ) } } export default ProfileImage // // // <Modal // animationType={"slide"} // transparent={true} // visible={this.state.modalVisible} // > // <View style={styles.modal}> // <TouchableOpacity // style={styles.modalBtn} // onPress= {() => this.chooseImageFromGallery()}> // <Text>사진첩</Text> // </TouchableOpacity> // <TouchableOpacity // style={styles.modalBtn} // onPress= {() => this.chooseImageFromCamera()}> // <Text>사진찍기</Text> // </TouchableOpacity> // <TouchableOpacity // style={styles.modalBtn} // onPress= {() => this.setState({modalVisible: false})}> // <Text>취소</Text> // </TouchableOpacity> // </View> // </Modal>
export default { login: config => { let data = JSON.parse(config.body) let userList = {} if (data.userName === 'admin') { userList = { token: 'Admin', name: '管理员' } } else if (data.userName === 'user') { userList = { token: 'Editor', name: '用户' } } else { return { code: -1, data: { msg: '只能使用admin/editor登录', status: 'fail' } } } return { code: 200, userList: userList } }, loginOut: config => { debugger return { code: 200, data: {} } }, getUserInfo: config => { let data = JSON.parse(config.body) let userList = {} if (data.token === 'Admin') { userList = { roles: 'Admin', name: '管理员' } } else if (data.token === 'user') { userList = { roles: 'Editor', name: '普通用户' } } else { return { code: -1, data: {} } } return { code: 200, userList: userList } } }
function componentApp() { //1) Standart h1 Elemt in React let title = React.createElement( "h1", { key: "headerApp", style: { color: "red", border: "1px solid black" }, id: "headApp" }, "App Header" ); //02) Inner Component let sub = React.createElement(componentSub, { key: "subComp1" }, null); //03) Create Div Element with inner element as children Children //-title simple element //-inner componentSub component let divContainer = React.createElement( "div", { style: { border: "1px solid black" } }, [title, sub] ); //return upLevel Element return divContainer; } function componentSub() { //standart javaScript // let pElement = React.createElement("p", // {style:{color:'red',border:'1px dashed red'},onClick:(e)=> alert('Sub Alert')}, //"Sub Comp"); //return pElement; //JSX Syntax return ( <p style={{ color: "red", border: "1px dashed red" }} onClick={e => alert("JSX ALERT")} > Click Me </p> ); //JSX //return ( //<button onClick={() => alert("AAAA")}> //Click me //</button> // ); } const htmlRoot = document.getElementById("root"); let appComponent = React.createElement(componentApp, {}, null); ReactDOM.render(appComponent, htmlRoot);
function updateInventory(arr1, arr2) { // Convert our arrays into objects to update and then convert back into array. let inventory = {}; for(let i = 0; i < arr1.length; i++) { if(!inventory.hasOwnProperty(arr1[i][1])) { inventory[arr1[i][1]] = arr1[i][0]; } } for(let i = 0; i < arr2.length; i++) { if(inventory.hasOwnProperty(arr2[i][1])) { inventory[arr2[i][1]] += arr2[i][0]; } else { inventory[arr2[i][1]] = arr2[i][0]; } } var updatedInventory = [], keys = []; for (let key in inventory) { keys.push(key); } keys = keys.sort(); for(let i = 0; i < keys.length; i++) { updatedInventory.push([inventory[keys[i]], keys[i]]); } return updatedInventory; } // Example inventory lists var curInv = [ [21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"] ]; var newInv = [ [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"] ];
// find // findIndex // indexOf // includes function linear_search(arr, val) { for (let i = 0; i < arr.length; i++) { const element = arr[i] if (element == val) return i } return -1 } console.log(linear_search([1, 2, 3, 4, 5, 6, 7, 8], 8))
const baseApi = (process.env.VUE_APP_API_SERVER || '') + '/rest/site/fe/user/notice' export default function create(tmsAxios) { return { uncloseList(siteId, missionId, batchArg) { const { page, size } = batchArg const params = { site: siteId, mission: missionId, page, size } return tmsAxios.get(`${baseApi}/uncloseList`, { params }).then((rst) => { return rst.data.data }) }, list(siteId, missionId, batchArg) { const { page, size } = batchArg const params = { site: siteId, mission: missionId, page, size } return tmsAxios.get(`${baseApi}/list`, { params }).then((rst) => { return rst.data.data }) }, close(siteId, noticeId) { const params = { site: siteId, id: noticeId } return tmsAxios.get(`${baseApi}/close`, { params }).then((rst) => { return rst.data.data }) }, count(siteId) { const params = { site: siteId } return tmsAxios.get(`${baseApi}/count`, { params }).then((rst) => { return rst.data.data }) }, } }
import React, { Component } from 'react'; import { fetchCampersData, sortData } from '../functions.js'; import shortid from 'shortid'; import Camper from './Camper'; export default class Leaderboard extends Component { constructor() { super(); this.state = {campers: [ {"username":"forkerino","img":"https://avatars.githubusercontent.com/u/16620061?v=3","alltime":5000,"recent":545,"lastUpdate":"2017-03-17T17:49:58.192Z"}]} } setCampers(campers) { this.setState({ campers: campers } ) } componentDidMount() { fetchCampersData().then( campers => this.setCampers(campers) ); } handleSort(e,campers) { const {id} = e.target; sortData(id, campers); this.setCampers(campers); } render () { const {campers} = this.state; return ( <div className="leaderboard"> <div className="title"> <h1>Leaderboard</h1> </div> <table className="table table-bordered table-striped"> <thead> <tr> <th>#</th> <th>Camper Name</th> <th> <a id="recent" href="#" onClick={(e) => this.handleSort(e,campers)}> {/* Note: createReactApp uses property initializer syntax so handleSort doesn't need to be bound. Read More towards the bottom of: https://facebook.github.io/react/docs/handling-events.html */} Points in the past 30 days </a> </th> <th> <a id="alltime" href="#" onClick={(e) => this.handleSort(e,campers)}> All time points </a> </th> </tr> </thead> <tbody> {campers.map ( (camper,count) => { count += 1; return ( <Camper camper={camper} key={shortid.generate()} num={count} /> )} )} </tbody> </table> </div> ); } }
$(document).ready(function () { var $el = $('.ee-flip-card'); $el.click(function () { $(this).toggleClass('-flipped'); }).mouseover(function () { if (!hasTouch()) $(this).addClass('-hovered'); }).mouseleave(function () { $(this).removeClass('-hovered'); }); function hasTouch() { return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; } });
setInterval((function() { const serverUrl = 'http://127.0.0.1:3000/directions'; $.get({ url: serverUrl, type: 'GET', success: (direction) => { //console.log(direction) SwimTeam.move(direction); }, error: (err) => console.log("There has been an error getting commands! ", err) }) }),0); setInterval((function() { const serverUrl = 'http://127.0.0.1:3000/background.jpg'; $.get({ url: serverUrl, type: 'GET', success: (imgUrl) => { // $(".bg").css("background-image", "url('/css/images/css.jpg')"); console.log(imgUrl); }, error: (err) => console.log("There has been an error getting images! ", err) }) }),3000);
import React from 'react'; export default class Ticket extends React.Component { render() { return ( <React.Fragment> <div className="get-more"> <div className="get-more-header row"> <div className="col-6"> <h3>Get More Tickets</h3> </div> <div className="col-6"> <button className="btn btn-primary">Buy</button> </div> </div> <div className="ticket-card mt-3"> <div className="row"> <div className="col-lg-12 col-sm-4"> <img src={require("../images/silver-card.png").default} height="180" width="130" alt="card" /> </div> <div className="col-lg-12 col-sm-4"> <img src={require("../images/gold-card.png").default} height="180" width="130" alt="card" /> </div> <div className="col-lg-12 col-sm-4"> <img src={require("../images/diamond-card.png").default} height="180" width="130" alt="card" /> </div> </div> </div> </div> </React.Fragment> ) } }
import axios from 'axios' const catAPI = axios.create({ baseURL : process.env.API_BASE_URL }) catAPI.defaults.headers['x-api-key'] = process.env.API_KEY export default catAPI console.log(process.env.API_BASE_URL) console.log(process.env.API_KEY) catAPI.get('images/search').then(console.log).catch(console.error) // export default async function api(params) { // const config = { // ...params, // url: `${process.env.API_BASE_URL}/${params.url}`, // headers: { // } // } // try { // const response = await axios(config) // return response // } catch (error) { // return error // } // }
import React, { useState } from 'react' import { Link as GatsbyLink } from 'gatsby' import { useStaticQuery, graphql } from 'gatsby' import { IoSearchOutline } from 'react-icons/io5' import SearchField from './SearchField' import { GiHamburgerMenu } from 'react-icons/gi' import { GrClose } from 'react-icons/gr' import { RiArrowDropRightLine, RiArrowDropDownLine } from 'react-icons/ri' import { ModalWrapper, Button, Container } from '../../elements' import styled from 'styled-components' import { css } from 'styled-components' const styleForMenuItemColors = ({ theme }) => css` cursor: pointer; color: ${theme.colors.menu.items.color}; background-color: ${theme.colors.menu.items.background}; :hover { background-color: ${theme.colors.menu.items.hover.background}; color: ${theme.colors.menu.items.hover.color}; } ` const NavbarWrapper = styled.nav` position: fixed; top: 0; left: 0; margin: 0; z-index: 6666; font-family: ${(props) => props.theme.fonts.menu}; font-weight: ${(props) => props.theme.fonts.weights.menu}; box-shadow: ${(props) => props.theme.shadows.medium}; background-color: ${(props) => props.theme.colors.menu.background}; ${(props) => props.horizontal ? `width: 100%;` : `@media ${props.theme.breakpoints.desktop} { height: 100%; } @media ${props.theme.breakpoints.touch} { width: 100%; }`} ` const NavbarContainer = styled(Container)`` const NavbarMenuList = styled.ul` display: ${(props) => (props.active ? 'flex' : 'none')}; margin: 0; list-style-type: none; flex-direction: column; padding: 0; @media ${(props) => props.theme.breakpoints.desktop} { height: 100%; } @media ${(props) => props.theme.breakpoints.touch} { width: 100%; text-align: center; } ${(props) => props.horizontal ? ` @media ${props.theme.breakpoints.desktop} { display: inline-flex; flex-direction: row; } ` : ``} ` const NavbarMenuItem = styled.li` position: relative; > a { ${styleForMenuItemColors}; } ${styleForMenuItemColors}; :hover { > ul { visibility: visible; opacity: 1; display: block; padding: 0; } } ` const NavbarTrigger = styled.div` padding: ${(props) => props.theme.spacings.xSmall} ${(props) => props.theme.spacings.small}; text-align: center; ${styleForMenuItemColors}; svg { transition: transform ${(props) => props.theme.animations.animTime} ease; transform: ${(props) => (props.active ? 'rotate(0)' : 'rotate(90deg)')}; } @media ${(props) => props.theme.breakpoints.touch} { display: inline-block; float: right; } ${(props) => props.horizontal ? `@media ${props.theme.breakpoints.desktop} { display: none; }` : ``} ` const NavbarSearchItem = styled.div` padding: ${(props) => props.theme.spacings.xSmall} ${(props) => props.theme.spacings.small}; text-align: center; ${styleForMenuItemColors}; @media ${(props) => props.theme.breakpoints.touch} { display: inline-block; float: right; } ${(props) => props.horizontal ? `@media ${props.theme.breakpoints.desktop} { display: inline-block; float: right; }` : ``} ` const NavbarMenuDropdown = styled.ul` border-radius: 0 ${(props) => props.theme.borders.control} ${(props) => props.theme.borders.control} 0; border-left: 1px solid ${(props) => props.theme.colors.menu.dropdown.border}; background-color: ${(props) => props.theme.colors.menu.dropdown.background}; visibility: hidden; opacity: 0; z-index: 6666; position: absolute; top: 0; left: 100%; list-style-type: none; display: none; li { clear: both; width: 100%; white-space: nowrap; } ` const NavbarMenuDropdownFirstLevel = styled(NavbarMenuDropdown)` ${(props) => (props.horizontal ? `top: unset; left: unset;` : ``)} ` const NavbarLink = styled(GatsbyLink)` display: block; padding: ${(props) => props.theme.spacings.small}; svg { @media ${(props) => props.theme.breakpoints.touch} { display: none; } } ` const ModalContent = styled.div` font-size: ${(props) => props.theme.fonts.sizes.large}; ` const ModalButton = styled(Button)` margin: ${(props) => props.theme.spacings.medium}; padding: ${(props) => props.theme.spacings.small}; border: 1px solid ${(props) => props.theme.colors.light}; background-color: rgba(0, 0, 0, 0.2); position: absolute; top: 0; right: 0; font-size: ${(props) => props.theme.fonts.sizes.large}; ` const Navbar = ({ logo, macroCategories }) => { const [active, setActive] = useState(false) const [showSearchModal, setShowSearchModal] = useState(false) const { navbar } = useStaticQuery(graphql` query Navbar { site { siteMetadata { website { navbar { HORIZONTAL HAS_SEARCH_MODAL HAS_SEARCH_FIELD } } } } } `).site.siteMetadata.website const isHorizontal = navbar.HORIZONTAL return ( <> <NavbarWrapper horizontal={isHorizontal} onMouseEnter={() => setActive(true)} onMouseLeave={() => { setActive(false) }} > <NavbarContainer> <NavbarTrigger horizontal={isHorizontal} active={active} onPointerUp={() => setActive(!active)} > <GiHamburgerMenu size='2em' /> </NavbarTrigger> {navbar.HAS_SEARCH_FIELD && ( <div className='navbar-item search-item is-clickable'> <SearchField /> </div> )} {navbar.HAS_SEARCH_MODAL && ( <NavbarSearchItem horizontal={isHorizontal}> <span onClick={() => { setShowSearchModal(true) }} > <IoSearchOutline size='2em' /> </span> </NavbarSearchItem> )} <NavbarMenuList horizontal={isHorizontal} active={active}> <NavbarMenuItem> <NavbarLink to='/'>Home</NavbarLink> </NavbarMenuItem> <NavbarMenuItem> <NavbarLink to='/about'>Chi Sono</NavbarLink> </NavbarMenuItem> <NavbarMenuItem> <NavbarLink to='/contact'>Contatti</NavbarLink> </NavbarMenuItem> {macroCategories && macroCategories.length > 0 && macroCategories.map((cat) => { //if has second-level subcategories if (cat.subCategories && cat.subCategories.length > 0) { return ( <> <NavbarMenuItem> <NavbarLink to={`/category/${cat.uid}`}> {cat.name}{' '} {isHorizontal ? ( <RiArrowDropDownLine /> ) : ( <RiArrowDropRightLine /> )} </NavbarLink> <NavbarMenuDropdownFirstLevel horizontal={isHorizontal}> {cat.subCategories.map((subCat) => { if ( subCat.subCategories && subCat.subCategories.length > 0 ) { return ( <NavbarMenuItem> <NavbarLink to={`/category/${subCat.uid}`}> {subCat.name} <RiArrowDropRightLine /> </NavbarLink> <NavbarMenuDropdown> {subCat.subCategories.map((tlCat) => ( <NavbarMenuItem> <NavbarLink to={`/category/${tlCat.uid}`} > {tlCat.name} </NavbarLink> </NavbarMenuItem> ))} </NavbarMenuDropdown> </NavbarMenuItem> ) } else return ( <NavbarMenuItem> <NavbarLink to={`/category/${subCat.uid}`}> {subCat.name} </NavbarLink> </NavbarMenuItem> ) })} </NavbarMenuDropdownFirstLevel> </NavbarMenuItem> </> ) } else { return ( <NavbarMenuItem> <NavbarLink to={`/category/${cat.uid}`}> {cat.name} </NavbarLink> </NavbarMenuItem> ) } })} </NavbarMenuList> </NavbarContainer> </NavbarWrapper> {/* SEARCH MODAL */} {showSearchModal && ( <ModalWrapper> <ModalContent> <SearchField modal autoFocusSearchBar /> </ModalContent> <ModalButton aria-label='close' onClick={() => { setShowSearchModal(false) }} > <GrClose /> </ModalButton> </ModalWrapper> )} </> ) } export default Navbar
import { Link } from 'react-router-dom'; import { useAuth } from './utilities/AuthContext.js'; import React, { useState } from 'react'; export default function Signup(props) { const [inputs, setInputs] = useState({}); const handleChange = e => setInputs(prevState => ({ ...prevState, [e.target.name]: e.target.value })); console.log(inputs); // setup form validation // setup error handling from axios call const { register } = useAuth(); const handleSubmit = e => { const data = { username: inputs.username, email: inputs.email, password: inputs.password}; register(data); } return ( <> <div className='col-12 text-center'> <h1 className='display-2'>Register</h1> </div> <div className='col-12'> <div className="mb-3"> <label htmlFor="formGroupExampleInput3" className="form-label">Username</label> <input type="text" className="form-control" id="formGroupExampleInput3" placeholder="" name="username" value={inputs.username || ''} onChange={handleChange}></input> </div> <div className="mb-3"> <label htmlFor="formGroupExampleInput5" className="form-label">Email</label> <input type="email" className="form-control" id="formGroupExampleInput5" placeholder="" name="email" value={inputs.email || ''} onChange={handleChange}></input> </div> <div className="mb-3"> <label htmlFor="formGroupExampleInput4" className="form-label">Password</label> <input type="password" className="form-control" id="formGroupExampleInput4" placeholder="" name="password" value={inputs.password || ''} onChange={handleChange}></input> </div> <div className="col-12 text-center mb-3"> <Link to='/' type="button" className="btn btn-dark">Cancel</Link> { ' ' } <button type="button" className="btn btn-dark" onClick={handleSubmit}>Submit</button> </div> </div> </> ); }
$(document).ready(function() { $('#release').click(function() { $('#release').fadeOut(4000); $('#seven').fadeIn(8000) }); });
import React from "react"; import corgiPuppy from "../images/corgi_puppy.jpg"; export function PetCard(props) { return ( <div> <div style={{ paddingBottom: "10px" }}> <b style={{ paddingLeft: "5px", fontSize: "18px" }}>{props.pet.name}</b> </div> <img src={corgiPuppy} className='ui large image' alt='pet' /> </div> ); }
import React from 'react'; import TermCreate from './TermCreate.jsx'; import { Router, Route, Link, hashHistory } from 'react-router'; import NotificationSystem from 'react-notification-system'; class TermsList extends React.Component { constructor(props) { super(props); this.state = { glossary: {}, terms: [], editTerm: false, termName: '', termDescription: '', activeTerm: null }; } componentDidMount() { this.serverRequest = $.get("/glossaries/" + this.props.glossary, function(result) { this.setState({ glossary: result.glossary, terms: result.terms }); }.bind(this)); this._notificationSystem = this.refs.notificationSystem; } componentWillUnmount() { this.serverRequest.abort(); } _handleTermAdd = (term) => { this.setState({ terms: this.state.terms.concat(term) }); } changeName = (event) => { this.setState({ termName: event.target.value }); } changeDescription = (event) => { this.setState({ termDescription: event.target.value }); } editTerm = (i, name, description) => { this.setState({ activeTerm: i, editTerm: true, termName: name, termDescription: description }); } saveTerm = (term_id, event) => { event.preventDefault(); $.ajax({ type: "PUT", url: "/terms/" + term_id, context: this, data: { name: this.state.termName, description: this.state.termDescription }, success() { var self = this; var modifiedTerm = this.state.terms.filter((i, _) => i["id"] === term_id); modifiedTerm.name = this.state.termName; modifiedTerm.description = this.state.termDescription; var newList = []; this.state.terms.map(function(term) { if (term.id === term_id) { term.name = self.state.termName; term.description = self.state.termDescription; } newList.push(term); }); this.setState({ terms: newList, editTerm: false, activeTerm: null }) } }); } deleteTerm = (term_id, term_name, event) => { var self = this; event.preventDefault(); this._notificationSystem.addNotification({ title: 'Confirmer la suppression', message: 'Voulez-vous supprimer le terme "' + term_name + '" ?', level: 'success', position: 'tc', timeout: '20000', action: { label: 'Oui', callback() { $.ajax({ type: "DELETE", url: "/terms/" + term_id, context: self, success() { self.setState({ terms: self.state.terms.filter((i, _) => i["id"] !== term_id) }) } }); } } }); } render() { var self = this; return( <div id="view-terms"> <NotificationSystem ref="notificationSystem" /> <div id="border"> <ul id="list-terms"> { this.state.terms.map(function(term, i){ return( <li key={term.id}> { i === self.state.activeTerm ? <div> <p> <input type="text" onChange={self.changeName} value={self.state.termName} /> </p> <p> <input type="text" onChange={self.changeDescription} value={self.state.termDescription} /> </p> <p> <button onClick={self.saveTerm.bind(self, term.id)}>Ok <i className="fa fa-check"></i></button> </p> </div> : <div> <p className="title">{term.name} : <a href="javascript:;" onClick={self.deleteTerm.bind(self, term.id, term.name)}> <i className="fa fa-trash-o"></i> </a> <a href="javascript:;" onClick={self.editTerm.bind(self, i, term.name, term.description)}> <i className="fa fa-pencil"></i> </a> </p> <p className="desc">{term.description}</p> </div> } </li> ) })} </ul> <div className="add_new_term"> <TermCreate glossary={this.state.glossary.id} addTerm={this._handleTermAdd}/> </div> </div> </div> ); } } export default TermsList;
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const blessed_1 = __importDefault(require("blessed")); const helper_1 = __importDefault(require("./helper")); const DEFAULT_SCROLL_OPTIONS = { scrollable: true, input: true, alwaysScroll: true, scrollbar: { ch: " ", inverse: true }, keys: true, vi: true, mouse: true }; class Dashboard { constructor() { this._logger = null; this._modal = null; this._loggerText = null; this._steps = null; this._progress = null; this._progressBar = null; this.assetTable = null; const options = { resizeTimeout: 300, dockBorders: true, cursor: { artificial: true, shape: 'line', blink: true, color: null }, debug: true, warnings: true, smartCSR: true, fullUnicode: true, autoPadding: true, }; this.screen = blessed_1.default.screen(options); this.actionForMessageType = { progress: this.setProgress.bind(this), logger: this.setLogger.bind(this), steps: this.setSteps.bind(this), }; this.screen.key(['escape', 'C-c'], function () { return process.exit(0); }); this.color = 'green'; this.layoutLog(); this.layoutSteps(); this.layoutProgress(); this.screen.render(); } layoutModal(options) { // this._modal = blessed.prompt(Object.assign({ // label: "Modal", // padding: 1, // top: 'center', // left: 'center', // width: '40%', // height: '40%', // censor: '*', // mouse: true, // inputOnFocus: true, // border: { // type: 'line', // }, // }, options)); // this._modal.readInput('你好','',()=>{ // this.setSteps({ // value:1, // }) // }); // this.screen.append(this._modal); } layoutProgress() { this._progress = blessed_1.default.box({ label: "Progress", padding: 1, width: '20%', height: '20%', left: 0, bottom: 0, border: { type: 'line' }, style: { fg: -1, border: { fg: this.color, }, } }); this._progressBar = blessed_1.default.progressbar({ parent: this._progress, height: 1, pch: '', filled: 0, value: 0, keys: false, mouse: false, width: "90%", top: "center", left: "center", orientation: "horizontal", style: { bar: { bg: this.color } } }); this.screen.append(this._progress); } layoutLog() { this._logger = blessed_1.default.box({ label: "Log", padding: 1, width: '80%', height: '100%', top: 0, right: 0, border: { type: 'line' }, style: { fg: -1, border: { fg: this.color, }, }, scrollbar: { ch: ' ', track: { bg: 'yellow' }, style: { inverse: true } } }); this._loggerText = blessed_1.default.log(Object.assign({}, DEFAULT_SCROLL_OPTIONS, { parent: this._logger, tags: true, width: "100%-5" })); this.screen.append(this._logger); } layoutSteps() { const option = { label: "Steps", // mouse: true, padding: 1, width: '20%', height: '80%', top: '0', left: 0, tags: true, invertSelected: false, border: { type: 'line' }, style: { fg: 'blue', bg: 'default', border: { fg: this.color, bg: 'default' }, selected: { bg: 'green' }, }, scrollbar: { ch: ' ', track: { bg: 'yellow' }, style: { inverse: true } } }; this._steps = blessed_1.default.list(option); this._steps.on('select', (item, select) => { if (this._steps) { console.log(1); this._steps.select(select); this._steps.focus(); } }); this.screen.append(this._steps); } setProgress(data) { const percent = parseFloat(data.value) * 1; const formattedPercent = `${percent.toFixed(1).toString()}%`; if (this._progressBar) { if (!percent) { this._progressBar.setProgress(percent); } this._progressBar.setContent(formattedPercent); this._progressBar.setProgress(percent); } } setLogger(data) { if (this._loggerText) { this._loggerText.log(data.value.replace(/[{}]/g, "")); } } setSteps(data) { if (this._steps) { data.forEach(this._steps.addItem.bind(this._steps)); this._steps.select(0); } } setData(dataArray) { dataArray.map(data => { return data.error ? Object.assign({}, data, { value: helper_1.default.deserializeError(data.value) }) : data; }).forEach(data => { this.actionForMessageType[data.type](data); }); this.screen.render(); } } exports.default = Dashboard;
describe("readFile", function() { var readFile = require("../lib/readfile"); const _ = require("underscore"); it("should be a function", function() { expect(_.isFunction(readFile)).toBe(true); }); it("should convert a given Twine story HTML file into objects", function(done) { var path = __dirname + "/support/test_story.html"; readFile(path, {}).then((story) => { expect(story).toBeDefined(); expect(story.ifid).toEqual("B3593454-5ADC-459D-982D-31E4A601EF01"); expect(story.name).toEqual("My First Story"); expect(story.startNode).toEqual(1); expect(story.format).toEqual("Snowman"); expect(story.passages.length).toEqual(5); expect(story.passages[0].pid).toEqual(1); expect(story.passages[0].name).toEqual("My First Room"); // check tag support expect(_.contains(story.passages[0].tags, "start")).toBe(true); expect(_.contains(story.passages[0].tags, "room")).toBe(true); expect(_.contains(story.passages[1].tags, "room")).toBe(true); done(); }).catch((err) => { throw err; }); }); it("should accept an ignorePassages option", function() { var path = __dirname + "/support/test_story.html"; readFile(path, {"ignorePassages": [1,2]}).then((story) => { expect(story).toBeDefined(); expect(story.passages.length).toEqual(3); expect(story.passages[0].pid).toEqual(3); expect(story.passages[0].name).toEqual("My Bedroom"); expect(story.passages[1].name).toEqual("My Bathroom"); expect(story.passages[2].name).toEqual("My Closet"); done(); }).catch((err) => { throw err; }); }); });
/* eslint-disable react-native/no-inline-styles */ import React from 'react'; import {View, Text} from 'react-native'; import ClickableButton from '../shared/components/ClickableButton'; import BrandLogo from '../shared/components/BrandLogo'; class HomeScreen extends React.Component { render() { const {navigation} = this.props; return ( <View style={{ flex: 1, alignItems: 'center', flexDirection: 'column', margin: 20, }}> <View style={{flex: 7}}> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}> <BrandLogo /> </View> </View> <View style={{flex: 2, alignSelf: 'stretch'}}> <View style={{flex: 1}}> <ClickableButton title="Log In" onPress={() => navigation.push('Login')} wrapperStyle={{marginHorizontal: '5%', marginBottom: 10}} /> <ClickableButton type="secondary" title="Sign Up" wrapperStyle={{marginHorizontal: '5%'}} /> </View> </View> <View style={{flex: 1, alignSelf: 'stretch'}}> <Text style={{textAlign: 'center'}}> Terms | Privacy Policy | Contact Us </Text> </View> </View> ); } } export default HomeScreen;
import firebase from "firebase"; import "firebase/database"; let config = { apiKey: "AIzaSyCPXfCHIXaAKBDGATNS2JzFrFnN4e7_cA4", authDomain: "master-d9449.firebaseapp.com", databaseURL: "https://master-d9449-default-rtdb.firebaseio.com", projectId: "master-d9449", storageBucket: "master-d9449.appspot.com", messagingSenderId: "534703447858", appId: "1:534703447858:web:c1e846f07afc217f4d412b", measurementId: "G-M7FF4YLYTS" }; firebase.initializeApp(config); export default firebase.database();
/** * 继承6:复制原型继承 * */ function Parent() { this.x = 10; } function Child() { var obj = new Parent(); obj.y = 20; return obj; } var childObj = new Child(); console.log(childObj.x);
const NewsAPI = require('newsapi'); const newsapi = new NewsAPI(process.env.NEWS_API_KEY); module.exports = { topHeadlines(callback) { newsapi.v2.topHeadlines({ language: 'en', pageSize: 49 }) .then((stories) => { let articles = stories.articles; // fill in missing data for (var i = articles.length - 1; i >= 0; i--) { if (articles[i].title === '' || !articles[i].title) { articles.splice(i, 1); } if (!articles[i].urlToImage) { articles[i].urlToImage = 'https://loremflickr.com/400/224/travel'; } if (!articles[i].description) { articles[i].description = articles[i].title || articles[i].content; } if (articles[i].content) { articles[i].content = articles[i].description || articles[i].title; } } callback(null, articles); }) .catch((err) => { callback(err); }) } };
if( isFileInURL( "contact" ) ) { displayContact(); } function displayContact() { //this ajax call will get the summary of my profile from LinkedIn, must use jsonp because it is cross domain $.ajax({ url: "https://api.linkedin.com//v1/people/~:(summary)", type: "GET", dataType: "jsonp", data: { "oauth2_access_token" : "AQXo0vRiE2VcPnruyXY_H2GzGvuoLhwTqwxuUjqvUXnebpNIS7FyrMgIrFd5kGfQfST-fMBeEM39_3AT7oebkMLk3xStUjg7p0gmA6-RrIcvPZejRsqA9RqJDwnDK7lCguw4s6aiMENI2Sbr0illan-H7y1w0sHyfvUUIic1u1X07YW8_DM", "format" : "jsonp" }, success: function( linkedInSummary ) { var summary = linkedInSummary.summary; summary = summary.split( ". " ).join( ". &nbsp;" ); //this just formats so that double spacing between sentences appears, it is based on https://gist.github.com/CrowderSoup/9095873 $( "#summary" ).html( summary ); } }); $( "textarea" ).keyup( function() //this method listens to keyups and wil keep the submit message button disabled until there are no errors and all textareas are completed, based on http://stackoverflow.com/questions/5614399/disabling-submit-button-until-all-fields-have-values { setTimeout( function() //this timeout of 1ms is because if there is no timeout, when there is an error, it will come up as undefined and then it will be print out "alert" on the next keyup { var empty = false; $( "textarea" ).each( function() { if( $( this ).val() === "" || $( "#contact-me" ).find( "ul" ).attr( "role" ) === "alert" ) //the right is what is what checks for errors, ul with "alert" roles are put into the .help-block divs { empty = true; } }); if( empty ) { $( "#submit-message" ).attr( "disabled", "disabled" ); } else { $( "#submit-message" ).removeAttr( "disabled" ); } }, 1 ); }); $( "textarea" ).not( "[type=submit]" ).jqBootstrapValidation({ //add the jqBootstrap functionality to the form and submitSuccess enters the information into the database preventSubmit: true, submitSuccess: function( $form, event ) { $.ajax({ url: "./server_functionality/contact-functions.php", type: "POST", dataType: "text", data: { name : $( "#name" ).val(), email : $( "#email" ).val(), message : $( "#message" ).val() }, success: function( databaseResponse ) { if( databaseResponse === "Success" ) { $( "#name" ).val( "" ); $( "#email" ).val( "" ); $( "#message" ).val( "" ); $( "#after-submit" ).html( "Your message has successfully been sent!" ); $( "#submit-message" ).attr( "disabled", "disabled" ); } else { $( "#after-submit" ).html( "Error with query!" ); } } }); event.preventDefault(); }, filter: function() { return $( this ).is( ":visible" ); } }); }
const express = require("express"); const Router = express.Router(); const mysqlConnetion = require("../model/connection"); //Atılan adım kayıtları Router.post("/get",(req,res)=>{ let date_ob = new Date(); var dateString = date_ob.getFullYear()+"-"+date_ob.getMonth()+"-"+date_ob.getDate(); console.log(dateString); mysqlConnetion.query("SELECT brand,product_name,step_goal,product_description,product_image,date_of_expiration FROM prizes WHERE prize_number>0 AND date_of_expiration>?",[dateString],(err, rows, fields)=>{ if(!err){ console.log(rows); res.send(rows); } else{ console.log(err);//Başarısız Hata } }); }); module.exports = Router;
const bcrypt = require('bcrypt'); const ServerError = require('../types/ServerError'); const AccessTokens = require('../models').AccessToken; const Scope = require('./Scope').Scope; const User = require('../models').User; function destroyInvalidCookies(req, res, next) { if (req.session.cookies && !req.session.user) { res.clearCookie('user_sid'); } next(); } /** * This middleware ensures that request is authorized by bearer token or session cookies. * Also it checks scopes for request and secured endpoint. Returns '401 Unauthorized' if any check fails * * @param scopes scopes that allowed for accessing this resources. NOTE that 'default' scope means any scope */ function allowFor(...scopes) { return function(req, res, next) { const authorization = req.headers.authorization || ""; // request with bearer token if (authorization.toLowerCase().startsWith('bearer')) { let access_token = authorization.replace(/bearer\s+/i, ''); return AccessTokens.findOne({ where: { token: access_token }}) .then(async (access) => { if (!access || access.token !== access_token) return next(new ServerError('Token is invalid or expired or granted to another client', 'Unauthorized', 401)); if (Date.now() > access.expires) return next(new ServerError('Token is invalid or expired or granted to another client', 'Unauthorized', 401)); // uploader_id will be accessible from further handlers const user = await User.findOne({ where: { id: access.user_id }}); req.uploader_id = user.shikimori_id; // TODO: optimize this let isAllowed = false; access.scopes.forEach(scope => { let scope_obj = new Scope(scope); scopes.forEach(scp => isAllowed |= scope_obj.isAllowedFor(scp)) }); if (isAllowed) return next(); else return next(new ServerError('Token is invalid or expired or granted to another client', 'Not Allowed', 403)); }) .catch(err => next(err)); } // request with session cookies if (req.session.user) { return next(); } return next(new ServerError('You are not authorized to access this', 'Unauthorized', 401)); } } async function validateUser(user, password) { return await bcrypt.compare(password, user.password) .then(ok => ok) .catch(err => { console.error(err); return false; }); } module.exports = { destroyInvalidCookies: destroyInvalidCookies, allowFor: allowFor, validateUser: validateUser };
'use strict'; angular.module('webappV2App') .config(function($routeProvider) { $routeProvider .when('/login', { template: '<login></login>' }); });
let div = document.createElement('div') document.body.appendChild(div); div.style.width = "300px"; div.style.height = "200px"; let parrafo = document.createElement('p'); div.appendChild(parrafo); level = 50 div.style.fontSize = level + "px" let texto = document.createTextNode('🎈'); parrafo.appendChild(texto); div.addEventListener("click", myFunction); function myFunction(){ level = 120 div.style.fontSize = level + "px" div.innerHTML = '💥'; } document.addEventListener('keydown', (event) => { if (event.keyCode === 38) { if (level >= 120) { div.innerHTML = '💥'; console.log('explota') }else { level = level + 10 div.style.fontSize = level + "px" console.log('Se hincha') } } else if (event.keyCode === 40){ if (level <= 50) { level = 50 div.style.fontSize = level + "px" console.log('No se deshincha mas') }else { if ( level >= 120){ level = 120 }else { level = level - 10 div.style.fontSize = level + "px" console.log('Se deshincha')} } } });
/* 获取父节点 element.parentNode; 获取子节点: element.firstChild; element.firstElementChild; element.lastChild; element.lastElementChild; 获取兄弟节点 element.previousSibling element.previousElementSibling element.nextSibling element.nextElementSibling 获取所有子节点: element.childNodes; element.children 获取任意兄弟节点 element.parentNode.children[index] */ /** *功能:传入一个父节点,获取第一个元素子节点 * @param ele * @returns {Element|*|Node} * */ function getFirstChild(ele){ var node=ele.firstElementChild || ele.firstChild; return node; } /** * * 功能: 传入父节点,获取当前父节点的最后一个元素子节点 * @param ele * @returns {Element|*|Node} */ function getLastChild(ele){ return ele.lastElementChild || ele.lastChild; } /** * * 功能: 传入元素对象,返回该元素对象的上一个兄弟元素节点 * @param ele * @returns {Element|*|Node} */ function getPreviousdSibling(ele){ return ele.previousElementSibling || ele.previousSibling; } /** * * 功能: 传入元素对象,返回该元素对象的下一个兄弟元素节点 * @param ele * @returns {Element|*|Node} */ function getNextSibling(ele){ return ele.nextElementSibling ||ele.nextSibling; } /** * 功能: 传入元素对象和索引,返回该元素对象的该索引值的兄弟元素节点 * * @param ele * @param index * @returns {*|HTMLElement} */ function getSiblingByIndex(ele,index){ return ele.parentNode.children[index]; } /** * * 功能: 传入元素对象,返回该元素对象的其他所有兄弟元素节点 返回数组 * @param ele * @returns {Array} */ function getAllSibling(ele){ var arr=[]; var p=ele.parentNode.children; for(var i=0;i< p.length;i++){ if(p[i]!==ele){ arr.push(p[i]); } } return arr; } /** * * 功能: 传入标签id,获取标签元素对象 * @param id * @returns {Element} */ function gid(id){ return document.getElementById(id); }
import React from 'react'; import {shallow, mount} from 'enzyme'; import AddForm from './add-form'; describe('<AddForm />', () => { //smoke test it('Renders without crashing', () => { shallow(<AddForm />); }); //the first test shows how you can make assertions about DOM elements //output by your component //wrapper has a similar API to jQuery for traversing //and manipulating the output //use the hasClass method to check that the root element //output by AddForm has the class add-button it('Renders the add button initially', () => { const wrapper = shallow(<AddForm />); expect(wrapper.hasClass('add-button')).toEqual(true); }); //The second test shows one of the ways to manipulate the //component's output, using .instance, which allows us to access instance //methods on the component. Calling .instance returns the instance of //the React component. We use this to call the setEditing method, which //updates the state of the component. When we call a method which //updates the state, Enzyme won't automatically rerender the component. //To make sure it rerenders we call the .update() method. Then we can // make assertions about its modified output. Here, we ensure that //the root element has changed from the <div> with class add-button //to the <form> with class add-form. it('Should render the add form when editing', () => { const wrapper = shallow(<AddForm />); wrapper.instance().setEditing(true); wrapper.update(); expect(wrapper.hasClass('add-form')).toEqual(true); }); //As well as directly manipulating elements, you can simulate DOM events using //the simulate method to ensure that your component responds correctly to user //interactions. Below, we simulate a click on the add button, and then //use the state method to check that the editing property of the component's //state has been set to true. Note that Enzyme automatically checks for updates //after simulating an event, so we don't need to call .update() here. it('Should switch to editing when the add button is clicked', () => { const wrapper = shallow(<AddForm />); wrapper.simulate('click'); expect(wrapper.state('editing')).toEqual(true); }); //full DOM rendering // Both tests start by using the jest.fn method to make a spy. Spies are small //functions that keep a record of each time they have been called. They are useful //for testing callback functions. In this case, we use a spy to make sure that //the component's onAdd callback is called correctly when the form is submitted. it('Should fire the onAdd callback when the form is submitted', () => { const callback = jest.fn(); //spy const wrapper = mount(<AddForm onAdd={callback} />); //render the component const value = 'Foobar'; wrapper.instance().setEditing(true); //setEditing method is called so the form is rendered wrapper.update(); wrapper.find('input[type="text"]').instance().value = value; //find the text input and set its value wrapper.simulate('submit'); //check whether the spy has been called, depending on if the text input was filled in expect(callback).toHaveBeenCalledWith(value); }); //full DOM rendering // it('Should not fire onAdd if the input is empty', () => { const callback = jest.fn(); const wrapper = mount(<AddForm onAdd={callback} />); wrapper.instance().setEditing(true); wrapper.simulate('submit'); expect(callback).not.toHaveBeenCalled(); }); });
jest.mock('../../../../../src/entities/user/createUser'); const { createUser } = require('../../../../../src/services/user'); const { createUser: createUserMock } = require('../../../../../src/entities/user'); const userFixture = { email: 'test@test.com', password: '123456', }; describe('User Service', () => { describe('Create User', () => { beforeEach(() => { createUserMock.mockClear(); }); it('should call createUser entity when create a user', async () => { createUserMock.mockReturnValue({ id: '3fa85f64-5717-4562-b3fc-2c963f66afa6', email: 'test@test.com', password: '123456', }); await createUser(userFixture); expect(createUserMock).toHaveBeenCalledTimes(1); }); }); });
import React, { Component } from 'react'; class Product extends Component { render() { return ( <div> <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <div className="thumbnail"> <img src="https://cdn.tgdd.vn/Products/Images/42/92962/iphone-6-32gb-gold-hh-600x600.jpg" alt="Iphone 6"/> <div className="caption"> <h3>Iphone 6 Plus</h3> <p> 16.000.000 VNĐ </p> <button type="button" className="btn btn-success">Mua Hang</button> </div> </div> </div> </div> ); } } export default Product;
// @depends(dna/prop/Prop) const df = { symbol: '$', productivity: .025, } class Factory extends dna.prop.Prop { constructor(st) { super( augment({}, df, st) ) } next() { // maybe spawn something? if (rnd() < this.productivity && !this._.isOccupied(this.x, this.y)) { this._.spawn( dna.bot.Mech, { team: 0, x: this.x, y: this.y, }) } } }
import React from 'react' import Icon from './Icon' const NodeCollapsedIcon = props => ( <Icon originalWidth={16} originalHeight={16} {...props}> <g> <rect x='1' y='1' rx='4' width='14' height='14' fill='#f0f0f0' stroke='#b5b5b5' strokeWidth='1' /> <line x1='2' y1='8' x2='14' y2='8' stroke='#b5b5b5' strokeWidth='2' /> <line x1='8' y1='2' x2='8' y2='14' stroke='#b5b5b5' strokeWidth='2' /> </g> </Icon> ) export default NodeCollapsedIcon
class Pikeman { constructor() { this.hitPoints = 5; this.trainingHitpoints = 3; this.trainingCost = 10; this.upgradeCost = 30; } upgrade() { return new Archer(); } } class Archer { constructor() { this.hitPoints = 10; this.trainingHitpoints = 7; this.trainingCost = 20; this.upgradeCost = 40; } upgrade() { return new Knigt(); } } class Knigt { constructor() { this.hitPoints = 20; this.trainingHitpoints = 10; this.trainingCost = 30; } } module.exports = { Pikeman, Archer, Knigt }
 var DeliverableModel = function () { this.ID; this.DeliverableID; this.NaturalUnitID; this.NaturalUnitName; this.Assumptions; this.LowCount; this.MedCount; this.HighCount; this.IterationCount; this.UserID; this.PercentComplete; }
import React from 'react'; import Navbar from '../Navbar/Navbar'; import './About.css' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faHandPointRight } from '@fortawesome/free-solid-svg-icons'; const About = () => { return ( <section className="about" style={{ backgroundColor:'#D8FFFB'}}> <h1 className="d-flex justify-content-center"> <span style={{marginTop:'30px'}}>About</span> </h1> <div className="container"> <div className="Card" style={{marginTop:'30px'}}> <div className="card-body"> <div className="container"> <div className="row"> <div className="col-md-6 col-sm-12"> <h3>Skills</h3> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> JavaScript(ES6)</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> React.js</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Node.js</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> HTML/CSS</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Bootstrap</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Material Ui</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Mongodb</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Firebase</h5> <h5><FontAwesomeIcon style={{color:'#5052d9'}} icon={faHandPointRight}/> Heroku</h5> </div> <div className="col-md-6 col-sm-12"> <h3>Summary</h3> <p>I am a front-end web developer. I have experience with building websites and web applications. I specialize in JavaScript ES6 and have experience working with React. I also have experience working with the express.js framework.</p> </div> </div> </div> </div> </div> </div> </section> ); }; export default About;
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var artefactSchema = new Schema({ title : String, creator : String, subject : String, description : String, publisher : String, contributor : String, date : Date, type : String, format : String, identifier : String, source : String, language : String, relation : String, coverage : String, rights : String }); var Artefacts = mongoose.model('Artefacts', artefactSchema); module.exports = Artefacts;
export function borderBox() { return ` -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; `; } export function widthFlex(width) { return ` -ms-flex-preferred-size: ${width}; flex-basis: ${width}; max-width: ${width}; `; } export function rowFlexBox(){ return ` box-sizing: border-box; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-flex: 0; -ms-flex: 0 1 auto; flex: 0 1 auto; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -ms-flex-wrap: wrap; flex-wrap: wrap; `; }
import Vue from 'vue' import Router from 'vue-router' const home = r => require.ensure([], () => r(require('../components/home')), 'home') const shouye = r => require.ensure([], () => r(require('../components/shouye')), 'shouye') const gerenzhongxin = r => require.ensure([], () => r(require('../components/gerenzhongxin')), 'gerenzhongxin') const guangchang = r => require.ensure([], () => r(require('../components/guangchang')), 'guangchang') const wenzhangxiangqing = r => require.ensure([], () => r(require('../components/wenzhangxiangqing')), 'wenzhangxiangqing') const zhuanfawenzhangxiangqing = r => require.ensure([], () => r(require('../components/zhuanfawenzhangxiangqing')), 'zhuanfawenzhangxiangqing') const register = r => require.ensure([], () => r(require('../components/register')), 'register') const login = r => require.ensure([], () => r(require('../components/login')), 'login') const xiangxixinxi = r => require.ensure([], () => r(require('../components/gerenzhongxin/xiangxixinxi')), 'xiangxixinxi') const fabuwenzhang = r => require.ensure([], () => r(require('../components/fabuwenzhang')), 'fabuwenzhang') const haoyouliebiao = r => require.ensure([], () => r(require('../components/gerenzhongxin/haoyouliebiao')), 'haoyouliebiao') const wodefabu = r => require.ensure([], () => r(require('../components/gerenzhongxin/wodefabu')), 'wodefabu') const wodeshoucang = r => require.ensure([], () => r(require('../components/gerenzhongxin/wodeshoucang')), 'wodeshoucang') const wodeqianbao = r => require.ensure([], () => r(require('../components/gerenzhongxin/wodeqianbao')), 'wodeqianbao') const jiaoyijilu = r => require.ensure([], () => r(require('../components/gerenzhongxin/jiaoyijilu')), 'jiaoyijilu') const yijianfankui = r => require.ensure([], () => r(require('../components/gerenzhongxin/yijianfankui')), 'yijianfankui') const wodexiaoxi = r => require.ensure([], () => r(require('../components/gerenzhongxin/wodexiaoxi')), 'wodexiaoxi') const gerenzhuye = r => require.ensure([], () => r(require('../components/gerenzhongxin/gerenzhuye')), 'gerenzhuye') const haoyoutuijian = r => require.ensure([], () => r(require('../components/gerenzhongxin/haoyoutuijian')), 'haoyoutuijian') const xiugaiyonghuming = r => require.ensure([], () => r(require('../components/gerenzhongxin/xiugaiyonghuming')), 'xiugaiyonghuming') const fabushuoshuo = r => require.ensure([], () => r(require('../components/fabushuoshuo')), 'fabushuoshuo') const chongzhi = r => require.ensure([], () => r(require('../components/gerenzhongxin/chongzhi')), 'chongzhi') const faqizhifu = r => require.ensure([], () => r(require('../components/gerenzhongxin/faqizhifu')), 'faqizhifu') const shezhizhifumima = r => require.ensure([], () => r(require('../components/gerenzhongxin/shezhizhifumima')), 'shezhizhifumima') const xiugaizhifumima = r => require.ensure([], () => r(require('../components/gerenzhongxin/xiugaizhifumima')), 'xiugaizhifumima') const wanshanziliao = r => require.ensure([], () => r(require('../components/gerenzhongxin/wanshanziliao')), 'wanshanziliao') const tixian = r => require.ensure([], () => r(require('../components/gerenzhongxin/tixian')), 'tixian') const xiufanghua = r => require.ensure([], () => r(require('../components/xiufanghua')), 'xiufanghua') const xiufanghuaxiangqing = r => require.ensure([], () => r(require('../components/xiufanghuaxiangqing')), 'xiufanghuaxiangqing') const youxiutuanduixiangqing = r => require.ensure([], () => r(require('../components/youxiutuanduixiangqing')), 'youxiutuanduixiangqing') const tuanduifengcaixiangqing = r => require.ensure([], () => r(require('../components/tuanduifengcaixiangqing')), 'tuanduifengcaixiangqing') const xitongxiaoxipinglunxiangqing = r => require.ensure([], () => r(require('../components/gerenzhongxin/xitongxiaoxipinglunxiangqing')), 'xitongxiaoxipinglunxiangqing') const gexingqianming = r => require.ensure([], () => r(require('../components/gerenzhongxin/gexingqianming')), 'gexingqianming') const xitongxiaoxidianzanxiangqing = r => require.ensure([], () => r(require('../components/gerenzhongxin/xitongxiaoxidianzanxiangqing')), 'xitongxiaoxidianzanxiangqing') const xiufengcai = r => require.ensure([], () => r(require('../components/xiufengcai')), 'xiufengcai') const fabuxiufengcai = r => require.ensure([], () => r(require('../components/fabuxiufengcai')), 'fabuxiufengcai') const fabuxiufengcaitest = r => require.ensure([], () => r(require('../components/fabuxiufengcaitest')), 'fabuxiufengcaitest') const xiufengcaixiangqing = r => require.ensure([], () => r(require('../components/xiufengcaixiangqing')), 'xiufengcaixiangqing') const guangchangxiangqing = r => require.ensure([], () => r(require('../components/guangchangxiangqing')), 'guangchangxiangqing') const shenfenrenzheng = r => require.ensure([], () => r(require('../components/gerenzhongxin/shenfenrenzheng')), 'shenfenrenzheng') const huojiangtuandui = r => require.ensure([], () => r(require('../components/huojiangtuandui')), 'huojiangtuandui') // 首页 const Index = r => require.ensure([], () => r(require('../components/home/Index')), 'Index') //签到 const Sign = r => require.ensure([], () => r(require('../components/home/Sign')), 'Sign') //签到详情 const SignDetail = r => require.ensure([], () => r(require('../components/home/SignDetail')), 'SignDetail') //基金 const JiJin = r => require.ensure([], () => r(require('../components/home/JiJin')), 'JiJin') //康养 const KangYang = r => require.ensure([], () => r(require('../components/home/KangYang')), 'KangYang') //基地 const Cell = r => require.ensure([], () => r(require('../components/home/Cell')), 'Cell') //秀头条 const XiuTouTiao = r => require.ensure([], () => r(require('../components/home/XiuTouTiao')), 'XiuTouTiao') const TTdetail = r => require.ensure([], () => r(require('../components/home/TouTiaoDetail')), 'TouTiaoDetail'); //积分兑换 const Exchange = r => require.ensure([], () => r(require('../components/home/exchange')), 'exchange') const newSign = r => require.ensure([], () => r(require('../components/sign/Sign')), 'newSign'); const Calendar = r => require.ensure([], () => r(require('../components/sign/Calendar')), 'Calendar'); const signRule = r => require.ensure([], () => r(require('../components/sign/Rule')), 'signRule'); const Workrank = r => require.ensure([], () => r(require('../components/sign/Workrank')), 'Workrank'); const Honor = r => require.ensure([], () => r(require('../components/sign/Honor')), 'Honor'); Vue.use(Router) export default new Router({ routes: [ { path: '/ttdetail', name: 'TTdetail', component: TTdetail, meta: { title: '秀头条详情', } }, { path: '/honor', name: 'honor', component: Honor, meta: { title: '荣誉卡', } }, { path: '/workrank', name: 'workrank', component: Workrank, meta: { title: '荣誉排行榜', } }, { path: '/signrule', name: 'signRule', component: signRule, meta: { title: '任务规则', keepAlive: false } }, { path: '/calendar', name: 'Calendar', component: Calendar, meta: { title: '签到记录', keepAlive: false } }, { path: '/newsign', name: 'newSign', component: newSign, meta: { title: '任务系统', keepAlive: false } }, { path: '/', name: 'home', component: home, meta: { title: '首页', keepAlive: false }, children: [ { path: '/guangchang', name: 'guangchang', component: guangchang, meta: { title: '秀生活', keepAlive: true }, }, { path: '/shouye', name: 'shouye', component: shouye, meta: { title: '秀文采', keepAlive: true }, }, { path: '/', name: 'Index', component: Index, meta: { title: '首页', KeepAlive:false }, }, { path: '/xiufanghua', name: 'xiufanghua', component: xiufanghua, meta: { title: '才艺大赛', keepAlive: true }, }, { path: '/gerenzhongxin', name: 'gerenzhongxin', component: gerenzhongxin, meta: { title: '个人中心', keepAlive: false }, } ] }, { path: '/sign', name: 'Sign', component: Sign, meta: { title: '签到', keepAlive: false }, }, { path: '/signdetail', name: 'SignDetail', component: SignDetail, meta: { title: '积分明细', keepAlive: false }, }, { path: '/exchange', name: 'Exchange', component: Exchange, meta: { title: '积分兑换', keepAlive: false }, }, { path: '/jijin', name: 'JiJin', component: JiJin, meta: { title: '互帮互助基金', keepAlive: false }, }, { path: '/kangyang', name: 'KangYang', component: KangYang, meta: { title: '康养基地', keepAlive: false }, }, { path: '/cell', name: 'Cell', component: Cell, meta: { title: '干细胞', keepAlive: false }, }, { path: '/topline', name: 'XiuTouTiao', component: XiuTouTiao, meta: { title: '秀头条', keepAlive: false }, }, { path: '/wenzhangxiangqing', name: 'wenzhangxiangqing', component: wenzhangxiangqing, meta: { title: '文章详情', keepAlive: false } }, { path: '/zhuanfawenzhangxiangqing', name: 'zhuanfawenzhangxiangqing', component: zhuanfawenzhangxiangqing, meta: { title: '文章详情', keepAlive: false } }, { path: '/login', name: 'login', component: login, meta: { title: '登录', }, }, { path: '/register', name: 'register', component: register, meta: { title: '注册', }, }, { path: '/xiangxixinxi', name: 'xiangxixinxi', component: xiangxixinxi, meta: { title: '个人信息', keepAlive: false }, }, { path: '/fabuwenzhang', name: 'fabuwenzhang', component: fabuwenzhang, meta: { title: '发布文章', keepAlive: false }, }, { path: '/fabushuoshuo', name: 'fabushuoshuo', component: fabushuoshuo, meta: { title: '发布说说', keepAlive: false }, }, { path: '/haoyouliebiao', name: 'haoyouliebiao', component: haoyouliebiao, meta: { title: '关注列表', keepAlive: false }, }, { path: '/wodefabu', name: 'wodefabu', component: wodefabu, meta: { title: '我的文章', keepAlive: false }, }, { path: '/wodeshoucang', name: 'wodeshoucang', component: wodeshoucang, meta: { title: '我的收藏', keepAlive: false } }, { path: '/wodeqianbao', name: 'wodeqianbao', component: wodeqianbao, meta: { title: '我的钱包', keepAlive: false } }, { path: '/jiaoyijilu', name: 'jiaoyijilu', component: jiaoyijilu, meta: { title: '我的钱包', keepAlive: false } }, { path: '/yijianfankui', name: 'yijianfankui', component: yijianfankui, meta: { title: '意见反馈', keepAlive: false } }, { path: '/wodexiaoxi', name: 'wodexiaoxi', component: wodexiaoxi, meta: { title: '我的消息', keepAlive: false } }, { path: '/gerenzhuye', name: 'gerenzhuye', component: gerenzhuye, meta: { title: '个人主页', keepAlive: false } }, { path: '/haoyoutuijian', name: 'haoyoutuijian', component: haoyoutuijian, meta: { title: '推荐笔友', keepAlive: false } }, { path: '/xiugaiyonghuming', name: 'xiugaiyonghuming', component: xiugaiyonghuming, meta: { title: '个人中心', keepAlive: false } }, { path: '/chongzhi', name: 'chongzhi', component: chongzhi, meta: { title: '充值', keepAlive: false } }, { path: '/faqizhifu', name: 'faqizhifu', component: faqizhifu, meta: { title: '支付', keepAlive: false } }, { path: '/shezhizhifumima', name: 'shezhizhifumima', component: shezhizhifumima, meta: { title: '设置支付密码', keepAlive: false } }, { path: '/xiugaizhifumima', name: 'xiugaizhifumima', component: xiugaizhifumima, meta: { title: '验证手机号', keepAlive: false } }, { path: '/wanshanziliao', name: 'wanshanziliao', component: wanshanziliao, meta: { title: '完善资料', keepAlive: false } }, { path: '/tixian', name: 'tixian', component: tixian, meta: { title: '提现', keepAlive: false } }, { path: '/xiufanghuaxiangqing', name: 'xiufanghuaxiangqing', component: xiufanghuaxiangqing, meta: { title: '获奖团队', keepAlive: false } }, { path: '/youxiutuanduixiangqing', name: 'youxiutuanduixiangqing', component: youxiutuanduixiangqing, meta: { title: '优秀团队', keepAlive: false } }, { path: '/tuanduifengcaixiangqing', name: 'tuanduifengcaixiangqing', component: tuanduifengcaixiangqing, meta: { title: '团队风采', keepAlive: false } }, { path: '/xitongxiaoxipinglunxiangqing', name: 'xitongxiaoxipinglunxiangqing', component: xitongxiaoxipinglunxiangqing, meta: { title: '消息', keepAlive: false } }, { path: '/gexingqianming', name: 'gexingqianming', component: gexingqianming, meta: { title: '个性签名', keepAlive: false } }, { path: '/xitongxiaoxidianzanxiangqing', name: 'xitongxiaoxidianzanxiangqing', component: xitongxiaoxidianzanxiangqing, meta: { title: '系统消息', keepAlive: false } }, { path: '/fabuxiufengcai', name: 'fabuxiufengcai', component: fabuxiufengcai, meta: { title: '发布图片', keepAlive: false } }, { path: '/fabuxiufengcaitest', name: 'fabuxiufengcaitest', component: fabuxiufengcaitest, meta: { title: '发布图片', keepAlive: false } },{ path: '/xiufengcaixiangqing', name: 'xiufengcaixiangqing', component: xiufengcaixiangqing, meta: { title: '秀风采详情', keepAlive: false } }, { path:'/guangchangxiangqing', name:'guangchangxiangqing', component:guangchangxiangqing, meta:{ title:'说说详情', keepAlive: false } }, { path:'/shenfenrenzheng', name:'shenfenrenzheng', component:shenfenrenzheng, meta:{ title:'身份认证', keepAlive: false } }, { path:'/huojiangtuandui', name:'huojiangtuandui', component:huojiangtuandui, meta:{ title:'获奖团队', keepAlive: false } }, ], })
import ServerProtocol from '../libs/serverProtocol.js' import BattlesModel from '../models/battlesModel.js' import AgreementsModel from '../models/agreementsModel.js' import ChronosModel from '../models/chronosModel.js' import PersonsModel from '../models/personsModel.js' class BattlesProtocol extends ServerProtocol { constructor() { super() this.init() } init() { super.addHandler('clQueryDataByYear', this.getDataByYear) super.addHandler('clGetCurrentYear', this.getCurrentYear) super.addHandler('clGetPersons', this.getPersons) super.addHandler('clGetPersonItem', this.getPersonItem) } getCurrentYear(socket, msg, cb) { let res = {} res.year = undefined // todo cb(JSON.stringify(res)) } getPersonItem(socket, msg, cb) { let data = JSON.parse(msg) let res = {} try { PersonsModel.find({ '_id': data.id }) .then( (res) => { if (res.length == 0) { throw new Error('Person by id is not Found') } else { cb( JSON.stringify(res[0]) ) } }) .catch((error) => { cb(JSON.stringify({ error: error })) }) } catch (err) { res.err = 'Ошибка возврата персоны: ' + err res.events = '' cb(JSON.stringify(res)) } } getDataByYear(socket, msg, cb) { let res = {} try { let data = JSON.parse(msg) let startDate = new Date(data.year, 0, 1).toISOString() let endDate = new Date(data.year, 11, 31).toISOString() const searchDates = { $gte: startDate, $lt: endDate, } const defaultSearchParam = { startDate: searchDates, } const promices = [ BattlesModel.find(defaultSearchParam), AgreementsModel.find(defaultSearchParam), ChronosModel.find({'start.year': data.year}), PersonsModel.find({ dateBirth: searchDates, }), PersonsModel.find({ dateAchievement: searchDates, }), PersonsModel.find({ dateDeath: searchDates, }), ] Promise.all(promices) .then((res) => { cb( JSON.stringify({ battles: res[0], agreements: res[1], chronos: res[2], personsBirth: res[3], personsAchievement: res[4], personsDeath: res[5], }) ) }) .catch((error) => { cb(JSON.stringify({ error: error })) }) } catch (err) { res.err = 'Ошибка парсинга даты: ' + err res.events = '' cb(JSON.stringify(res)) } } } export default new BattlesProtocol()
define([ 'fmwk/core/BaseView', 'text!templates/home.html' ], function (root, homeTemplate) { root.app.HomeView = root.BaseView.extend({ el: '#home-view', template: _.template(homeTemplate), initialize: function () { this.$el.html(this.template()); this.video = document.getElementById("home-video"); }, playVideo: function () { this.video.play(); }, stopVideo: function () { this.video.pause(); } }); return root; });
/** * === page === * * created at: Tue Jun 27 2017 18:27:29 GMT+0800 (CST) */ import { React, Page } from 'zola' // import ArticleMap from 'data/article' import AsyncComponent from 'modules/AsyncComponent' import ArticleRender from 'modules/ArticleRender' export default class Index extends Page { render () { const filePath = this.props.params.path const path = `/article/${filePath}.md` return ( <div> <ArticleRender articlePath={path}/> </div> ) } }
var mongoose = require('mongoose'), Transaction = mongoose.model('Transaction'); exports.clear = function () { Transaction.remove({}, function (err) { if (err) { console.log(err); } else { console.log('Transaction collection dropped'); } return; }) } exports.all = function (callback) { Transaction.find(function (err, transactions) { if (err) { console.log(err); return; } else { console.log('Transactions found: ' + transactions); callback(transactions); } }); }; exports.find = function (queryData, callback) { var query = queryBuilder(queryData); Transaction.find(query, function (err, transactions) { if (err) { console.log(err); callback(null); } else if (transactions.length <= 0) { console.log('No transactions found'); callback(null); } else { console.log('Transactions found: ' + transactions); callback(transactions); } }); }; function queryBuilder(queryData) { var query = {}; query.userId = queryData.userId; if (queryData.productId) { query.productId = queryData.productId; } return query; } exports.insert = function (transactionData, callback) { Transaction.create({ userId: transactionData.userId, productId: transactionData.productId }, function (err, transaction) { if (err) { console.log(err); } else { //console.log("Transaction created: " + transaction); callback(); } }) }
var path = require('path'); var webpack = require('webpack'); var DedupePlugin = webpack.optimize.DedupePlugin; var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var isDev = process.env.COINS_ENV === 'development'; var clientEntry = path.join(__dirname, 'src', 'client', 'client.js'); var clientOutput = path.join(__dirname, 'dist', 'client', 'dist'); module.exports = { bail: true, entry: { client: clientEntry }, output: { path: clientOutput, filename: '[name].js' }, plugins: [ new DedupePlugin(), ].concat(!isDev ? [ new UglifyJsPlugin({ sourceMap: false, compress: { warnings: false } }) ] : []), module: { loaders: [ { test: /\.json$/, loader: 'json' }, { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel', // 'babel-loader' is also a legal name to reference query: { presets: ['es2015'] } } ] }, externals: [ { url: false } ], node: { fs: "empty" } };
var products; var productGroups; var currentProduct; ricoApp.config(function ($routeProvider) { $routeProvider. when('/overview', { templateUrl: 'MarketOverview.tpl.html', controller: 'MarketOverviewControll', resolve: { init: ['InitService', function(Init) { return Init.promise; }] } }). when('/product/:productId', { templateUrl: 'MarketProduct.tpl.html', controller: 'MarketProductControll', controllerAs: 'app' }). when('/basket', { templateUrl: 'MarketBasket.tpl.html', controller: 'MarketBasketControll', controllerAs: 'app' }); }); ricoApp.controller('ControllMarketplace',function($scope,IndexedDb){ IndexedDb.readConfig('customerId').then(function(customerId){ IndexedDb.getCustomer(customerId).then( function(customer){ currentCustomer=customer; if(currentCustomer.ordering != undefined && currentCustomer.ordering.length>0){ var o=currentCustomer.ordering[currentCustomer.ordering.length-1]; if(o.orderingPos!=undefined){ // }else{ currentCustomer.ordering[currentCustomer.ordering.length-1].orderingPos=[]; }; }else{ currentCustomer.ordering=[{orderingPos:[]}]; }; }); }); $scope.orderPosCount=function(){ if(currentCustomer!=undefined && currentCustomer.ordering != undefined && currentCustomer.ordering.length>0 && currentCustomer.ordering[currentCustomer.ordering.length-1].orderingPos !=undefined){ return currentCustomer.ordering[currentCustomer.ordering.length-1].orderingPos.length; }else{ return ""; } }; }); ricoApp.service('InitService', ['$q','IndexedDb', function ( $q, IndexedDb) { var defer = $q.defer(); IndexedDb.readProducts().then(function(data){ products=data; productGroups=[]; for(var i=0;i<products.length;i++){ if (productGroups.indexOf(products[i].prodGroup)<0){ productGroups.push(products[i].prodGroup); }; }; IndexedDb.readConfig('customerId').then(function(customerId){ IndexedDb.getCustomer(customerId).then( function(customer){ currentCustomer=customer; defer.resolve(); }); }); }); return { defer: defer, promise: defer.promise }; }]);
export default { namespaced: true, state: { items: [ { name: 'products', title: 'Products' }, { name: 'cart', title: 'Cart' }, { name: 'order', title: 'Checkout' } ] }, getters: { items(state){ return state.items; } }, mutations: { }, actions: { } }
const https = require('https'); const fs = require('fs'); const _exec = require('child_process').exec; function MKVBait(msg){ try { msg.reply('Generating your bait...') const [file, rnum] = [msg.attachments.array()[0].url, Math.floor(Math.random() * 999)] https.get(file, function (response) { if(process.platform === 'linux') { var [A, B] = [`MakeBait/Workspace/A_${rnum}`, `MakeBait/Results/Bait_${rnum}.mp3`]; var DeleteFiles = `rm -rf "${A}" "${B}"` } else if(process.platform === 'win32') { var [A, B] = [`MakeBait\\Workspace\\A_${rnum}`, `MakeBait\\Results\\Bait_${rnum}.mp3`]; var DeleteFiles = `Del "${A}" "${B}"` }; var endFile = fs.createWriteStream(A); var stream = response.pipe(endFile); stream.on('finish', function () { _exec(`ffmpeg -i ${A} -f matroska -acodec libmp3lame -ac 1 -aq 0 -ar 8000 -ss 0 -to 0.45 ${B}`, function (err) { if (err) throw err; msg.member.send({ embed: { "title": `Generated your bait :)`, "color": 0X36393F, "author": { "name": msg.author.username, "icon_url": msg.author.avatarURL() } }}).then(()=>{ msg.reply('Sent the bait to your dms :)'); msg.member.send({ files: [B] }) }).catch(() => {msg.reply('Error sending the file to your dms. Make sure your dms are enabled!')}) setTimeout(() => { _exec(DeleteFiles, () => { console.log('Deleted All Files') }) }, 15000); }); }); }); } catch { msg.reply('Error Occured.'); }; }; function WEBMBait(msg){ try { msg.reply('Generating your bait...') const [file, rnum] = [msg.attachments.array()[0].url, Math.floor(Math.random() * 999)] https.get(file, function (response) { if(process.platform === 'linux') { var [A, B, C] = [`MakeBait/Workspace/A_${rnum}`, `MakeBait/Workspace/B_${rnum}.ogg`,`MakeBait/Results/Bait_${rnum}.ogg`]; var DeleteFiles = `rm -rf "${A}" "${B}" "${C}"` } else if(process.platform === 'win32') { var [A, B, C] = [`MakeBait\\Workspace\\A_${rnum}`, `MakeBait\\Workspace\\B_${rnum}.ogg`,`MakeBait\\Results\\Bait_${rnum}.ogg`]; var DeleteFiles = `Del "${A}" "${B}" "${C}"` }; var endFile = fs.createWriteStream(A); var stream = response.pipe(endFile); stream.on('finish', function () { _exec(`ffmpeg -i ${A} -f webm -acodec libvorbis -ac 1 -ar 44100 -ss 00:00:00 -t 00:01:15 ${B}`, function (err) { if (err) throw err; fs.readFile(B, 'binary', function (err, data) { if (err) throw err; data = data.replace(/webm/, ' anti || https://discord.gg/m4DETpH4hp '); fs.writeFile(C, data, 'binary', function (err) { if (err) throw err; msg.member.send({ embed: { "title": `Generated your bait :)`, "color": 0X36393F, "author": { "name": msg.author.username, "icon_url": msg.author.avatarURL() } }}).then(()=>{ msg.reply('Sent the bait to your dms :)'); msg.member.send({ files: [C] }) }).catch(() => {msg.reply('Error sending the file to your dms. Make sure your dms are enabled!')}) setTimeout(() => { _exec(DeleteFiles, () => { console.log('Deleted All Files') }) }, 15000); }); }); }); }); }); } catch { msg.reply('Error Occured.'); }; }; module.exports = {MKVBait: MKVBait, WEBMBait: WEBMBait};
export * from './Home' export * from './Error' export * from './About'
$(document).ready(function () { $('#nav_user').click(function () { $('.chat-sidebar').toggleClass('focus'); }); }); function LikeUnlikeSatus($id) { $.post('/post-like', {'id_article': $id}, function (data) { if(data === 'like'){ $('#status_'+$id +' .like-Unlike').attr('action', 'unlike'); $('#status_'+$id +' .like-Unlike').html('<i class="fa fa-thumbs-o-down">Unlike</i>'); $val = parseInt($('#status_'+$id +' .like-Unlike').parent().find('.pull-right.text-muted').children('.count-like').text()) + 1; $('#status_'+$id +' .like-Unlike').parent().find('.pull-right.text-muted').children('.count-like').text($val); }else { $('#status_'+$id +' .like-Unlike').attr('action', 'like'); $('#status_'+$id +' .like-Unlike').html('<i class="fa fa-thumbs-o-up">Like</i>'); $val = parseInt($('#status_'+$id +' .like-Unlike').parent().find('.pull-right.text-muted').children('.count-like').text()) - 1; $('#status_'+$id +' .like-Unlike').parent().find('.pull-right.text-muted').children('.count-like').text($val); } }); } function getAddFriend() { $.post('/get-list-addfriend/', {}, function (data) { $('#content_addfriend').html(data); }); } function ConfirmAddFriend($id) { $.post('/confirm-friend/' + $id, {'id_friend': $id}, function (data) { }); $('#fr_'+$id).remove(); } function ReadAllMessage() { $.post('/read-allmessage', {}, function (data) { }); $('#content_allmessage').html(''); } function ReadOneChat($chat){ $.post('/read-allmessage?chat='+$chat, {}, function (data) { }); } function ReadAllNotification(){ $.post('/read-notification', {}, function (data) { }); $('#content_notifycation').html(''); } function ReadOneNotify($notify){ $.post('/read-notification?notify='+$notify, {}, function (data) { }); } $('.addfriend_unfriend').click(function (e) { $id_other = $(this).attr('id-other'); $action = $(this).attr('action'); if ($action === 'send') { $.post("/send-add-friend/" + $id_other, {}, function (data) { }); $(this).text('cancel add friend'); } if ($action === 'unfriend') { $.post('/send-unfriend/' + $id_other, {}, function (data) { }); $(this).text('add friend'); } if ($action === 'cancelsend') { $.post('/send-unsendfriend/' + $id_other, {}, function (data) { }); $(this).text('add friend'); } }); $('.join-group').click(function (e) { $id_group = $(this).attr('id_group'); $action = $(this).attr('action'); if ($action === 'join') { $.post("/join-group/" + $id_group, {}, function (data) { }); $(this).attr('unjoin'); $(this).text('UnJoin Group'); } if ($action === 'unjoin') { $.post('/unjoin-group/' + $id_group, {}, function (data) { }); $(this).attr('join'); $(this).text('Join Group'); } }); function handleEnterComment(e,id_status){ var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { if($.trim($('#status_'+id_status+' input[name="content_comment"]').val()) != '') { var content = $.trim($('#status_'+id_status+' input[name="content_comment"]').val()); var action = $('#status_'+id_status+' input[name="content_comment"]').attr('action'); $.post('/post-comment/' + id_status, {'content_stt':content,'action':action}, function (data) { if(action === '') { if ($('#status_' + id_status + ' .box-footer.box-comments .box-comment').length === 0) { $('#status_' + id_status).children('.boxmain-comment').append('<div class="box-footer box-comments" style="display: block;">' + data + '</div>'); } else { $('#status_' + id_status + ' .boxmain-comment .box-footer.box-comments .box-comment').last().after(data); } }else { var id_cmt = action.split('_'); $('#comment_'+id_status+'_'+id_cmt[1]+ ' .content-comment').text(content); } }); $('#status_'+id_status+' input[name="content_comment"]').val(''); $('#status_'+id_status+' input[name="content_comment"]').attr('action',''); } } } // preview image function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#myAvatar_preview').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#myAvatar").change(function () { readURL(this); }); function readURL1(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#myCover_preview').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#myCover").change(function () { readURL1(this); }); function readURL2(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#addImageGroup1').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#addImageGroup").change(function () { readURL2(this); }); //Check File API support if (window.File && window.FileList && window.FileReader) { var filesInput = document.getElementById("addImageStatus"); if(filesInput != null) { filesInput.addEventListener("change", function (event) { var files = event.target.files; //FileList object var output = document.getElementById("results_upload"); for (var i = 0; i < files.length; i++) { var file = files[i]; //Only pics if (!file.type.match('image')) continue; var picReader = new FileReader(); picReader.addEventListener("load", function (event) { var picFile = event.target; var div = document.createElement("li"); div.innerHTML = "<img class='thumbnail' style='margin-bottom: 0px;' width='100' height='100' src='" + picFile.result + "'" + "title='" + picFile.name + "'/> <a style='cursor: pointer;' onclick='removeHtml(this)' class='remove_pict'>X</a>"; output.insertBefore(div, null); }); //Read the image picReader.readAsDataURL(file); } }); } } $("#results_upload").on("click", ".remove_pict", function () { $(this).parent().remove(); }); function DeleteComment($id_status, $id_comment) { $.post('/delete-commentstatus/', {"id_status":$id_status,"id_comment":$id_comment}, function (data) { $('#comment_'+$id_status+'_'+$id_comment).remove(); }); } function EditComment($id_status, $id_comment,$curr) { var curr_content = $($curr).parent().parent().parent().parent().find('.content-comment').text(); $('#status_'+$id_status+' input[name="content_comment"]').val(curr_content); $('#status_'+$id_status+' input[name="content_comment"]').attr('action','editcomment_'+$id_comment); } function readmore_comment($id) { $('.readmore_comment').hide(); $.post('/readmore-comment/'+$id, {}, function (data) { var domain = 'http://localhost:8080/readmore-comment/'+$id; $('#status_'+$id+' .box-footer.box-comments').prepend($('<div>').load(domain, function () { })); }); } function delete_status(event) { $(event).children('ul').toggle(); } function action_delete_status($id) { $.post('/delete-status', {'id_status':$id}, function (data) { if(data === 'ok'){ $('#status_'+$id).remove(); } }); } $(document).ready(function () { setInterval(function () { $.post('/update-noti',{}, function (data) { var result = JSON.parse(data); if(result.mess.length >0){ $('#inbox').html('<span class="red">'+result.mess.length+'</span>'); }else { } if(result.chat.length >0){ $('#notifications').html('<span class="red">'+result.chat.length+'</span>'); }else { } }); },30000); }); function StatusHastag() { $('#status-hastag').html('<textarea id="hero-demo" name="list_has_tag"></textarea>'); $('#hero-demo').tagEditor({ placeholder: 'Enter tags ...', autocomplete: { source: googleSuggest, minLength: 3, delay: 250, html: true } }); } // var cache = {}; function googleSuggest(request, response) { var term = request.term; // if (term in cache) { response(cache[term]); return; } $.ajax({ url: '/suggest-hastag', type: 'POST', data: { format: 'json', q: term }, success: function(data) { var suggestions = []; suggestions = data; // cache[term] = suggestions; response(suggestions); } }); } $(document).ready(function () { $('#tray-icon').click(function () { $('#select-icon').toggle(); var domain = '/load-icon'; $('#list_icon').append($('<div>').load(domain, function () { })); }); $("#select-icon tr td").click(function () { var icon = $(this).html(); var content = $("#content_chat").html(); $("#content_chat").html(content+icon); }); $("#content_chat").click(function () { $('#select-icon').hide(); }); }); function LoadIcon() { $('#list-icon-home').toggle(); if($('#list-icon-home').html().trim() === "") { $.post('/list-icon', {}, function (data) { $('#list-icon-home').html(data); }); } } function InsertIcon(img) { var icon = '<img src="'+img+'">'; var html = icon; tinymce.activeEditor.execCommand('mceInsertContent', false, html); }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var positionSchema = new Schema ({ title: { type: String, required: true}, level: { type:Number, required: true}, skills: Array, competencies: Array, nextPositions: Array }); var Position = mongoose.model('Position', positionSchema); module.exports = {Position};
/* eslint new-parens: off */ /* eslint no-console: off */ /* eslint no-unused-vars: off */ const fs = require('fs') const documentClient = new (require('aws-sdk/clients/dynamodb')).DocumentClient({ region: process.argv[2] ? process.argv[2] : 'eu-west-1' }) const env = process.env.ENVIRONMENT || 'dev' const TableName = process.argv[3] ? process.argv[3] : 'aws-sns-sqs-config' const getConfigFromDB = async (lastEvaluatedKey, accumulatedResults = []) => { const params = { TableName } if (lastEvaluatedKey) { params.ExclusiveStartKey = lastEvaluatedKey } const result = await documentClient.scan(params).promise() const totalResults = accumulatedResults.concat(result.Items) if (result.LastEvaluatedKey) { return getConfigFromDB(result.LastEvaluatedKey, totalResults) } return totalResults } const deleteFromDB = async (configs) => { for (const { userId, resource } of configs) { const params = { TableName, Key: { userId, resource } } await documentClient.delete(params).promise() } } const putConfig = async () => { const files = fs.readdirSync(`${__dirname}/../config/${env}/`) for (const file of files) { const config = require(`../config/${env}/${file}`) const userId = file.match(/([\d]{2}).json/)[1] const userIsDisabled = config.enabled === false console.log(`Deploying config for user: ${userId}`) for (const { resource, type, enabled, frequency } of config.resources) { const scheduledFrequency = (frequency === 10 || frequency === 60) ? frequency : 1 const params = { TableName, Item: { userId, resource, enabled: userIsDisabled ? false : enabled, type, frequency: scheduledFrequency } } await documentClient.put(params).promise() } } } const deployConfig = async () => { const oldConfigs = await getConfigFromDB() await deleteFromDB(oldConfigs) await putConfig() } deployConfig() .then(() => { console.log('Config/s deployed successfully') }) .catch((error) => { console.log(error) process.exit(1) })
var ssSlides = ['/sierra-friends', "Sierra Friends Camp: more fun than, well, just about anything. Don't believe us? Click here!", '/sierra-friends/trips', "Ready to have the time of your life in some of the most beautiful places on earth? Click to learn about Sierra Friends Camp trips.", '/staff', "Our counselors are pretty much superheroes. Click to find out about all the amazing things they do.", '/sierra-friends/questions', "Got questions about what it's like to be a Sierra Friends Camper? We've got answers!", '/teen-leadership', "Announcing Teen Leadership Camp: fantastic adventures and learning for 15-16 year-olds. Learn more about it here.", '/staff/cit', "Our Counselor-In-Training program gives opportunities for fun and growth for ages 17+. Check it out here.", '/parents', "To learn more about our transformative programs, browse the parents' resources section. Click for dates, rates, FAQs packing list and more.", '/gallery', "See more wild camp pics: check out our photo gallery!"]; var ssPlace = 0; var ssEnd = ssSlides.length/2; function changeSlide(){ if( ++ssPlace == ssEnd ){ ssPlace = 0; } $('#camp-slideshow-image, #camp-slideshow-description').animate({opacity:0},'fast', function() { $('#camp-slideshow-image').css('background-position','0 '+(-300*ssPlace)+'px'); $('#camp-slideshow-link').attr('href',ssSlides[ssPlace*2]); $('#camp-slideshow-description').html(ssSlides[ssPlace*2+1]); $('#camp-slideshow-image, #camp-slideshow-description').animate({opacity:1},150); }); } $(document).ready(function (){ window.setInterval( changeSlide, 30000 ); });