Best JavaScript code snippet using root
report.js
Source:report.js
1(function ($) {2"use strict";3$.report = $.report || {};4$.extend($.report,{5 init: function(action, options){6 var me = this;7 me[action].call(me);8 },9 bindSearchForm: function(form, searchBtn, resetBtn,options){10 var grid = this;11 grid.searchFormFields = [];12 $.each($('input', $(form)), function(i, n){13 var item = $(n);14 if (item.attr('name') && item.attr('searchType')){15 grid.searchFormFields.push({16 elem: item,17 op: item.attr('searchType'),18 name: item.attr('name')19 });20 }21 });22 if (searchBtn){23 $(searchBtn).click(function(){24 var ruleGroup = "{\"groupOp\":\"AND\",\"rules\":[";25 var gi=0;26 $.each(grid.searchFormFields, function(i, item){27 var value = item.elem.val();28 if (value){29 if (gi > 0) {30 ruleGroup += ",";31 }32 ruleGroup += "{\"field\":\"" + item.name + "\",";33 ruleGroup += "\"op\":\"" + item.op + "\",";34 ruleGroup += "\"data\":\"" + value.replace(/\\/g,'\\\\').replace(/\"/g,'\\"') + "\"}";35 gi++;36 }37 });38 ruleGroup += "]}";39 options.data="filters="+ruleGroup;40 if($.fields.validateForm("#search")){41 $.ajax(options);42 }43 });44 }45 if (resetBtn){46 $(resetBtn).click(function(){47 $.each($(form + ' input'), function(i, n){48 var item = $(n);49 if (item.attr('name') && item.attr('searchType') && 'true' != item.attr('noreset')){50 item.val('').trigger('valuechange');51 }52 });53 //ææä¸æå表-å·²åºå¼54 if (searchBtn){55 options.data="filters=";56 $(searchBtn).click();57 }58 else{59 options.data="filters=";60 $.ajax(options);61 }62 });63 }64 },65 insertField : function(tr, field){66 var makers = {//ç®åè¾å
¥ï¼ä¸formatterå
¼å®¹67 integer : $.fields.integer,68 number : $.fields.number,69 date : $.fields.datepicker,70 time : $.fields.timepicker,71 yearmonth : $.fields.yearmonthpicker,72 dictionary : $.fields.dict_combobox,73 organization: $.fields.org_combobox,74 select:$.fields.select75 };76 var maker = makers[field.searchInput || field.formatter];77 if (!maker){//å¹é
searchInputæå®çè¾å
¥æ¡ç±»å78 maker = $.fields[field.searchInput];79 }80 if (!maker){81 maker = $.fields.text;82 }83 tr.append('<td class="search-form-label" nowrap="nowrap">' + field.label + '</td>');84 var td = $('<td class="search-form-field-container" nowrap="nowrap"/>');85 tr.append(td);86 var fieldAttr = $.extend({87 attr:{88 maxLength: 30,89 name : field.name,90 searchType : field.searchType,91 required:field.required92 },93 name : field.name,94 fieldClass: 'in' == field.searchType ? 'search-form-field-half' : 'search-form-field'95 }, field.formatoptions || {});96 fieldAttr = $.extend(fieldAttr, field.searchOption || {});97 if ('in' == field.searchType){98 fieldAttr.attr.searchType = 'ge';99 fieldAttr.attr.id="s"+field.name;100 fieldAttr.attr.lable="å¼å§æ¶é´";101 fieldAttr.maxdate={type:'id',data:"e"+field.name};102 fieldAttr.defValue=field.miValue;103 maker(td, fieldAttr);104 td.append('è³');105 fieldAttr.attr.searchType = 'le';106 fieldAttr.attr.id="e"+field.name;107 fieldAttr.attr.lable="ç»ææ¶é´";108 fieldAttr.defValue=field.mValue;109 fieldAttr.maxdate={type:'other',data:'$'};110 fieldAttr.mindate={type:'id',data:"s"+field.name};111 maker(td, fieldAttr);112 }113 else{114 maker(td, fieldAttr);115 }116 },117 addSearchForm : function(elem,celModel,options){118 var fields = [];119 for (var i in celModel){120 var model = celModel[i];121 if (model.searchType){122 model.label = model.label ? model.label : colNames[i];123 fields.push(model);124 }125 }126 if (fields.length > 0){127 var idPrefix = elem.replace('#', '');128 var formId = idPrefix + '_form';129 var searchBtnId = idPrefix + '_searchBtn';130 var resetBtnId = idPrefix + '_resetBtn';131 var formContainer = $('<div><form id="' + formId + '"><table class="search-table"></table></form></div>');132 $(elem).addClass("search-container");133 $(elem).append(formContainer);134 formContainer.addClass("search-form-container");135 var table = $('#' + formId + ' table[class="search-table"]');136 var line = 0;137 var trs = [];138 for (var j in fields){139 if (j % 3 == 0){140 var tr = $('<tr></tr>');141 trs.push(tr);142 table.append(tr);143 }144 this.insertField(tr, fields[j]);145 }146 var j = fields.length % 3;147 j = j ? (3 - j) : 0;//å¦æä¸æ¯3çåæ°ï¼åéè¦è¡¥é½148 for (var k = 0; k < j;){149 tr.append('<td></td><td></td>');150 k += 1;151 }152 if (trs.length > 0){153 trs[0].append('<td class="search-btns-container"><input id="' + searchBtnId + '" type="button" class="bttn bicon-search" value="æ¥è¯¢"/></td>');154 trs[trs.length - 1].append('<td class="search-btns-container"><input id="' + resetBtnId + '" type="button" class="bttn bicon-reset" value="éç½®"/></td>');155 for (var i = 1; i < trs.length - 1;){156 trs[i].append('<td class="search-btns-container"></td>');157 i += 1;158 }159 }160 this.bindSearchForm('#' + formId, '#' + searchBtnId, '#' + resetBtnId,options);161 }162 },163 fusioncharts:function(opts){164 var option = $.extend({165 width:'100%',166 height:'450',167 renderAt:'',168 dataFormat:'json',169 dataSource:{170 chart:{171 caption:opts.title||"",172 formatNumberScale:false,173 },174 data:opts.data,175 categories:opts.categories,176 dataset:opts.dataset177 }178 }, opts || {});179 $("#"+opts.renderAt).children().remove();180 FusionCharts.ready(function () {181 var tempVsSalesChart = new FusionCharts(option);182 tempVsSalesChart.render();183 });184 },185 orgFusionCharts:function(title,url,formatter){186 var me=this;187 $.container.generate(".chart",{188 type: 'row',189 items:[{fieldCols: 2,fields:[{},{}]}]190 });191 $(".chart").find("td").first().attr("id","chart-container");192 $(".chart").find("td").last().attr("id","chart-container1");193 var obj = [];194 var options = {195 type: 'POST',196 title:title,197 async:true,198 url: CONTEXT_PATH+'/data/jzgl/cxtj/sjfx/'+url,199 cache: false,200 dataType: 'json',201 success: function(data, success, http){202 if (data){203 obj = [];204 if(data.length>0){205 for(var i in data){206 var name =data[i][1];207 if(formatter){208 name=formatter(data[i][1]);209 }210 var temp={211 name: name,212 value:data[i][0]213 };214 obj.push(temp);215 }216 }else{217 obj=[{}];218 }219 }220 else{221 $.dialog.error('è·å' + (options.title || '') + 'ä¿¡æ¯å¤±è´¥ï¼è¯·ç¨ååè¯ .');222 }223 },224 error: function(){225 $.dialog.error('è·å' + (options.title || '') + 'ä¿¡æ¯å¤±è´¥ï¼è¯·ç¨ååè¯ .');226 },227 complete:function(){228 me.fusioncharts({type: 'column3d',renderAt:'chart-container',title:title+"æ±ç¶å¾",data:obj});229 me.fusioncharts({type: 'pie3d',renderAt:'chart-container1',title:title+"饼å¾",data:obj});230 }231 };232 $.ajax(options);233 return options;234 },235 fzlx:function(){236 var me=this;237 var options=me.orgFusionCharts("ç¯ç½ªç±»ååæ","fzlxReport.action",$.dictionary.formatter("FZLX", 'ä¸è¯¦'));238 var celModel = [ {239 name : 'responseOrg',240 label : 'ç«æ£æºæ',241 formatter : 'organization',242 searchType : 'cn',243 searchOption : {244 useCOrg : true,245 notShowType : '1,4,5,6,7,8,9',246 level : 2,247 showRoot : false,248 allowSearch : true249 }250 },{251 name : 'adjustType',252 label : 'ç«æ£ç±»å',253 formatter : 'dictionary',254 formatoptions : {code : 'JZLB'},255 searchType : 'eq'256 }, {257 name : 'sex',258 label : 'æ§å«',259 formatter : 'dictionary',260 formatoptions : {code : 'XB'},261 searchType : 'eq'262 }, {263 name : 'educationDegree',264 label : 'æåç¨åº¦',265 formatter : 'dictionary',266 formatoptions : {267 code : 'WHCD',268 allowSearch : true269 },270 searchType : 'eq'271 }, {272 name : 'workState',273 label : 'å°±ä¸å°±å¦æ
åµ',274 formatter : 'dictionary',275 formatoptions : {276 code : 'JYJX',277 allowSearch : true278 },279 searchType : 'eq',280 } , {281 name : 'natureHome',282 label : 'æ·ç±æ§è´¨',283 formatter : 'dictionary',284 formatoptions : {285 code : 'HJXZ',286 allowSearch : true287 },288 searchType : 'eq'289 },{290 name : 'state',291 label : '人åç¶åµ',292 formatter : 'dictionary',293 formatoptions: {code:'JZRYZT',filter:'5,999'},294 searchType : 'eq'295 }];296 this.addSearchForm("#search", celModel,options);297 },298 jyjx:function(){299 var me=this;300 var options=me.orgFusionCharts("å°±ä¸å°±å¦åæ","jyjxReport.action",$.dictionary.formatter("JYJX", 'ä¸è¯¦'));301 var celModel = [ {302 name : 'responseOrg',303 label : 'ç«æ£æºæ',304 formatter : 'organization',305 searchType : 'cn',306 searchOption : {307 useCOrg : true,308 notShowType : '1,4,5,6,7,8,9',309 level : 2,310 showRoot : false,311 allowSearch : true312 }313 },{314 name : 'adjustType',315 label : 'ç«æ£ç±»å',316 formatter : 'dictionary',317 formatoptions : {code : 'JZLB'},318 searchType : 'eq'319 }, {320 name : 'sex',321 label : 'æ§å«',322 formatter : 'dictionary',323 formatoptions : {code : 'XB'},324 searchType : 'eq'325 }, {326 name : 'crimeType',327 label : 'ç¯ç½ªç±»å',328 formatter : 'dictionary',329 formatoptions : {330 code : 'FZLX',331 allowSearch : true332 },333 searchType : 'eq'334 } , {335 name : 'educationDegree',336 label : 'æåç¨åº¦',337 formatter : 'dictionary',338 formatoptions : {339 code : 'WHCD',340 allowSearch : true341 },342 searchType : 'eq'343 }, {344 name : 'natureHome',345 label : 'æ·ç±æ§è´¨',346 formatter : 'dictionary',347 formatoptions : {348 code : 'HJXZ',349 allowSearch : true350 },351 searchType : 'eq'352 },{353 name : 'state',354 label : '人åç¶åµ',355 formatter : 'dictionary',356 formatoptions: {code:'JZRYZT',filter:'5,999'},357 searchType : 'eq'358 }];359 this.addSearchForm("#search", celModel,options);360 },361 whcd:function(){362 var me=this;363 var options=me.orgFusionCharts("æåç¨åº¦åæ","whcdReport.action",$.dictionary.formatter("WHCD", 'ä¸è¯¦'));364 var celModel = [ {365 name : 'responseOrg',366 label : 'ç«æ£æºæ',367 formatter : 'organization',368 searchType : 'cn',369 searchOption : {370 useCOrg : true,371 notShowType : '1,4,5,6,7,8,9',372 level : 2,373 showRoot : false,374 allowSearch : true375 }376 },{377 name : 'adjustType',378 label : 'ç«æ£ç±»å',379 formatter : 'dictionary',380 formatoptions : {code : 'JZLB'},381 searchType : 'eq'382 }, {383 name : 'sex',384 label : 'æ§å«',385 formatter : 'dictionary',386 formatoptions : {code : 'XB'},387 searchType : 'eq'388 }, {389 name : 'crimeType',390 label : 'ç¯ç½ªç±»å',391 formatter : 'dictionary',392 formatoptions : {393 code : 'FZLX',394 allowSearch : true395 },396 searchType : 'eq'397 } , {398 name : 'workState',399 label : 'å°±ä¸å°±å¦æ
åµ',400 formatter : 'dictionary',401 formatoptions : {402 code : 'JYJX',403 allowSearch : true404 },405 searchType : 'eq'406 } , {407 name : 'natureHome',408 label : 'æ·ç±æ§è´¨',409 formatter : 'dictionary',410 formatoptions : {411 code : 'HJXZ',412 allowSearch : true413 },414 searchType : 'eq'415 },{416 name : 'state',417 label : '人åç¶åµ',418 formatter : 'dictionary',419 formatoptions: {code:'JZRYZT',filter:'5,999'},420 searchType : 'eq'421 }];422 this.addSearchForm("#search", celModel,options);423 },424 hjxz:function(){425 var me=this;426 var options=me.orgFusionCharts("æ·ç±æ§è´¨åæ","hjxzReport.action",$.dictionary.formatter("HJXZ", 'ä¸è¯¦'));427 var celModel = [ {428 name : 'responseOrg',429 label : 'ç«æ£æºæ',430 formatter : 'organization',431 searchType : 'cn',432 searchOption : {433 useCOrg : true,434 notShowType : '1,4,5,6,7,8,9',435 level : 2,436 showRoot : false,437 allowSearch : true438 }439 },{440 name : 'adjustType',441 label : 'ç«æ£ç±»å',442 formatter : 'dictionary',443 formatoptions : {code : 'JZLB'},444 searchType : 'eq'445 }, {446 name : 'sex',447 label : 'æ§å«',448 formatter : 'dictionary',449 formatoptions : {code : 'XB'},450 searchType : 'eq'451 }, {452 name : 'crimeType',453 label : 'ç¯ç½ªç±»å',454 formatter : 'dictionary',455 formatoptions : {456 code : 'FZLX',457 allowSearch : true458 },459 searchType : 'eq'460 } , {461 name : 'workState',462 label : 'å°±ä¸å°±å¦æ
åµ',463 formatter : 'dictionary',464 formatoptions : {465 code : 'JYJX',466 allowSearch : true467 },468 searchType : 'eq'469 } , {470 name : 'educationDegree',471 label : 'æåç¨åº¦',472 formatter : 'dictionary',473 formatoptions : {474 code : 'WHCD',475 allowSearch : true476 },477 searchType : 'eq'478 },{479 name : 'state',480 label : '人åç¶åµ',481 formatter : 'dictionary',482 formatoptions: {code:'JZRYZT',filter:'5,999'},483 searchType : 'eq'484 }];485 this.addSearchForm("#search", celModel,options);486 },487 nld:function(){488 var me=this;489 var options=me.orgFusionCharts("å¹´é¾æ®µåæ","nldReport.action");490 var celModel = [ {491 name : 'responseOrg',492 label : 'ç«æ£æºæ',493 formatter : 'organization',494 searchType : 'cn',495 searchOption : {496 useCOrg : true,497 notShowType : '1,4,5,6,7,8,9',498 level : 2,499 showRoot : false,500 allowSearch : true501 }502 },{503 name : 'adjustType',504 label : 'ç«æ£ç±»å',505 formatter : 'dictionary',506 formatoptions : {code : 'JZLB'},507 searchType : 'eq'508 }, {509 name : 'sex',510 label : 'æ§å«',511 formatter : 'dictionary',512 formatoptions : {code : 'XB'},513 searchType : 'eq'514 }, {515 name : 'crimeType',516 label : 'ç¯ç½ªç±»å',517 formatter : 'dictionary',518 formatoptions : {519 code : 'FZLX',520 allowSearch : true521 },522 searchType : 'eq'523 } , {524 name : 'workState',525 label : 'å°±ä¸å°±å¦æ
åµ',526 formatter : 'dictionary',527 formatoptions : {528 code : 'JYJX',529 allowSearch : true530 },531 searchType : 'eq'532 } , {533 name : 'educationDegree',534 label : 'æåç¨åº¦',535 formatter : 'dictionary',536 formatoptions : {537 code : 'WHCD',538 allowSearch : true539 },540 searchType : 'eq'541 }, {542 name : 'natureHome',543 label : 'æ·ç±æ§è´¨',544 formatter : 'dictionary',545 formatoptions : {546 code : 'HJXZ',547 allowSearch : true548 },549 searchType : 'eq'550 },{551 name : 'state',552 label : '人åç¶åµ',553 formatter : 'dictionary',554 formatoptions: {code:'JZRYZT',filter:'5,999'},555 searchType : 'eq'556 }];557 this.addSearchForm("#search", celModel,options);558 },559 jzlx:function(){560 var me=this;561 var options=me.orgFusionCharts("ç«æ£ç±»ååæ","jzlxReport.action",$.dictionary.formatter("JZLB", 'ä¸è¯¦'));562 var celModel = [ {563 name : 'responseOrg',564 label : 'ç«æ£æºæ',565 formatter : 'organization',566 searchType : 'cn',567 searchOption : {568 useCOrg : true,569 notShowType : '1,4,5,6,7,8,9',570 level : 2,571 showRoot : false,572 allowSearch : true573 }574 }, {575 name : 'sex',576 label : 'æ§å«',577 formatter : 'dictionary',578 formatoptions : {code : 'XB'},579 searchType : 'eq'580 }, {581 name : 'crimeType',582 label : 'ç¯ç½ªç±»å',583 formatter : 'dictionary',584 formatoptions : {585 code : 'FZLX',586 allowSearch : true587 },588 searchType : 'eq'589 } , {590 name : 'workState',591 label : 'å°±ä¸å°±å¦æ
åµ',592 formatter : 'dictionary',593 formatoptions : {594 code : 'JYJX',595 allowSearch : true596 },597 searchType : 'eq'598 } , {599 name : 'educationDegree',600 label : 'æåç¨åº¦',601 formatter : 'dictionary',602 formatoptions : {603 code : 'WHCD',604 allowSearch : true605 },606 searchType : 'eq'607 }, {608 name : 'natureHome',609 label : 'æ·ç±æ§è´¨',610 formatter : 'dictionary',611 formatoptions : {612 code : 'HJXZ',613 allowSearch : true614 },615 searchType : 'eq'616 },{617 name : 'state',618 label : '人åç¶åµ',619 formatter : 'dictionary',620 formatoptions: {code:'JZRYZT',filter:'5,999'},621 searchType : 'eq'622 }];623 this.addSearchForm("#search", celModel,options);624 },625 rysl:function(){626 var me=this;627 $.container.generate(".chart",{628 type: 'row',629 items:[{fieldCols: 1,fields:[{}]}]630 });631 $(".chart").find("td").first().attr("id","chart-container");632 var dataset = [];633 var categories=[];634 var options = {635 type: 'POST',636 title:"å¨ç«äººåè¶å¿åæ",637 async:true,638 url: CONTEXT_PATH+'/data/jzgl/cxtj/sjfx/'+'ryslReport.action',639 cache: false,640 dataType: 'json',641 success: function(data, success, http){642 if (data){643 if(data.category){644 categories=[{category:data.category}];645 }646 if(data.dataset){647 dataset=data.dataset;648 }649 }650 else{651 $.dialog.error('è·å' + (options.title || '') + 'ä¿¡æ¯å¤±è´¥ï¼è¯·ç¨ååè¯ .');652 }653 },654 error: function(){655 $.dialog.error('è·å' + (options.title || '') + 'ä¿¡æ¯å¤±è´¥ï¼è¯·ç¨ååè¯ .');656 },657 complete:function(){658 me.fusioncharts({type: 'msline',renderAt:'chart-container',title:"å¨ç«äººåè¶å¿å¾",categories:categories,dataset:dataset});659 }660 };661 var date=new Date();662 var month=date.getMonth();663 if(month<10){664 month="0"+month;665 }666 var celModel = [ {667 name : 'time',668 label : 'ç»è®¡æ¶é´',669 searchType : 'in',670 searchInput : 'yearmonth',671 required:true,672 mValue:date.getFullYear()+"-"+month,673 miValue:(date.getFullYear()-1)+"-"+month674 }];675 this.addSearchForm("#search", celModel,options);676 $("#search_searchBtn").click();677 $("#search_resetBtn").unbind("click");678 $("#search_resetBtn").click(function(){679 $("#stime").val(date.getFullYear()-1+"-"+month);680 $("#etime").val(date.getFullYear()+"-"+month);681 $("#search_searchBtn").click();682 });683 }684});...
jquery.fmatter.js
Source:jquery.fmatter.js
1/*2**3 * formatter for values but most of the values if for jqGrid4 * Some of this was inspired and based on how YUI does the table datagrid but in jQuery fashion5 * we are trying to keep it as light as possible6 * Joshua Burnett josh@9ci.com 7 * http://www.greenbill.com8 *9 * Changes from Tony Tomov tony@trirand.com10 * Dual licensed under the MIT and GPL licenses:11 * http://www.opensource.org/licenses/mit-license.php12 * http://www.gnu.org/licenses/gpl-2.0.html13 * 14**/15/*jshint eqeqeq:false */16/*global jQuery, define */17(function( factory ) {18 "use strict";19 if ( typeof define === "function" && define.amd ) {20 // AMD. Register as an anonymous module.21 define([22 "jquery",23 "./grid.base"24 ], factory );25 } else {26 // Browser globals27 factory( jQuery );28 }29}(function( $ ) {30"use strict";31//module begin32 $.fmatter = {};33 //opts can be id:row id for the row, rowdata:the data for the row, colmodel:the column model for this column34 //example {id:1234,}35 $.extend($.fmatter,{36 isBoolean : function(o) {37 return typeof o === 'boolean';38 },39 isObject : function(o) {40 return (o && (typeof o === 'object' || $.isFunction(o))) || false;41 },42 isString : function(o) {43 return typeof o === 'string';44 },45 isNumber : function(o) {46 return typeof o === 'number' && isFinite(o);47 },48 isValue : function (o) {49 return (this.isObject(o) || this.isString(o) || this.isNumber(o) || this.isBoolean(o));50 },51 isEmpty : function(o) {52 if(!this.isString(o) && this.isValue(o)) {53 return false;54 }55 if (!this.isValue(o)){56 return true;57 }58 o = $.trim(o).replace(/\ \;/ig,'').replace(/\ \;/ig,'');59 return o===""; 60 }61 });62 $.fn.fmatter = function(formatType, cellval, opts, rwd, act) {63 // build main options before element iteration64 var v=cellval;65 opts = $.extend({}, $.jgrid.getRegional(this, 'formatter') , opts);66 try {67 v = $.fn.fmatter[formatType].call(this, cellval, opts, rwd, act);68 } catch(fe){}69 return v;70 };71 $.fmatter.util = {72 // Taken from YAHOO utils73 NumberFormat : function(nData,opts) {74 if(!$.fmatter.isNumber(nData)) {75 nData *= 1;76 }77 if($.fmatter.isNumber(nData)) {78 var bNegative = (nData < 0);79 var sOutput = String(nData);80 var sDecimalSeparator = opts.decimalSeparator || ".";81 var nDotIndex;82 if($.fmatter.isNumber(opts.decimalPlaces)) {83 // Round to the correct decimal place84 var nDecimalPlaces = opts.decimalPlaces;85 var nDecimal = Math.pow(10, nDecimalPlaces);86 sOutput = String(Math.round(nData*nDecimal)/nDecimal);87 nDotIndex = sOutput.lastIndexOf(".");88 if(nDecimalPlaces > 0) {89 // Add the decimal separator90 if(nDotIndex < 0) {91 sOutput += sDecimalSeparator;92 nDotIndex = sOutput.length-1;93 }94 // Replace the "."95 else if(sDecimalSeparator !== "."){96 sOutput = sOutput.replace(".",sDecimalSeparator);97 }98 // Add missing zeros99 while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {100 sOutput += "0";101 }102 }103 }104 if(opts.thousandsSeparator) {105 var sThousandsSeparator = opts.thousandsSeparator;106 nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);107 nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;108 var sNewOutput = sOutput.substring(nDotIndex);109 var nCount = -1, i;110 for (i=nDotIndex; i>0; i--) {111 nCount++;112 if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) {113 sNewOutput = sThousandsSeparator + sNewOutput;114 }115 sNewOutput = sOutput.charAt(i-1) + sNewOutput;116 }117 sOutput = sNewOutput;118 }119 // Prepend prefix120 sOutput = (opts.prefix) ? opts.prefix + sOutput : sOutput;121 // Append suffix122 sOutput = (opts.suffix) ? sOutput + opts.suffix : sOutput;123 return sOutput;124 125 }126 return nData;127 }128 };129 $.fn.fmatter.defaultFormat = function(cellval, opts) {130 return ($.fmatter.isValue(cellval) && cellval!=="" ) ? cellval : opts.defaultValue || " ";131 };132 $.fn.fmatter.email = function(cellval, opts) {133 if(!$.fmatter.isEmpty(cellval)) {134 return "<a href=\"mailto:" + cellval + "\">" + cellval + "</a>";135 }136 return $.fn.fmatter.defaultFormat(cellval,opts );137 };138 $.fn.fmatter.checkbox =function(cval, opts) {139 var op = $.extend({},opts.checkbox), ds;140 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {141 op = $.extend({},op,opts.colModel.formatoptions);142 }143 if(op.disabled===true) {ds = "disabled=\"disabled\"";} else {ds="";}144 if($.fmatter.isEmpty(cval) || cval === undefined ) {cval = $.fn.fmatter.defaultFormat(cval,op);}145 cval=String(cval);146 cval=(cval+"").toLowerCase();147 var bchk = cval.search(/(false|f|0|no|n|off|undefined)/i)<0 ? " checked='checked' " : "";148 return "<input type=\"checkbox\" " + bchk + " value=\""+ cval+"\" offval=\"no\" "+ds+ "/>";149 };150 $.fn.fmatter.link = function(cellval, opts) {151 var op = {target:opts.target};152 var target = "";153 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {154 op = $.extend({},op,opts.colModel.formatoptions);155 }156 if(op.target) {target = 'target=' + op.target;}157 if(!$.fmatter.isEmpty(cellval)) {158 return "<a "+target+" href=\"" + cellval + "\">" + cellval + "</a>";159 }160 return $.fn.fmatter.defaultFormat(cellval,opts);161 };162 $.fn.fmatter.showlink = function(cellval, opts) {163 var op = {baseLinkUrl: opts.baseLinkUrl,showAction:opts.showAction, addParam: opts.addParam || "", target: opts.target, idName: opts.idName},164 target = "", idUrl;165 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {166 op = $.extend({},op,opts.colModel.formatoptions);167 }168 if(op.target) {target = 'target=' + op.target;}169 idUrl = op.baseLinkUrl+op.showAction + '?'+ op.idName+'='+opts.rowId+op.addParam;170 if($.fmatter.isString(cellval) || $.fmatter.isNumber(cellval)) { //add this one even if its blank string171 return "<a "+target+" href=\"" + idUrl + "\">" + cellval + "</a>";172 }173 return $.fn.fmatter.defaultFormat(cellval,opts);174 };175 $.fn.fmatter.integer = function(cellval, opts) {176 var op = $.extend({},opts.integer);177 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {178 op = $.extend({},op,opts.colModel.formatoptions);179 }180 if($.fmatter.isEmpty(cellval)) {181 return op.defaultValue;182 }183 return $.fmatter.util.NumberFormat(cellval,op);184 };185 $.fn.fmatter.number = function (cellval, opts) {186 var op = $.extend({},opts.number);187 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {188 op = $.extend({},op,opts.colModel.formatoptions);189 }190 if($.fmatter.isEmpty(cellval)) {191 return op.defaultValue;192 }193 return $.fmatter.util.NumberFormat(cellval,op);194 };195 $.fn.fmatter.currency = function (cellval, opts) {196 var op = $.extend({},opts.currency);197 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {198 op = $.extend({},op,opts.colModel.formatoptions);199 }200 if($.fmatter.isEmpty(cellval)) {201 return op.defaultValue;202 }203 return $.fmatter.util.NumberFormat(cellval,op);204 };205 $.fn.fmatter.date = function (cellval, opts, rwd, act) {206 var op = $.extend({},opts.date);207 if(opts.colModel !== undefined && opts.colModel.formatoptions !== undefined) {208 op = $.extend({},op,opts.colModel.formatoptions);209 }210 if(!op.reformatAfterEdit && act === 'edit'){211 return $.fn.fmatter.defaultFormat(cellval, opts);212 }213 if(!$.fmatter.isEmpty(cellval)) {214 return $.jgrid.parseDate.call(this, op.srcformat,cellval,op.newformat,op);215 }216 return $.fn.fmatter.defaultFormat(cellval, opts);217 };218 $.fn.fmatter.select = function (cellval,opts) {219 // jqGrid specific220 cellval = String(cellval);221 var oSelect = false, ret=[], sep, delim;222 if(opts.colModel.formatoptions !== undefined){223 oSelect= opts.colModel.formatoptions.value;224 sep = opts.colModel.formatoptions.separator === undefined ? ":" : opts.colModel.formatoptions.separator;225 delim = opts.colModel.formatoptions.delimiter === undefined ? ";" : opts.colModel.formatoptions.delimiter;226 } else if(opts.colModel.editoptions !== undefined){227 oSelect= opts.colModel.editoptions.value;228 sep = opts.colModel.editoptions.separator === undefined ? ":" : opts.colModel.editoptions.separator;229 delim = opts.colModel.editoptions.delimiter === undefined ? ";" : opts.colModel.editoptions.delimiter;230 }231 if (oSelect) {232 var msl = (opts.colModel.editoptions != null && opts.colModel.editoptions.multiple === true) === true ? true : false,233 scell = [], sv;234 if(msl) {scell = cellval.split(",");scell = $.map(scell,function(n){return $.trim(n);});}235 if ($.fmatter.isString(oSelect)) {236 // mybe here we can use some caching with care ????237 var so = oSelect.split(delim), j=0, i;238 for(i=0; i<so.length;i++){239 sv = so[i].split(sep);240 if(sv.length > 2 ) {241 sv[1] = $.map(sv,function(n,i){if(i>0) {return n;}}).join(sep);242 }243 if(msl) {244 if($.inArray(sv[0],scell)>-1) {245 ret[j] = sv[1];246 j++;247 }248 } else if($.trim(sv[0]) === $.trim(cellval)) {249 ret[0] = sv[1];250 break;251 }252 }253 } else if($.fmatter.isObject(oSelect)) {254 // this is quicker255 if(msl) {256 ret = $.map(scell, function(n){257 return oSelect[n];258 });259 } else {260 ret[0] = oSelect[cellval] || "";261 }262 }263 }264 cellval = ret.join(", ");265 return cellval === "" ? $.fn.fmatter.defaultFormat(cellval,opts) : cellval;266 };267 $.fn.fmatter.rowactions = function(act) {268 var $tr = $(this).closest("tr.jqgrow"),269 rid = $tr.attr("id"),270 $id = $(this).closest("table.ui-jqgrid-btable").attr('id').replace(/_frozen([^_]*)$/,'$1'),271 $grid = $("#"+$id),272 $t = $grid[0],273 p = $t.p,274 cm = p.colModel[$.jgrid.getCellIndex(this)],275 $actionsDiv = cm.frozen ? $("tr#"+rid+" td:eq("+$.jgrid.getCellIndex(this)+") > div",$grid) :$(this).parent(),276 op = {277 extraparam: {}278 },279 saverow = function(rowid, res) {280 if($.isFunction(op.afterSave)) { op.afterSave.call($t, rowid, res); }281 $actionsDiv.find("div.ui-inline-edit,div.ui-inline-del").show();282 $actionsDiv.find("div.ui-inline-save,div.ui-inline-cancel").hide();283 },284 restorerow = function(rowid) {285 if($.isFunction(op.afterRestore)) { op.afterRestore.call($t, rowid); }286 $actionsDiv.find("div.ui-inline-edit,div.ui-inline-del").show();287 $actionsDiv.find("div.ui-inline-save,div.ui-inline-cancel").hide();288 };289 if (cm.formatoptions !== undefined) {290 op = $.extend(op,cm.formatoptions);291 }292 if (p.editOptions !== undefined) {293 op.editOptions = p.editOptions;294 }295 if (p.delOptions !== undefined) {296 op.delOptions = p.delOptions;297 }298 if ($tr.hasClass("jqgrid-new-row")){299 op.extraparam[p.prmNames.oper] = p.prmNames.addoper;300 }301 var actop = {302 keys: op.keys,303 oneditfunc: op.onEdit,304 successfunc: op.onSuccess,305 url: op.url,306 extraparam: op.extraparam,307 aftersavefunc: saverow,308 errorfunc: op.onError,309 afterrestorefunc: restorerow,310 restoreAfterError: op.restoreAfterError,311 mtype: op.mtype312 };313 switch(act)314 {315 case 'edit':316 $grid.jqGrid('editRow', rid, actop);317 $actionsDiv.find("div.ui-inline-edit,div.ui-inline-del").hide();318 $actionsDiv.find("div.ui-inline-save,div.ui-inline-cancel").show();319 $grid.triggerHandler("jqGridAfterGridComplete");320 break;321 case 'save':322 if ($grid.jqGrid('saveRow', rid, actop)) {323 $actionsDiv.find("div.ui-inline-edit,div.ui-inline-del").show();324 $actionsDiv.find("div.ui-inline-save,div.ui-inline-cancel").hide();325 $grid.triggerHandler("jqGridAfterGridComplete");326 }327 break;328 case 'cancel' :329 $grid.jqGrid('restoreRow', rid, restorerow);330 $actionsDiv.find("div.ui-inline-edit,div.ui-inline-del").show();331 $actionsDiv.find("div.ui-inline-save,div.ui-inline-cancel").hide();332 $grid.triggerHandler("jqGridAfterGridComplete");333 break;334 case 'del':335 $grid.jqGrid('delGridRow', rid, op.delOptions);336 break;337 case 'formedit':338 $grid.jqGrid('setSelection', rid);339 $grid.jqGrid('editGridRow', rid, op.editOptions);340 break;341 }342 };343 $.fn.fmatter.actions = function(cellval,opts) {344 var op={keys:false, editbutton:true, delbutton:true, editformbutton: false},345 rowid=opts.rowId, str="",ocl,346 nav = $.jgrid.getRegional(this, 'nav'),347 classes = $.jgrid.styleUI[(opts.styleUI || 'jQueryUI')].fmatter,348 common = $.jgrid.styleUI[(opts.styleUI || 'jQueryUI')].common;349 if(opts.colModel.formatoptions !== undefined) {350 op = $.extend(op,opts.colModel.formatoptions);351 }352 if(rowid === undefined || $.fmatter.isEmpty(rowid)) {return "";}353 var hover = "onmouseover=jQuery(this).addClass('" + common.hover +"'); onmouseout=jQuery(this).removeClass('" + common.hover +"'); ";354 if(op.editformbutton){ 355 ocl = "id='jEditButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'formedit'); " + hover;356 str += "<div title='"+nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='" + common.icon_base +" "+classes.icon_edit +"'></span></div>";357 } else if(op.editbutton){358 ocl = "id='jEditButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'edit'); " + hover;359 str += "<div title='"+nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='" + common.icon_base +" "+classes.icon_edit +"'></span></div>";360 }361 if(op.delbutton) {362 ocl = "id='jDeleteButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'del'); " + hover;363 str += "<div title='"+nav.deltitle+"' style='float:left;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='" + common.icon_base +" "+classes.icon_del +"'></span></div>";364 }365 ocl = "id='jSaveButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'save'); " + hover;366 str += "<div title='"+nav.savetitle+"' style='float:left;display:none' class='ui-pg-div ui-inline-save' "+ocl+"><span class='" + common.icon_base +" "+classes.icon_save +"'></span></div>";367 ocl = "id='jCancelButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'cancel'); " + hover;368 str += "<div title='"+nav.canceltitle+"' style='float:left;display:none;' class='ui-pg-div ui-inline-cancel' "+ocl+"><span class='" + common.icon_base +" "+classes.icon_cancel +"'></span></div>";369 return "<div style='margin-left:8px;'>" + str + "</div>";370 };371 $.unformat = function (cellval,options,pos,cnt) {372 // specific for jqGrid only373 var ret, formatType = options.colModel.formatter,374 op =options.colModel.formatoptions || {}, sep,375 re = /([\.\*\_\'\(\)\{\}\+\?\\])/g,376 unformatFunc = options.colModel.unformat||($.fn.fmatter[formatType] && $.fn.fmatter[formatType].unformat);377 if(unformatFunc !== undefined && $.isFunction(unformatFunc) ) {378 ret = unformatFunc.call(this, $(cellval).text(), options, cellval);379 } else if(formatType !== undefined && $.fmatter.isString(formatType) ) {380 var opts = $.jgrid.getRegional(this, 'formatter') || {}, stripTag;381 switch(formatType) {382 case 'integer' :383 op = $.extend({},opts.integer,op);384 sep = op.thousandsSeparator.replace(re,"\\$1");385 stripTag = new RegExp(sep, "g");386 ret = $(cellval).text().replace(stripTag,'');387 break;388 case 'number' :389 op = $.extend({},opts.number,op);390 sep = op.thousandsSeparator.replace(re,"\\$1");391 stripTag = new RegExp(sep, "g");392 ret = $(cellval).text().replace(stripTag,"").replace(op.decimalSeparator,'.');393 break;394 case 'currency':395 op = $.extend({},opts.currency,op);396 sep = op.thousandsSeparator.replace(re,"\\$1");397 stripTag = new RegExp(sep, "g");398 ret = $(cellval).text();399 if (op.prefix && op.prefix.length) {400 ret = ret.substr(op.prefix.length);401 }402 if (op.suffix && op.suffix.length) {403 ret = ret.substr(0, ret.length - op.suffix.length);404 }405 ret = ret.replace(stripTag,'').replace(op.decimalSeparator,'.');406 break;407 case 'checkbox':408 var cbv = (options.colModel.editoptions) ? options.colModel.editoptions.value.split(":") : ["Yes","No"];409 ret = $('input',cellval).is(":checked") ? cbv[0] : cbv[1];410 break;411 case 'select' :412 ret = $.unformat.select(cellval,options,pos,cnt);413 break;414 case 'actions':415 return "";416 default:417 ret= $(cellval).text();418 }419 }420 return ret !== undefined ? ret : cnt===true ? $(cellval).text() : $.jgrid.htmlDecode($(cellval).html());421 };422 $.unformat.select = function (cellval,options,pos,cnt) {423 // Spacial case when we have local data and perform a sort424 // cnt is set to true only in sortDataArray425 var ret = [];426 var cell = $(cellval).text();427 if(cnt===true) {return cell;}428 var op = $.extend({}, options.colModel.formatoptions !== undefined ? options.colModel.formatoptions: options.colModel.editoptions),429 sep = op.separator === undefined ? ":" : op.separator,430 delim = op.delimiter === undefined ? ";" : op.delimiter;431 432 if(op.value){433 var oSelect = op.value,434 msl = op.multiple === true ? true : false,435 scell = [], sv;436 if(msl) {scell = cell.split(",");scell = $.map(scell,function(n){return $.trim(n);});}437 if ($.fmatter.isString(oSelect)) {438 var so = oSelect.split(delim), j=0, i;439 for(i=0; i<so.length;i++){440 sv = so[i].split(sep);441 if(sv.length > 2 ) {442 sv[1] = $.map(sv,function(n,i){if(i>0) {return n;}}).join(sep);443 } 444 if(msl) {445 if($.inArray($.trim(sv[1]),scell)>-1) {446 ret[j] = sv[0];447 j++;448 }449 } else if($.trim(sv[1]) === $.trim(cell)) {450 ret[0] = sv[0];451 break;452 }453 }454 } else if($.fmatter.isObject(oSelect) || $.isArray(oSelect) ){455 if(!msl) {scell[0] = cell;}456 ret = $.map(scell, function(n){457 var rv;458 $.each(oSelect, function(i,val){459 if (val === n) {460 rv = i;461 return false;462 }463 });464 if( rv !== undefined ) {return rv;}465 });466 }467 return ret.join(", ");468 }469 return cell || "";470 };471 $.unformat.date = function (cellval, opts) {472 var op = $.jgrid.getRegional(this, 'formatter.date') || {};473 if(opts.formatoptions !== undefined) {474 op = $.extend({},op,opts.formatoptions);475 } 476 if(!$.fmatter.isEmpty(cellval)) {477 return $.jgrid.parseDate.call(this, op.newformat,cellval,op.srcformat,op);478 }479 return $.fn.fmatter.defaultFormat(cellval, opts);480 };481//module end...
SLC.grid.formatters.js
Source:SLC.grid.formatters.js
1/*2 * Copyright 2012 Shared Learning Collaborative, LLC3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/*17 * SLC grid formatters18 * Handles all the methods for displaying cutpoints, lozenge, fuelGauge, grade and teardrop in the grid19 */20/*global SLC $ */21SLC.namespace('SLC.grid.formatters', (function () {22 23 var grid = SLC.grid,24 util = SLC.util;25 /* formatoptions : {1:{color:'green'}, 2:{color:'grey'},...} */26 function CutPoint(value, options, rowObject) {27 var cutPoints = util.sortObject(options.colModel.formatoptions.cutPoints, util.compareInt),28 style,29 cutPoint;30 31 if (!value && value !== 0) {32 return '';33 }34 for (cutPoint in cutPoints) {35 if (cutPoints.hasOwnProperty(cutPoint)) {36 style = cutPoints[cutPoint].style;37 if (value - cutPoint <= 0) {38 break;39 }40 }41 }42 43 return "<span class='" + cutPoints[cutPoint].style + "'>" + value + "</span>";44 }45 46 function CutPointReverse(value, options, rowObject) {47 var cutPoints = util.sortObject(options.colModel.formatoptions.cutPoints, util.compareInt),48 style;49 50 if (!value && value !== 0) {51 return '';52 }53 54 for (var cutPoint in cutPoints) {55 if (cutPoints.hasOwnProperty(cutPoint)) {56 if (value - cutPoint < 0) {57 break;58 }59 style = cutPoints[cutPoint].style;60 }61 }62 return "<span class='" + style + "'>" + value + "</span>";63 }64 65 function PercentBar(value, options, rowObject) {66 var color,67 colorValue = value,68 formatoptions = options.colModel.formatoptions,69 low = 30, 70 medium = 70;71 72 if (value === null || value === "") {73 return "";74 }75 76 if (formatoptions && formatoptions.reverse === true) {77 colorValue = 100 - value;78 }79 80 if (formatoptions && formatoptions.low) {81 low = formatoptions.low;82 }83 84 if (formatoptions && formatoptions.medium) {85 medium = formatoptions.medium;86 }87 88 if (colorValue < low) {89 color = "red";90 } else if (colorValue < medium) {91 color = "silver";92 } else {93 color = "green";94 }95 96 return "<span style='display: inline-block;height: 6px;-moz-border-radius: 3px;-webkit-border-radius: 3px;background:" + color + ";width:" + value * 0.9 + "%'></span>";97 }98 99 function Lozenge(value, options, rowObject) { 100 return util.renderLozenges(rowObject);101 }102 103 function FuelGauge(value, options, rowObject) {104 var name = options.colModel.formatoptions.name,105 valueField = options.colModel.formatoptions.valueField,106 assessments = (name) ? rowObject.assessments[name]: rowObject.assessments,107 score, fieldName, cutPoints, cutPointsArray, perfLevel, perfLevelClass, divId,108 returnValue, width, height;109 if (!assessments || assessments === undefined) {110 return "" ;111 }112 113 score = (assessments[valueField]) ? assessments[valueField] : rowObject[valueField];114 115 if (!score || score === undefined || value === undefined || value === null) {116 score = 0;117 }118 119 fieldName = options.colModel.formatoptions.fieldName;120 cutPoints = (assessments.assessments) ? assessments.assessments.assessmentPerformanceLevel : assessments.assessmentPerformanceLevel;121 cutPointsArray = options.colModel.formatoptions.cutPointsArray;122 123 if (cutPointsArray === null || cutPointsArray === undefined) {124 cutPointsArray = grid.cutPoints.toArray(cutPoints);125 }126 127 perfLevel = options.colModel.formatoptions.perfLevel;128 129 if (perfLevel === null || perfLevel === undefined ) {130 perfLevel = grid.cutPoints.getLevelFromArray(cutPointsArray, score);131 }132 133 perfLevelClass = options.colModel.formatoptions.perfLevelClass;134 135 if (perfLevelClass === null || perfLevelClass === undefined) {136 var cutPointLevel = options.colModel.formatoptions.cutPoints[perfLevel];137 if (cutPointLevel !== null && cutPointLevel !== undefined) {138 perfLevelClass = cutPointLevel.style;139 } else {140 perfLevelClass = "";141 }142 }143 144 divId = fieldName + util.counter();145 returnValue = "<div id='" + divId + "' class='fuelGauge " + perfLevelClass + "' >";146 147 returnValue += "<script>";148 returnValue += "var cutPoints = new Array(" + grid.cutPoints.getArrayToString(cutPointsArray) + ");";149 returnValue += "$('#" + divId + "').parent().attr('title', '" + score + "');"; 150 returnValue += "var fuelGauge = new SLC.grid.FuelGauge ('" + divId + "', " + score + ", cutPoints);";151 152 width = options.colModel.formatoptions.fuelGaugeWidth;153 154 if (width === null || width === undefined) {155 width = options.colModel.width;156 if (width !== null && width !== undefined) {157 width = Math.round(width * 9 / 100) * 10;158 } else {159 width = 0;160 }161 }162 163 height = Math.sqrt(width);164 height -= height % 1;//removing the decimals.165 166 returnValue += "fuelGauge.setSize('" + width + "', '" + height + "');";167 returnValue += "fuelGauge.create();";168 returnValue += "</script>";169 returnValue += "</div>";170 171 return returnValue;172 }173 174 function FuelGaugeWithScore(value, options, rowObject) {175 var perfLevelClass = "",176 name = options.colModel.formatoptions.name,177 valueField = options.colModel.formatoptions.valueField,178 assessments = (name) ? rowObject.assessments[name]: rowObject.assessments,179 score, cutPoints, cutPointsArray, perfLevel, defaultCutPointsSettings,180 cutPointsSettings, cutPointLevel, width;181 182 if (value === undefined || value === null) {183 return "<span class='fuelGauge-perfLevel'></span>";184 }185 186 if (!assessments || assessments === undefined) {187 188 if (value === undefined || value === null) {189 value = "!";190 }191 return "<span class='fuelGauge-perfLevel'>" + value + "</span>" ;192 }193 194 score = (assessments[valueField]) ? assessments[valueField] : rowObject[valueField];195 196 if (!score || score === undefined) {197 return "<span class='fuelGauge-perfLevel'>" + value + "</span>" ;198 }199 200 cutPoints = (assessments.assessments) ? assessments.assessments.assessmentPerformanceLevel : assessments.assessmentPerformanceLevel;201 cutPointsArray = grid.cutPoints.toArray(cutPoints);202 perfLevel = grid.cutPoints.getLevelFromArray(cutPointsArray, score);203 defaultCutPointsSettings = { 5:{style:'color-widget-darkgreen'}, 4:{style:'color-widget-green'}, 3:{style:'color-widget-yellow'}, 2:{style:'color-widget-orange'}, 1:{style:'color-widget-red'}};204 cutPointsSettings = (options.colModel.formatoptions.cutPoints) ? options.colModel.formatoptions.cutPoints : defaultCutPointsSettings;205 cutPointLevel = cutPointsSettings[perfLevel];206 207 if (cutPointLevel !== null && cutPointLevel !== undefined) {208 perfLevelClass = cutPointLevel.style;209 }210 211 width = options.colModel.width;212 213 if (width !== null && width !== undefined) {214 options.colModel.formatoptions.fuelGaugeWidth = Math.round(width * 3/400) * 100;215 }216 217 options.colModel.formatoptions.cutPointsArray = cutPointsArray;218 options.colModel.formatoptions.perfLevel = perfLevel;219 options.colModel.formatoptions.perfLevelClass = perfLevelClass;220 221 return "<span class='" + perfLevelClass + " fuelGauge-perfLevel'>" + $.jgrid.htmlEncode(value) + "</span>" + FuelGauge(value, options, rowObject);222 }223 224 function Grade(value, options, rowobject) {225 var div = "<div class=\"",226 closeDiv = "\">",227 endDiv = "</div>",228 styleClass = "",229 innerHtml = "";230 231 if (value === undefined || value === null) {232 return div + styleClass + closeDiv + innerHtml + endDiv;233 }234 235 if (value.gradeEarned !== null && value.gradeEarned !== undefined) {236 innerHtml = value.gradeEarned;237 if (isNaN(value.gradeEarned)) {238 styleClass = grid.teardrop.getStyle(value.gradeEarned, null); 239 } else {240 styleClass = "numericGradeColumn"; 241 }242 } 243 244 return div + styleClass + closeDiv + $.jgrid.htmlEncode(innerHtml) + endDiv;245 }246 247 function TearDrop(value, options, rowObject) {248 var div = "<div class=\"",249 closeDiv = "\">",250 endDiv = "</div>",251 styleClass = "",252 innerHtml = "",253 divs = "",254 courseIndex;255 256 if (value === undefined || value === null) {257 return divs;258 }259 260 for(courseIndex = 0; courseIndex < value.length; courseIndex++){261 innerHtml = "";262 styleClass = "";263 var course = value[courseIndex];264 if(course.letterGrade !== null && course.letterGrade !== undefined) {265 innerHtml = course.letterGrade;266 styleClass = grid.teardrop.getStyle(course.letterGrade, null);267 divs = divs + div + styleClass + closeDiv + $.jgrid.htmlEncode(innerHtml) + endDiv;268 }269 }270 return divs;271 }272 273 function restLink(value, options, rowObject) {274 var link = options.colModel.formatoptions.link,275 level = options.colModel.formatoptions.level,276 contextRootPath = util.getContextRootPath();277 278 if (typeof link !== 'string') {279 return value;280 }281 282 if (level != null && level !== undefined && rowObject.level != null && rowObject.level !== undefined &&283 level !== rowObject.level) {284 return value;285 }286 287 return '<a href="' + util.getLayoutLink(link, rowObject.id) +'">'+$.jgrid.htmlEncode(value)+'</a>';288 }289 290 function dataColorBox(value, options, rowObject) {291 var cssClass = options.colModel.formatoptions.style;292 293 if (typeof cssClass === 'string') {294 return '<span class=' + cssClass + '>' + value + '</span>';295 } else {296 return value;297 }298 }299 300 return {301 CutPoint: CutPoint,302 CutPointReverse: CutPointReverse,303 PercentBar: PercentBar,304 Lozenge: Lozenge,305 FuelGaugeWithScore: FuelGaugeWithScore,306 FuelGauge: FuelGauge,307 Grade: Grade,308 TearDrop: TearDrop,309 restLink: restLink,310 dataColorBox: dataColorBox311 };312 }())...
format-test.js
Source:format-test.js
1var assert = require('assert');2var vows = require('vows');3var formatFrom = require('../../lib/options/format').formatFrom;4vows.describe(formatFrom)5 .addBatch({6 'undefined': {7 'topic': function () {8 return formatFrom(undefined);9 },10 'is false': function (formatOptions) {11 assert.deepEqual(formatOptions, false);12 }13 },14 'false': {15 'topic': function () {16 return formatFrom(false);17 },18 'is false': function (formatOptions) {19 assert.deepEqual(formatOptions, false);20 }21 },22 'true': {23 'topic': function () {24 return formatFrom(true);25 },26 'is default': function (formatOptions) {27 assert.deepEqual(formatOptions, {28 breaks: {29 afterAtRule: false,30 afterBlockBegins: false,31 afterBlockEnds: false,32 afterComment: false,33 afterProperty: false,34 afterRuleBegins: false,35 afterRuleEnds: false,36 beforeBlockEnds: false,37 betweenSelectors: false38 },39 indentBy: 0,40 indentWith: ' ',41 spaces: {42 aroundSelectorRelation: false,43 beforeBlockBegins: false,44 beforeValue: false45 },46 wrapAt: false,47 semicolonAfterLastProperty: false48 });49 }50 },51 'hash': {52 'topic': function () {53 return formatFrom({ breaks: { afterProperty: true }, indentBy: 1 });54 },55 'is merged with default': function (formatOptions) {56 assert.deepEqual(formatOptions, {57 breaks: {58 afterAtRule: false,59 afterBlockBegins: false,60 afterBlockEnds: false,61 afterComment: false,62 afterProperty: true,63 afterRuleBegins: false,64 afterRuleEnds: false,65 beforeBlockEnds: false,66 betweenSelectors: false67 },68 indentBy: 1,69 indentWith: ' ',70 spaces: {71 aroundSelectorRelation: false,72 beforeBlockBegins: false,73 beforeValue: false74 },75 wrapAt: false,76 semicolonAfterLastProperty: false77 });78 }79 },80 'hash with indentBy as string': {81 'topic': function () {82 return formatFrom({ indentBy: '2' });83 },84 'is merged with default': function (formatOptions) {85 assert.deepEqual(formatOptions, {86 breaks: {87 afterAtRule: false,88 afterBlockBegins: false,89 afterBlockEnds: false,90 afterComment: false,91 afterProperty: false,92 afterRuleBegins: false,93 afterRuleEnds: false,94 beforeBlockEnds: false,95 betweenSelectors: false96 },97 indentBy: 2,98 indentWith: ' ',99 spaces: {100 aroundSelectorRelation: false,101 beforeBlockBegins: false,102 beforeValue: false103 },104 wrapAt: false,105 semicolonAfterLastProperty: false106 });107 }108 },109 'hash with explicit indentWith': {110 'topic': function () {111 return formatFrom({ indentWith: '\t' });112 },113 'is merged with default': function (formatOptions) {114 assert.deepEqual(formatOptions, {115 breaks: {116 afterAtRule: false,117 afterBlockBegins: false,118 afterBlockEnds: false,119 afterComment: false,120 afterProperty: false,121 afterRuleBegins: false,122 afterRuleEnds: false,123 beforeBlockEnds: false,124 betweenSelectors: false125 },126 indentBy: 0,127 indentWith: '\t',128 spaces: {129 aroundSelectorRelation: false,130 beforeBlockBegins: false,131 beforeValue: false132 },133 wrapAt: false,134 semicolonAfterLastProperty: false135 });136 }137 },138 'hash with implicit indentWith': {139 'topic': function () {140 return formatFrom({ indentWith: 'tab' });141 },142 'is merged with default': function (formatOptions) {143 assert.deepEqual(formatOptions, {144 breaks: {145 afterAtRule: false,146 afterBlockBegins: false,147 afterBlockEnds: false,148 afterComment: false,149 afterProperty: false,150 afterRuleBegins: false,151 afterRuleEnds: false,152 beforeBlockEnds: false,153 betweenSelectors: false154 },155 indentBy: 0,156 indentWith: '\t',157 spaces: {158 aroundSelectorRelation: false,159 beforeBlockBegins: false,160 beforeValue: false161 },162 wrapAt: false,163 semicolonAfterLastProperty: false164 });165 }166 },167 'string': {168 'topic': function () {169 return formatFrom('breaks:afterProperty=on;indentBy:3;wrapAt:25');170 },171 'is merged with default': function (formatOptions) {172 assert.deepEqual(formatOptions, {173 breaks: {174 afterAtRule: false,175 afterBlockBegins: false,176 afterBlockEnds: false,177 afterComment: false,178 afterProperty: true,179 afterRuleBegins: false,180 afterRuleEnds: false,181 beforeBlockEnds: false,182 betweenSelectors: false183 },184 indentBy: 3,185 indentWith: ' ',186 spaces: {187 aroundSelectorRelation: false,188 beforeBlockBegins: false,189 beforeValue: false190 },191 wrapAt: 25,192 semicolonAfterLastProperty: false193 });194 }195 },196 'string with indentWith': {197 'topic': function () {198 return formatFrom('indentWith:tab');199 },200 'is merged with default': function (formatOptions) {201 assert.deepEqual(formatOptions, {202 breaks: {203 afterAtRule: false,204 afterBlockBegins: false,205 afterBlockEnds: false,206 afterComment: false,207 afterProperty: false,208 afterRuleBegins: false,209 afterRuleEnds: false,210 beforeBlockEnds: false,211 betweenSelectors: false212 },213 indentBy: 0,214 indentWith: '\t',215 spaces: {216 aroundSelectorRelation: false,217 beforeBlockBegins: false,218 beforeValue: false219 },220 wrapAt: false,221 semicolonAfterLastProperty: false222 });223 }224 },225 'beautify keyword': {226 'topic': function () {227 return formatFrom('beautify');228 },229 'resolves correctly': function (formatOptions) {230 assert.deepEqual(formatOptions, {231 breaks: {232 afterAtRule: true,233 afterBlockBegins: true,234 afterBlockEnds: true,235 afterComment: true,236 afterProperty: true,237 afterRuleBegins: true,238 afterRuleEnds: true,239 beforeBlockEnds: true,240 betweenSelectors: true241 },242 indentBy: 2,243 indentWith: ' ',244 spaces: {245 aroundSelectorRelation: true,246 beforeBlockBegins: true,247 beforeValue: true248 },249 wrapAt: false,250 semicolonAfterLastProperty: false251 });252 }253 },254 'keep-breaks keyword': {255 'topic': function () {256 return formatFrom('keep-breaks');257 },258 'resolves correctly': function (formatOptions) {259 assert.deepEqual(formatOptions, {260 breaks: {261 afterAtRule: true,262 afterBlockBegins: true,263 afterBlockEnds: true,264 afterComment: true,265 afterProperty: false,266 afterRuleBegins: false,267 afterRuleEnds: true,268 beforeBlockEnds: true,269 betweenSelectors: false270 },271 indentBy: 0,272 indentWith: ' ',273 spaces: {274 aroundSelectorRelation: false,275 beforeBlockBegins: false,276 beforeValue: false277 },278 wrapAt: false,279 semicolonAfterLastProperty: false280 });281 }282 }283 })...
FormatHelper-dbg.js
Source:FormatHelper-dbg.js
1/*2 * Copyright (C) 2009-2014 SAP SE or an SAP affiliate company. All rights reserved3 */4// Provides class sap.ca.ui.model.format.FormatHelper5jQuery.sap.declare("sap.ca.ui.model.format.FormatHelper");6jQuery.sap.require("sap.ui.core.format.NumberFormat");7jQuery.sap.require("sap.ui.core.LocaleData");8sap.ui.base.Object.extend("sap.ca.ui.model.format.FormatHelper", {});9sap.ca.ui.model.format.FormatHelper.stringToNumeric = function(str) {10 // Regexp for detecting hexadecimal prefix => requires parseInt instead of parseFloat11 var hexaDetect = /^\s*[\+-]?0[xX]/;12 if (hexaDetect.test(str)) {13 return parseInt(str, 16);14 }15 else {16 return parseFloat(str);17 }18};19sap.ca.ui.model.format.FormatHelper.toNumeric = function(obj) {20 if ((obj === null) || (obj === undefined)) {21 return NaN;22 }23 var t = typeof obj;24 var result;25 switch (t) {26 case "number":27 result = obj;28 break;29 case "string":30 result = sap.ca.ui.model.format.FormatHelper.stringToNumeric(obj);31 break;32 case "object":33 var v = obj.valueOf();34 if (typeof v === "number") {35 // Value object (e.g. Number)36 result = v;37 }38 else if (Array.isArray(obj)) {39 result = NaN;40 }41 else {42 result = sap.ca.ui.model.format.FormatHelper.stringToNumeric(obj.toString());43 }44 break;45 default:46 result = NaN;47 break;48 }49 return result;50};51sap.ca.ui.model.format.FormatHelper.isNumeric = function(obj) {52 return isFinite(sap.ca.ui.model.format.FormatHelper.toNumeric(obj));53};54sap.ca.ui.model.format.FormatHelper.getFormatOptions = function(options, locale) {55 var formatOptions = {};56 formatOptions.locale = locale;57 var t = typeof options;58 switch (t) {59 case "number":60 formatOptions.decimals = options;61 break;62 case "object":63 if (typeof options.locale === "string") {64 formatOptions.locale = new sap.ui.core.Locale(options.locale);65 }66 else if (options.locale) {67 formatOptions.locale = options.locale;68 }69 formatOptions.decimals = options.decimals;70 formatOptions.rounding = options.rounding;71 formatOptions.formatStyle = options.formatStyle;72 formatOptions.shortDecimals = options.shortDecimals;73 formatOptions.shortRounding = options.shortRounding;74 break;75 }76 if (!formatOptions.locale) {77 if (sap.ui.getCore().getConfiguration().getLanguage() == "ZH") {78 formatOptions.locale = new sap.ui.core.Locale("zh_CN");79 }80 else {81 formatOptions.locale = sap.ui.getCore().getConfiguration().getFormatSettings().getFormatLocale();82 }83 }84 return formatOptions;85};86sap.ca.ui.model.format.FormatHelper.hasRounding = function (options) {87 var rounding;88 if (options !== undefined) {89 if (typeof options === "number") {90 rounding = true;91 }92 else {93 if (options.formatStyle === "short") {94 rounding = (options.shortDecimals !== undefined) || (options.shortRounding !== undefined);95 }96 else {97 rounding = (options.decimals !== undefined) || (options.rounding !== undefined);98 }99 }100 }101 else {102 rounding = false;103 }104 return rounding;105};106sap.ca.ui.model.format.FormatHelper.roundNumber = function(number, options) {107 options = options || {};108 var roundedNumber;109 var fRounding, oDecimals;110 if (options.formatStyle === "short") {111 fRounding = options.shortRounding;112 oDecimals = options.shortDecimals;113 }114 else {115 fRounding = options.rounding;116 oDecimals = options.decimals;117 }118 if (fRounding) {119 roundedNumber = fRounding(number);120 }121 // WARNING: oDecimals can be 0 => we cannot simply test (oDecimals)122 else if (oDecimals !== undefined) {123 var decimals = sap.ca.ui.model.format.FormatHelper._getDecimals(oDecimals, number);124 roundedNumber = number.toFixed(decimals);125 }126 else {127 roundedNumber = number;128 }129 return roundedNumber;130};131sap.ca.ui.model.format.FormatHelper._getDecimals = function (oDecimals, number) {132 var decimals;133 if (typeof oDecimals === "function") {134 decimals = oDecimals(number);135 }136 else {137 decimals = oDecimals;138 }139 return decimals;140};141/**142 * Fix for Id4019bf373d32035a8061baa59a436e55f1872ea143 */144sap.ca.ui.model.format.FormatHelper._getUi5DecimalsFormatOptions = function (formatOptions, numValue, number) {145 var ui5FormatOptions = {};146 var oDecimals = null;147 if (formatOptions.formatStyle === "short") {148 oDecimals = formatOptions.shortDecimals;149 }150 else if (formatOptions.decimals || formatOptions.decimals === 0) {151 oDecimals = formatOptions.decimals;152 }153 if (oDecimals !== null) {154 var iDecimals = sap.ca.ui.model.format.FormatHelper._getDecimals(oDecimals, numValue);155 ui5FormatOptions.minFractionDigits = iDecimals;156 ui5FormatOptions.maxFractionDigits = iDecimals;157 }158 else if (typeof number === "string") {159 // If decimals format options are not set then preserve server side formatting.160 var decimalPos = number.indexOf(".");161 var iDecimalsCount = (decimalPos > -1) ? Math.max(number.length - decimalPos - 1, 0) : 0;162 ui5FormatOptions.minFractionDigits = iDecimalsCount;163 ui5FormatOptions.maxFractionDigits = iDecimalsCount;164 }165 return ui5FormatOptions;166};167// TODO: handle NaN and Infinity through "symbols-latn-infinity" and "symbols-latn-nan" properties168sap.ca.ui.model.format.FormatHelper.formatNumber = function(number, options) {169 var numValue = sap.ca.ui.model.format.FormatHelper.toNumeric(number);170 if (!isFinite(numValue)) {171 return "";172 }173 var formatOptions = sap.ca.ui.model.format.FormatHelper.getFormatOptions(options);174 var ui5FormatOptions = sap.ca.ui.model.format.FormatHelper._getUi5DecimalsFormatOptions(formatOptions, numValue, number);175 var numberFormatter = sap.ui.core.format.NumberFormat.getFloatInstance(ui5FormatOptions, formatOptions.locale);176 if (sap.ca.ui.model.format.FormatHelper.hasRounding(options)) {177 numValue = sap.ca.ui.model.format.FormatHelper.roundNumber(numValue, formatOptions);178 return numberFormatter.format(numValue);179 }180 else {181 // If no rounding is specified, pass the initial parameter to UI5 as it could be pre-formatted182 return numberFormatter.format(number);183 }184};185sap.ca.ui.model.format.FormatHelper.getMagnitude = function(number) {186 // Currently, only supported multiples are { k, M, G, T }187 var _magnitudes = [188 { value: 1e3, suffix: "Kilo" }189 , { value: 1e6, suffix: "Mega" }190 , { value: 1e9, suffix: "Giga" }191 , { value: 1e12, suffix: "Tera" }192 , { value: 1e15, suffix: "Peta" }193 , { value: 1e18, suffix: "Exa" }194 , { value: 1e21, suffix: "Zetta" }195 , { value: 1e24, suffix: "Yotta" }196 ];197 var num = (number >= 0 ? number : -number);198 for (var idx = _magnitudes.length - 1; idx >= 0; --idx) {199 var mag = _magnitudes[idx];200 if (num >= mag.value) {201 return mag;202 }203 }204 return { value: 1, suffix: "" };...
index.js
Source:index.js
1import requiredArgs from "../_lib/requiredArgs/index.js";2/**3 * @name intlFormat4 * @category Common Helpers5 * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).6 *7 * @description8 * Return the formatted date string in the given format.9 * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside.10 * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options)11 *12 * > â ï¸ Please note that before Node version 13.0.0, only the locale data for en-US is available by default.13 *14 * @param {Date|Number} argument - the original date.15 * @param {Object} [formatOptions] - an object with options.16 * @param {'lookup'|'best fit'} [formatOptions.localeMatcher='best fit'] - locale selection algorithm.17 * @param {'narrow'|'short'|'long'} [formatOptions.weekday] - representation the days of the week.18 * @param {'narrow'|'short'|'long'} [formatOptions.era] - representation of eras.19 * @param {'numeric'|'2-digit'} [formatOptions.year] - representation of years.20 * @param {'numeric'|'2-digit'|'narrow'|'short'|'long'} [formatOptions.month='numeric'] - representation of month.21 * @param {'numeric'|'2-digit'} [formatOptions.day='numeric'] - representation of day.22 * @param {'numeric'|'2-digit'} [formatOptions.hour='numeric'] - representation of hours.23 * @param {'numeric'|'2-digit'} [formatOptions.minute] - representation of minutes.24 * @param {'numeric'|'2-digit'} [formatOptions.second] - representation of seconds.25 * @param {'short'|'long'} [formatOptions.timeZoneName] - representation of names of time zones.26 * @param {'basic'|'best fit'} [formatOptions.formatMatcher='best fit'] - format selection algorithm.27 * @param {Boolean} [formatOptions.hour12] - determines whether to use 12-hour time format.28 * @param {String} [formatOptions.timeZone] - the time zone to use.29 * @param {Object} [localeOptions] - an object with locale.30 * @param {String|String[]} [localeOptions.locale] - the locale code31 * @returns {String} the formatted date string.32 * @throws {TypeError} 1 argument required.33 * @throws {RangeError} `date` must not be Invalid Date34 *35 * @example36 * // Represent 10 October 2019 in German.37 * // Convert the date with format's options and locale's options.38 * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {39 * weekday: 'long',40 * year: 'numeric',41 * month: 'long',42 * day: 'numeric',43 * }, {44 * locale: 'de-DE',45 * })46 * //=> Freitag, 4. Oktober 201947 *48 * @example49 * // Represent 10 October 2019.50 * // Convert the date with format's options.51 * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), {52 * year: 'numeric',53 * month: 'numeric',54 * day: 'numeric',55 * hour: 'numeric',56 * })57 * //=> 10/4/2019, 12 PM58 *59 * @example60 * // Represent 10 October 2019 in Korean.61 * // Convert the date with locale's options.62 * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {63 * locale: 'ko-KR',64 * })65 * //=> 2019. 10. 4.66 *67 * @example68 * // Represent 10 October 2019 in middle-endian format:69 * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456))70 * //=> 10/4/201971 */72export default function intlFormat(date, formatOrLocale, localeOptions) {73 var _localeOptions;74 requiredArgs(1, arguments);75 var formatOptions;76 if (isFormatOptions(formatOrLocale)) {77 formatOptions = formatOrLocale;78 } else {79 localeOptions = formatOrLocale;80 }81 return new Intl.DateTimeFormat((_localeOptions = localeOptions) === null || _localeOptions === void 0 ? void 0 : _localeOptions.locale, formatOptions).format(date);82}83function isFormatOptions(opts) {84 return opts !== undefined && !('locale' in opts);...
CurrencyFormatter.ts
Source:CurrencyFormatter.ts
1import { format as currencyFormatter } from 'currency-formatter';2import {3 ITableDataItem,4 ITableFieldMetaData,5 ITableFields,6} from '@common/core/types';7const DEFAULT_CURRENCY_CODE = 'EUR';8export interface ICurrencyFormatterOptions {9 code?: string;10 locale?: string;11 // tslint:disable-next-line no-reserved-keywords12 symbol?: string;13 decimal?: string;14 thousand?: string;15 precision?: number;16 format?: string | {17 pos: string;18 neg: string;19 zero: string;20 };21}22export class CurrencyFormatter {23 private value: number;24 private formatOptions: ICurrencyFormatterOptions;25 constructor (26 value: string,27 field: ITableFieldMetaData,28 row: ITableDataItem,29 fields: ITableFields,30 ) {31 const formatOptions: ICurrencyFormatterOptions = {};32 const { fieldTypeFormatterOptions, precision: fieldPrecision } = field;33 if (fieldTypeFormatterOptions) {34 const { code, codeFieldName, codeFieldValueExtract } = fieldTypeFormatterOptions;35 if (code) {36 formatOptions.code = code;37 } else if (codeFieldName) {38 const codeFieldMetaData = fields.find(39 ({ fieldName }) => fieldName === codeFieldName,40 );41 if (codeFieldMetaData) {42 const codeRawValue = row[codeFieldMetaData.fieldName];43 if (codeRawValue != null && typeof codeRawValue === 'string') {44 if (codeFieldValueExtract) {45 const extracted = codeRawValue.match(codeFieldValueExtract);46 formatOptions.code = extracted ? extracted[1] : codeRawValue;47 } else {48 formatOptions.code = codeRawValue;49 }50 }51 }52 }53 }54 if (typeof fieldPrecision === 'number') {55 formatOptions.precision = fieldPrecision;56 } else if (typeof fieldPrecision === 'function') {57 formatOptions.precision = fieldPrecision(row, fields, field);58 }59 this.value = Number(String(value || '0.0'));60 this.formatOptions = formatOptions;61 }62 public static format(63 value: number,64 options: ICurrencyFormatterOptions = {},65 ): string {66 return currencyFormatter(value, {67 symbol: options.code ? void 0 : '', // default symbol placeholder68 code: DEFAULT_CURRENCY_CODE,69 ...options,70 });71 }72 public toString(): string {73 return CurrencyFormatter.format(this.value, this.formatOptions);74 }...
main.js
Source:main.js
1const HTML = DOM.find("html");2const DEFAULT_LANGUAGE = HTML.get("lang") || void 0;3const globalFormatters = DOM.findAll("meta[name^='data-format:']").reduce((globalFormatters, meta) => {4 const key = meta.get("name").split(":")[1].trim();5 const formatOptions = JSON.parse(meta.get("content"));6 if (key) {7 try {8 globalFormatters[key] = new window.Intl.DateTimeFormat(DEFAULT_LANGUAGE, formatOptions);9 } catch(err) {}10 }11 return globalFormatters;12}, {});13DOM.extend("local-time", {14 constructor() {15 const lang = this.get("lang") || DEFAULT_LANGUAGE;16 const dateValue = new Date(this.get("datetime"));17 const formatOptions = this.get("data-format");18 this.value(this._formatDate(dateValue, lang, formatOptions));19 },20 _formatDate(dateValue, lang, formatOptions) {21 const formatter = globalFormatters[formatOptions];22 try {23 if (formatter && lang === DEFAULT_LANGUAGE) {24 return formatter.format(dateValue);25 } else {26 return dateValue.toLocaleString(lang, formatOptions ? JSON.parse(formatOptions) : {});27 }28 } catch (err) {29 return dateValue.toLocaleString();30 }31 }...
Using AI Code Generation
1console.log("root.formatOptions() = ", root.formatOptions());2console.log("child.formatOptions() = ", child.formatOptions());3console.log("root.formatOptions() = ", root.formatOptions());4console.log("child.formatOptions() = ", child.formatOptions());5var root = {6 formatOptions: function() {7 return "root.formatOptions()";8 }9};10module.exports = root;11var root = require("./root");12var child = Object.create(root);13child.formatOptions = function() {14 return "child.formatOptions()";15};16module.exports = child;17root.formatOptions() = root.formatOptions()18child.formatOptions() = child.formatOptions()19root.formatOptions() = root.formatOptions()20child.formatOptions() = child.formatOptions()21console.log("root.formatOptions() = ", root.formatOptions());22console.log("child.formatOptions() = ", child.formatOptions());23console.log("root.formatOptions() = ", root.formatOptions());24console.log("child.formatOptions() = ", child.formatOptions());25var root = {26 formatOptions: function() {27 return "root.formatOptions()";
Using AI Code Generation
1var root = require('root');2var formatOptions = root.formatOptions;3var options = { "name": "John", "age": 30, "city": "New York" };4var result = formatOptions(options);5console.log(result);6var root = {};7root.formatOptions = function (options) {8 var result = "";9 for (var key in options) {10 if (options.hasOwnProperty(key)) {11 result += key + " = " + options[key] + ";";12 }13 }14 return result;15};16module.exports = root;17name = John;age = 30;city = New York;18var root = {19 formatOptions: function (options) {20 var result = "";21 for (var key in options) {22 if (options.hasOwnProperty(key)) {23 result += key + " = " + options[key] + ";";24 }25 }26 return result;27 }28};29module.exports = root;
Using AI Code Generation
1var root = require('root');2var rootObj = new root();3var result = rootObj.formatOptions('test');4console.log(result);5function root() {6}7root.prototype.formatOptions = function (value) {8 return value.toUpperCase();9}10module.exports = root;11var child = require('child');12var childObj = new child();13var result = childObj.formatOptions('test');14console.log(result);15var root = require('root');16function child() {17 root.call(this);18}19child.prototype = Object.create(root.prototype);20child.prototype.constructor = child;21module.exports = child;22var child = require('child');23var childObj = new child();24childObj.test();25function child() {26}27child.prototype.test = function () {28 console.log('test');29}30module.exports = child;31var child = require('child');32var childObj = new child();33childObj.test();34function child() {35}36child.prototype.test = function () {37 var root = require('root');38 var rootObj = new root();39 var result = rootObj.formatOptions('test');40 console.log(result);41}42module.exports = child;43var child = require('child');
Using AI Code Generation
1require(["dojo/domReady!"], function(){2 var root = require("root");3 root.formatOptions({key1: "value1", key2: "value2"});4});5define(["dojo/_base/declare", "myModule"], function(declare, myModule){6 var root = declare(null, {7 formatOptions: function(options){8 return options;9 }10 });11 return new root();12});13define(["dojo/_base/declare"], function(declare){14 var myModule = declare(null, {15 formatOptions: function(options){16 return options;17 }18 });19 return myModule;20});21require(["dojo/domReady!", "root"], function(root){22 root.formatOptions({key1: "value1", key2: "value2"});23});24require(["dojo/domReady!", "myModule"], function(myModule){25 myModule.formatOptions({key1: "value1", key2: "value2"});26});27require(["dojo/domReady!", "root"],
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!