code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-11-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); var form = new Ext.form.Form({ labelAlign:'right', labelWidth:100, url:'../j_acegi_security_check', method: 'POST', waitMsgTarget:'login-box' }); var username = new Ext.form.TextField({ name:'j_username', fieldLabel:'用户名', width:175, allowBlank:false }); var password = new Ext.form.TextField({ name:'j_password', inputType:'password', fieldLabel:'密 码', width:175, allowBlank:false }); var rememberMe = new Ext.form.Checkbox({ name:'_acegi_security_remember_me', fieldLabel:'记住我', width:175, boxLabel:'保存登录信息' }); var captcha = new Ext.form.TextField({ name:'j_captcha_response', fieldLabel:'验证码', width:175, allowBlank:false }); form.fieldset( {id:'login',legend:'登录'}, username, password, rememberMe, captcha ); form.addButton('提交'); form.addButton('重置'); form.render('login-form'); form.buttons[0].addListener("click", function() { if (form.isValid()) { form.submit({ success:function(form, action){ Ext.suggest.msg('信息', '登录成功'); window.open("index.htm", '_self'); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'登录中...' }); } }); form.buttons[1].addListener("click", function() { form.reset(); }); // 创建彩色验证码图片 var login = Ext.get("login"); var c = login.createChild({ tag:'center', cn:[{ tag:'img', id:'imageCaptcha', src:'../captcha.jpg?' + new Date().getTime(), style:'cursor:pointer;border:0px black solid;', onclick:'changeCaptcha()' },{ tag:'a', id:'tip', html:'刷新图片', href:'#', onclick:'changeCaptcha()' }] }); }); Ext.suggest = function(){ var msgCt; function createBox(t, s){ return ['<div class="msg">', '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>', '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', '</div>'].join(''); } return { msg : function(title, format){ if(!msgCt){ msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true); } msgCt.alignTo(document, 't-t'); var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1)); var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true); m.slideIn('t').pause(1).ghost("t", {remove:true}); }, init : function(){ var s = Ext.get('extlib'), t = Ext.get('exttheme'); if(!s || !t){ // run locally? return; } var lib = Cookies.get('extlib') || 'ext', theme = Cookies.get('exttheme') || 'aero'; if(lib){ s.dom.value = lib; } if(theme){ t.dom.value = theme; Ext.get(document.body).addClass('x-'+theme); } s.on('change', function(){ Cookies.set('extlib', s.getValue()); setTimeout(function(){ window.location.reload(); }, 250); }); t.on('change', function(){ Cookies.set('exttheme', t.getValue()); setTimeout(function(){ window.location.reload(); }, 250); }); } }; }(); function changeCaptcha() { var imageCaptcha = document.getElementById("imageCaptcha"); imageCaptcha.src = '../captcha.jpg?' + new Date().getTime(); }
JavaScript
function convertCurrency(currencyDigits) { // Constants: var MAXIMUM_NUMBER = 99999999999.99; // Predefine the radix characters and currency symbols for output: var CN_ZERO = "零"; var CN_ONE = "壹"; var CN_TWO = "贰"; var CN_THREE = "叁"; var CN_FOUR = "肆"; var CN_FIVE = "伍"; var CN_SIX = "陆"; var CN_SEVEN = "柒"; var CN_EIGHT = "捌"; var CN_NINE = "玖"; var CN_TEN = "<b>拾</b>"; var CN_HUNDRED = "<b>佰</b>"; var CN_THOUSAND = "<b>仟</b>"; var CN_TEN_THOUSAND = "<b>万</b>"; var CN_HUNDRED_MILLION = "<b>亿</b>"; var CN_SYMBOL = "<b>人民币 </b>"; var CN_DOLLAR = "<b>元</b>"; var CN_TEN_CENT = "<b>角</b>"; var CN_CENT = "<b>分</b>"; var CN_INTEGER = "<b> 整</b>"; // Variables: var integral; // Represent integral part of digit number. var decimal; // Represent decimal part of digit number. var outputCharacters; // The output result. var parts; var digits, radices, bigRadices, decimals; var zeroCount; var i, p, d; var quotient, modulus; // Validate input string: currencyDigits = currencyDigits.toString(); if (currencyDigits == "") { alert("Empty input!"); return ""; } if (currencyDigits.match(/[^,.\d]/) != null) { alert("Invalid characters in the input string!"); return ""; } if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) { alert("Illegal format of digit number!"); return ""; } // Normalize the format of input digits: currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters. currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning. // Assert the number is not greater than the maximum number. if (Number(currencyDigits) > MAXIMUM_NUMBER) { alert("Too large a number to convert!"); return ""; } // Process the coversion from currency digits to characters: // Separate integral and decimal parts before processing coversion: parts = currencyDigits.split("."); if (parts.length > 1) { integral = parts[0]; decimal = parts[1]; // Cut down redundant decimal digits that are after the second. decimal = decimal.substr(0, 2); } else { integral = parts[0]; decimal = ""; } // Prepare the characters corresponding to the digits: digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE); radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND); bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION); decimals = new Array(CN_TEN_CENT, CN_CENT); // Start processing: outputCharacters = ""; // Process integral part if it is larger than 0: if (Number(integral) > 0) { zeroCount = 0; for (i = 0; i < integral.length; i++) { p = integral.length - i - 1; d = integral.substr(i, 1); quotient = p / 4; modulus = p % 4; if (d == "0") { zeroCount++; } else { if (zeroCount > 0) { outputCharacters += digits[0]; } zeroCount = 0; outputCharacters += digits[Number(d)] + radices[modulus]; } if (modulus == 0 && zeroCount < 4) { outputCharacters += bigRadices[quotient]; } } outputCharacters += CN_DOLLAR; } // Process decimal part if there is: if (decimal != "") { for (i = 0; i < decimal.length; i++) { d = decimal.substr(i, 1); if (d != "0") { outputCharacters += digits[Number(d)] + decimals[i]; } } } // Confirm and return the final output string: if (outputCharacters == "") { outputCharacters = CN_ZERO + CN_DOLLAR; } if (decimal == "") { outputCharacters += CN_INTEGER; } outputCharacters = CN_SYMBOL + outputCharacters; return outputCharacters; }
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '添加订单', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "管理订单", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id:'id', qtip:"ID", vType:"integer", allowBlank:true,defValue:-1,w:50}, {id:'code', qtip:"订单编号", vType:"alphanum", allowBlank:false,w:200}, {id:'customer', qtip:"客户", vType:"chn", allowBlank:false,w:100}, {id:'orderDate', qtip:"订货日期", vType:"date", allowBlank:false,w:100}, {id:'amount', qtip:"总金额", vType:"float", allowBlank:false,w:80}, {id:'handMan', qtip:"经手人", vType:"chn", allowBlank:false,w:80}, {id:'payment', qtip:"付款情况", vType:"comboBox", allowBlank:false,w:80}, {id:'delivery', qtip:"运货情况", vType:"comboBox", allowBlank:false,w:80}, {id:'status', qtip:"状态", vType:"comboBox", allowBlank:false,w:100,showInGrid:false}, {id:'inputMan', qtip:"录入人", vType:"chn", allowBlank:false,w:100,showInGrid:false}, {id:'inputTime', qtip:"录入时间", vType:"date", allowBlank:false,w:100,showInGrid:false}, {id:'descn', qtip:"备注", vType:"editor", allowBlank:false,w:100,showInGrid:false} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); var manageButton = new Ext.Toolbar.Button({ icon : "../widgets/lingo/list-items.gif", id : 'manageButton', text : '管理', cls : 'add', tooltip : '管理', handler : lightGrid.edit.createDelegate(lightGrid) }); var printButton = new Ext.Toolbar.Button({ icon : "../widgets/lingo/list-items.gif", id : 'printButton', text : '打印', cls : 'add', tooltip : '打印', handler : function() { alert("还没做完呢,2007-10-26 00:31"); } }); var print2Button = new Ext.Toolbar.Button({ icon : "../widgets/lingo/list-items.gif", id : 'print2Button', text : '打印送货单', cls : 'add', tooltip : '打印送货单', handler : function() { alert("还没做完呢,2007-10-26 00:31"); } }); var print3Button = new Ext.Toolbar.Button({ icon : "../widgets/lingo/list-items.gif", id : 'print3Button', text : '打印送货汇总', cls : 'add', tooltip : '打印送货汇总', handler : function() { alert("还没做完呢,2007-10-26 00:31"); } }); lightGrid.toolbar.insertButton(3, manageButton); lightGrid.toolbar.insertButton(4, printButton); lightGrid.toolbar.insertButton(5, print2Button); lightGrid.toolbar.insertButton(6, print3Button); Ext.get("add").setStyle("display", "none"); Ext.get("edit").setStyle("display", "none"); Ext.get("del").setStyle("display", "none"); // ==================================================== // 添加订单的部分 var orderDate = new Ext.form.DateField({ id:'orderDateIn' ,name:'orderDate' ,format:'Y-m-d' ,readOnly:true }); orderDate.setValue(new Date()); var customer = new Ext.form.TextField({ id:'customerIn' ,name:'customer' }); var linkMan = new Ext.form.TextField({ id:'linkMan' ,name:'linkMan' }); var tel = new Ext.form.TextField({ id:'tel' ,name:'tel' }); orderDate.applyTo('orderDateIn'); customer.applyTo('customerIn'); linkMan.applyTo('linkMan'); tel.applyTo('tel'); // ==================================================== // 添加订单条目 var cm = new Ext.grid.ColumnModel([{ header: "产品名", dataIndex: "product", sortable:false, width: 100, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "类别", dataIndex: "type", sortable:false, width: 100, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "单位", dataIndex: "unit", sortable:false, width: 50, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "长", dataIndex: "height", sortable:false, width: 50, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "宽", dataIndex: "width", sortable:false, width: 50, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "面积(尺寸)", dataIndex: "area", sortable:false, width: 70, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "单价(元)", dataIndex: "price", sortable:false, width: 60, editor: new Ext.grid.GridEditor(new Ext.form.NumberField({allowBlank: false})) }, { header: "金额(元)", dataIndex: "amount", sortable:false, width: 60, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "数量", dataIndex: "num", sortable:false, width: 50, editor: new Ext.grid.GridEditor(new Ext.form.NumberField({allowBlank: false})) }, { header: "单位类型", dataIndex: "unitType", sortable:false, width: 80, editor: new Ext.grid.GridEditor(new Ext.form.ComboBox({ typeAhead: true, triggerAction: 'all', transform:'unitSelect', lazyRender:true })) }, { header: "状态", dataIndex: "status", sortable:false, width: 80, editor: new Ext.grid.GridEditor(new Ext.form.ComboBox({ typeAhead: true, triggerAction: 'all', transform:'statusSelect', lazyRender:true })) }]); cm.defaultSortable = true;//排序 var orderInfoRecord = Ext.data.Record.create([ {name: "product", type: "string"}, {name: "type", type: "string"}, {name: "unit", type: "string"}, {name: "height", type: "string"}, {name: "width", type: "string"}, {name: "area", type: "string"}, {name: "price", type: "string"}, {name: "amount", type: "string"}, {name: "price", type: "string"}, {name: "status", type: "string"} ]); var ds = new Ext.data.Store({ proxy: new Ext.data.DataProxy(), reader: new Ext.data.DataReader({ id:0 }, orderInfoRecord), remoteSort: false }); var grid = new Ext.grid.EditorGrid("orderInfoGrid", { ds: ds, cm: cm, enableDragDrop : false, clicksToEdit:1, selModel:new Ext.grid.RowSelectionModel() }); grid.render(); var gridHead = grid.getView().getHeaderPanel(true); var header = new Ext.Toolbar(gridHead, [{ text: '添加行', handler : function(){ var orderInfo = new orderInfoRecord({ id: Ext.id(), product: '', type:'', unit:'', height:'', width:'', area:'', price:'', amount:'', status:'', num:'', unitType:'' }); ds.insert(0, orderInfo); } },{ text: '删除行', handler : function(){ grid.stopEdit(); var selections = grid.getSelections(); if (selections.length == 0) { Ext.MessageBox.alert("提示", "请选择希望删除的记录!"); return; } else { Ext.Msg.confirm("提示", "是否确定删除?", function(btn, text) { if (btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ ds.remove(selections[i]);//从表格中删除 } } }); } } }]); grid.on("click", function() { var selections = grid.getSelections(); var amount = 0; for(var i = 0, len = selections.length; i < len; i++){ var record = selections[i]; var num = record.data.num; var price = record.data.price; record.data.amount = num * price; amount += record.data.amount; } document.getElementById("amount1").innerHTML = amount; document.getElementById("amount2").innerHTML = convertCurrency(amount); }); var resetFields = function() { grid.stopEditing(); ds.removeAll(); orderDate.reset(); customer.reset(); linkMan.reset(); tel.reset(); }; var submitAndSave = function() { grid.stopEditing(); var data = {}; data.orderDate = orderDate.getRawValue(); data.customer = customer.getValue(); data.linkMan = linkMan.getValue(); data.tel = tel.getValue(); data.amount = document.getElementById("amount1").innerHTML; data.infos = []; for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); var item = {}; item.product = record.data.product; item.type = record.data.type; item.unit = record.data.unit; item.height = record.data.height; item.width = record.data.width; item.area = record.data.area; item.price = record.data.price; item.amount = record.data.amount; item.status = record.data.status; item.num = record.data.num; item.unitType = record.data.unitType; data.infos.push(item); } Ext.lib.Ajax.request( 'POST', 'insert.htm', {success:function() { Ext.MessageBox.alert(' 提示', '操作成功'); resetFields(); },failure:function(){Ext.MessageBox.alert('提示', '操作失败!')}}, 'data=' + encodeURIComponent(Ext.encode(data)) ); }; var save = new Ext.Button('save', { text:'保存', handler: submitAndSave }); var add = new Ext.Button('addOrderInfo', { text:'添加新单据', handler:resetFields }); var submit = new Ext.Button('submit', { text:'确认单据', handler:submitAndSave }); var del = new Ext.Button('delOrderInfo', { text:'删除', handler:resetFields }); var print = new Ext.Button('print', { text:'打印', handler:function() { grid.stopEditing(); alert("还没做好呢。2007-10-25 23:29"); } }); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '原材料', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id:'id', qtip:"ID", vType:"integer", allowBlank:true,defValue:-1,w:50}, {id:'name', qtip:"名称", vType:"chn", allowBlank:false,w:100}, {id:'source', qtip:"产地", vType:"chn", allowBlank:false,w:100}, {id:'supplier', qtip:"供应商", vType:"chn", allowBlank:false,w:100}, {id:'price', qtip:"单价", vType:"float", allowBlank:false,w:80}, {id:'unit', qtip:"计量单位", vType:"chn", allowBlank:false,w:80}, {id:'status', qtip:"状态", vType:"integer", allowBlank:false,w:100}, {id:'inputMan', qtip:"录入人", vType:"chn", allowBlank:false,w:100}, {id:'inputTime', qtip:"录入时间", vType:"date", allowBlank:false,w:100}, {id:'descn', qtip:"备注", vType:"editor", allowBlank:false,w:100,showInGrid:false} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '产品', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id:'id', qtip:"ID", vType:"integer", allowBlank:true,defValue:-1,w:50}, {id:'name', qtip:"名称", vType:"chn", allowBlank:false,w:80}, {id:'code', qtip:"产品编码", vType:"chn", allowBlank:false,w:80}, {id:'type', qtip:"产品类别", vType:"chn", allowBlank:false,w:80}, {id:'buyPrice', qtip:"采购价格", vType:"float", allowBlank:false,w:60}, {id:'salePrice', qtip:"销售价格", vType:"float", allowBlank:false,w:60}, {id:'unit', qtip:"单位", vType:"chn", allowBlank:false,w:40}, {id:'pic', qtip:"图片", vType:"chn", allowBlank:false,w:80}, {id:'status', qtip:"状态", vType:"integer", allowBlank:false,w:80}, {id:'inputMan', qtip:"录入人", vType:"chn", allowBlank:false,w:80}, {id:'inputTime', qtip:"录入时间", vType:"date", allowBlank:false,w:90}, {id:'descn', qtip:"备注", vType:"editor", allowBlank:false,w:80,showInGrid:false} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '配方', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id:'id', qtip:"ID", vType:"integer", allowBlank:true,defValue:-1,w:50}, {id:'product', qtip:"产品", vType:"comboBox", allowBlank:false,w:200,skip:true}, {id:'material', qtip:"原料", vType:"comboBox", allowBlank:false,w:100,skip:true}, {id:'rate', qtip:"比率", vType:"alphanum", allowBlank:false,w:100}, {id:'unit', qtip:"计量单位", vType:"alphanum", allowBlank:false,w:80}, {id:'status', qtip:"状态", vType:"comboBox", allowBlank:false,w:100}, {id:'inputMan', qtip:"录入人", vType:"chn", allowBlank:false,w:100,showInGrid:false}, {id:'inputTime', qtip:"录入时间", vType:"date", allowBlank:false,w:100,showInGrid:false}, {id:'descn', qtip:"备注", vType:"editor", allowBlank:false,w:100,showInGrid:false} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); lightGrid.createDialog(); var productRecord = Ext.data.Record.create([ {name: 'id'}, {name: 'name'} ]); var materialRecord = Ext.data.Record.create([ {name: 'id'}, {name: 'name'} ]); var productStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erpproduct/pagedQuery.htm'}), reader: new Ext.data.JsonReader({root:'result'},productRecord) }); var materialStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erpmaterial/pagedQuery.htm'}), reader: new Ext.data.JsonReader({root:'result'},materialRecord) }); lightGrid.columns.product_id = new Ext.form.ComboBox({ id:'productId', name:'product', fieldLabel: '产品', hiddenName:'product_id', store: productStore, valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:200, transform:'product_id' }); lightGrid.columns.material_id = new Ext.form.ComboBox({ id:'materialId', name:'material', fieldLabel: '原材料', hiddenName:'material_id', store: materialStore, valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:200, transform:'material_id' }); productStore.load(); materialStore.load(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-08 * http://code.google.com/p/anewssystem/ */ /** * 继承JsonTree,自定义树形. * * @param container 被渲染的html元素的id,<div id="lighttree"></div> * @param config 需要的配置{} */ TrackerTree = function(container, config) { TrackerTree.superclass.constructor.call(this, container, config); }; Ext.extend(TrackerTree, Ext.lingo.JsonTree, { // 生成工具条 buildToolbar : function() { this.toolbar = new Ext.Toolbar(this.treePanel.el.createChild({tag:'div'})); this.toolbar.add({ text : '添加新项目', icon : '../widgets/lingo/list-items.gif', cls : 'x-btn-text-icon album-btn', tooltip : '添加选中节点的下级分类', handler : this.createNewProject.createDelegate(this) }, { text : '刷新', icon : '../widgets/lingo/list-items.gif', cls : 'x-btn-text-icon album-btn', tooltip : '刷新所有节点', handler : this.refresh.createDelegate(this) }); } // 生成右键菜单 , buildContextMenu : function() { this.contextMenu = new Ext.menu.Menu({ id : 'copyCtx', items : [{ id : 'createChild', icon : '../widgets/lingo/list-items.gif', handler : this.createNewProject.createDelegate(this), cls : 'create-mi', text : '添加新项目' },{ id : 'remove', icon : '../widgets/lingo/list-items.gif', handler : this.removeNode.createDelegate(this), cls : 'remove-mi', text : '删除节点' },'-',{ id : 'refresh', icon : '../widgets/lingo/list-items.gif', handler : this.refresh.createDelegate(this), cls : 'refresh', text : '刷新' },{ id : 'config', icon : '../widgets/lingo/list-items.gif', handler : this.configInfo.createDelegate(this), text : '详细配置' }] }); } // 生成新项目 , createNewProject : function() { this.createNode(this.treePanel.getRootNode()); } });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-08 * http://code.google.com/p/anewssystem/ */ /** * 继承JsonGrid,自定义表格. * * @param container 被渲染的html元素的id,<div id="lightgrid"></div> * @param config 需要的配置{} */ TrackerGrid = function(container, config) { TrackerGrid.superclass.constructor.call(this, container, config); }; Ext.extend(TrackerGrid, Ext.lingo.JsonGrid, { // 提交添加,修改表单 submitForm : function(item) { if (item['trackerProject.id'] === "0") { item['trackerProject.id'] = Tracker.grid.projectId; } this.dialog.el.mask('提交数据,请稍候...', 'x-mask-loading'); var hide = function() { this.dialog.el.unmask(); this.dialog.hide(); this.refresh.apply(this); }.createDelegate(this); Ext.lib.Ajax.request( 'POST', this.urlSave, {success:hide,failure:hide}, 'data=' + encodeURIComponent(Ext.encode(item)) ); } // 设置baseParams , setBaseParams : function() { // 读取数据 this.dataStore.on('beforeload', function() { this.dataStore.baseParams = { filterValue : this.filter.getValue() , filterTxt : this.filterTxt , projectId : this.projectId }; }.createDelegate(this)); } });
JavaScript
Tracker = { // 初始化 init : function() { // 开启提示功能 Ext.QuickTips.init(); this.buildLayout(); this.buildTree(); this.buildGrid(); } // 布局 , buildLayout : function() { var layout = new Ext.BorderLayout(document.body, { hideOnLayout:false, west: { initialSize:169, minSize:169, split:true, titlebar:true }, north: { initialSize:31, split:false, titlebar:false }, center: { alwaysShowTabs:true, closeOnTab: true, tabPosition:'top' }, south:{ initialSize:18, split:false, titlebar:false } }); layout.beginUpdate(); this.nav_area = layout.add('north', new Ext.ContentPanel('nav_area', { fitToFrame:true, autoScroll:false, autoCreate:true })).el; this.tree_areaEl = layout.add('west', new Ext.ContentPanel('tree_area', { title:'分类', fitToFrame:true, autoScroll:true, autoCreate:true })).el.unselectable(); this.state_areaEl = layout.add('south', new Ext.ContentPanel('state_area', { fitToFrame:true, autoScroll:false, autoCreate:true })).el; this.main_areaEl = layout.add('center', new Ext.ContentPanel('main_area', { title:'列表', fitToFrame:true, autoScroll:false, autoCreate:true })).el; layout.endUpdate(); layout.layout(); this.centerRegion = layout.getRegion('center'); } // 左侧树形 , buildTree : function() { var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1}, {id : 'name', qtip : "项目名称", vType : "chn", allowBlank : false}, {id : 'founder', qtip : "创建者", vType : "chn", allowBlank : false}, {id : 'summary', qtip : "项目描述", vType : "editor", allowBlank : true} ]; Tracker.tree = new TrackerTree("tree_area", { metaData : metaData, rootName : '所有工程', dlgWidth : 450, dlgHeight : 250, dialogContent : "tree_content", urlGetAllTree : "../trackerproject/getAllTree.htm", urlInsertTree : "../trackerproject/insertTree.htm", urlRemoveTree : "../trackerproject/removeTree.htm", urlSortTree : "../trackerproject/sortTree.htm", urlLoadData : "../trackerproject/loadData.htm", urlUpdateTree : "../trackerproject/updateTree.htm" }); Tracker.tree.render(); Tracker.tree.treePanel.on("click", function(node, e) { Tracker.updateGrid(node); }); } // 创建表格 , buildGrid : function() { var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1, w:40}, {id : 'project_id', qtip : "项目id", vType : "integer", allowBlank : false,mapping:'trackerProject.id',showInGrid:false}, {id : 'issuename', qtip : "任务名称", vType : "chn", allowBlank : false, w:160, mapping:'name'}, {id : 'priority', qtip : "优先级", vType : "comboBox", allowBlank : false, w:50, renderer:this.renderPriority}, {id : 'severity', qtip : "严重度", vType : "comboBox", allowBlank : false, w:50, renderer:this.renderSeverity}, {id : 'status', qtip : "状态", vType : "comboBox", allowBlank : true, w:50, renderer:this.renderStatus}, {id : 'assignTo', qtip : "负责人", vType : "chn", allowBlank : false, w:60}, {id : 'submitBy', qtip : "提交者", vType : "chn", allowBlank : false, w:60}, {id : 'addTime', qtip : "提交时间", vType : "date", allowBlank : false, w:100}, {id : 'updateDate', qtip : "修改时间", vType : "date", allowBlank : false, w:100}, {id : 'content', qtip : "内容", vType : "editor", allowBlank : true, w:100, renderer:this.renderContent}, {id : 'file', qtip : "附件", vType : "alphanum", allowBlank : true, w:50} ]; Tracker.grid = new TrackerGrid("main_area", { metaData : metaData, dlgWidth : 450, dlgHeight : 250, dialogContent : "grid_content", urlPagedQuery : "../trackerissue/pagedQuery.htm", urlSave : "../trackerissue/save.htm", urlLoadData : "../trackerissue/loadData.htm", urlRemove : "../trackerissue/remove.htm" }); Tracker.grid.render(); } // 更新grid显示对应projectId的数据 , updateGrid : function(node) { Tracker.grid.projectId = node.id; Tracker.grid.dataStore.reload(); } // priority优先级 , renderPriority : function(value) { if (value == 0) { return "<span style='color:green;font-style:italic;'>低</span>"; } else if (value == 1) { return "<span style='color:black;font-weight:normal;'>中</span>" } else { return "<span style='color:red;font-weight:bold;'>高</span>" } } // severity严重度 , renderSeverity : function(value) { if (value == 0) { return "<span style='color:green;font-style:italic;'>轻微</span>"; } else if (value == 1) { return "<span style='color:black;font-weight:normal;'>一般</span>" } else { return "<span style='color:red;font-weight:bold;'>严重</span>" } } // status状态 , renderStatus : function(value) { if (value == 0) { return "<span style='color:red;font-weight:bold;'>待处理</span>"; } else if (value == 1) { return "<span style='color:green;font-weight:normal;'>已处理</span>" } else { return "<span style='color:gray;font-style:italic;'>已关闭</span>" } } // content内容 , renderContent : function(value) { if (value.length > 6) { return value.substring(0, 6) + "..."; } else { return value; } } }; Ext.onReady(Tracker.init, Tracker);
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-25 * http://code.google.com/p/anewssystem/ */ var index = function() { var layout; return { init : function() { this.loginSuccessDelegate = this.loginSuccess.createDelegate(this); this.prepareLoginDelegate = this.prepareLogin.createDelegate(this); this.setLoginNameDelegate = this.setLoginName.createDelegate(this); // 使用cookie保存状态 //Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 创建主面板 layout = new Ext.BorderLayout(document.body, { north: { split : false, initialSize : 40, titlebar : false }, west: { split : true, initialSize : 200, minSize : 150, maxSize : 400, titlebar : true, collapsible : true, animate : true, useShim : true, cmargins : {top:2,bottom:2,right:2,left:2}, collapsed: true }, center: { titlebar : false, title : '', autoScroll : false } }); // 让布局在我们安排了所以部分之后,再显示 var innerLayout = new Ext.BorderLayout('south', { center: { autoScroll : false, split : true , titlebar : false, collapsible : true, showPin : true, animate : true }, south: { initialSize : '26px', autoScroll : false, split : false } }); this.createToolbar(); innerLayout.add('center', new Ext.ContentPanel('menu-tree')); innerLayout.add('south', new Ext.ContentPanel('toolbar')); layout.beginUpdate(); layout.add('north', new Ext.ContentPanel('header')); layout.add('west', new Ext.NestedLayoutPanel(innerLayout)); layout.add('center', new Ext.ContentPanel('main', {title: '', fitToFrame: true})); layout.restoreState(); layout.endUpdate(); //------------------------------------------------------------------------------ this.menuLayout = layout.getRegion("west"); this.menuLayout.id = 'menuLayout'; this.iframe = Ext.get('main').dom; this.loadMain('./needLogin.htm'); //checkLogin(); } // 检测用户是否已经登录 , checkLogin : function() { // 如果已经登录,就显示菜单 // 如果还未登录,就弹出对话框 Ext.lib.Ajax.request( 'POST', "../login/isLogin.htm", {success:this.loginSuccessDelegate,failure:this.prepareLoginDelegate}, '' ); } // 准备登录,包括隐藏菜单,弹出对话框 , prepareLogin : function() { this.menuLayout.collapse(); Ext.lingo.LoginDialog.init(this.loginSuccessDelegate); } // 注销 , logout : function() { Ext.lib.Ajax.request( 'POST', "../j_acegi_logout", {success:this.prepareLoginDelegate,failure:this.prepareLoginDelegate}, '' ); this.loadMain('./needLogin.htm'); } // 登录成功后执行的函数 , loginSuccess : function(data) { eval("var json=" + data.responseText + ";"); if (json.success) { this.setLoginName(json.response); //Ext.lib.Ajax.request( // 'POST', // "../login/getLoginName.htm", // {success:this.setLoginNameDelegate,failure:this.setLoginNameDelegate}, // '' //); MenuHelper.getMenus(this.render); if (!json.callback) { this.loadMain("./welcome.htm"); } else { this.loadMain(json.callback); } } else { this.prepareLogin(); } } // 创建更换主题的菜单 , createToolbar : function() { var theme = Cookies.get('xrinsurtheme') || 'aero' var menu = new Ext.menu.Menu({ id: 'mainMenu', items: [ new Ext.menu.CheckItem({ id: 'aero', text: '默认风格', checked: (theme == 'aero' ? true : false), group: 'theme', handler: Ext.theme.apply }), new Ext.menu.CheckItem({ id: 'vista', text: '夜色朦胧', checked: (theme == 'vista' ? true : false), group: 'theme', handler: Ext.theme.apply }), new Ext.menu.CheckItem({ id: 'gray', text: '秋意盎然', checked: (theme == 'gray' ? true : false), group: 'theme', handler: Ext.theme.apply }), new Ext.menu.CheckItem({ id: 'default', text: '蓝色回忆', checked: (theme == 'default' ? true : false), group: 'theme', handler: Ext.theme.apply }) ] }); var tb = new Ext.Toolbar('toolbar'); tb.add({ cls : 'theme' , text : '系统风格' , menu : menu }, '-', { cls : 'add' , text : '注销' , handler : this.logout.createDelegate(this) }); } // 获得layout , getLayout : function() { return layout; } // 设置登录名 , setLoginName : function(user) { user = user == null ? '' : user; this.menuLayout.updateTitle("登录用户:" + user); } // 点左边,链接,右边的iframe更新 , loadMain : function(url) { this.iframe.src = url; Cookies.set('xrinsurMainSrc', url); } // 渲染accordion菜单 , render : function(data) { var menuList = data; Ext.get('menu-tree').update(''); var hdt = new Ext.Template('<div><div>{head}</div></div>'); // hdt.compile(); var bdt = new Ext.Template('<div></div>'); // bdt.compile(); var itemTpl = new Ext.Template( '<div class="dl-group-child">' + '<div class="dl-selection">' + '<img src=../widgets/extjs/1.1/resources/images/default/user/tree/{image}>&nbsp;' + '<span>{title}</span>' + '</div>' + '</div>' ); itemTpl.compile(); var acc = new Ext.ux.Accordion('menu-tree', { boxWrap : false, body : 'menu-tree', fitContainer : true, fitToFrame : true, draggable : false, fitHeight : true, useShadow : false, initialHeight: layout.getRegion("west").el.getHeight() - 50 }); for(var g in menuList) { var group = menuList[g]; var hd = hdt.append('menu-tree', {head: g}); var bd = bdt.append(hd); acc.add(new Ext.ux.InfoPanel(hd, {autoScroll:true,icon: '../widgets/extjs/1.1/resources/images/default/user/menu/' + (group[0] ? group[0].parentImg : '')})); //, collapsed: true, showPin: false, collapseOnUnpin: true for(var i = 0; i < group.length; i++) { var f = group[i]; var item = itemTpl.append(bd, f, true); var cb = item.dom.firstChild.firstChild; f.cb = cb; //cb.disabled = (g == '<title>'); item.mon('click', function(e) { if(e.getTarget() != this.cb && !this.cb.disabled){ index.loadMain(this.href ? './' + this.href : 'http://localhost:8080/'); } }, f, true); item.addClassOnOver('dl-selection-over'); } } layout.getRegion("west").expand(); } } }(); function info(o) { var buff = ""; for (var i in o) { buff += "" + i + "," + o[i] + "\n"; } return buff; } Ext.onReady(index.init, index, true);
JavaScript
var menuManage = function(){ //建立DataGrid 对象 //@dlgContentDiv: 弹出框内容 //@dlgWidth: 弹出框宽度 //@dlgHeight: 弹出框高度 //@dlgTitle: 弹出框标题 //@initPaging: Grid分页数据读取路径 //@paging: 是否分页 //@pageSize: 每页数据条数 //@exec: 业务对象,对应dwr.xml var grid = new Ext.DataGrid({ gridDiv: 'datagrid', dlgTitle: '菜单设置', dlgContentDiv: 'content', dlgWidth: 560, dlgHeight: 360, paging: true, pageSize: 15, exec: 'MenuHelper' }); // return a public interface return { init : function(){ // 打开提示功能 Ext.QuickTips.init(); Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); var layout = new Ext.BorderLayout(document.body, { center: { autoScroll:true, titlebar: false, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: true, resizeTabs: true, fillToFrame: true } }); layout.beginUpdate(); var tb = new Ext.Toolbar('toolbar'); //绑定表格对象 tb.bind(grid); //设置工具条按钮 //@ text:按钮名称 //@ cls:按钮样式表 //@ dlgWidth:弹出框宽度 //@ dlgHeight:弹出框高度 //@ btnText:弹出框提交按钮名称 //@ tooltip:按钮标签 tb.add( {text: '新增', cls: 'add', btnText: '保存'}, '-', {text: '删除', cls: 'del', btnText: '确定'}, '-', {text: '修改', cls: 'edit', btnText: '保存'} ); Forms.createQuicksearch({tb: tb}, function(value){ var param = [{pName: 'name', pMore: 'like', pValue: value, pType:'String'}]; grid.render(param); }); layout.add('center', new Ext.ContentPanel('tab1', { title: '菜单设置', toolbar: tb, closable: false, fitToFrame:true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: tb, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); //Grid列定义 //@ header:列名称 //@ width :列宽度 //@ align :对齐方式 //@ sortable:是否排序 //@ type: (link:'查看'链接) grid.setHeader([ {header: "", width: 30, sortable: true, type: 'link'}, {header: "菜单名称", width: 100, sortable: true, type: 'link'}, {header: "访问路径", width: 200, sortable: true, align: 'left'}, {header: "上级ID", width: 80, sortable: true, align: 'left'}, {header: "排序", width: 40, sortable: true, align: 'left'}, {header: "操作", width: 240, sortable: true, align: 'left'} ]); grid.defaultSort = {field: 'theSort', dir: 'desc'}; grid.render(); } }; }(); Ext.onReady(menuManage.init, menuManage, true);
JavaScript
/** * Copyright(c) 2006-2007, FeyaSoft Inc. * * This JS is mainly used to handle action in the list * and create, edit, delete. * There includes Search function, paging function etc * Create/update is using pop-up dialog * Delete can select multiple line */ Ext.onReady(function(){ var myPageSize = 10; // shorthand alias var fm = Ext.form, Ed = Ext.grid.GridEditor; //we enable the QuickTips for the later Pagebar Ext.QuickTips.init(); function formatBoolean(value){ return value ? 'Yes' : 'No'; } function formatDate(value){ return value ? value.dateFormat('m d, Y') : ''; } /************************************************************ * Display the result in page * the column model has information about grid columns * dataIndex maps the column to the specific data field in * the data store (created below) ************************************************************/ var cm = new Ext.grid.ColumnModel([{ id: 'id', header: "序号", dataIndex: 'id', width: 150 }, { header: "关键字", dataIndex: 'name', width: 90 } ]); // by default columns are sortable cm.defaultSortable = false; // this could be inline, but we want to define the NewAccount record // type so we can add records dynamically var Tag = Ext.data.Record.create([ {name: 'id', type: 'int'}, {name: 'name', type: 'string'} ]); /************************************************************ * connect to backend - grid - core part * create the Data Store * connect with backend and list the result in page * through JSON format ************************************************************/ var ds = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(NewsTagHelper.getItems, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, Tag), remoteSort: true }); ds.setDefaultSort('id', 'ASC'); // create the editor grid var grid = new Ext.ux.CheckRowSelectionGrid('editor-grid', { ds: ds, cm: cm, //selModel: new Ext.grid.CellSelectionModel(), //selModel: new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock:false }); var layout = Ext.BorderLayout.create({ center: { margins:{left:2,top:3,right:2,bottom:3}, panels: [new Ext.GridPanel(grid)] } }, 'grid-panel'); // render it grid.render(); /************************************************************ * create header panel * add filter field - search function ************************************************************/ var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead); filterButton = new Ext.Toolbar.MenuButton({ icon: 'public/image/list-items.gif', cls: 'x-btn-text-icon', text: 'Choose Filter', tooltip: 'Select one of filter', menu: {items: [ new Ext.menu.CheckItem({ text: 'name', value: 'name', checked: true, group: 'filter', checkHandler: onItemCheck }) ]}, minWidth: 105 }); tb.add(filterButton); // Create the filter field var filter = Ext.get(tb.addDom({ // add a DomHelper config to the toolbar and return a reference to it tag: 'input', type: 'text', size: '30', value: '', style: 'background: #F0F0F9;' }).el); // press enter keyboard filter.on('keypress', function(e) { // setup an onkeypress event handler if(e.getKey() == e.ENTER && this.getValue().length > 0) {// listen for the ENTER key ds.load({params:{start:0, limit:myPageSize}}); } }); filter.on('keyup', function(e) { // setup an onkeyup event handler if(e.getKey() == e.BACKSPACE && this.getValue().length === 0) {// listen for the BACKSPACE key and the field being empty ds.load({params:{start:0, limit:myPageSize}}); } }); // Update search button text with selected item function onItemCheck(item, checked) { if(checked) { filterButton.setText(item.text + ':'); } } /************************************************************ * create footer panel * actions and paging ************************************************************/ var gridFoot = grid.getView().getFooterPanel(true); // add a paging toolbar to the grid's footer var paging = new Ext.PagingToolbar(gridFoot, ds, { pageSize: myPageSize, displayInfo: true, displayMsg: 'total {2} results found. Current shows {0} - {1}', emptyMsg: "not result to display" }); // add the detailed add button paging.add('-', { pressed: true, enableToggle:true, text: 'Add', cls: '', toggleHandler: doAdd }); // add the detailed delete button paging.add('-', { pressed: true, enableToggle:true, text: 'Delete', cls: '', toggleHandler: doDel }); // --- end -- create foot panel /************************************************************ * load parameter to backend * have beforelaod function ************************************************************/ ds.on('beforeload', function() { ds.baseParams = { // modify the baseParams setting for this request filterValue: filter.getValue(),// retrieve the value of the filter input and assign it to a property named filter filterTxt: filterButton.getText() }; }); // trigger the data store load ds.load({params:{start:0, limit:myPageSize}}); /************************************************************ * Action - delete * start to handle delete function * need confirm to delete ************************************************************/ function doDel(){ var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('Message', 'Do you really want to delete them?' , doDel2); } else { Ext.MessageBox.alert('Error', 'Please select at least one item to delete'); } } function doDel2(btn) { if(btn == 'yes') { var m = grid.getSelections(); var data = new Array(); for (var i = 0, len = m.length; i < len; i++) { data.push(m[i].get("id")); ds.remove(m[i]); } NewsTagHelper.removeAll(data); } } /************************************************************ * Add an "clickoutside" event to a Grid. * @param grid {Ext.grid.Grid} The grid to add a clickoutside event to. * The handler is passed the Event and the Grid. ************************************************************/ function addClickOutsideEvent(grid) { if (!grid.events.clickoutside) { grid.addEvents({"clickoutside": true}); } if (!Ext.grid.Grid.prototype.handleClickOutside) { Ext.grid.Grid.override({ handleClickOutside: function(e) { var p = Ext.get(e.getTarget()).findParent(".x-grid-container"); if (p != this.container.dom) { this.fireEvent("clickoutside", e, grid); } } }); } Ext.get(document.body).on("click", grid.handleClickOutside, grid); } /************************************************************ * Create a new dialog - reuse by create and edit part ************************************************************/ function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:true, autoTabs:true, proxyDrag:true, resizable:false, width: 480, height: 302, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('Cancel', function() {thisDialog.hide();}); return thisDialog; }; /************************************************************ * Action - update * handle double click * user select one of the item and want to update it ************************************************************/ grid.on('rowdblclick', function(grid, rowIndex, e) { var selectedId = ds.data.items[rowIndex].id; // get information from DB and set form now... var account_data = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'loadData.htm?id=' + selectedId}), reader: new Ext.data.JsonReader({},['id','name']), remoteSort: false }); account_data.on('load', function() { console.info(account_data); // set value now var updateId = account_data.getAt(0).data['id']; name_show.setValue(account_data.getAt(0).data['name']); console.info(account_data.getAt(0).data['name']); var updateInstanceDlg; if (!updateInstanceDlg) { updateInstanceDlg = createNewDialog("a-updateInstance-dlg"); updateInstanceDlg.addButton('Save', function() { // submit now... all the form information are submit to the server // handle response after that... if (form_instance_update.isValid()) { form_instance_update.submit({ params:{id : updateId}, waitMsg:'更新数据...', reset: false, failure: function(form_instance_update, action) { Ext.MessageBox.alert('Error Message', action.result.errorInfo); }, success: function(form_instance_update, action) { Ext.MessageBox.alert('Confirm', action.result.info); updateInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('Errors', 'Please fix the errors noted.'); } }); var layout = updateInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: 'Update Account'})); layout.endUpdate(); updateInstanceDlg.show(); } }); account_data.load(); }); /************************************************************ * Action - add * start to handle add function * new page appear and allow to submit ************************************************************/ /************************************************************ * To create add new account dialog now.... ************************************************************/ function doAdd() { var aAddInstanceDlg; if (!aAddInstanceDlg) { aAddInstanceDlg = createNewDialog("a-addInstance-dlg"); aAddInstanceDlg.addButton('Reset', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('Save', function() { // submit now... all the form information are submit to the server // handle response after that... if (form_instance_create.isValid()) { form_instance_create.submit({ waitMsg:'Creating new account now...', reset: false, failure: function(form_instance_create, action) { var info = Ext.MessageBox.alert('Error Message', action.result.errorInfo); }, success: function(form_instance_create, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('Errors', 'Please fix the errors noted.'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-addInstance-inner', {title: 'create account'})); layout.endUpdate(); resetForm(); aAddInstanceDlg.show(); } } /************************************************************ * Form information - pop-up dialog * turn on validation errors beside the field globally ************************************************************/ Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; /************************************************************ * Create new form to hold user enter information * This form is used to create new instance ************************************************************/ var name_tf = new Ext.form.TextField({ fieldLabel: '关键字', name: 'name', allowBlank:false }); var form_instance_create = new Ext.form.Form({ labelAlign: 'right', url:'insertRow.htm' }); form_instance_create.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_create.fieldset( {id:'desc', legend:'Please fill the field'}, name_tf ); form_instance_create.applyIfToFields({width:255}); form_instance_create.render('a-addInstance-form'); form_instance_create.end(); resetForm = function() { name_tf.setValue(''); }; /************************************************************ * Create form to hold user enter information * This form is used to update current instance ************************************************************/ var name_show = new Ext.form.TextField({ // labelStyle: 'display: none', fieldLabel: '关键字', name: 'name', readOnly: false, allowBlank:false }); var form_instance_update = new Ext.form.Form({ labelAlign: 'right', url:'updateRow.htm' }); form_instance_update.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_update.fieldset( {id:'', legend:'修改'}, name_show ); form_instance_update.applyIfToFields({width:255}); form_instance_update.render('a-updateInstance-form'); form_instance_update.end(); //右键菜单 function contextmenu(grid, rowIndex,e){ e.preventDefault(); e.stopEvent(); var infoMenu = new Ext.menu.Item({ id:'infoMenu', text: 'infoMenu', handler:function(){ Ext.MessageBox.alert("info",Ext.util.JSON.encode(grid.dataSource.getAt(rowIndex).data)); } }); var menuList = [infoMenu]; grid_menu = new Ext.menu.Menu({ id: 'mainMenu', items: menuList }); var coords = e.getXY(); grid_menu.showAt([coords[0], coords[1]]); } grid.addListener('rowcontextmenu', contextmenu); });
JavaScript
Ext.data.DWRProxy = function(dwrCall, pagingAndSort) { Ext.data.DWRProxy.superclass.constructor.call(this); this.dwrCall = dwrCall; //this.args = args; this.pagingAndSort = (pagingAndSort!=undefined ? pagingAndSort : true); }; Ext.extend(Ext.data.DWRProxy, Ext.data.DataProxy, { load : function(params, reader, callback, scope, arg) { if(this.fireEvent("beforeload", this, params) !== false) { //var sort; // if(params.sort && params.dir) sort = params.sort + ' ' + params.dir; //else sort = ''; var delegate = this.loadResponse.createDelegate(this, [reader, callback, scope, arg], 1); var callParams = new Array(); //if(arg.arg) { // callParams = arg.arg.slice(); //} //if(this.pagingAndSort) { //callParams.push(params.start); //callParams.push(params.limit); //callParams.push(sort); //} callParams.push(arg.params); callParams.push(delegate); this.dwrCall.apply(this, callParams); } else { callback.call(scope || this, null, arg, false); } }, loadResponse : function(listRange, reader, callback, scope, arg) { var result; try { result = reader.read(listRange); } catch(e) { this.fireEvent("loadexception", this, null, response, e); callback.call(scope, null, arg, false); return; } callback.call(scope, result, arg, true); }, update : function(dataSet){}, updateResponse : function(dataSet) {} }); Ext.data.ListRangeReader = function(meta, recordType){ Ext.data.ListRangeReader.superclass.constructor.call(this, meta, recordType); this.recordType = recordType; }; Ext.extend(Ext.data.ListRangeReader, Ext.data.DataReader, { getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), read : function(o){ var recordType = this.recordType, fields = recordType.prototype.fields; //Generate extraction functions for the totalProperty, the root, the id, and for each field if (!this.ef) { if(this.meta.totalProperty) { this.getTotal = this.getJsonAccessor(this.meta.totalProperty); } if(this.meta.successProperty) { this.getSuccess = this.getJsonAccessor(this.meta.successProperty); } if (this.meta.id) { var g = this.getJsonAccessor(this.meta.id); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } this.ef = []; for(var i = 0; i < fields.length; i++){ f = fields.items[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; this.ef[i] = this.getJsonAccessor(map); } } var records = []; var root = o.result, c = root.length, totalRecords = c, success = true; if(this.meta.totalProperty){ var v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(this.meta.successProperty){ var v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } for(var i = 0; i < c; i++){ var n = root[i]; var values = {}; var id = this.getId(n); for(var j = 0; j < fields.length; j++){ f = fields.items[j]; var v = this.ef[j](n); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue); } var record = new recordType(values, id); records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; } });
JavaScript
// JavaScript Document Ext.onReady (function() { function formatBoolean(value){ return value ? 'Yes' : 'No'; }; function formatDate(value){ return value ? value.dateFormat('M, d, Y') : ''; }; deleteRow = function(){ if (confirm('确定要删除?')) { var sm = grid.getSelectionModel(); var cell = sm.getSelectedCell(); var ds = grid.getDataSource(); var record = ds.getAt(cell[0]); var doSuccess = function() { ds.remove(record); }; NewsTagHelper.removeRow(record.id, doSuccess); } } function deleteRowRender(value){ var htmlString = '<input title="delete" value="x" type="button" class="delete" onclick="deleteRow()"/>'; return htmlString; } var cm = new Ext.grid.ColumnModel([{ header: "序号", dataIndex: "id", width: 100 }, { header: "关键字", dataIndex: "name", width: 100, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { id: "deleteRow", header: "删除", dataIndex: "deleteRow", renderer: deleteRowRender, width: 50 }]); cm.defaultSortable = true;//排序 var Tag = Ext.data.Record.create([ {name: "id", type: "int"}, {name: "name", type: "string"} ]); var ds = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(NewsTagHelper.getItems, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, Tag), remoteSort: true }); var grid = new Ext.grid.EditorGrid("grid-example", {ds: ds, cm: cm, enableColLock: false}); var layout = Ext.BorderLayout.create({ center: {margins:{left:30,top:30,right:100,bottom:100}, panels: [new Ext.GridPanel(grid)]} }, document.body); // make the grid resizable, do before render for better performance var rz = new Ext.Resizable('grid-example', { wrap:true, minHeight:100, pinned:true, handles:'s' }); rz.on('resize', grid.autoSize, grid); grid.render(); var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead, [{ text: '新增关键字', handler : function(){ var tag = new Tag({ id: -1, name: '' }); grid.stopEditing(); ds.insert(0, tag); grid.startEditing(0, 1); } }, { text: '保存', handler: function() { grid.stopEditing(); var data = new Array(); for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); if (record.data.id == -1 || record.dirty) { data.push(record.data.name); } } var doSuccess = function() { //alert("完成"); ds.load({start:0,limit:10}); }; NewsTagHelper.save(data, doSuccess); } }]); var gridFoot = grid.getView().getFooterPanel(true); // add a paging toolbar to the grid's footer var paging = new Ext.PagingToolbar(gridFoot, ds, { pageSize: 10, displayInfo: true, displayMsg: '显示 {0} - {1} 共 {2}', emptyMsg: "没有数据" }); //查询时需要用到的参数 //ds.on('beforeload', function() { // ds.baseParams = { // param1: 'test111', // param2: true // }; //}); //分页基本参数 ds.load({params:{start:0, limit:10}}); });
JavaScript
Ext.namespace('Ext.ux'); // --- Ext.ux.CheckRowSelectionGrid --- // Ext.ux.CheckRowSelectionGrid = function(container, config) { var id = this.root_cb_id = Ext.id(null, 'cbsm-'); var cb_html = String.format("<input type='checkbox' id='{0}'/>", this.root_cb_id); var grid = this; var cm = config.cm; // Hack var cm = config.cm || config.colModel; cm.config.unshift({ id: id, header: cb_html, width: 20, resizable: false, fixed: true, sortable: false, dataIndex: -1, renderer: function(data, cell, record, rowIndex, columnIndex, store) { return String.format( "<input type='checkbox' id='{0}-{1}' {2}/>", id, rowIndex, grid.getSelectionModel().isSelected(rowIndex) ? "checked='checked'" : '' ); } }); cm.lookup[id] = cm.config[0]; Ext.ux.CheckRowSelectionGrid.superclass.constructor.call(this, container, config); } Ext.extend(Ext.ux.CheckRowSelectionGrid, Ext.grid.Grid, { root_cb_id : null, getSelectionModel: function() { if (!this.selModel) { this.selModel = new Ext.ux.CheckRowSelectionModel(); } return this.selModel; } }); Ext.ux.CheckRowSelectionModel = function(options) { Ext.ux.CheckRowSelectionModel.superclass.constructor.call(this, options); } Ext.extend(Ext.ux.CheckRowSelectionModel, Ext.grid.RowSelectionModel, { init: function(grid) { Ext.ux.CheckRowSelectionModel.superclass.init.call(this, grid); // Start of dirty hacking // Hacking grid if (grid.processEvent) { grid.__oldProcessEvent = grid.processEvent; grid.processEvent = function(name, e) { // The scope of this call is the grid object var target = e.getTarget(); var view = this.getView(); var header_index = view.findHeaderIndex(target); if (name == 'contextmenu' && header_index === 0) { return; } this.__oldProcessEvent(name, e); } } // Hacking view var gv = grid.getView(); if (gv.beforeColMenuShow) { gv.__oldBeforeColMenuShow = gv.beforeColMenuShow; gv.beforeColMenuShow = function() { // The scope of this call is the view object this.__oldBeforeColMenuShow(); // Removing first - checkbox column from the column menu this.colMenu.remove(this.colMenu.items.first()); // he he } } // End of dirty hacking }, initEvents: function() { Ext.ux.CheckRowSelectionModel.superclass.initEvents.call(this); this.grid.getView().on('refresh', this.onGridRefresh, this); }, selectRow: function(index, keepExisting, preventViewNotify) { Ext.ux.CheckRowSelectionModel.superclass.selectRow.call( this, index, keepExisting, preventViewNotify ); var row_id = this.grid.root_cb_id + '-' + index; var cb_dom = Ext.fly(row_id).dom; cb_dom.checked = true; }, deselectRow: function(index, preventViewNotify) { Ext.ux.CheckRowSelectionModel.superclass.deselectRow.call( this, index, preventViewNotify ); var row_id = this.grid.root_cb_id + '-' + index; var cb_dom = Ext.fly(row_id).dom; cb_dom.checked = false; }, onGridRefresh: function() { Ext.fly(this.grid.root_cb_id).on('click', this.onAllRowsCheckboxClick, this, {stopPropagation:true}); // Attaching to row checkboxes events for (var i = 0; i < this.grid.getDataSource().getCount(); i++) { var cb_id = this.grid.root_cb_id + '-' + i; Ext.fly(cb_id).on('mousedown', this.onRowCheckboxClick, this, {stopPropagation:true}); } }, onAllRowsCheckboxClick: function(event, el) { if (el.checked) { this.selectAll(); } else { this.clearSelections(); } }, onRowCheckboxClick: function(event, el) { var rowIndex = /-(\d+)$/.exec(el.id)[1]; if (el.checked) { this.deselectRow(rowIndex); el.checked = true; } else { this.selectRow(rowIndex, true); el.checked = false; } } }); // --- end of Ext.ux.CheckRowSelectionGrid --- //
JavaScript
/* * Ext JS Library 1.0.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ var Example = { init : function(){ // some data yanked off the web var myData = [ ['3m Co',71.72,0.02,0.03,'9/1 12:00am'], ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'], ['Altria Group Inc',83.81,0.28,0.34,'9/1 12:00am'], ['American Express Company',52.55,0.01,0.02,'9/1 12:00am'], ['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'], ['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'], ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'], ['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am'], ['Citigroup, Inc.',49.37,0.02,0.04,'9/1 12:00am'], ['E.I. du Pont de Nemours and Company',40.48,0.51,1.28,'9/1 12:00am'], ['Exxon Mobil Corp',68.1,-0.43,-0.64,'9/1 12:00am'], ['General Electric Company',34.14,-0.08,-0.23,'9/1 12:00am'], ['General Motors Corporation',30.27,1.09,3.74,'9/1 12:00am'], ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'], ['Honeywell Intl Inc',38.77,0.05,0.13,'9/1 12:00am'], ['Intel Corporation',19.88,0.31,1.58,'9/1 12:00am'], ['International Business Machines',81.41,0.44,0.54,'9/1 12:00am'], ['Johnson & Johnson',64.72,0.06,0.09,'9/1 12:00am'], ['JP Morgan & Chase & Co',45.73,0.07,0.15,'9/1 12:00am'], ['McDonald\'s Corporation',36.76,0.86,2.40,'9/1 12:00am'], ['Merck & Co., Inc.',40.96,0.41,1.01,'9/1 12:00am'], ['Microsoft Corporation',25.84,0.14,0.54,'9/1 12:00am'], ['Pfizer Inc',27.96,0.4,1.45,'9/1 12:00am'], ['The Coca-Cola Company',45.07,0.26,0.58,'9/1 12:00am'], ['The Home Depot, Inc.',34.64,0.35,1.02,'9/1 12:00am'], ['The Procter & Gamble Company',61.91,0.01,0.02,'9/1 12:00am'], ['United Technologies Corporation',63.26,0.55,0.88,'9/1 12:00am'], ['Verizon Communications',35.57,0.39,1.11,'9/1 12:00am'], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81,'9/1 12:00am'] ]; var ds = new Ext.data.Store({ proxy: new Ext.data.MemoryProxy(myData), reader: new Ext.data.ArrayReader({}, [ {name: 'company'}, {name: 'price', type: 'float'}, {name: 'change', type: 'float'}, {name: 'pctChange', type: 'float'}, {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'} ]) }); ds.load(); // example of custom renderer function function italic(value){ return '<i>' + value + '</i>'; } // example of custom renderer function function change(val){ if(val > 0){ return '<span style="color:green;">' + val + '</span>'; }else if(val < 0){ return '<span style="color:red;">' + val + '</span>'; } return val; } // example of custom renderer function function pctChange(val){ if(val > 0){ return '<span style="color:green;">' + val + '%</span>'; }else if(val < 0){ return '<span style="color:red;">' + val + '%</span>'; } return val; } // the DefaultColumnModel expects this blob to define columns. It can be extended to provide // custom or reusable ColumnModels var colModel = new Ext.grid.ColumnModel([ {header: "Company", width: 160, sortable: true, locked:false, dataIndex: 'company'}, {header: "Price", width: 75, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'}, {id:'change',header: "Change", width: 75, sortable: true, renderer: change, dataIndex: 'change'}, {header: "% Change", width: 75, sortable: true, renderer: pctChange, dataIndex: 'pctChange'}, {header: "Last Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'} ]); // create the Grid var grid = new Ext.grid.Grid('grid-example', { ds: ds, cm: colModel, autoExpandColumn: 'change' }); var layout = Ext.BorderLayout.create({ center: { margins:{left:3,top:3,right:3,bottom:3}, panels: [new Ext.GridPanel(grid)] } }, 'grid-panel'); grid.render(); grid.getSelectionModel().selectFirstRow(); //右键菜单 function contextmenu(grid, rowIndex,e){ e.preventDefault(); e.stopEvent(); var infoMenu = new Ext.menu.Item({ id:'infoMenu', text: 'infoMenu', handler:function(){ Ext.MessageBox.alert("info",Ext.util.JSON.encode(grid.dataSource.getAt(rowIndex).data)); } }); var menuList = [infoMenu]; grid_menu = new Ext.menu.Menu({ id: 'mainMenu', items: menuList }); var coords = e.getXY(); grid_menu.showAt([coords[0], coords[1]]); } grid.addListener('rowcontextmenu', contextmenu); } }; Ext.onReady(Example.init, Example);
JavaScript
Ext.tree.DWRTreeLoader = function(config) { Ext.tree.DWRTreeLoader.superclass.constructor.call(this, config); }; Ext.extend(Ext.tree.DWRTreeLoader, Ext.tree.TreeLoader, { requestData : function(node, callback) { if (this.fireEvent("beforeload", this, node, callback) !== false) { //todo //var params = this.getParams(node); var callParams = new Array(); var success = this.handleResponse.createDelegate(this, [node, callback], 1); var error = this.handleFailure.createDelegate(this, [node, callback], 1); callParams.push(node.id); callParams.push({callback:success, errorHandler:error}); //todo: do we need to set this to something else? this.transId=true; this.dataUrl.apply(this, callParams); } else { // if the load is cancelled, make sure we notify // the node that we are done if (typeof callback == "function") { alert(callback); callback(); } } }, processResponse : function(response, node, callback){ try { for(var i = 0; i < response.length; i++){ var n = this.createNode(response[i]); if(n){ node.appendChild(n); } } if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response, node, callback){ this.transId = false; this.processResponse(response, node, callback); this.fireEvent("load", this, node, response); }, handleFailure : function(response, node, callback){ this.transId = false; this.fireEvent("loadexception", this, node, response); if(typeof callback == "function"){ callback(this, node); } } });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-11-11 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '采购订单管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'订单编号',sortable:true,dataIndex:'code',width:80}, {header:'订单状态',sortable:true,dataIndex:'status',width:70,renderer:function(value){ if (value == 0) { return '待审'; } else if (value == 1) { return '审核'; } else if (value == 2) { return '完成'; } }}, {header:'订单名称',sortable:true,dataIndex:'name',width:80}, {header:'供应商',sortable:true,dataIndex:'supplier',width:60}, {header:'联系人',sortable:true,dataIndex:'linkman',width:60}, {header:'要求供货日期',sortable:true,dataIndex:'provideDate',width:80}, {header:'审核受理',sortable:true,dataIndex:'audit',width:60,renderer:function(value){ if (value == 0) { return '立即审核'; } else if (value == 1) { return '常规审核'; } }}, {header:'签订日期',sortable:true,dataIndex:'orderDate',width:80}, {header:'订单签订人员',sortable:true,dataIndex:'username',width:80} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'code'}, {name:'status'}, {name:'name'}, {name:'supplier',mapping:'erp2Supplier.name'}, {name:'linkman'}, {name:'provideDate'}, {name:'audit'}, {name:'orderDate'}, {name:'username'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','采购订单管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var code = new Ext.form.TextField({ id:'code', name:'code', fieldLabel:'订单编号', width:100 }); var status = new Ext.form.ComboBox({ id:'statusId', name:'status', readOnly:true, fieldLabel:'订单状态', hiddenName:'status', store:new Ext.data.SimpleStore({ fields:['id', 'name'], data:[[0,'待审'],[1,'审核'],[2,'完成']] }), valueField:'id', displayField:'name', typeAhead:true, mode:'local', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, hideClearButton:false, hideTrigger:false, resizable:false, width:120 }); var name = new Ext.form.TextField({ id:'name', name:'name', fieldLabel:'订单名称', width:100 }); var orderDate = new Ext.form.DateField({ id:'orderDate', name:'orderDate', fieldLabel:'签订日期', width:100 }); code.applyTo('code'); status.applyTo('statusId'); name.applyTo('name'); orderDate.applyTo('orderDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); status.setValue(''); status.setRawValue('请选择'); status.clearValue(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">填写采购清单</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var updateHtml = '<div style="width:100%px;margin:auto;" id="update-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">修改采购清单</h3>' + '<div id="update-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '填写采购订单', insertHtml, true); var insertForm = EditForm.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); var update = new Ext.Button('update-button', { text:'修改', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择修改的记录'); } else if (m.length == 1) { var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('update-tab', '修改采购清单', updateHtml, true); var closeTabDelegate = tabs.removeTab.createDelegate(tabs, ['update-tab']); var updateForm = EditForm.getUpdateForm(closeTabDelegate, m[0].get('id')); tabs.activate('update-tab'); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var remove = new Ext.Button('remove-button', { text:'删除', handler:function() { var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '是否确定删除', function(btn){ if(btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ try { selections[i].get("id"); ids[i] = selections[i].get("id"); dataStore.remove(selections[i]);//从表格中删除 } catch (e) { } } Ext.Ajax.request({ url : 'remove.htm?ids=' + ids, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); //dataStore.reload(); }, failure : function(){Ext.MessageBox.alert('提示', '删除失败!');} }); } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }); dataStore.on('beforeload', function() { dataStore.baseParams = { code : code.getValue(), status : status.getValue(), name : name.getValue(), orderDate : orderDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); EditForm = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (!form.isValid()){ return; } form.el.mask('提交数据,请稍候...', 'x-mask-loading'); var hide = function(){ form.el.unmask(); }; var buyOrderValue = EditForm.form.getValues(); buyOrderValue.totalPrice = document.getElementById("amount1").innerHTML; EditForm.grid.stopEditing(); var infoValues = new Array(); var ds = EditForm.grid.dataSource; for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); var item = {}; item.id = record.data.id; item.productId = record.data.productId; item.code = record.data.code; item.parameter = record.data.parameter; item.num = record.data.num; item.unit = record.data.unit; item.price = record.data.price; item.totalPrice = record.data.totalPrice; item.descn = record.data.descn; infoValues.push(item); } var json = {buyOrderValue:buyOrderValue,infos:infoValues} Ext.lib.Ajax.request( 'POST', './insert.htm', {success:function(){ form.el.unmask(); Ext.MessageBox.confirm('提示', '保存添加成功,是否继续添加', function(btn){ if (btn == 'yes') { form.reset(); EditForm.grid.dataSource.removeAll(); EditForm.form.findField("statusId2").clearValue(""); EditForm.form.findField("supplierNameId2").clearValue(""); EditForm.form.findField("auditId2").clearValue(""); } else { closeTagHandler(); } }); },failure:function(){ form.el.unmask(); }}, 'data=' + encodeURIComponent(Ext.encode(json)) ); } }); form.addButton({ text:'重置', handler:function(){ form.reset(); EditForm.grid.dataSource.removeAll(); EditForm.form.findField("statusId2").clearValue(""); EditForm.form.findField("supplierNameId2").clearValue(""); EditForm.form.findField("auditId2").clearValue(""); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); this.createGrid(); var grid = this.grid; return form; }, getUpdateForm : function(closeTagHandler, id) { this.createForm('./update.htm', 'update-box'); this.id = id; var form = this.form; form.load({url:'./loadData.htm?id=' + id}); form.addButton({ text:'提交', handler:function(){ if (!form.isValid()) { return; } form.el.mask('提交数据,请稍候...', 'x-mask-loading'); var hide = function() { form.el.unmask(); }; var buyOrderValue = EditForm.form.getValues(); buyOrderValue.totalPrice = document.getElementById("amount1").innerHTML; buyOrderValue.id = EditForm.id; EditForm.grid.stopEditing(); var infoValues = new Array(); var ds = EditForm.grid.dataSource; for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); var item = {}; item.id = record.data.id; item.productId = record.data.productId; item.code = record.data.code; item.parameter = record.data.parameter; item.num = record.data.num; item.unit = record.data.unit; item.price = record.data.price; item.totalPrice = record.data.totalPrice; item.descn = record.data.descn; infoValues.push(item); } var json = {buyOrderValue:buyOrderValue,infos:infoValues} Ext.lib.Ajax.request( 'POST', './update.htm', {success:function(){ form.el.unmask(); Ext.MessageBox.confirm('提示', '修改成功,是否返回' , function(btn){ if (btn == 'yes') { closeTagHandler(); } else { form.reset(); EditForm.grid.dataSource.load({params:{id:EditForm.id}}); } }); },failure:function(){ form.el.unmask(); }}, 'data=' + encodeURIComponent(Ext.encode(json)) ); } }); form.addButton({ text:'重置', handler:function(){ form.load({url:'./loadData.htm?id=' + this.id}); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("update-form"); this.createGrid(); var grid = this.grid; grid.dataSource.load({params:{id:id}}); return form; }, getRecordBuyOrderInfo : function() { // 数据模型 this.RecordBuyOrderInfo = Ext.data.Record.create([ {name:"id"}, {name:"code"}, {name:'productId',mapping:'erp2Product.id'}, {name:"productName",mapping:'erp2Product.name'}, {name:"productType",mapping:'erp2Product.type'}, {name:"material",mapping:'erp2Product.material'}, {name:'parameter'}, {name:"factory",mapping:'erp2Product.factory'}, {name:"num"}, {name:"unit"}, {name:"price"}, {name:"totalPrice"}, {name:"descn"} ]); }, createForm : function(url, waitMsgTarget) { this.getRecordBuyOrderInfo(); var form = new Ext.form.Form({ labelAlign:'right', labelWidth:80, url:url, method: 'POST', waitMsgTarget:waitMsgTarget, reader : new Ext.data.JsonReader({}, [ 'code', 'status', 'name', {name:'supplierName',mapping:'erp2Supplier.name'}, 'linkman', 'provideDate', 'orderDate', 'audit', 'username' ]) }); form.fieldset( {legend:'采购订单', hideLabels:false} ); var supplierDataStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2supplier/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','name']) }) var supplierName = new Ext.form.ComboBox({ id:'supplierNameId2', name:'supplierName', readOnly:true, fieldLabel:'供应商名称', hiddenName:'supplierName', store: supplierDataStore, valueField:'id', displayField:'name', typeAhead:true, mode:'remove', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false, pageSize:10 }); form.column( {width:320}, new Ext.form.TextField({ fieldLabel:'采购订单编号', name:'code', width:200 }), new Ext.form.ComboBox({ id:'statusId2', name:'status', readOnly:true, fieldLabel:'订单状态', hiddenName:'status', store: new Ext.data.SimpleStore({ fields:['id', 'name'], data:[[0,'待审'],[1,'审核'],[2,'完成']] }), valueField:'id', displayField:'name', typeAhead:true, mode:'local', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'订单名称', name:'name', width:200 }), supplierName, new Ext.form.TextField({ fieldLabel:'联系人', name:'linkman', width:200 }) ); form.column( {width:320, clear:true}, new Ext.form.DateField({ fieldLabel:'要求供货日期', name:'provideDate', width:200, format:'Y-m-d' }), new Ext.form.DateField({ fieldLabel:'签订日期', name:'orderDate', width:200, format:'Y-m-d' }), new Ext.form.ComboBox({ id:'auditId2', name:'audit', readOnly:true, fieldLabel:'审核受理', hiddenName:'audit', store: new Ext.data.SimpleStore({ fields:['id', 'name'], data:[[0,'立即审核'],[1,'常规审核']] }), valueField:'id', displayField:'name', typeAhead:true, mode:'local', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'订单签订人员', name:'username', width:200 }) ); form.end(); form.fieldset( {id:'insert-grid', legend:'订单详情', hideLabels:true} ); // this.form = form; }, createGrid : function() { // 选择产品的combo var productDataStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2product/pagedQuery.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','name','material','factory','type','price','unit']) }); var productCombo = new Ext.form.ComboBox({ id:'productId2', name:'productName', readOnly:true, fieldLabel:'产品名称', hiddenName:'productName', store:productDataStore, valueField:'id', displayField:'name', typeAhead:true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false, pageSize:10 }); // 列模型 var cm = new Ext.grid.ColumnModel([{ header:"序号", dataIndex:"id", width:40 },{ header:"编号", dataIndex:"code", editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})), width:40 },{ header:"商品名称", dataIndex:"productName", editor:new Ext.grid.GridEditor(productCombo), width:100, renderer:function(value, cellmeta, record, RowIndex, ColumnIndex, store){ try { var productId = productCombo.getValue(); var productRecord = productDataStore.getById(productId); return productRecord.data.name; } catch(e) { return value; } } },{ header:"类别", dataIndex:"productType", width:40, renderer:function(value){ if (value == 0) { return "<span style='color:green;'>染料</span>"; } else if (value == 1) { return "<span style='color:black;'>助剂</span>"; } else if (value == 2) { return "<span style='color:blue;'>设备</span>"; } } },{ header:"型号", dataIndex:"material", width:40 },{ header:"生产厂家", dataIndex:"factory", width:70 },{ header:"技术参数", dataIndex:"parameter", editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})), width:70 },{ header:'数量', dataIndex:'num', editor:new Ext.grid.GridEditor(new Ext.form.NumberField({allowBlank:false})), width:50 },{ header:'计量单位', dataIndex:'unit', width:70, renderer:function(value){ if (value == 0) { return '千克'; } else if (value == 1) { return '克'; } else if (value == 2) { return '升'; } else if (value == 3) { return '毫升'; } else if (value == 4) { return '台'; } }, editor:new Ext.grid.GridEditor(new Ext.form.ComboBox({ id:'unitId', name:'unit', readOnly:true, fieldLabel: '计量单位', hiddenName:'unit', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [['0','千克'],['1','克'],['2','升'],['3','毫升'],['4','台']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true })) },{ header:'单价(元)', dataIndex:'price', editor:new Ext.grid.GridEditor(new Ext.form.NumberField({allowBlank:false})), width:70 },{ header:'金额(元)', dataIndex:'totalPrice', width:70 },{ header:'备注', dataIndex:'descn', editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})), width:70 }]); cm.defaultSortable = true;//排序 // 数据存储器 var ds = new Ext.data.Store({ proxy:new Ext.data.HttpProxy({url:'getBuyOrderInfosByBuyOrder.htm'}), reader:new Ext.data.JsonReader({}, this.RecordBuyOrderInfo), remoteSort:false }); productCombo.on('select', function(){ // 取得产品信息 var productId = productCombo.getValue(); var productRecord = productDataStore.getById(productId); // 取得选中这行的record var cell = grid.getSelectionModel().getSelectedCell(); var record = ds.getAt(cell[0]); record.data.productId = productRecord.data.id; if (productRecord.data.type == 0) { record.data.code = 'RL' + new Date().format("Ymd") + "xxxx"; } else if (productRecord.data.type == 1) { record.data.code = 'ZJ' + new Date().format("Ymd") + "xxxx"; } else if (productRecord.data.type == 2) { record.data.code = 'SB' + new Date().format("Ymd") + "xxxx"; } record.data.productName = productRecord.data.name; record.data.productType = productRecord.data.type; record.data.material = productRecord.data.material; record.data.factory = productRecord.data.factory; record.data.unit = productRecord.data.unit; record.data.price = productRecord.data.price; return false; }); var gridDiv = Ext.get('insert-grid'); gridDiv.createChild({ tag:'div', id:'insert-grid2-container', cn:[{ tag:'div', id:'insert-grid2', style:'border:1px solid #6FA0DF;' },{ tag:'div', style:'margin-top:5px;margin-bottom:5px;', cn:[{ tag:'span', html:'金额合计:' },{ tag:'span', id:'amount1', html:'0' },{ tag:'span', html:'元 (大写) ' },{ tag:'span', id:'amount2', html:'零' }] }] }); /* insertGrid.createChild({ tag:'div', id:'insert-grid2-resize' }); */ var grid = new Ext.grid.EditorGrid('insert-grid2', {ds: ds, cm: cm, enableColLock: false}); ds.on("update", function() { var amount = 0; for(var i = 0, len = ds.getCount(); i < len; i++){ var record = ds.getAt(i); var num = record.data.num; var price = record.data.price; record.data.totalPrice = num * price; amount += record.data.totalPrice; } document.getElementById("amount1").innerHTML = amount; document.getElementById("amount2").innerHTML = convertCurrency(amount); }); /* var rz = new Ext.Resizable('insert-grid2-resize', { wrap:true, minHeight:100, pinned:true, handles:'s' }); rz.on('resize', insertGrid.autoSize, insertGrid); */ grid.render(); // 页头 var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead, [{ text: '添加', handler : function(){ var entity = new EditForm.RecordBuyOrderInfo({ id:-1, code:'', productId:-1, productName:'', productType:'', material:'', parameter:'', factory:'', num:0, unit:'', price:'', totalPrice:'', descn:'' }); grid.stopEditing(); ds.insert(0, entity); grid.startEditing(0, 1); } }, { text: '删除', handler: function() { if(grid.getSelectionModel().hasSelection()) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var cell = grid.getSelectionModel().getSelectedCell(); var record = ds.getAt(cell[0]); var id = record.get("id"); ds.remove(record); if (id != -1) { Ext.Ajax.request({ url : '../erp2buyorderinfo/remove.htm?ids=' + id, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); }, failure : function(){ Ext.MessageBox.alert('提示', '删除失败!'); } }); } } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }]); this.grid = grid; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-11-12 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '采购合同管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'合同编号',sortable:true,dataIndex:'code',width:80}, {header:'合同状态',sortable:true,dataIndex:'status',width:70}, {header:'合同名称',sortable:true,dataIndex:'name',width:80}, {header:'供应商',sortable:true,dataIndex:'supplier',width:60}, {header:'联系人',sortable:true,dataIndex:'linkman',width:60}, {header:'要求供货日期',sortable:true,dataIndex:'provideDate',width:100}, {header:'收货情况',sortable:true,dataIndex:'receipt',width:80}, {header:'签订日期',sortable:true,dataIndex:'contractDate',width:80}, {header:'订单签订人员',sortable:true,dataIndex:'username',width:80} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'code'}, {name:'status'}, {name:'name'}, {name:'supplier',mapping:"erp2Supplier.name"}, {name:'linkman'}, {name:'provideDate'}, {name:'receipt'}, {name:'contractDate'}, {name:'username'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','采购合同管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var code = new Ext.form.TextField({ id:'code', name:'code', fieldLabel: '合同编号', width:100 }); var status = new Ext.form.TextField({ id:'status', name:'status', fieldLabel:'合同状态', width:100 }); var name = new Ext.form.TextField({ id:'name', name:'name', fieldLabel:'合同名称', width:100 }); var contractDate = new Ext.form.DateField({ id:'contractDate', name:'contractDate', format:'Y-m-d', fieldLabel:'签订日期', width:100 }); code.applyTo('code'); status.applyTo('status'); name.applyTo('name'); contractDate.applyTo('contractDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">添加采购合同</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var updateHtml = '<div style="width:100%px;margin:auto;" id="update-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">修改采购合同</h3>' + '<div id="update-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '添加采购合同', insertHtml, true); var insertForm = EditForm.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); var update = new Ext.Button('update-button', { text:'修改', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择修改的记录'); } else if (m.length == 1) { var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('update-tab', '修改采购合同', updateHtml, true); var closeTabDelegate = tabs.removeTab.createDelegate(tabs, ['update-tab']); var updateForm = EditForm.getUpdateForm(closeTabDelegate, m[0].get('id')); tabs.activate('update-tab'); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var remove = new Ext.Button('remove-button', { text:'删除', handler:function() { var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ try { selections[i].get("id"); ids[i] = selections[i].get("id"); dataStore.remove(selections[i]);//从表格中删除 } catch (e) { } } Ext.Ajax.request({ url : 'remove.htm?ids=' + ids, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); //dataStore.reload(); }, failure : function(){Ext.MessageBox.alert('提示', '删除失败!');} }); } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }); dataStore.on('beforeload', function() { dataStore.baseParams = { code : code.getValue(), status : status.getValue(), name : name.getValue(), contractDate : contractDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); EditForm = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ success:function(form, action){ Ext.MessageBox.confirm('提示', '保存添加成功,是否继续添加' , function(btn){ if (btn == 'yes') { form.reset(); } else { closeTagHandler(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ EditForm.form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); return form; }, getUpdateForm : function(closeTagHandler, id) { this.createForm('./insert.htm', 'update-box'); this.id = id; var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ params:{id:EditForm.id}, success:function(form, action){ Ext.MessageBox.confirm('提示', '保存修改成功,是否返回' , function(btn){ if (btn == 'yes') { closeTagHandler(); } else { form.reset(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("update-form"); form.load({url:'./loadData.htm?id=' + id}); return form; }, createForm : function(url, waitMsgTarget) { var form = new Ext.form.Form({ labelAlign:'right', labelWidth:80, url:url, method: 'POST', waitMsgTarget:waitMsgTarget, reader : new Ext.data.JsonReader({}, [ {name:'code'}, {name:'status'}, {name:'name'}, {name:'supplier',mapping:"erp2Supplier.name"}, {name:'linkman'}, {name:'provideDate'}, {name:'receipt'}, {name:'contractDate'}, {name:'username'} ]) }); form.fieldset( {legend:'采购合同信息', hideLabels:false}, new Ext.form.TextField({ fieldLabel:'合同编号', name:'code', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'合同状态', name:'status', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'合同名称', name:'name', width:400, allowBlank:false }), new Ext.form.ComboBox({ id:'supplierNameId2', name:'supplier', readOnly:true, fieldLabel:'供应商', hiddenName:'supplier', store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2supplier/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','name']) }), valueField:'id', displayField:'name', typeAhead:true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:400, allowBlank:false, pageSize:10 }), new Ext.form.TextField({ fieldLabel:'联系人', name:'linkman', width:400, allowBlank:false }), new Ext.form.DateField({ fieldLabel:'要求供货日期', name:'provideDate', format:'Y-m-d', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'收货状态', name:'receipt', width:400, allowBlank:false }), new Ext.form.DateField({ fieldLabel:'签订日期', name:'contractDate', format:'Y-m-d', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'订单签订人员', name:'username', width:400, allowBlank:false }) ); // this.form = form; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '招标投标管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'投标单位名称',sortable:true,dataIndex:'companyName',width:80}, {header:'所投标书编号',sortable:true,dataIndex:'bidCode',width:90}, {header:'竞标价格',sortable:true,dataIndex:'price',width:80}, {header:'投标单位地址',sortable:true,dataIndex:'address',width:80}, {header:'联系电话',sortable:true,dataIndex:'tel',width:100}, {header:'投标日期',sortable:true,dataIndex:'bidDate',width:100}, {header:'电子信箱',sortable:true,dataIndex:'email',width:80}, {header:'详细说明',sortable:true,dataIndex:'descn',width:100,renderer:function(value){ if (value.length > 10) { return value.substring(0, 5) + "..."; } else { return value; } }} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'companyName',mapping:'erp2Supplier.name'}, {name:'bidCode',mapping:"erp2Bid.code"}, {name:'price'}, {name:'address'}, {name:'tel'}, {name:'bidDate'}, {name:'email'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','投标管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var bidStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2bid/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['code']) }); var bidCode = new Ext.form.ComboBox({ id:'bidCodeId', name:'bidCode', readOnly:false, fieldLabel:'标书编号', hiddenName:'bidCode', store:bidStore, valueField:'code', displayField:'code', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); var bidDate = new Ext.form.DateField({ id:'bidDate', name:'bidDate', format:'Y-m-d', fieldLabel:'投标时间' }); bidCode.applyTo('bidCodeId'); bidDate.applyTo('bidDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); bidCode.clearValue(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">欢迎您投标</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '填写投标书', insertHtml, true); var insertForm = EditForm.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); dataStore.on('beforeload', function() { dataStore.baseParams = { bidCode : bidCode.getValue(), bidDate : bidDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); EditForm = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ success:function(form, action){ Ext.MessageBox.confirm('提示', '添加成功,是否继续填写其他投标单' , function(btn){ if (btn == 'yes') { form.reset(); } else { closeTagHandler(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ EditForm.form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); return form; }, createForm : function(url, waitMsgTarget) { var form = new Ext.form.Form({ labelAlign:'right', labelWidth:150, url:url, method: 'POST', waitMsgTarget:waitMsgTarget }); form.fieldset( {legend:'标书单', hideLabels:false}, new Ext.form.ComboBox({ id:'supplierNameId2', name:'supplierName', readOnly:true, fieldLabel:'投标单位名称', hiddenName:'supplierName', store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2supplier/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','name']) }), valueField:'id', displayField:'name', typeAhead:true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:400, allowBlank:false, pageSize:10 }), new Ext.form.ComboBox({ id:'bidCodeId2', name:'bidCode', readOnly:true, fieldLabel:'所投标书编号', hiddenName:'bidCode', store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2bid/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','code']) }), valueField:'id', displayField:'code', typeAhead:true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:400, allowBlank:false, pageSize:10 }), new Ext.form.NumberField({ fieldLabel:'竞标价格', name:'price', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'投标单位地址', name:'address', width:400, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'联系电话', name:'tel', width:400, allowBlank:false }), new Ext.form.DateField({ fieldLabel:'投标日期', name:'bidDate', width:400, format:'Y-m-d', readOnly:true, allowBlank:false }), new Ext.form.TextField({ fieldLabel:'电子邮箱', name:'email', width:400, allowBlank:false }), new Ext.form.TextArea({ fieldLabel:'详细说明', name:'descn', width:400, height:100 }) ); // this.form = form; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '招标投标管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'标书编号',sortable:true,dataIndex:'code',width:80}, {header:'产品名称',sortable:true,dataIndex:'productName',width:70}, {header:'产品数量',sortable:true,dataIndex:'productNum',width:80}, {header:'技术参数',sortable:true,dataIndex:'parameter',width:60}, {header:'投标开始日期',sortable:true,dataIndex:'startDate',width:100}, {header:'投标截止日期',sortable:true,dataIndex:'endDate',width:100}, {header:'开标日期',sortable:true,dataIndex:'openDate',width:80}, {header:'备注',sortable:true,dataIndex:'descn',width:100,renderer:function(value){ if (value.length > 10) { return value.substring(0, 5) + "..."; } else { return value; } }} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'code'}, {name:'productName',mapping:"erp2Product.name"}, {name:'productNum'}, {name:'parameter'}, {name:'startDate'}, {name:'endDate'}, {name:'openDate'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','招标管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var code = new Ext.form.TextField({ id:'code', name:'code', fieldLabel: '标书编号' }); var productStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2product/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['name']) }); var productName = new Ext.form.ComboBox({ id:'productNameId', name:'productName', readOnly:false, fieldLabel: '产品名称', hiddenName:'productName', store: productStore, valueField:'name', displayField:'name', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); var startDate = new Ext.form.DateField({ id:'startDate', name:'startDate', format:'Y-m-d', fieldLabel:'招标开始时间' }); code.applyTo('code'); productName.applyTo('productNameId'); startDate.applyTo('startDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); productName.clearValue(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">添加标书</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var updateHtml = '<div style="width:100%px;margin:auto;" id="update-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">修改标书</h3>' + '<div id="update-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '添加标书', insertHtml, true); var insertForm = Bid.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); var update = new Ext.Button('update-button', { text:'修改', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择修改的记录'); } else if (m.length == 1) { var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('update-tab', '修改标书', updateHtml, true); var closeTabDelegate = tabs.removeTab.createDelegate(tabs, ['update-tab']); var updateForm = Bid.getUpdateForm(closeTabDelegate, m[0].get('id')); tabs.activate('update-tab'); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var remove = new Ext.Button('remove-button', { text:'删除', handler:function() { var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ try { selections[i].get("id"); ids[i] = selections[i].get("id"); dataStore.remove(selections[i]);//从表格中删除 } catch (e) { } } Ext.Ajax.request({ url : 'remove.htm?ids=' + ids, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); //dataStore.reload(); }, failure : function(){Ext.MessageBox.alert('提示', '删除失败!');} }); } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }); dataStore.on('beforeload', function() { dataStore.baseParams = { code : code.getValue(), productName : productName.getRawValue(), startDate : startDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); Bid = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ success:function(form, action){ Ext.MessageBox.confirm('提示', '保存添加成功,是否继续添加' , function(btn){ if (btn == 'yes') { form.reset(); } else { closeTagHandler(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ Bid.form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); return form; }, getUpdateForm : function(closeTagHandler, id) { this.createForm('./insert.htm', 'update-box'); this.id = id; var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ params:{id:Bid.id}, success:function(form, action){ Ext.MessageBox.confirm('提示', '保存修改成功,是否返回' , function(btn){ if (btn == 'yes') { closeTagHandler(); } else { form.reset(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("update-form"); form.load({url:'./loadData.htm?id=' + id}); // 初始化地区的省市县信息 Ext.lib.Ajax.request( 'GET', './loadData.htm?id=' + this.id, {success:function(response){ var entity = Ext.decode(response.responseText); var productId = entity[0].erp2Product.id; var productName = entity[0].erp2Product.name; form.findField('product').setValue(productId); form.findField('productId2').setRawValue(productName); },failure:function(){}} ); return form; }, createForm : function(url, waitMsgTarget) { var form = new Ext.form.Form({ labelAlign:'right', labelWidth:80, url:url, method: 'POST', waitMsgTarget:waitMsgTarget, reader : new Ext.data.JsonReader({}, [ {name:'code'}, {name:'productNum'}, {name:'parameter'}, {name:'startDate'}, {name:'endDate'}, {name:'openDate'}, {name:'fax'}, {name:'descn'} ]) }); form.fieldset( {legend:'标书信息', hideLabels:false} ); form.column( {width:300}, new Ext.form.TextField({ fieldLabel:'标书编号', name:'code', width:200, allowBlank:false }), new Ext.form.TextField({ fieldLabel: '技术参数', name: 'parameter', width:200, allowBlank:false }), new Ext.form.DateField({ fieldLabel: '投标开始时间', name: 'startDate', format:'Y-m-d', width:200, allowBlank:false }), new Ext.form.DateField({ fieldLabel: '投标截止时间', name: 'endDate', format:'Y-m-d', width:200, allowBlank:false }), new Ext.form.DateField({ fieldLabel: '开标时间', name: 'openDate', format:'Y-m-d', width:200, allowBlank:false }) ); form.column( {width:300}, new Ext.form.ComboBox({ id:'productId2', name:'product', readOnly:true, fieldLabel:'产品名称', hiddenName:'product', store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2product/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','name']) }), valueField:'id', displayField:'name', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false, pageSize:10 }), new Ext.form.NumberField({ fieldLabel: '产品数量', name: 'productNum', width:200, allowBlank:false }), new Ext.form.TextArea({ fieldLabel:'备注', name:'descn', width:200, height:80 }) ); // this.form = form; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '招标投标管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'投标单位名称',sortable:true,dataIndex:'companyName',width:80}, {header:'所投标书编号',sortable:true,dataIndex:'bidCode',width:90}, {header:'竞标价格',sortable:true,dataIndex:'price',width:80}, {header:'投标单位地址',sortable:true,dataIndex:'address',width:80}, {header:'联系电话',sortable:true,dataIndex:'tel',width:100}, {header:'投标日期',sortable:true,dataIndex:'bidDate',width:100}, {header:'电子信箱',sortable:true,dataIndex:'email',width:80}, {header:'详细说明',sortable:true,dataIndex:'descn',width:100,renderer:function(value){ if (value.length > 10) { return value.substring(0, 5) + "..."; } else { return value; } }} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'companyName',mapping:'erp2Supplier.name'}, {name:'bidCode',mapping:"erp2Bid.code"}, {name:'price'}, {name:'address'}, {name:'tel'}, {name:'bidDate'}, {name:'email'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQueryForStat.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','投标管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var bidStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2bid/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['code']) }); var bidCode = new Ext.form.ComboBox({ id:'bidCodeId', name:'bidCode', readOnly:false, fieldLabel:'标书编号', hiddenName:'bidCode', store:bidStore, valueField:'code', displayField:'code', typeAhead: true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); var supplierStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2supplier/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['name']) }); var supplierName = new Ext.form.ComboBox({ id:'supplierNameId', name:'supplierName', readOnly:false, fieldLabel:'投标单位名称', hiddenName:'supplierName', store:supplierStore, valueField:'name', displayField:'name', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); var bidDate = new Ext.form.DateField({ id:'bidDate', name:'bidDate', format:'Y-m-d', fieldLabel:'投标时间' }); bidCode.applyTo('bidCodeId'); supplierName.applyTo('supplierNameId'); bidDate.applyTo('bidDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); bidCode.clearValue(); } }); dataStore.on('beforeload', function() { dataStore.baseParams = { bidCode : bidCode.getValue(), supplierName : supplierName.getRawValue(), bidDate : bidDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '招标投标管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'公示结果日期',sortable:true,dataIndex:'publishDate',width:80}, {header:'标书编号',sortable:true,dataIndex:'bidCode',width:90}, {header:'中标单位',sortable:true,dataIndex:'supplierName',width:80}, {header:'招标内容',sortable:true,dataIndex:'bidContent',width:80}, {header:'中标成交金额',sortable:true,dataIndex:'price',width:150}, {header:'中标、成交项目主要内容',sortable:true,dataIndex:'descn',width:200,renderer:function(value){ if (value.length > 10) { return value.substring(0, 5) + "..."; } else { return value; } }} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'publishDate'}, {name:'bidCode',mapping:"erp2InviteBid.erp2Bid.code"}, {name:'supplierName',mapping:'erp2InviteBid.erp2Supplier.name'}, {name:'bidContent'}, {name:'price'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','中标结果'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var bidStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2bid/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['code']) }); var bidCode = new Ext.form.ComboBox({ id:'bidCodeId', name:'bidCode', readOnly:false, fieldLabel:'标书编号', hiddenName:'bidCode', store:bidStore, valueField:'code', displayField:'code', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); var bidContent = new Ext.form.TextField({ id:'bidContent', name:'bidContent', fieldLabel:'招标内容' }); var publishDate = new Ext.form.DateField({ id:'publishDate', name:'publishDate', format:'Y-m-d', fieldLabel:'公示结果日期' }); bidCode.applyTo('bidCodeId'); bidContent.applyTo('bidContent'); publishDate.applyTo('publishDate'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">添加中标结果</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var updateHtml = '<div style="width:100%px;margin:auto;" id="update-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">修改中标结果</h3>' + '<div id="update-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '填写中标结果', insertHtml, true); var insertForm = EditForm.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); var update = new Ext.Button('update-button', { text:'修改', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择修改的记录'); } else if (m.length == 1) { var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('update-tab', '修改中标结果', updateHtml, true); var closeTabDelegate = tabs.removeTab.createDelegate(tabs, ['update-tab']); var updateForm = EditForm.getUpdateForm(closeTabDelegate, m[0].get('id')); tabs.activate('update-tab'); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var remove = new Ext.Button('remove-button', { text:'删除', handler:function() { var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ try { selections[i].get("id"); ids[i] = selections[i].get("id"); dataStore.remove(selections[i]);//从表格中删除 } catch (e) { } } Ext.Ajax.request({ url : 'remove.htm?ids=' + ids, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); //dataStore.reload(); }, failure : function(){Ext.MessageBox.alert('提示', '删除失败!');} }); } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }); dataStore.on('beforeload', function() { dataStore.baseParams = { bidCode : bidCode.getValue(), bidContent : bidContent.getValue(), publishDate : publishDate.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); EditForm = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ success:function(form, action){ Ext.MessageBox.confirm('提示', '添加成功,是否继续填写其他投标单' , function(btn){ if (btn == 'yes') { form.reset(); } else { closeTagHandler(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ EditForm.form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); return form; }, getUpdateForm : function(closeTagHandler, id) { this.createForm('./insert.htm', 'update-box'); var form = this.form; this.id = id; form.addButton({ text:'提交', handler:function(){ if (form.isValid()) { form.submit({ params:{id:EditForm.id}, success:function(form, action){ Ext.MessageBox.confirm('提示', '修改成功,是否返回' , function(btn){ if (btn == 'yes') { closeTagHandler(); } else { form.reset(); } }); } ,failure:function(form, action){ Ext.suggest.msg('错误', action.result.response); } ,waitMsg:'提交中...' }); } } }); form.addButton({ text:'重置', handler:function(){ EditForm.form.reset(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("update-form"); form.load({url:'./loadData.htm?id=' + id}); // 初始化级联的信息 Ext.lib.Ajax.request( 'GET', './loadData.htm?id=' + this.id, {success:function(response){ var entity = Ext.decode(response.responseText); var inviteBid = entity[0].erp2InviteBid; var bidId = inviteBid.erp2Bid.id; var bidCode = inviteBid.erp2Bid.code; var inviteBidId = inviteBid.id; var supplierName = inviteBid.erp2Supplier.name; form.findField('bidCode').setValue(bidId); form.findField('bidCodeId2').setRawValue(bidCode); form.findField('supplierName').setValue(inviteBidId); form.findField('supplierNameId2').setRawValue(supplierName); },failure:function(){}} ); return form; }, createForm : function(url, waitMsgTarget) { var form = new Ext.form.Form({ labelAlign:'right', labelWidth:150, url:url, method: 'POST', waitMsgTarget:waitMsgTarget, reader : new Ext.data.JsonReader({}, [ {name:'publishDate'}, {name:'bidContent'}, {name:'price'}, {name:'descn'} ]) }); var publishDate = new Ext.form.DateField({ id:'publishDate', name:'publishDate', readOnly:true, fieldLabel:'公示结果日期', format:'Y-m-d', width:400 }); var bidCode = new Ext.form.ComboBox({ id:'bidCodeId2', name:'bidCode', readOnly:true, fieldLabel:'所投标书编号', hiddenName:'bidCode', store: new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2bid/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id','code']) }), valueField:'id', displayField:'code', typeAhead:true, mode:'remote', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:400, allowBlank:false, pageSize:10 }); var supplierDataStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2invitebid/pagedQueryByBidId.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['id',{name:'name',mapping:'erp2Supplier.name'}]) }); var supplierName = new Ext.form.ComboBox({ id:'supplierNameId2', name:'supplierName', readOnly:true, fieldLabel:'中标单位名称', hiddenName:'supplierName', store: supplierDataStore, valueField:'id', displayField:'name', typeAhead:true, mode:'local', triggerAction:'all', emptyText:'请选择', selectOnFocus:true, width:400, allowBlank:false, pageSize:10 }); bidCode.on('select', function() { bidId = bidCode.getValue(); supplierName.clearValue(); supplierDataStore.load({ params:{bidCode:bidId} }); }); var bidContent = new Ext.form.TextField({ fieldLabel:'招标内容', name:'bidContent', width:400, allowBlank:false }); var price = new Ext.form.NumberField({ fieldLabel:'中标成交金额(元)', name:'price', width:400 }); var descn = new Ext.form.TextArea({ fieldLabel:'中标、成交项目主要内容', name:'descn', width:400, height:100 }); form.fieldset( {legend:'中标结果', hideLabels:false}, publishDate, bidCode, supplierName, bidContent, price, descn ); // this.form = form; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '基础信息管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'供应商名称',sortable:true,dataIndex:'name',width:80}, {header:'类别',sortable:true,dataIndex:'type',width:70,renderer:function(value){ if (value == 0) { return "<span style='color:green;'>染料供应商</span>"; } else if (value == 1) { return "<span style='color:black;'>助剂供应商</span>"; } else if (value == 2) { return "<span style='color:blue;'>设备供应商</span>"; } else if (value == 3) { return "<span style='color:red;'>综合供应商</span>"; } }}, {header:'所在地',sortable:true,dataIndex:'area',width:80}, {header:'联系人',sortable:true,dataIndex:'linkman',width:60}, {header:'电话',sortable:true,dataIndex:'tel',width:60}, {header:'传真',sortable:true,dataIndex:'fax',width:60}, {header:'地址',sortable:true,dataIndex:'address',width:60}, {header:'邮编',sortable:true,dataIndex:'zip',width:80}, {header:'E-mail',sortable:true,dataIndex:'email',width:80}, {header:'信用等级',sortable:true,dataIndex:'rank',width:60,renderer:function(value){ if (value == 0) { return "<span style='color:green;'>优秀</span>"; } else if (value == 1) { return "<span style='color:black;'>良好</span>"; } else if (value == 2) { return "<span style='color:blue;'>一般</span>"; } else if (value == 3) { return "<span style='color:red;'>差</span>"; } }} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'name'}, {name:'type'}, {name:'area'}, {name:'linkman'}, {name:'tel'}, {name:'fax'}, {name:'address'}, {name:'zip'}, {name:'email'}, {name:'rank'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','供应商列表'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var name = new Ext.form.TextField({ id:'name', name:'name', fieldLabel: '供应商名称' }); var type = new Ext.form.ComboBox({ id:'typeId', name:'type', readOnly:true, fieldLabel: '类别', hiddenName:'type', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [[0,'染料供应商'],[1,'助剂供应商'],[2,'设备供应商'],[3,'综合供应商']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false }); var linkman = new Ext.form.TextField({ id:'linkman', name:'linkman', fieldLabel:'联系人', width:100 }); var no = new Ext.form.NumberField({ id:'no', name:'no', fieldLabel:'序号', width:60 }); name.applyTo('name'); type.applyTo('typeId'); linkman.applyTo('linkman'); no.applyTo('no'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); type.setValue(''); type.setRawValue('请选择'); type.clearValue(); } }); var insertHtml = '<div style="width:100%px;margin:auto;" id="insert-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">添加供应商</h3>' + '<div id="insert-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var updateHtml = '<div style="width:100%px;margin:auto;" id="update-box">' + '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>' + '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">' + '<h3 style="text-align:left;">修改供应商</h3>' + '<div id="update-form"></div>' + '</div></div></div>' + '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>' + '</div>' + '<div class="x-form-clear"></div>'; var view = new Ext.Button('view-button', { text:'查看', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择查看的记录'); } else if (m.length == 1) { window.open('./view.htm?id=' + m[0].get('id')); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var insert = new Ext.Button('insert-button', { text:'添加', handler:function(){ //layout.getRegion("center").showPanel("tab1"); var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('insert-tab', '添加供应商', insertHtml, true); var insertForm = Supplier.getInsertForm(tabs.removeTab.createDelegate(tabs, ['insert-tab'])); tabs.activate('insert-tab'); } }); var update = new Ext.Button('update-button', { text:'修改', handler:function(){ var m = grid.getSelections(); if(m.length == 0) { Ext.MessageBox.alert('提示', '请选择修改的记录'); } else if (m.length == 1) { var tabs = layout.getRegion("center").tabs; tabs.removeTab('insert-tab'); tabs.removeTab('update-tab'); var tab = tabs.addTab('update-tab', '修改供应商', updateHtml, true); var closeTabDelegate = tabs.removeTab.createDelegate(tabs, ['update-tab']); var updateForm = Supplier.getUpdateForm(closeTabDelegate, m[0].get('id')); tabs.activate('update-tab'); } else { Ext.MessageBox.alert('提示', '每次只能选择一条记录'); } } }); var remove = new Ext.Button('remove-button', { text:'删除', handler:function() { var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var selections = grid.getSelections(); var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ try { selections[i].get("id"); ids[i] = selections[i].get("id"); dataStore.remove(selections[i]);//从表格中删除 } catch (e) { } } Ext.Ajax.request({ url : 'remove.htm?ids=' + ids, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); //dataStore.reload(); }, failure : function(){Ext.MessageBox.alert('提示', '删除失败!');} }); } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }); dataStore.on('beforeload', function() { dataStore.baseParams = { name : name.getValue(), type : type.getValue(), linkman : linkman.getValue(), no : no.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); }); Supplier = { getInsertForm : function(closeTagHandler) { this.createForm('./insert.htm', 'insert-box'); var form = this.form; form.addButton({ text:'提交', handler:function(){ if (!form.isValid()) { return; } form.el.mask('提交数据,请稍候...', 'x-mask-loading'); var hide = function() { form.el.unmask(); }; var supplierValue = Supplier.form.getValues(); Supplier.grid.stopEditing(); var productValues = new Array(); var ds = Supplier.grid.dataSource; for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); var item = {}; item.id = record.data.id; item.name = record.data.name; item.type = record.data.type; item.material = record.data.material; item.factory = record.data.factory; item.price = record.data.price; item.unit = record.data.unit; productValues.push(item); } var json = {supplierValue:supplierValue,products:productValues} Ext.lib.Ajax.request( 'POST', './insert.htm', {success:function(){ form.el.unmask(); Ext.MessageBox.confirm('提示', '保存添加成功,是否继续添加' , function(btn){ if (btn == 'yes') { form.reset(); form.findField("typeId2").clearValue(""); form.findField("rankId").clearValue(""); Supplier.grid.dataSource.removeAll(); } else { closeTagHandler(); } }); },failure:function(){ form.el.unmask(); }}, 'data=' + encodeURIComponent(Ext.encode(json)) ); } }); form.addButton({ text:'重置', handler:function(){ Supplier.form.reset(); form.findField("typeId2").clearValue(""); form.findField("rankId").clearValue(""); Supplier.grid.dataSource.removeAll(); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("insert-form"); this.createGrid(); var grid = this.grid; return form; }, getUpdateForm : function(closeTagHandler, id) { this.createForm('./update.htm', 'update-box'); this.id = id; var form = this.form; form.load({url:'./loadData.htm?id=' + id}); // 初始化地区的省市县信息 Ext.lib.Ajax.request( 'GET', './getRegion.htm?id=' + this.id, {success:function(response){ var region = Ext.decode(response.responseText); Supplier.form.findField("town").setValue(region.id); Supplier.form.findField("townId").setRawValue(region.name); Supplier.form.findField("city").setValue(region.parent.id); Supplier.form.findField("cityId").setRawValue(region.parent.name); Supplier.form.findField("province").setValue(region.parent.parent.id); Supplier.form.findField("provinceId").setRawValue(region.parent.parent.name); },failure:function(){}} ); form.addButton({ text:'提交', handler:function(){ if (!form.isValid()) { return; } form.el.mask('提交数据,请稍候...', 'x-mask-loading'); var hide = function() { form.el.unmask(); }; var supplierValue = Supplier.form.getValues(); supplierValue.id = Supplier.id; Supplier.grid.stopEditing(); var productValues = new Array(); var ds = Supplier.grid.dataSource; for (var i = 0; i < ds.getCount(); i++) { var record = ds.getAt(i); var item = {}; item.id = record.data.id; item.name = record.data.name; item.type = record.data.type; item.material = record.data.material; item.factory = record.data.factory; item.price = record.data.price; item.unit = record.data.unit; productValues.push(item); } var json = {supplierValue:supplierValue,products:productValues} Ext.lib.Ajax.request( 'POST', './update.htm', {success:function(){ form.el.unmask(); Ext.MessageBox.confirm('提示', '修改成功,是否返回' , function(btn){ if (btn == 'yes') { closeTagHandler(); } else { form.reset(); Supplier.grid.dataSource.load({params:{id:Supplier.id}}); } }); },failure:function(){ form.el.unmask(); }}, 'data=' + encodeURIComponent(Ext.encode(json)) ); } }); form.addButton({ text:'重置', handler:function(){ form.load({url:'./loadData.htm?id=' + this.id}); } }); form.addButton({ text:'取消', handler:closeTagHandler }); form.render("update-form"); this.createGrid(); var grid = this.grid; grid.dataSource.load({params:{id:id}}); return form; }, createForm : function(url, waitMsgTarget) { var form = new Ext.form.Form({ labelAlign:'right', labelWidth:80, url:url, method: 'POST', waitMsgTarget:waitMsgTarget, reader : new Ext.data.JsonReader({}, [ {name:'name'}, {name:'code'}, {name:'homepage'}, {name:'type'}, {name:'area'}, {name:'linkman'}, {name:'lead'}, {name:'tel'}, {name:'fax'}, {name:'address'}, {name:'zip'}, {name:'email'}, {name:'rank'}, {name:'descn'} ]) }); form.fieldset( {legend:'供应商信息', hideLabels:false} ); form.column( {width:320}, new Ext.form.TextField({ fieldLabel: '供应商名称', name: 'name', width:200 }), new Ext.form.ComboBox({ id:'typeId2', name:'type', readOnly:true, fieldLabel:'类别', hiddenName:'type', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [[0,'染料供应商'],[1,'助剂供应商'],[2,'设备供应商'],[3,'综合供应商']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false }), new Ext.form.TextField({ fieldLabel: '联系人', name: 'linkman', width:200 }), new Ext.form.TextField({ fieldLabel: '负责人', name: 'lead', width:200 }), new Ext.form.TextField({ fieldLabel: '电话', name: 'tel', width:200 }), new Ext.form.ComboBox({ id:'rankId', name:'rank', readOnly:true, fieldLabel: '信用等级', hiddenName:'rank', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [[0,'优秀'],[1,'良好'],[2,'一般'],[3,'差']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:200, allowBlank:false }) ); form.column( {width:320, clear:true}, new Ext.form.TextField({ fieldLabel: '供应商编号', name: 'code', width:200 }), new Ext.form.TextField({ fieldLabel: '邮编', name: 'zip', width:200 }), new Ext.form.TextField({ fieldLabel: '传真', name: 'fax', width:200 }), new Ext.form.TextField({ fieldLabel: 'Email', name: 'email', width:200 }), new Ext.form.TextField({ fieldLabel: '主页', name: 'homepage', width:200 }), new Ext.form.TextField({ fieldLabel: '地址', name: 'address', width:200 }) ); // 省市县三级级联 var regionRecord = Ext.data.Record.create([ {name: 'id'}, {name: 'name'} ]); var provinceStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../region/getChildren.htm'}), reader: new Ext.data.JsonReader({},regionRecord) }); var cityStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../region/getChildren.htm'}), reader: new Ext.data.JsonReader({},regionRecord) }); var townStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../region/getChildren.htm'}), reader: new Ext.data.JsonReader({},regionRecord) }); var province = new Ext.form.ComboBox({ id:'provinceId', name:'province', fieldLabel: '省', hiddenName:'province', store: provinceStore, valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:100, readOnly:true, allowBlank:false }); var city = new Ext.form.ComboBox({ id:'cityId', name:'city', fieldLabel: '市', hiddenName:'city', store: cityStore, valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:100, readOnly:true, allowBlank:false }); var town = new Ext.form.ComboBox({ id:'townId', name:'town', fieldLabel: '县', hiddenName:'town', store: townStore, valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, width:100, readOnly:true, allowBlank:true }); provinceStore.load(); //cityStore.load(); //townStore.load(); province.on('select',function() { provinceId = province.getValue(); cityStore.load({ params:{node:provinceId} }); }); city.on('select',function() { cityId = city.getValue(); townStore.load({ params:{node:cityId} }); }); form.column({width:210, labelWidth:80}, province); form.column({width:210, labelWidth:80}, city); form.column({width:210, labelWidth:80, clear:true}, town); form.column({width:640, clear:true}, new Ext.form.TextField({ id:'descn', name:'descn', fieldLabel:'备注', width:520, height:60 }) ); form.end(); form.fieldset( {id:'insert-grid', legend:'供应商品', hideLabels:true} ); // this.form = form; }, createGrid : function() { // 列模型 var cm = new Ext.grid.ColumnModel([{ header:"序号", dataIndex:"id" },{ header:"品名", dataIndex:"name", editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})) },{ header:"类别", dataIndex:"type", renderer:function(value){ if (value == 0) { return '染料'; } else if (value == 1) { return '助剂'; } else if (value == 2) { return '设备'; } }, editor:new Ext.grid.GridEditor(new Ext.form.ComboBox({ id:'typeId3', name:'type2', readOnly:true, fieldLabel: '类别', hiddenName:'type2', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [['0','染料'],['1','助剂'],['2','设备']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true })) },{ header:"型号", dataIndex:"material", editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})) },{ header:"生产厂家", dataIndex:"factory", editor:new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank:false})) },{ header:"单价", dataIndex:"price", editor:new Ext.grid.GridEditor(new Ext.form.NumberField({allowBlank:false})) },{ header:"计量单位", dataIndex:"unit", renderer:function(value){ if (value == 0) { return '千克'; } else if (value == 1) { return '克'; } else if (value == 2) { return '升'; } else if (value == 3) { return '毫升'; } else if (value == 4) { return '台'; } }, editor:new Ext.grid.GridEditor(new Ext.form.ComboBox({ id:'unitId', name:'unit', readOnly:true, fieldLabel: '计量单位', hiddenName:'unit', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [['0','千克'],['1','克'],['2','升'],['3','毫升'],['4','台']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true })) }]); cm.defaultSortable = true;//排序 // 数据模型 var RecordProduct = Ext.data.Record.create([ {name: "id"}, {name: "name"}, {name: "type"}, {name: "material"}, {name: "factory"}, {name: "price"}, {name: "unit"} ]); // 数据存储器 var ds = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'getProductsBySupplier.htm'}), reader: new Ext.data.JsonReader({}, RecordProduct), remoteSort: false }); var gridDiv = Ext.get('insert-grid'); gridDiv.createChild({ tag:'div', id:'insert-grid2', style:'border:1px solid #6FA0DF;' }); /* insertGrid.createChild({ tag:'div', id:'insert-grid2-resize' }); */ var grid = new Ext.grid.EditorGrid('insert-grid2', {ds: ds, cm: cm, enableColLock: false}); /* var rz = new Ext.Resizable('insert-grid2-resize', { wrap:true, minHeight:100, pinned:true, handles:'s' }); rz.on('resize', insertGrid.autoSize, insertGrid); */ grid.render(); // 页头 var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead, [{ text: '添加', handler : function(){ var entity = new RecordProduct({ id:-1, name:'', type:0, material:'', factory:'', price:0, unit:0 }); grid.stopEditing(); ds.insert(0, entity); grid.startEditing(0, 1); } }, { text: '删除', handler: function() { if(grid.getSelectionModel().hasSelection()) { Ext.MessageBox.confirm('提示', '是否确定删除' , function(btn){ if(btn == 'yes') { var cell = grid.getSelectionModel().getSelectedCell(); var record = ds.getAt(cell[0]); var id = record.get("id"); ds.remove(record); if (id != -1) { Ext.Ajax.request({ url : '../erp2product/remove.htm?ids=' + id, success : function() { Ext.MessageBox.alert('提示', '删除成功!'); }, failure : function(){ Ext.MessageBox.alert('提示', '删除失败!'); } }); } } }); } else { Ext.MessageBox.alert('警告', '至少要选择一条记录'); } } }]); this.grid = grid; } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-10-02 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : false, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '基础信息管理', toolbar : null, closable : false, fitToFrame : true })); /* layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); */ layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 表格的列模型 var columnModel = new Ext.grid.ColumnModel([ {header:'序号',sortable:true,dataIndex:'id',width:40}, {header:'品名',sortable:true,dataIndex:'name',width:80}, {header:'类别',sortable:true,dataIndex:'type',width:70,renderer:function(value){ if (value == 0) { return "<span style='color:green;'>染料</span>"; } else if (value == 1) { return "<span style='color:black;'>助剂</span>"; } else if (value == 2) { return "<span style='color:blue;'>设备</span>"; } }}, {header:'型号',sortable:true,dataIndex:'material',width:80}, {header:'供应商',sortable:true,dataIndex:'supplier',width:60}, {header:'生产厂家',sortable:true,dataIndex:'factory',width:60}, {header:'数量',sortable:true,dataIndex:'num',width:60}, {header:'计量单位',sortable:true,dataIndex:'unit',width:60,renderer:function(value){ if (value == 0) { return '千克'; } else if (value == 1) { return '克'; } else if (value == 2) { return '升'; } else if (value == 3) { return '毫升'; } else if (value == 4) { return '台'; } }}, {header:'单价',sortable:true,dataIndex:'price',width:100}, {header:'总额',sortable:true,dataIndex:'sum',width:100} ]); columnModel.defaultSortable = false; // 创建数据模型 var dataRecord = Ext.data.Record.create([ {name:'id'}, {name:'name'}, {name:'type'}, {name:'material'}, {name:'supplier',mapping:"erp2Supplier.name"}, {name:'factory'}, {name:'num'}, {name:'unit'}, {name:'price'}, {name:'sum'}, {name:'descn'} ]); // 创建数据存储 var dataStore = new Ext.lingo.Store({ proxy : new Ext.data.HttpProxy({url:'pagedQuery.htm'}), reader : new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" }, dataRecord), remoteSort : true }); var grid = new Ext.lingo.CheckRowSelectionGrid('main-grid', { ds : dataStore , cm : columnModel , selModel : new Ext.lingo.CheckRowSelectionModel({useHistory:false}) , enableColLock : false , loadMask : true }); //grid.on('rowdblclick', this.edit, this); //右键菜单 //grid.addListener('rowcontextmenu', this.contextmenu, this); // 渲染表格 grid.render(); // 页头 var gridHeader = grid.getView().getHeaderPanel(true); var toolbar = new Ext.Toolbar(gridHeader); toolbar.add('-','库存信息管理'); // 页脚 var gridFooter = grid.getView().getFooterPanel(true); // 把分页工具条,放在页脚 var paging = new Ext.PagingToolbar(gridFooter, dataStore, { pageSize : 15 , displayInfo : true , displayMsg : '显示: {0} - {1} 共 {2} 条记录' , emptyMsg : "没有找到相关数据" , beforePageText : "第" , afterPageText : "页,共{0}页" }); var pageSizePlugin = new Ext.ux.PageSizePlugin(); pageSizePlugin.init(paging); // 查询 var name = new Ext.form.TextField({ id:'name', name:'name', fieldLabel: '品名' }); var type = new Ext.form.ComboBox({ id:'typeId', name:'type', readOnly:true, fieldLabel: '类别', hiddenName:'type', store: new Ext.data.SimpleStore({ fields: ['id', 'name'], data : [[0,'染料'],[1,'助剂'],[2,'设备']] }), valueField:'id', displayField:'name', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false }); var supplierStore = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'../erp2supplier/pagedQueryForCombo.htm'}), reader: new Ext.data.JsonReader({ root : "result", totalProperty : "totalCount", id : "id" },['name']) }); var supplier = new Ext.form.ComboBox({ id:'supplierId', name:'supplier', readOnly:false, fieldLabel: '供应商', hiddenName:'supplier', store: supplierStore, valueField:'name', displayField:'name', typeAhead: true, mode: 'remote', triggerAction: 'all', emptyText:'请选择', selectOnFocus:true, hideClearButton: false, hideTrigger: false, resizable:false, pageSize:10 }); //supplierStore.load({params:{limit:100}}); var no = new Ext.form.NumberField({ id:'no', name:'no', fieldLabel:'序号', width:60 }); name.applyTo('name'); type.applyTo('typeId'); supplier.applyTo('supplierId'); no.applyTo('no'); var search = new Ext.Button('search-button', { text:'查询', handler:function() { dataStore.reload(); type.setValue(''); type.setRawValue('请选择'); type.clearValue(); } }); dataStore.on('beforeload', function() { dataStore.baseParams = { name : name.getValue(), type : type.getValue(), supplier : supplier.getRawValue(), no : no.getValue() }; }); dataStore.load({ params:{start:0, limit:paging.pageSize} }); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-06 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 打开提示功能 Ext.QuickTips.init(); // ==================================================== // 开始构造树形 // ==================================================== var treeloader = new Ext.tree.TreeLoader({dataUrl:'getAllTree.htm'}); var tree = new Ext.tree.TreePanel('main', { animate:false, containerScroll: true, enableDD:true, lines: true, loader: treeloader }); // 不使用自动排序 //new Ext.tree.TreeSorter(tree, {folderSort:true}); tree.el.addKeyListener(Ext.EventObject.DELETE, removeNode); // ==================================================== // 工具栏 // ==================================================== var tb = new Ext.Toolbar(tree.el.createChild({tag:'div'})); tb.add({ text: '新增子分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '添加选中节点的下级分类', handler: createChild }, { text: '新增兄弟分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '添加选中节点的同级分类', handler: createBrother }, { text: '修改分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '修改选中分类', handler: updateNode }, { text: '删除分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'删除一个分类', handler:removeNode }, '-', { text: '排序', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'保存排序结果', handler:save }, '-', { text: '展开', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'展开所有分类', handler:expandAll }, { text: '关闭', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'关闭所有分类', handler:collapseAll }, { text: '刷新', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'刷新所有节点', handler:refresh }); // ==================================================== // 工具栏操作函数 // ==================================================== function createChild() { var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if (!n) { n = tree.getRootNode(); } else { n.expand(false, false); } createNode(n); } function createBrother() { var n = tree.getSelectionModel().getSelectedNode(); if (!n) { Ext.Msg.alert('提示', "请选择一个节点"); } else if (n == tree.getRootNode()) { Ext.Msg.alert('提示', "不能为根节点增加兄弟节点"); } else { createNode(n.parentNode); } } function createNode(n) { var node = n.appendChild(new Ext.tree.TreeNode({ id:-1, text:'请输入分类名', cls:'album-node', allowDrag:true, allowDelete:true, allowEdit:true, allowChildren:true })); tree.getSelectionModel().select(node); setTimeout(function(){ ge.editNode = node; ge.startEdit(node.ui.textNode); }, 10); } function updateNode() { var n = tree.getSelectionModel().getSelectedNode(); if (!n) { Ext.Msg.alert('提示', "请选择一个节点"); } else if (n == tree.getRootNode()) { Ext.Msg.alert('提示', "不能为根节点增加兄弟节点"); } else { setTimeout(function(){ ge.editNode = n; ge.startEdit(n.ui.textNode); }, 10); } } function removeNode() { var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if(n && n.attributes.allowDelete){ tree.getSelectionModel().selectPrevious(); tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); Ext.lib.Ajax.request( 'POST', 'removeTree.htm', {success:hide,failure:hide}, 'id='+n.id ); n.parentNode.removeChild(n); } } function appendNode(node, array) { if (!node || node.childNodes.length < 1) { return; } for (var i = 0; i < node.childNodes.length; i++) { var child = node.childNodes[i]; array.push({id:child.id,parentId:child.parentNode.id}); appendNode(child, array); } } function save() { // 向数据库发送一个json数组,保存排序信息 tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); var ch = []; appendNode(root, ch); Ext.lib.Ajax.request( 'POST', 'sortTree.htm', {success:hide,failure:hide}, 'data='+encodeURIComponent(Ext.encode(ch)) ); } function collapseAll(){ ctxMenu.hide(); setTimeout(function(){ root.eachChild(function(n){ n.collapse(true, false); }); }, 10); } function expandAll(){ ctxMenu.hide(); setTimeout(function(){ root.eachChild(function(n){ n.expand(false, false); }); }, 10); } function refresh() { tree.root.reload(); tree.root.expand(true, false); } // ==================================================== // 树节点的即时编辑器 // ==================================================== var ge = new Ext.tree.TreeEditor(tree, { allowBlank:false, blankText:'请添写名称', selectOnFocus:true }); ge.on('beforestartedit', function(){ var node = ge.editNode; if(!node.attributes.allowEdit){ return false; } else { node.attributes.oldText = node.text; } }); ge.on('complete', function() { var node = ge.editNode; // 如果节点没有改变,就向服务器发送修改信息 if (node.attributes.oldText == node.text) { node.attributes.oldText = null; return true; } var item = { id: node.id, text: node.text, parentId: node.parentNode.id }; tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); var doSuccess = function(responseObject) { eval("var o = " + responseObject.responseText + ";"); ge.editNode.id = o.id; hide(); }; Ext.lib.Ajax.request( 'POST', 'insertTree.htm', {success:doSuccess,failure:hide}, 'data='+encodeURIComponent(Ext.encode(item)) ); }); // ==================================================== // 树型的根节点 // ==================================================== var root = new Ext.tree.AsyncTreeNode({ text: '菜单', draggable:true, id:-1 }); tree.setRootNode(root); tree.render(); // true说明展开所有节点,false说明不使用动画 root.expand(true, false); // ==================================================== // 弹出对话框 // ==================================================== function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:true, autoTabs:true, proxyDrag:true, resizable:false, width: 410, height: 300, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('取消', function() {thisDialog.hide();}); return thisDialog; }; function configMenu(){ var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); // Ext.MessageBox.prompt('当前菜单URL:'+n.attributes.url, '请输入新的URL:', showResultText); var menuData = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'loadData.htm?id=' + n.id}), reader: new Ext.data.JsonReader({},['id','name',"tip","forward","descn"]), remoteSort: false }); menuData.on('load', function() { var id = menuData.getAt(0).data['id']; var name = menuData.getAt(0).data['name']; fieldName.setValue(name); var image = menuData.getAt(0).data['image']; fieldImage.setValue(image); var tip = menuData.getAt(0).data['tip']; fieldTip.setValue(tip); var forward = menuData.getAt(0).data['forward']; fieldForward.setValue(forward); var descn = menuData.getAt(0).data['descn']; fieldDescn.setValue(descn); var dialog; if (!dialog) { dialog = createNewDialog("a-updateInstance-dialog"); dialog.addButton('提交', function() { if (menuForm.isValid()) { menuForm.submit({ params:{id : id}, waitMsg:'更新数据...', reset: false, failure: function(menuForm, action) { Ext.MessageBox.alert('错误', action.result.errorInfo); }, success: function(menuForm, action) { Ext.MessageBox.alert('成功', action.result.info); dialog.hide(); refresh(); } }); }else{ Ext.MessageBox.alert('错误', '请查看错误信息'); } }); var layout = dialog.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: '修改菜单信息'})); layout.endUpdate(); dialog.show(); } }); menuData.load(); } // 打开验证功能 Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; var fieldName = new Ext.form.TextField({ fieldLabel: '名称', name: 'name', width:170, readOnly: false, allowBlank:false }); var fieldForward = new Ext.form.TextField({ fieldLabel: '链接', name: 'forward', width:170, readOnly: false, allowBlank:false }); var fieldImage = new Ext.form.TextField({ fieldLabel: '图标', name: 'image', width:170, readOnly: false, allowBlank: false }); var fieldTip = new Ext.form.TextField({ fieldLabel: '提示', name: 'tip', width:170, readOnly: false, allowBlank:true }); var fieldDescn = new Ext.form.TextField({ fieldLabel: '描述', name: 'descn', width:170, readOnly: false, allowBlank:true }); var menuForm = new Ext.form.Form({ labelAlign: 'right', url:'update.htm' }); menuForm.column({width: 360, labelWidth:100, style:'margin-left:10px;margin-top:10px'}); menuForm.fieldset( {id:'id', legend:'修改'}, fieldName, fieldImage, fieldForward, fieldTip, fieldDescn ); menuForm.applyIfToFields({width:255}); menuForm.render('a-updateInstance-form'); menuForm.end(); function showResultText(btn, text){ var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if(btn == 'ok'){ Ext.example.msg('数据提交中....', '请稍候'); Ext.Ajax.request({ url:'menu.do?method=updateMenuUrl', success:function(){ Ext.MessageBox.alert('提示', '配置成功!'); tree.getNodeById(n.id).reload(); }, failure:function(){Ext.MessageBox.alert('提示', '配置失败!');}, params:{id:n.id,url:text} }); }else{ return; } }; // ==================================================== // 右键菜单 // ==================================================== tree.on('contextmenu', prepareCtx); var ctxMenu = new Ext.menu.Menu({ id:'copyCtx', items: [{ id:'展开', handler:expandAll, cls:'expand-all', text:'展开' },{ id:'收起', handler:collapseAll, cls:'collapse-all', text:'收起' },{ id:'remove', handler:removeNode, cls:'remove-mi', text: '删除' },{ id:'config', handler:configMenu, text: '配置菜单' }] }); function prepareCtx(node, e){ node.select(); ctxMenu.items.get('remove')[node.attributes.allowDelete ? 'enable' : 'disable'](); ctxMenu.showAt(e.getXY()); } // ==================================================== // 拖拽 // ==================================================== tree.on("nodedragover", function(e){ var n = e.target; if (n.leaf) { n.leaf = false; } return true; }); // 拖拽后,就向服务器发送消息,更新数据 // 本人不喜欢这种方式,屏蔽 /* tree.on('nodedrop', function(e){ var n = e.dropNode; var item = { id: n.id, text: n.text, parentId: e.target.id }; tree.el.mask('正在向服务器发送信息...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); Ext.lib.Ajax.request( 'POST', 'insertTree.htm', {success:hide,failure:hide}, 'data='+encodeURIComponent(Ext.encode(item)) ); }); */ });
JavaScript
Ext.data.DWRProxy = function(dwrCall, pagingAndSort) { Ext.data.DWRProxy.superclass.constructor.call(this); this.dwrCall = dwrCall; //this.args = args; this.pagingAndSort = (pagingAndSort!=undefined ? pagingAndSort : true); }; Ext.extend(Ext.data.DWRProxy, Ext.data.DataProxy, { load : function(params, reader, callback, scope, arg) { if(this.fireEvent("beforeload", this, params) !== false) { //var sort; // if(params.sort && params.dir) sort = params.sort + ' ' + params.dir; //else sort = ''; var delegate = this.loadResponse.createDelegate(this, [reader, callback, scope, arg], 1); var callParams = new Array(); //if(arg.arg) { // callParams = arg.arg.slice(); //} //if(this.pagingAndSort) { //callParams.push(params.start); //callParams.push(params.limit); //callParams.push(sort); //} callParams.push(arg.params); callParams.push(delegate); this.dwrCall.apply(this, callParams); } else { callback.call(scope || this, null, arg, false); } }, loadResponse : function(listRange, reader, callback, scope, arg) { var result; try { result = reader.read(listRange); } catch(e) { this.fireEvent("loadexception", this, null, response, e); callback.call(scope, null, arg, false); return; } callback.call(scope, result, arg, true); }, update : function(dataSet){}, updateResponse : function(dataSet) {} }); Ext.data.ListRangeReader = function(meta, recordType){ Ext.data.ListRangeReader.superclass.constructor.call(this, meta, recordType); this.recordType = recordType; }; Ext.extend(Ext.data.ListRangeReader, Ext.data.DataReader, { getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), read : function(o){ var recordType = this.recordType, fields = recordType.prototype.fields; //Generate extraction functions for the totalProperty, the root, the id, and for each field if (!this.ef) { if(this.meta.totalProperty) { this.getTotal = this.getJsonAccessor(this.meta.totalProperty); } if(this.meta.successProperty) { this.getSuccess = this.getJsonAccessor(this.meta.successProperty); } if (this.meta.id) { var g = this.getJsonAccessor(this.meta.id); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } this.ef = []; for(var i = 0; i < fields.length; i++){ f = fields.items[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; this.ef[i] = this.getJsonAccessor(map); } } var records = []; var root = o.result, c = root.length, totalRecords = c, success = true; if(this.meta.totalProperty){ var v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(this.meta.successProperty){ var v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } for(var i = 0; i < c; i++){ var n = root[i]; var values = {}; var id = this.getId(n); for(var j = 0; j < fields.length; j++){ f = fields.items[j]; try { var v = this.ef[j](n); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue); } catch(e) { values[f.name] = ""; } } var record = new recordType(values, id); records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; } });
JavaScript
Ext.namespace('Ext.ux'); // --- Ext.ux.CheckRowSelectionGrid --- // Ext.ux.CheckRowSelectionGrid = function(container, config) { var id = this.root_cb_id = Ext.id(null, 'cbsm-'); var cb_html = String.format("<input type='checkbox' id='{0}'/>", this.root_cb_id); var grid = this; var cm = config.cm; // Hack var cm = config.cm || config.colModel; cm.config.unshift({ id: id, header: cb_html, width: 20, resizable: false, fixed: true, sortable: false, dataIndex: -1, renderer: function(data, cell, record, rowIndex, columnIndex, store) { return String.format( "<input type='checkbox' id='{0}-{1}' {2}/>", id, rowIndex, grid.getSelectionModel().isSelected(rowIndex) ? "checked='checked'" : '' ); } }); cm.lookup[id] = cm.config[0]; Ext.ux.CheckRowSelectionGrid.superclass.constructor.call(this, container, config); } Ext.extend(Ext.ux.CheckRowSelectionGrid, Ext.grid.Grid, { root_cb_id : null, getSelectionModel: function() { if (!this.selModel) { this.selModel = new Ext.ux.CheckRowSelectionModel(); } return this.selModel; } }); Ext.ux.CheckRowSelectionModel = function(options) { Ext.ux.CheckRowSelectionModel.superclass.constructor.call(this, options); } Ext.extend(Ext.ux.CheckRowSelectionModel, Ext.grid.RowSelectionModel, { init: function(grid) { Ext.ux.CheckRowSelectionModel.superclass.init.call(this, grid); // Start of dirty hacking // Hacking grid if (grid.processEvent) { grid.__oldProcessEvent = grid.processEvent; grid.processEvent = function(name, e) { // The scope of this call is the grid object var target = e.getTarget(); var view = this.getView(); var header_index = view.findHeaderIndex(target); if (name == 'contextmenu' && header_index === 0) { return; } this.__oldProcessEvent(name, e); } } // Hacking view var gv = grid.getView(); if (gv.beforeColMenuShow) { gv.__oldBeforeColMenuShow = gv.beforeColMenuShow; gv.beforeColMenuShow = function() { // The scope of this call is the view object this.__oldBeforeColMenuShow(); // Removing first - checkbox column from the column menu this.colMenu.remove(this.colMenu.items.first()); // he he } } // End of dirty hacking }, initEvents: function() { Ext.ux.CheckRowSelectionModel.superclass.initEvents.call(this); this.grid.getView().on('refresh', this.onGridRefresh, this); }, selectRow: function(index, keepExisting, preventViewNotify) { Ext.ux.CheckRowSelectionModel.superclass.selectRow.call( this, index, keepExisting, preventViewNotify ); var row_id = this.grid.root_cb_id + '-' + index; var cb_dom = Ext.fly(row_id).dom; cb_dom.checked = true; }, deselectRow: function(index, preventViewNotify) { Ext.ux.CheckRowSelectionModel.superclass.deselectRow.call( this, index, preventViewNotify ); var row_id = this.grid.root_cb_id + '-' + index; var cb_dom = Ext.fly(row_id).dom; cb_dom.checked = false; }, onGridRefresh: function() { Ext.fly(this.grid.root_cb_id).on('click', this.onAllRowsCheckboxClick, this, {stopPropagation:true}); // Attaching to row checkboxes events for (var i = 0; i < this.grid.getDataSource().getCount(); i++) { var cb_id = this.grid.root_cb_id + '-' + i; Ext.fly(cb_id).on('mousedown', this.onRowCheckboxClick, this, {stopPropagation:true}); } }, onAllRowsCheckboxClick: function(event, el) { if (el.checked) { this.selectAll(); } else { this.clearSelections(); } }, onRowCheckboxClick: function(event, el) { var rowIndex = /-(\d+)$/.exec(el.id)[1]; if (el.checked) { this.deselectRow(rowIndex); el.checked = true; } else { this.selectRow(rowIndex, true); el.checked = false; } } }); // --- end of Ext.ux.CheckRowSelectionGrid --- //
JavaScript
/* * Ext JS Library 1.0.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ var Example = { init : function(){ // some data yanked off the web var myData = [ ['3m Co',71.72,0.02,0.03,'9/1 12:00am'], ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'], ['Altria Group Inc',83.81,0.28,0.34,'9/1 12:00am'], ['American Express Company',52.55,0.01,0.02,'9/1 12:00am'], ['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'], ['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'], ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'], ['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am'], ['Citigroup, Inc.',49.37,0.02,0.04,'9/1 12:00am'], ['E.I. du Pont de Nemours and Company',40.48,0.51,1.28,'9/1 12:00am'], ['Exxon Mobil Corp',68.1,-0.43,-0.64,'9/1 12:00am'], ['General Electric Company',34.14,-0.08,-0.23,'9/1 12:00am'], ['General Motors Corporation',30.27,1.09,3.74,'9/1 12:00am'], ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'], ['Honeywell Intl Inc',38.77,0.05,0.13,'9/1 12:00am'], ['Intel Corporation',19.88,0.31,1.58,'9/1 12:00am'], ['International Business Machines',81.41,0.44,0.54,'9/1 12:00am'], ['Johnson & Johnson',64.72,0.06,0.09,'9/1 12:00am'], ['JP Morgan & Chase & Co',45.73,0.07,0.15,'9/1 12:00am'], ['McDonald\'s Corporation',36.76,0.86,2.40,'9/1 12:00am'], ['Merck & Co., Inc.',40.96,0.41,1.01,'9/1 12:00am'], ['Microsoft Corporation',25.84,0.14,0.54,'9/1 12:00am'], ['Pfizer Inc',27.96,0.4,1.45,'9/1 12:00am'], ['The Coca-Cola Company',45.07,0.26,0.58,'9/1 12:00am'], ['The Home Depot, Inc.',34.64,0.35,1.02,'9/1 12:00am'], ['The Procter & Gamble Company',61.91,0.01,0.02,'9/1 12:00am'], ['United Technologies Corporation',63.26,0.55,0.88,'9/1 12:00am'], ['Verizon Communications',35.57,0.39,1.11,'9/1 12:00am'], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81,'9/1 12:00am'] ]; var ds = new Ext.data.Store({ proxy: new Ext.data.MemoryProxy(myData), reader: new Ext.data.ArrayReader({}, [ {name: 'company'}, {name: 'price', type: 'float'}, {name: 'change', type: 'float'}, {name: 'pctChange', type: 'float'}, {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'} ]) }); ds.load(); // example of custom renderer function function italic(value){ return '<i>' + value + '</i>'; } // example of custom renderer function function change(val){ if(val > 0){ return '<span style="color:green;">' + val + '</span>'; }else if(val < 0){ return '<span style="color:red;">' + val + '</span>'; } return val; } // example of custom renderer function function pctChange(val){ if(val > 0){ return '<span style="color:green;">' + val + '%</span>'; }else if(val < 0){ return '<span style="color:red;">' + val + '%</span>'; } return val; } // the DefaultColumnModel expects this blob to define columns. It can be extended to provide // custom or reusable ColumnModels var colModel = new Ext.grid.ColumnModel([ {header: "Company", width: 160, sortable: true, locked:false, dataIndex: 'company'}, {header: "Price", width: 75, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'}, {id:'change',header: "Change", width: 75, sortable: true, renderer: change, dataIndex: 'change'}, {header: "% Change", width: 75, sortable: true, renderer: pctChange, dataIndex: 'pctChange'}, {header: "Last Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'} ]); // create the Grid var grid = new Ext.grid.Grid('grid-example', { ds: ds, cm: colModel, autoExpandColumn: 'change' }); var layout = Ext.BorderLayout.create({ center: { margins:{left:3,top:3,right:3,bottom:3}, panels: [new Ext.GridPanel(grid)] } }, 'grid-panel'); grid.render(); grid.getSelectionModel().selectFirstRow(); //右键菜单 function contextmenu(grid, rowIndex,e){ e.preventDefault(); e.stopEvent(); var infoMenu = new Ext.menu.Item({ id:'infoMenu', text: 'infoMenu', handler:function(){ Ext.MessageBox.alert("info",Ext.util.JSON.encode(grid.dataSource.getAt(rowIndex).data)); } }); var menuList = [infoMenu]; grid_menu = new Ext.menu.Menu({ id: 'mainMenu', items: menuList }); var coords = e.getXY(); grid_menu.showAt([coords[0], coords[1]]); } grid.addListener('rowcontextmenu', contextmenu); } }; Ext.onReady(Example.init, Example);
JavaScript
// JavaScript Document Ext.onReady (function() { function formatBoolean(value){ return value ? 'Yes' : 'No'; }; function formatDate(value){ return value ? value.dateFormat('M, d, Y') : ''; }; var cm = new Ext.grid.ColumnModel([{ header: "姓名", dataIndex: "name", width: 100, editor: new Ext.grid.GridEditor(new Ext.form.TextField({allowBlank: false})) }, { header: "性别", dataIndex: "sex", width: 100, editor: new Ext.grid.GridEditor(new Ext.form.ComboBox({ typeAhead: true,//自动完成 triggerAction: "all",// transform: "sex",//列表(select)元素 lazyRender: true })) }, { header: "工资", dataIndex: "money", width: 100, align: "right", renderer: "usMoney", editor: new Ext.grid.GridEditor(new Ext.form.NumberField({ allowBlank: false,//不允许空 allowNegative: false,//不允许负数 maxValue: 1000//最大值 })) }, {header: "参加工作时间", dataIndex: "time", width: 100, renderer: formatDate, editor: new Ext.grid.GridEditor(new Ext.form.DateField({ format: "m/d/y", minValue: "01/01/06", disabledDays: [0,6],//不允许的日期 disabledDaysText: "不允许为又休日" })) }, { header: "是否优秀", dataIndex: "isGood", width: 50, renderer: formatBoolean, editor: new Ext.grid.GridEditor(new Ext.form.Checkbox()) }]); cm.defaultSortable = true;//排序 var User = Ext.data.Record.create([ {name: "name", type: "string"}, {name: "address", type: "string"}, {name: "sex"}, {name: "money", type: "float"}, {name: "time", mapping: "startworktime", type: "date", dateFormat: "m/d/Y"}, {name: "isGood", type: "bool"} ]); var ds = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url: "userinfo.xml"}), reader: new Ext.data.XmlReader({record: "user"}, User) }); var grid = new Ext.grid.EditorGrid("myeditordata", {ds: ds, cm: cm, enableColLock: false}); var layout = Ext.BorderLayout.create({ center: {margins:{left:3,top:3,right:3,bottom:3}, panels: [new Ext.GridPanel(grid)]} }, "mygridpanel"); grid.render(); var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead, [{ text: '新增人员信息', handler : function(){ var p = new User({ name: '姓名', sex: '男', money: 0, time: new Date(), isGood: false }); grid.stopEditing(); ds.insert(0, p); grid.startEditing(0, 0); } }]); // trigger the data store load ds.load(); } );
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-06 * http://code.google.com/p/anewssystem/ */ function checkRoleForUser(id){ UserHelper.getRolesForUser(id,function(roles){ if(id==null||roles==""||!roles){ Ext.MessageBox.alert('提示:', '该用户还没角色授权!'); } Ext.MessageBox.alert('提示:', '已授权的角色:' + roles); }); } Ext.onReady(function(){ // 新节点后缀 var cseed = 0, oseed = 0; var myPageSize = 20; // 快速提示 Ext.QuickTips.init(); // main-ct添加子无素 var cview = Ext.DomHelper.append('main-ct', {cn:[{id:'main-tb'},{id:'cbody'}]} ); var selectNode; var deptId = 0; var userId = 0; //建列表====================================================================================== // 建一个用户数据映射数组 var recordType = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "password", mapping:"password", type: "string"}, {name: "username", mapping:"username", type: "string"}, {name: "descn", mapping:"descn", type: "string"}, {name: "status", mapping:"status", type: "int"}, {name: "email", mapping:"email", type: 'string'}, {name: "dept", mapping:"dept.name", type: 'string'}, {name: "roles", mapping:"roles", type: ''} ]); // 建一个角色数据映射数组 var recordTypeRole = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "name", mapping:"name", type: "string"}, {name: "descn", mapping:"descn", type: "string"}, {name: "authorized", mapping:"authorized", type: "boolean"} ]); //设置数据仓库,使用DWRProxy,ListRangeReader,recordType var dsRole = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(RoleHelper.getRoleForUserPage, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, recordTypeRole), // 远端排序开关 remoteSort: false }); //设置数据仓库,使用DWRProxy,ListRangeReader,recordType var ds = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(UserHelper.pagedQuery, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, recordType), // 远端排序开关 remoteSort: false }); //创建表格头格式 var cm = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id: 'id', header: "编号", dataIndex: "id", width: 100, sortable: true, renderer: renderNamePlain, css: 'white-space:normal;' },{ id: 'username', header: "用户名", dataIndex: "username", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'email', header: "电子邮件", dataIndex: "email", sortable: true, width: 150 },{ id: 'dept', header: "所属部门", dataIndex: "dept", sortable: true, width: 150 },{ id: 'op', header: "所属角色", width: 150, renderer:renderOP }]); //创建Role表格头格式 var cmRole = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id: 'id', header: "编号", dataIndex: "id", width: 100, sortable: true, css: 'white-space:normal;' },{ id: 'name', header: "角色", dataIndex: "name", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'descn', header: "描述", dataIndex: "descn", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'authorized', header: "是否授权", dataIndex: "authorized", sortable: true, width: 80, renderer:renderAuthorized }]); function renderAuthorized(value, p, record){ if(record.data['authorized']==true){ return String.format("<b><font color=green>已分配</font></b>"); }else{ return String.format("<b><font color=red>未分配</font></b>"); } } //渲染表格的方法 function renderHaveRole(value, p, record){ var role=checkRoleForUser(record.data['id']); return String.format(role); // return String.format('<a href=# onclick="checkRoleForUser({0})">查看</a>',record.data['id']); } function renderOP(value, p, record){ return String.format('<a href=# onclick="checkRoleForUser({0})">查看</a>',record.data['id']); } function renderName(value, p, record){ return String.format('<b>{0}</b><br>{1}', value, record.data['descn']==null?"":record.data['descn']); } function renderNamePlain(value){ return String.format('{0}', value); } function renderaddtime(value){ return String.format('<b>{0}</b>', typeof(value)=='string'?"":value.format('Y-m-d')); } // 新建一个表格实例 var grid = new Ext.grid.EditorGrid('main-tb', { ds: ds, cm: cm, //selModel: new Ext.grid.CellSelectionModel(), selModel: new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock:false }); var grid1 = new Ext.grid.Grid('userAuthRole-grid', { ds: dsRole, cm: cmRole, selModel: new Ext.grid.RowSelectionModel({singleSelect:true}), enableColLock:false, loadMask: false }); //================================================================================ // 实例化布局 var layout = new Ext.BorderLayout(document.body, { west: { split:true, initialSize: 200, minSize: 175, maxSize: 400, titlebar: true, margins:{left:5,right:0,bottom:5,top:5} }, center: { title:'用户列表', resizeTabs: true, margins:{left:5,right:0,bottom:5,top:5} } }, 'main-ct'); layout.batchAdd({ west: { id: 'source-files', autoCreate:true, title:'部门树', autoScroll:true, fitToFrame:true }, center : { el: cview, autoScroll:true, fitToFrame:true, resizeEl:'main-tb' } }); grid.on('cellcontextmenu', gridPrepareCtx); //============================================================== //渲染表格 grid1.render(); grid.render(); //取得表格的表脚 var gridFoot = grid.getView().getFooterPanel(true); var gridFootRole = grid1.getView().getFooterPanel(true); // 分页工具栏 var paging = new Ext.PagingToolbar(gridFoot, ds, { pageSize: myPageSize, displayInfo: true, displayMsg: '数据: {0} - {1} 共 {2}', emptyMsg: "没有找到相关数据" }); // 分页工具栏 var pagingRole = new Ext.PagingToolbar(gridFootRole, dsRole, { pageSize: myPageSize, displayInfo: true, displayMsg: '数据: {0} - {1} 共 {2}', emptyMsg: "没有找到相关数据" }); // 向表脚加视图按键 pagingRole.add('-', { pressed: true, enableToggle:true, text: '授权', toggleHandler: function(){ //授权事件 var mRole = grid1.getSelections(); var mUser = grid.getSelections(); if(mRole.length<=0){ Ext.MessageBox.alert('提示', '请选择至少一个角色操作!'); return; }else if(mUser.length==1){ userid=mUser[0].get('id'); roleid=mRole[0].get('id'); UserHelper.authRoleForUser(userid,roleid,false,function(aa){Ext.MessageBox.alert('提示', '授权成功!');}); }else{ for(var i = 0, len = mUser.length; i < len; i++){ userid=mUser[i].get('id'); roleid=mRole[0].get('id'); UserHelper.authRoleForUser(userid,roleid,false,function(aa){Ext.MessageBox.alert('提示', len+'用户授权成功!');}); } } dsRole.load({params:{start:0, limit:myPageSize}}); } }, '-', { pressed: true, enableToggle:true, text: '取消授权', toggleHandler: function(){ //授权事件 var m = grid1.getSelections(); var m1 = grid.getSelections(); if(m.length<=0){ Ext.MessageBox.alert('提示', '请选择至少一个角色操作!'); return; }else if(m1.length==1){ userid=m1[0].get('id'); roleid=m[0].get('id'); UserHelper.authRoleForUser(userid,roleid,true,function(aa){Ext.MessageBox.alert('提示', '授权取消成功!');}); }else{ for(var i = 0, len = m1.length; i < len; i++){ userid=m1[i].get('id'); roleid=m[0].get('id'); UserHelper.authRoleForUser(userid,roleid,true,function(aa){Ext.MessageBox.alert('提示', len+'用户授权取消成功!');}); } } dsRole.load({params:{start:0, limit:myPageSize,id:m1[0].get('id')}}); } }); // 向表脚加视图按键 paging.add('-', { pressed: true, enableToggle:true, text: '详细信息', // cls: 'x-btn-text-icon details', toggleHandler: toggleDetails }); paging.add('-', { pressed: true, enableToggle:true, text: '新增', cls: '', toggleHandler: doAdd }, '-', { pressed: true, enableToggle:true, text: '修改', cls: '', toggleHandler: doSave }, '-', { pressed: true, enableToggle:true, text: '删除', cls: '', toggleHandler: doDel }, '-', { pressed: true, enableToggle:true, text: '角色授权', cls: '', toggleHandler: doAuth }); var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead); filterButton = new Ext.Toolbar.MenuButton({ cls: 'x-btn-text-icon', text: '请选择', tooltip: '选择搜索的字段', menu: {items: [ new Ext.menu.CheckItem({ text: '名称', value: 'username', checked: true, group: 'filter', checkHandler: onItemCheck }) ]}, minWidth: 105 }); tb.add(filterButton); // 过滤器 var filter = Ext.get(tb.addDom({ tag: 'input', type: 'text', size: '30', value: '', style: 'background: #F0F0F9;' }).el); // 回车 filter.on('keypress', function(e) { if(e.getKey() == e.ENTER && this.getValue().length > 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); // 空格 filter.on('keyup', function(e) { if(e.getKey() == e.BACKSPACE && this.getValue().length === 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); // 更新搜索文字 function onItemCheck(item, checked) { if(checked) { filterButton.setText(item.text + ':'); } } /* ds.on('beforeload', function() { ds.baseParams = { deptId: deptId }; }); */ // 为表格加载数据 ds.load({params:{start:0, limit:myPageSize}}); function toggleDetails(btn, pressed){ cm.getColumnById('username').renderer = pressed ? renderNamePlain : renderName; grid.getView().refresh(); } //当点树接点将在列表中打开该部门下的下一级部门 function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:false, autoTabs:true, proxyDrag:true, resizable:true, width: 480, height: 302, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('关闭', function() {thisDialog.hide();}); return thisDialog; }; //----------------------Begin----------------添加表单动作(提交) function doAdd(){ var aAddInstanceDlg; if(!selectNode){ Ext.MessageBox.alert('提示:', '请先选择部门!'); } if(selectNode.leaf==false){ Ext.MessageBox.alert('提示:', '不能在当前部门下创建用户!'); return; } if (!aAddInstanceDlg) { aAddInstanceDlg = createNewDialog("a-addInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { deptId_tf.setValue(deptId); // 数据校验 if (deptId_tf.getValue()==''||deptId_tf.getValue()==0) { Ext.MessageBox.alert('提示:', '请在部门树中选择你的所属部门!'); return; } if (password_tf.getValue()!=cPassword_tf.getValue()) { password_tf.markInvalid("2次输入的密码不正确!"); password_tf.focus(); return; } //设置所属部门的ID if (form_instance_create.isValid()) { form_instance_create.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_create, action) { var info = Ext.MessageBox.alert('错误信息', action.result.errorInfo); }, success: function(form_instance_create, action) { Ext.MessageBox.alert('成功', action.result.info); aAddInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('提示', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-addInstance-inner', {title: '添加用户'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } //End----------------------------------------------- //----------------------Begin----------------修改表单动作(提交) function doSave(){ var aAddInstanceDlg; if (!aAddInstanceDlg) { var m = grid.getSelections(); if(m.length!=1){ Ext.MessageBox.alert('Error', '只允许选择单行纪录进行修改!'); return; } id_show.setValue(m[0].get("id")); name_show.setValue(m[0].get("username")); email_show.setValue(m[0].get("email")); descn_show.setValue(m[0].get("descn")); deptId_show.setValue(selectNode.id); dept_show.setValue(selectNode.text); password_show.setValue(""); cPassword_show.setValue(""); aAddInstanceDlg = createNewDialog("a-updateInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { if(password_show.getValue()==""){ Ext.MessageBox.alert('提示', '请输入密码!'); } if (password_show.getValue()!=cPassword_show.getValue()) { password_show.markInvalid("2次输入的密码不正确!"); password_show.focus(); return; } if(selectNode.leaf!=true){ Ext.MessageBox.alert('提示', '用户不能创建在该部门下!'); return; } // 向服务器提交数据 if (form_instance_update.isValid()) { form_instance_update.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_update, action) { alert(action.result); var info = Ext.MessageBox.alert('Error Message', action.result.errorInfo); }, success: function(form_instance_update, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('提示', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: '用户更新'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } function doAuth(){ var m = grid.getSelections(); if(m.length<=0){ Ext.MessageBox.alert('提示', '请选择需要授权的用户!'); return; } dsRole.load({params:{start:0, limit:myPageSize,id:m[0].get('id')}}); var aAddInstanceDlg = createNewDialog("userAuthRole-dlg"); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('userAuthRole-inner', {title: '用户授权'})); layout.endUpdate(); aAddInstanceDlg.show(); } //删除按钮方法 function doDel(){ var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '确定要删除吗?' , doDel2); } else { Ext.MessageBox.alert('提示', '请选择要删除的数据行!'); } } //删除回调方法 function doDel2(btn) { if(btn=='yes'){ var m = grid.getSelections(); var userid =new Array(); for(var i = 0, len = m.length; i < len; i++){ m[i].get("id"); userid[i]=m[i].get("id"); ds.remove(m[i]); } Ext.Ajax.request({ url:'remove.htm?id='+userid, success:function(){ Ext.MessageBox.alert('提示', '删除成功!'); ds.load({params:{start:0, limit:myPageSize}}); }, failure:function(){Ext.MessageBox.alert('提示', '删除失败!');} }); }else{ return; } } // 提供验证功能 Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; // 添加表单 var name_tf = new Ext.form.TextField({ fieldLabel: '用户名', name: 'username', allowBlank:false }); var password_tf = new Ext.form.TextField({ fieldLabel: '密码', name: 'password', inputType: 'password', allowBlank:false }); var cPassword_tf = new Ext.form.TextField({ fieldLabel: '密码确认', name: 'cPassword', inputType: 'password', allowBlank:false }); var deptId_tf = new Ext.form.TextField({ name: 'deptId', inputType:'hidden', labelStyle:'display: none' }); var descn_tf = new Ext.form.TextField({ fieldLabel: '描述', name: 'descn', allowBlank:true }); var email_tf = new Ext.form.TextField({ fieldLabel: '电子邮件', name: 'email', allowBlank:true }); var form_instance_create = new Ext.form.Form({ labelAlign: 'right', url:'insert.htm' }); form_instance_create.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_create.fieldset({ id:'adduser', legend:'添加用户----请填写数据:'}, name_tf, password_tf, cPassword_tf, descn_tf, email_tf, deptId_tf ); form_instance_create.applyIfToFields({width:255}); form_instance_create.render('a-addInstance-form'); form_instance_create.end(); resetForm = function() { name_tf.setValue(''); email_tf.setValue(''); descn_tf.setValue(''); deptId_tf.setValue(''); password_tf.setValue(''); cPassword_tf.setValue(''); }; // 更新表单 var id_show = new Ext.form.TextField({ // labelStyle: 'display: none', inputType: 'hidden', name: 'id', readOnly: true, allowBlank:false, labelStyle:'display: none' }); var name_show = new Ext.form.TextField({ fieldLabel: '用户名', name: 'username', allowBlank:false }); var password_show = new Ext.form.TextField({ fieldLabel: '密码', name: 'password', inputType: 'password', allowBlank:false }); var cPassword_show = new Ext.form.TextField({ fieldLabel: '密码确认', name: 'cPassword', inputType: 'password', allowBlank:false }); var descn_show = new Ext.form.TextField({ fieldLabel: '描述', name: 'descn', allowBlank:true }); var email_show = new Ext.form.TextField({ fieldLabel: '电子邮件', name: 'email', allowBlank:true }); var dept_show = new Ext.form.TextField({ fieldLabel: '所属部门', name: 'orgText', allowBlank:false }); var deptId_show = new Ext.form.TextField({ inputType: 'hidden', name: 'deptId', readOnly: true, allowBlank:false, labelStyle:'display: none' }); var form_instance_update = new Ext.form.Form({ labelAlign: 'right', url:'update.htm' }); form_instance_update.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_update.fieldset({ id:'updateuser', legend:'更新用户----请填写数据:'}, name_show, password_show, cPassword_show, descn_show, email_show, dept_show, deptId_show, id_show ); form_instance_update.applyIfToFields({width:255}); form_instance_update.render('a-updateInstance-form'); form_instance_update.end(); //-------------------------表格右键菜单BEGAIN var gridCtxMenu = new Ext.menu.Menu({ id:'gridCtx', items: [{ id:'addDept', handler:gridAddDept, cls:'collapse-all', text:'添加部门' },{ id:'addUser', handler:gridAddUser, cls:'collapse-all', text:'添加用户' },'-',{ id:'remove', cls:'remove-mi', text: '移除' }] }); function gridPrepareCtx(grid, rowIndex,cellIndex,e){ ctxMenu.items.get('remove')[node.attributes.allowDelete ? 'enable' : 'disable'](); gridCtxMenu.showAt(e.getXY()); } function gridAddDept(node){ gridCtxMenu.hide(); setTimeout(function(){ node.eachChild(function(n){ //n.collapse(false, false); }); }, 10); } function gridAddUser(node){ gridCtxMenu.hide(); setTimeout(function(){ node.eachChild(function(n){ // n.expand(false, false); }); }, 10); } //-------------------------表格右键菜单END //============================================================= //================创建用户树============================ var userTreeloader = new Ext.tree.TreeLoader({ dataUrl:'#user.do?method=rendererUserTree' }); var Tree = Ext.tree; var tree = new Tree.TreePanel('source-files', { animate:true, loader: new Tree.TreeLoader({ dataUrl:'../dept/getAllTree.htm' }), enableDD:true, containerScroll: true, dropConfig: {appendOnly:true} }); tree.on('move',function(tree,thisnode,oldParent,newParent,index){ //操作 }); // 树的根节点 var root = new Tree.AsyncTreeNode({ text: '临远研发中心', draggable:false, id:'1', cls:'folder', leaf:false }); tree.setRootNode(root); //tree.on("expand",reloadds); tree.on('contextmenu', prepareCtx); tree.on('click',function(node,e){ selectNode = node; }); tree.on('click',reloadds); // 渲染树 tree.render(); root.expand(); function reloadds(node,e){ deptId=node.id; deptId_show.setValue(selectNode.id); dept_show.setValue(selectNode.text); ds.load({params:{start:0, limit:myPageSize,deptId:node.id}}); } //---------------树右键菜单BEGAIN var ctxMenu = new Ext.menu.Menu({ id:'copyCtx', items: [{ id:'expand', handler:expandAll, cls:'expand-all', text:'展开' },{ id:'collapse', handler:collapseAll, cls:'collapse-all', text:'收拢' },{ id:'addDept', handler:collapseAll, cls:'collapse-all', text:'添加部门' },{ id:'addUser', handler:collapseAll, cls:'collapse-all', text:'添加用户' },'-',{ id:'remove', cls:'remove-mi', text: '删除' }] }); function prepareCtx(node, e){ node.select(); // ctxMenu.items.get('remove')[node.attributes.allowDelete ? 'enable' : 'disable'](); ctxMenu.items.get('addUser')[node.isLeaf ? 'enable' : 'disable'](); ctxMenu.items.get('addDept')[node.isLeaf ? 'disable' : 'enable'](); ctxMenu.showAt(e.getXY()); } function collapseAll(node){ ctxMenu.hide(); setTimeout(function(){ node.eachChild(function(n){ n.collapse(false, false); }); }, 10); } function expandAll(node){ ctxMenu.hide(); setTimeout(function(){ node.eachChild(function(n){ n.expand(false, false); }); }, 10); } //---------------树右键菜单END ds.on('beforeload', function() { ds.baseParams = { deptId: deptId }; }); dsRole.on('beforeload', function() { dsRole.baseParams = { userId:grid.getSelections()[0].id }; }); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-20 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '资源管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1, w:150}, {id : 'name', qtip : "资源名称", vType : "chn", allowBlank : false, w:150}, {id : 'resType', qtip : "资源类型", vType : "chn", allowBlank : false, w:150}, {id : 'resString', qtip : "资源内容", vType : "chn", allowBlank : false, w:150}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true, w:170} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-21 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '角色管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1, w:260}, {id : 'name', qtip : "角色名称", vType : "chn", allowBlank : false, w:260}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true, w:260} ]; // 创建表格 var lightGrid = new Ext.lingo.JsonGrid("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); // ======================================================================== // ======================================================================== // 在工具栏上添加选择资源的按钮 lightGrid.toolbar.insertButton(3, { icon : "../widgets/lingo/list-items.gif", id : 'selectResource', text : '配置资源', cls : 'add', tooltip : '配置资源', handler : selectResource }); // 在工具栏上添加选择菜单的按钮 lightGrid.toolbar.insertButton(4, { icon : "../widgets/lingo/list-items.gif", id : 'selectMenu', text : '配置菜单', cls : 'add', tooltip : '配置菜单', handler : selectMenu }); // ======================================================================== // ======================================================================== // 渲染表格的方法 function renderResource(value, p, record) { if(record.data['authorized'] == true) { return String.format("<b><font color=green>已分配</font></b>"); } else { return String.format("<b><font color=red>未分配</font></b>"); } } function renderNamePlain(value) { return String.format('{0}', value); } // 建一个资源数据映射数组 var resourceRecord = Ext.data.Record.create([ {name: "id", mapping: "id", type: "int"}, {name: "resType", mapping: "resType", type: "string"}, {name: "name", mapping: "name", type: "string"}, {name: "resString", mapping: "resString", type: "string"}, {name: "descn", mapping: "descn", type: "string"}, {name: "authorized", mapping: "authorized", type: "boolean"} ]); // 配置资源 var resStore = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({url:'getResources.htm'}), reader : new Ext.data.JsonReader({},resourceRecord), remoteSort : false }); var resColumnModel = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id : 'id', header : "编号", dataIndex : "id", width : 80, sortable : true, renderer : renderNamePlain, css : 'white-space:normal;' }, { id : 'name', header : "资源名称", dataIndex : "name", sortable : true, width : 150 , css : 'white-space:normal;' }, { id : 'resType', header : "资源类型", dataIndex : "resType", sortable : true, width : 80 }, { id : 'resString', header : "资源地址", dataIndex : "resString", sortable : true, width : 150 }, { id : 'descn', header : "资源描述", dataIndex : "descn", sortable : true, width : 80 }, { id : 'authorized', header : "是否授权", dataIndex : "authorized", sortable : true, width : 80, renderer : renderResource }]); var resourceGrid = new Ext.grid.EditorGrid('resource-grid', { ds : resStore, cm : resColumnModel, selModel : new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock : false, loadMask : false }); // 渲染表格 resourceGrid.render(); var resourceFooter = resourceGrid.getView().getFooterPanel(true); var resourcePaging = new Ext.PagingToolbar(resourceFooter, resStore, { pageSize : 10, displayInfo : true, displayMsg : '显示: {0} - {1} 共 {2}', emptyMsg : "没有找到相关数据" }); resourcePaging.add('-', { pressed : true, enableToggle : true, text : '授权', cls : '', toggleHandler : resourceAuth }, '-', { pressed : true, enableToggle : true, text : '取消', cls : '', toggleHandler: resourceCancel }); function resourceAuth() { resourceAuthDo(true); } function resourceCancel() { resourceAuthDo(false); } function resourceAuthDo(isAuth) { //授权事件 var mRole = lightGrid.grid.getSelections(); var mResc = resourceGrid.getSelections(); if(mResc.length <= 0) { Ext.MessageBox.alert('提示', '请选择至少一行纪录进行操作!'); return; } else { var ids = new Array(); for (var i = 0; i < mResc.length; i++) { var rescId = mResc[i].get('id'); ids[ids.length] = rescId; } var roleId = mRole[0].get('id'); Ext.lib.Ajax.request( 'POST', 'auth.htm', {success:end,failure:end}, 'ids=' + ids.join(",") + "&roleId=" + roleId + "&isAuth=" + isAuth ); } resStore.reload(); } function end() { Ext.Msg.alert("提示", "操作成功"); resStore.reload(); } // 选择资源 function selectResource() { var m = lightGrid.grid.getSelections(); if(m.length <= 0) { Ext.MessageBox.alert('提示', '请选择需要配置的角色!'); return; } // 读取数据需要的参数 resStore.on('beforeload', function() { resStore.baseParams = { roleId : lightGrid.grid.getSelections()[0].get('id') }; }); resStore.load({params:{ start : 0, limit : 10 }}); var resourceDialog = Ext.lingo.FormUtils.createLayoutDialog("resource-dlg"); var layout = resourceDialog.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('resource-inner', {title: '角色授权'})); layout.endUpdate(); resourceDialog.show(Ext.get("selectResource")); } // 选择菜单成功 function solveMenuResponse() { Ext.Msg.alert("提示", "操作成功"); this.menuTree.root.reload(); this.menuTree.root.expand(true, false); } var configMenuDialog; // 选择菜单 function selectMenu() { var m = lightGrid.grid.getSelections(); if(m.length <= 0) { Ext.MessageBox.alert('提示', '请选择需要配置的角色!'); return; } this.currentRoleId = m[0].id; //Ext.lingo.FormUtils.createDialogContent({id:'menuDialog',title:'选择菜单'}); //var configMenuDialog = Ext.lingo.FormUtils.createDialog({id:'menuDialog' + "-dialog-content"}); if (!configMenuDialog) { var id = 'menuDialog' + Ext.id(); configMenuDialog = Ext.lingo.FormUtils.createTabedDialog(id, ['选择菜单','帮助']); this.yesBtn = configMenuDialog.addButton("确定", function() { // 如果不全部展开,那么未展开的部分,无法取得数据。 //this.menuTree.root.expand(true, false); Ext.lib.Ajax.request( 'POST', 'selectMenu.htm', {success:solveMenuResponse.createDelegate(this),failure:solveMenuResponse.createDelegate(this)}, 'ids=' + this.menuTree.getChecked().join(",") + "&roleId=" + lightGrid.grid.getSelections()[0].id ); }.createDelegate(this), configMenuDialog); this.tabs = configMenuDialog.getTabs(); this.tabs.getTab(0).on("activate", function() { this.yesBtn.show(); }, this, true); this.tabs.getTab(1).on("activate", function() { this.yesBtn.hide(); }, this, true); var treeId = 'menuTree' + Ext.id(); this.tabs.getTab(0).setContent("<div id='" + treeId + "'></div>"); //this.tabs.getTab(0).setContent(Ext.get("tree-div").dom.innerHTML); this.menuTree = new Ext.tree.TreePanel(treeId, { rootVisible : true, animate : true, loader : new Ext.tree.CustomUITreeLoader({ dataUrl : 'getMenuByRole.htm', baseAttr : { uiProvider : Ext.tree.CheckboxNodeUI } }), enableDD : false, containerScroll : true, rootUIProvider : Ext.tree.CheckboxNodeUI, selModel : new Ext.tree.CheckNodeMultiSelectionModel(), rootVisible : false }); this.menuTree.getLoader().baseParams = {id: this.currentRoleId}; //var dialogContent = Ext.get(this.config.dialogContent + "-content"); //this.tabs.getTab(0).setContent(dialogContent.dom.innerHTML); //this.applyElements(); this.noBtn = configMenuDialog.addButton("取消", configMenuDialog.hide, configMenuDialog); // 设置根节点 this.treeRoot = new Ext.tree.AsyncTreeNode({ text : '选择菜单', draggable : false, id : '0', uiProvider : Ext.tree.CheckboxNodeUI }); this.menuTree.setRootNode(this.treeRoot); // 渲染树 this.menuTree.render(); } this.menuTree.getLoader().baseParams = {id: this.currentRoleId}; this.treeRoot.reload(); this.treeRoot.expand(true, false); configMenuDialog.show(Ext.get("selectMenu")); } });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-13 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '数据字典', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1}, {id : 'name', qtip : "数据字典", vType : "chn", allowBlank : false}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true} ]; // 创建树形 var lightTree = new Ext.lingo.JsonTree("lighttree", { metaData : metaData, dlgWidth : 450, dlgHeight : 250, rootName : '数据字典', dialogContent : "content" }); // 渲染树形 lightTree.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-06 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 新节点的后缀 var cseed = 0, oseed = 0; var myPageSize = 20; // 打开提示功能 Ext.QuickTips.init(); // 为main-ct添加子无素 var cview = Ext.DomHelper.append('main-ct', {cn:[{id:'main-tb'},{id:'cbody'}]} ); var selectNode; var recordTypeRole = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "name", mapping:"name", type: "string"}, {name: "descn", mapping:"descn", type: "string"} ]); // 建一个资源数据映射数组 var recordTypeResc = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "resType", mapping:"resType", type: "string"}, {name: "name", mapping:"name", type: "string"}, {name: "resString", mapping:"resString", type: "string"}, {name: "descn", mapping:"descn", type: "string"}, {name: "authorized", mapping:"authorized", type: "boolean"} ]); //设置数据仓库,使用DWRProxy,ListRangeReader,recordType var dsRole = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(RoleHelper.getRoleForUserPage, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, recordTypeRole), // 远端排序开关 remoteSort: false }); // 设置数据仓库,使用DWRProxy,ListRangeReader,recordType var dsResc = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(ResourceHelper.getResourceForRolePage, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, recordTypeResc), // 远端排序开关 remoteSort: false }); //创建Role表格头格式 var cmRole = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id: 'id', header: "编号", dataIndex: "id", width: 100, sortable: true, css: 'white-space:normal;' },{ id: 'name', header: "角色名称", dataIndex: "name", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'descn', header: "描述", dataIndex: "descn", sortable: true, width: 150 , css: 'white-space:normal;' }]); var cmResc = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id: 'id', header: "编号", dataIndex: "id", width: 80, sortable: true, renderer: renderNamePlain, css: 'white-space:normal;' },{ id: 'name', header: "资源名称", dataIndex: "name", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'resType', header: "资源类型", dataIndex: "resType", sortable: true, width: 80 },{ id: 'resString', header: "资源地址", dataIndex: "resString", sortable: true, width: 150 },{ id: 'descn', header: "资源描述", dataIndex: "descn", sortable: true, width: 80 },{ id: 'authorized', header: "是否授权", dataIndex: "authorized", sortable: true, width: 80, renderer:renderOP }]); // 渲染表格的方法 function renderOP(value, p, record){ if(record.data['authorized']==true){ return String.format("<b><font color=green>已分配</font></b>"); }else{ return String.format("<b><font color=red>未分配</font></b>"); } } function renderName(value, p, record){ return String.format('<b>{0}</b><br>{1}', value, record.data['descn']==null?"":record.data['descn']); } function renderNamePlain(value){ return String.format('{0}', value); } function renderaddtime(value){ return String.format('<b>{0}</b>', typeof(value)=='string'?"":value.format('Y-m-d')); } // 创建一个表格实例 var grid = new Ext.grid.EditorGrid('main-tb', { ds: dsRole, cm: cmRole, selModel: new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock:false, loadMask: false }); var gridResc = new Ext.grid.EditorGrid('roleAuthResc-grid', { ds: dsResc, cm: cmResc, selModel: new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock:false, loadMask: false }); // 实例化布局 var layout = new Ext.BorderLayout(document.body, { center: { title:'角色列表', resizeTabs: true, margins:{left:5,right:0,bottom:5,top:5} } }, 'main-ct'); layout.batchAdd({ center : { el: cview, autoScroll:true, fitToFrame:true, resizeEl:'main-tb' } }); // 渲染表格 grid.render(); gridResc.render(); // 取得表格的表脚 var gridFoot = grid.getView().getFooterPanel(true); var gridFootResc = gridResc.getView().getFooterPanel(true); // 分页工具条 var paging = new Ext.PagingToolbar(gridFoot, dsRole, { pageSize: myPageSize, displayInfo: true, displayMsg: '数据: {0} - {1} 共 {2}', emptyMsg: "没有找到相关数据" }); var pagingResc = new Ext.PagingToolbar(gridFootResc, dsResc, { pageSize: myPageSize, displayInfo: true, displayMsg: '数据: {0} - {1} 共 {2}', emptyMsg: "没有找到相关数据" }); pagingResc.add('-', { pressed: true, enableToggle:true, text: '授权', cls: '', toggleHandler: function(){ //授权事件 var mRole = grid.getSelections(); var mResc = gridResc.getSelections(); if(mResc.length<=0){ Ext.MessageBox.alert('提示', '请选择至少一行纪录进行操作!'); return; }else if(mResc.length==1){ roleid=mRole[0].get('id'); rescid=mResc[0].get('id'); RoleHelper.authResourceForRole( roleid, rescid, false, function(aa){ Ext.MessageBox.alert('提示', '授权成功!'); }); }else{ for(var i = 0, len = mResc.length; i < len; i++){ rescid=mResc[i].get('id'); roleid=mRole[0].get('id'); RoleHelper.authResourceForRole( roleid, rescid, false, function(aa){ Ext.MessageBox.alert('提示', len+'角色授权成功!'); }); } } dsResc.load({params:{start:0, limit:myPageSize,id:mRole[0].get('id')}}); } }, '-', { pressed: true, enableToggle:true, text: '取消', cls: '', toggleHandler: function(){ //取消授权事件 var mRole = grid.getSelections(); var mResc = gridResc.getSelections(); console.info(mRole + "," + mRole); if(mResc.length<=0){ Ext.MessageBox.alert('提示', '请选择至少一行纪录进行操作!'); return; }else if(mResc.length==1){ roleid=mRole[0].get('id'); rescid=mResc[0].get('id'); RoleHelper.authResourceForRole(roleid,rescid,true,function(aa){Ext.MessageBox.alert('提示', '授权取消成功!');}); }else{ for(var i = 0, len = mResc.length; i < len; i++){ rescid=mResc[i].get('id'); roleid=mRole[0].get('id'); RoleHelper.authResourceForRole(roleid,rescid,true,function(aa){Ext.MessageBox.alert('提示', len+'角色授权取消成功!');}); } } dsResc.load({params:{start:0, limit:myPageSize,id:mRole[0].get('id')}}); } }); // 向表脚加视图按键 paging.add('-', { pressed: true, enableToggle:true, text: '详细信息', // cls: 'x-btn-text-icon details', toggleHandler: toggleDetails }, '-', { pressed: true, enableToggle:true, text: '新增', cls: '', toggleHandler: doAdd }, '-', { pressed: true, enableToggle:true, text: '修改', cls: '', toggleHandler: doSave }, '-', { pressed: true, enableToggle:true, text: '删除', cls: '', toggleHandler: doDel }, '-', { pressed: true, enableToggle:true, text: '资源配置', cls: '', toggleHandler: doAuth }); var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead); filterButton = new Ext.Toolbar.MenuButton({ cls: 'x-btn-text-icon', text: '请选择', tooltip: '请选择...', menu: {items: [ new Ext.menu.CheckItem({ text: '名称', value: 'name', checked: true, group: 'filter', checkHandler: onItemCheck }) ]}, minWidth: 105 }); tb.add(filterButton); // 过滤器 var filter = Ext.get(tb.addDom({ tag: 'input', type: 'text', size: '30', value: '', style: 'background: #F0F0F9;' }).el); // 回车键 filter.on('keypress', function(e) { if(e.getKey() == e.ENTER && this.getValue().length > 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); // 空格键 filter.on('keyup', function(e) { if(e.getKey() == e.BACKSPACE && this.getValue().length === 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); // 更新选择按钮 function onItemCheck(item, checked) { if(checked) { filterButton.setText(item.text + ':'); } } dsRole.on('beforeload', function() { //表格加载前的动作! }); // 为表格加载数据 dsRole.load({params:{start:0, limit:myPageSize}}); function toggleDetails(btn, pressed){ cmRole.getColumnById('name').renderer = pressed ? renderNamePlain : renderName; grid.getView().refresh(); } // 新建对话框 function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:false, autoTabs:true, proxyDrag:true, resizable:true, width: 650, height: 500, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('关闭', function() {thisDialog.hide();}); return thisDialog; }; //----------------------Begin----------------添加表单动作(提交) function doAdd(){ var aAddInstanceDlg; if (!aAddInstanceDlg) { aAddInstanceDlg = createNewDialog("a-addInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { // 提交 if (form_instance_create.isValid()) { form_instance_create.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_create, action) { var info = Ext.MessageBox.alert('Error Message', action.result.errorInfo); }, success: function(form_instance_create, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); dsRole.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('Errors', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-addInstance-inner', {title: 'create account'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } //End----------------------------------------------- //----------------------Begin----------------修改表单动作(提交) function doSave(){ var aAddInstanceDlg; if (!aAddInstanceDlg) { var m = grid.getSelections(); if(m.length!=1){ Ext.MessageBox.alert('Error', '只允许选择单行纪录进行修改!'); return; } id_show.setValue(m[0].get("id")); name_show.setValue(m[0].get("name")); descn_show.setValue(m[0].get("descn")); aAddInstanceDlg = createNewDialog("a-updateInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { // 提交 if (form_instance_update.isValid()) { form_instance_update.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_update, action) { alert(action.result); var info = Ext.MessageBox.alert('提示信息', action.result.errorInfo); }, success: function(form_instance_update, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); dsRole.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('提示', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: '角色更新'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } function doAuth(){ var m = grid.getSelections(); if(m.length<=0){ Ext.MessageBox.alert('提示', '请选择需要配置的角色!'); return; } dsResc.load({params:{start:0, limit:myPageSize,id:m[0].get('id')}}); var aAddInstanceDlg = createNewDialog("userAuthRole-dlg"); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('userAuthRole-inner', {title: '角色授权'})); layout.endUpdate(); aAddInstanceDlg.show(); } // 删除按钮方法 function doDel(){ var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '确定要删除吗?' , doDel2); } else { Ext.MessageBox.alert('提示', '请选择要删除的数据行!'); } } // 删除回调方法 function doDel2(btn) { if(btn=='yes'){ var m = grid.getSelections(); var roleid =new Array(); for(var i = 0, len = m.length; i < len; i++){ m[i].get("id"); roleid[i]=m[i].get("id"); dsRole.remove(m[i]);//从表格中删除 } Ext.Ajax.request({ url:'remove.htm?id='+roleid, success:function(){ Ext.MessageBox.alert('提示', '删除成功!'); dsRole.load({params:{start:0, limit:myPageSize}}); }, failure:function(){Ext.MessageBox.alert('提示', '删除失败!');} }); }else{ return; } } // 提交数据校验功能 Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; // 新建表单 var name_tf = new Ext.form.TextField({ fieldLabel: '角色名称', name: 'name', allowBlank:false }); var descn_tf = new Ext.form.TextField({ fieldLabel: '角色描述', name: 'descn', allowBlank:true }); var form_instance_create = new Ext.form.Form({ labelAlign: 'right', url:'insert.htm' }) form_instance_create.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_create.fieldset({ id:'addresc', legend:'添加角色----请填写数据:'}, name_tf, descn_tf ); form_instance_create.applyIfToFields({width:255}); form_instance_create.render('a-addInstance-form'); form_instance_create.end(); resetForm = function() { name_tf.setValue(''); descn_tf.setValue(''); }; // 更新表单 var id_show = new Ext.form.TextField({ // labelStyle: 'display: none', inputType: 'hidden', name: 'id', readOnly: true, allowBlank:false, labelStyle:'display: none' }); var name_show = new Ext.form.TextField({ fieldLabel: '角色名称', name: 'name', allowBlank:false }); var descn_show = new Ext.form.TextField({ fieldLabel: '角色描述', name: 'descn', allowBlank:true }); var form_instance_update = new Ext.form.Form({ labelAlign: 'right', url:'update.htm' }); form_instance_update.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_update.fieldset({ id:'updateResc', legend:'更新角色----请填写数据:'}, name_show, descn_show, id_show ); form_instance_update.applyIfToFields({width:255}); form_instance_update.render('a-updateInstance-form'); form_instance_update.end(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-06 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 打开提示功能 Ext.QuickTips.init(); // ==================================================== // 开始构造树形 // ==================================================== var treeloader = new Ext.tree.TreeLoader({dataUrl:'getAllTree.htm'}); var tree = new Ext.tree.TreePanel('main', { animate:false, containerScroll: true, enableDD:true, lines: true, loader: treeloader }); // 不使用自动排序 //new Ext.tree.TreeSorter(tree, {folderSort:true}); tree.el.addKeyListener(Ext.EventObject.DELETE, removeNode); // ==================================================== // 工具栏 // ==================================================== var tb = new Ext.Toolbar(tree.el.createChild({tag:'div'})); tb.add({ text: '新增子分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '添加选中节点的下级分类', handler: createChild }, { text: '新增兄弟分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '添加选中节点的同级分类', handler: createBrother }, { text: '修改分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip: '修改选中分类', handler: updateNode }, { text: '删除分类', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'删除一个分类', handler:removeNode }, '-', { text: '排序', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'保存排序结果', handler:save }, '-', { text: '展开', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'展开所有分类', handler:expandAll }, { text: '关闭', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'关闭所有分类', handler:collapseAll }, { text: '刷新', icon: '../widgets/images/list-items.gif', cls: 'x-btn-text-icon album-btn', tooltip:'刷新所有节点', handler:refresh }); // ==================================================== // 工具栏操作函数 // ==================================================== function createChild() { var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if (!n) { n = tree.getRootNode(); } else { n.expand(false, false); } createNode(n); } function createBrother() { var n = tree.getSelectionModel().getSelectedNode(); if (!n) { Ext.Msg.alert('提示', "请选择一个节点"); } else if (n == tree.getRootNode()) { Ext.Msg.alert('提示', "不能为根节点增加兄弟节点"); } else { createNode(n.parentNode); } } function createNode(n) { var node = n.appendChild(new Ext.tree.TreeNode({ id:-1, text:'请输入分类名', cls:'album-node', allowDrag:true, allowDelete:true, allowEdit:true, allowChildren:true })); tree.getSelectionModel().select(node); setTimeout(function(){ ge.editNode = node; ge.startEdit(node.ui.textNode); }, 10); } function updateNode() { var n = tree.getSelectionModel().getSelectedNode(); if (!n) { Ext.Msg.alert('提示', "请选择一个节点"); } else if (n == tree.getRootNode()) { Ext.Msg.alert('提示', "不能为根节点增加兄弟节点"); } else { setTimeout(function(){ ge.editNode = n; ge.startEdit(n.ui.textNode); }, 10); } } function removeNode() { var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if(n && n.attributes.allowDelete){ tree.getSelectionModel().selectPrevious(); tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); Ext.lib.Ajax.request( 'POST', 'removeTree.htm', {success:hide,failure:hide}, 'id='+n.id ); n.parentNode.removeChild(n); } } function appendNode(node, array) { if (!node || node.childNodes.length < 1) { return; } for (var i = 0; i < node.childNodes.length; i++) { var child = node.childNodes[i]; array.push({id:child.id,parentId:child.parentNode.id}); appendNode(child, array); } } function save() { // 向数据库发送一个json数组,保存排序信息 tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); var ch = []; appendNode(root, ch); Ext.lib.Ajax.request( 'POST', 'sortTree.htm', {success:hide,failure:hide}, 'data='+encodeURIComponent(Ext.encode(ch)) ); } function collapseAll(){ ctxMenu.hide(); setTimeout(function(){ root.eachChild(function(n){ n.collapse(true, false); }); }, 10); } function expandAll(){ ctxMenu.hide(); setTimeout(function(){ root.eachChild(function(n){ n.expand(false, false); }); }, 10); } function refresh() { tree.root.reload(); tree.root.expand(true, false); } // ==================================================== // 树节点的即时编辑器 // ==================================================== var ge = new Ext.tree.TreeEditor(tree, { allowBlank:false, blankText:'请添写名称', selectOnFocus:true }); ge.on('beforestartedit', function(){ var node = ge.editNode; if(!node.attributes.allowEdit){ return false; } else { node.attributes.oldText = node.text; } }); ge.on('complete', function() { var node = ge.editNode; // 如果节点没有改变,就向服务器发送修改信息 if (node.attributes.oldText == node.text) { node.attributes.oldText = null; return true; } var item = { id: node.id, text: node.text, parentId: node.parentNode.id }; tree.el.mask('正在与服务器交换数据...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); var doSuccess = function(responseObject) { eval("var o = " + responseObject.responseText + ";"); ge.editNode.id = o.id; hide(); }; Ext.lib.Ajax.request( 'POST', 'insertTree.htm', {success:doSuccess,failure:hide}, 'data='+encodeURIComponent(Ext.encode(item)) ); }); // ==================================================== // 树型的根节点 // ==================================================== var root = new Ext.tree.AsyncTreeNode({ text: '部门', draggable:true, id:-1 }); tree.setRootNode(root); tree.render(); // true说明展开所有节点,false说明不使用动画 root.expand(true, false); // ==================================================== // 弹出对话框 // ==================================================== function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:true, autoTabs:true, proxyDrag:true, resizable:false, width: 410, height: 300, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('取消', function() {thisDialog.hide();}); return thisDialog; }; function configMenu(){ var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); // Ext.MessageBox.prompt('当前菜单URL:'+n.attributes.url, '请输入新的URL:', showResultText); var menuData = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'loadData.htm?id=' + n.id}), reader: new Ext.data.JsonReader({},['id','name',"descn"]), remoteSort: false }); menuData.on('load', function() { var id = menuData.getAt(0).data['id']; var name = menuData.getAt(0).data['name']; fieldName.setValue(name); var descn = menuData.getAt(0).data['descn']; fieldDescn.setValue(descn); var dialog; if (!dialog) { dialog = createNewDialog("a-updateInstance-dialog"); dialog.addButton('提交', function() { if (menuForm.isValid()) { menuForm.submit({ params:{id : id}, waitMsg:'更新数据...', reset: false, failure: function(menuForm, action) { Ext.MessageBox.alert('错误', action.result.errorInfo); }, success: function(menuForm, action) { Ext.MessageBox.alert('成功', action.result.info); dialog.hide(); refresh(); } }); }else{ Ext.MessageBox.alert('错误', '请查看错误信息'); } }); var layout = dialog.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: '修改菜单信息'})); layout.endUpdate(); dialog.show(); } }); menuData.load(); } // 打开验证功能 Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; var fieldName = new Ext.form.TextField({ fieldLabel: '名称', name: 'name', width:170, readOnly: false, allowBlank:false }); var fieldDescn = new Ext.form.TextField({ fieldLabel: '描述', name: 'descn', width:170, readOnly: false, allowBlank:true }); var menuForm = new Ext.form.Form({ labelAlign: 'right', url:'update.htm' }); menuForm.column({width: 360, labelWidth:100, style:'margin-left:10px;margin-top:10px'}); menuForm.fieldset( {id:'id', legend:'修改'}, fieldName, fieldDescn ); menuForm.applyIfToFields({width:255}); menuForm.render('a-updateInstance-form'); menuForm.end(); function showResultText(btn, text){ var sm = tree.getSelectionModel(); var n = sm.getSelectedNode(); if(btn == 'ok'){ Ext.example.msg('数据提交中....', '请稍候'); Ext.Ajax.request({ url:'menu.do?method=updateMenuUrl', success:function(){ Ext.MessageBox.alert('提示', '配置成功!'); tree.getNodeById(n.id).reload(); }, failure:function(){Ext.MessageBox.alert('提示', '配置失败!');}, params:{id:n.id,url:text} }); }else{ return; } }; // ==================================================== // 右键菜单 // ==================================================== tree.on('contextmenu', prepareCtx); var ctxMenu = new Ext.menu.Menu({ id:'copyCtx', items: [{ id:'展开', handler:expandAll, cls:'expand-all', text:'展开' },{ id:'收起', handler:collapseAll, cls:'collapse-all', text:'收起' },{ id:'remove', handler:removeNode, cls:'remove-mi', text: '删除' },{ id:'config', handler:configMenu, text: '配置部门' }] }); function prepareCtx(node, e){ node.select(); ctxMenu.items.get('remove')[node.attributes.allowDelete ? 'enable' : 'disable'](); ctxMenu.showAt(e.getXY()); } // ==================================================== // 拖拽 // ==================================================== tree.on("nodedragover", function(e){ var n = e.target; if (n.leaf) { n.leaf = false; } return true; }); // 拖拽后,就向服务器发送消息,更新数据 // 本人不喜欢这种方式,屏蔽 /* tree.on('nodedrop', function(e){ var n = e.dropNode; var item = { id: n.id, text: n.text, parentId: e.target.id }; tree.el.mask('正在向服务器发送信息...', 'x-mask-loading'); var hide = tree.el.unmask.createDelegate(tree.el); Ext.lib.Ajax.request( 'POST', 'insertTree.htm', {success:hide,failure:hide}, 'data='+encodeURIComponent(Ext.encode(item)) ); }); */ });
JavaScript
var Index = function() { var layout, center; var classClicked = function(e, target){ Index.loadDoc(target.href); }; return { init : function() { Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); layout = new Ext.BorderLayout(document.body, { north: { split:false, initialSize: 32, titlebar: false }, west: { split:true, initialSize: 250, minSize: 175, maxSize: 400, titlebar: true, collapsible: true, animate: true, useShim:true, cmargins: {top:2,bottom:2,right:2,left:2} }, center: { titlebar: true, title: '工作区', autoScroll:false, tabPosition: 'top', closeOnTab: true, //alwaysShowTabs: true, resizeTabs: true } }); layout.beginUpdate(); layout.add('north', new Ext.ContentPanel('header')); layout.add('west', new Ext.ContentPanel('classes', {title: '功能菜单', fitToFrame:true})); center = layout.getRegion('center'); center.add(new Ext.ContentPanel('main', {fitToFrame:true})); layout.restoreState(); layout.endUpdate(); var classes = Ext.get('classes'); if(Index.classData){ var tree = new Ext.tree.TreePanel(classes, { loader: new Ext.tree.TreeLoader(), rootVisible:false, animate:false }); new Ext.tree.TreeSorter(tree, {folderSort:true,leafAttr:'isClass'}); var root = new Ext.tree.AsyncTreeNode({ text:'Ext Docs', children: [Index.classData] }); tree.setRootNode(root); tree.on('click', function(n){ if(n.isLeaf()){ Index.loadDoc(''+n.attributes.fullName+'.jsp'); } }); tree.render(); }else{ classes.on('click', classClicked, null, {delegate: 'a', stopEvent:true}); classes.select('h3').each(function(el){ var c = new NavNode(el.dom); if(!/^\s*(?:新闻管理|权限管理)\s*$/.test(el.dom.innerHTML)){ c.collapse(); } }); } var page = window.location.href.split('#')[1]; if(!page){ page = 'welcome.htm'; } this.loadDoc(page); // safari and opera have iframe sizing issue, relayout fixes it if(Ext.isSafari || Ext.isOpera){ layout.layout(); } var loading = Ext.get('loading'); var mask = Ext.get('loading-mask'); mask.setOpacity(.8); mask.shift({ xy:loading.getXY(), width:loading.getWidth(), height:loading.getHeight(), remove:true, duration:1, opacity:.3, easing:'bounceOut', callback : function(){ loading.fadeOut({duration:.2,remove:true}); } }); }, loadDoc : function(url){ Ext.get('main').dom.src = url; } }; }(); Ext.onReady(Index.init, Index, true); var NavNode = function(clickEl, collapseEl){ this.clickEl = Ext.get(clickEl); if(!collapseEl){ collapseEl = this.clickEl.dom.nextSibling; while(collapseEl.nodeType != 1){ collapseEl = collapseEl.nextSibling; } } this.collapseEl = Ext.get(collapseEl); this.clickEl.addClass('collapser-expanded'); this.clickEl.mon('click', function(){ this.collapsed === true ? this.expand() : this.collapse(); }, this, true); }; NavNode.prototype = { collapse : function(){ this.collapsed = true; this.collapseEl.setDisplayed(false); this.clickEl.replaceClass('collapser-expanded','collapser-collapsed'); }, expand : function(){ this.collapseEl.setDisplayed(true); this.collapsed = false; this.collapseEl.setStyle('height', ''); this.clickEl.replaceClass('collapser-collapsed','collapser-expanded'); } };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-13 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '菜单管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1}, {id : 'url', qtip : "链接地址", vType : "url", allowBlank : false}, {id : 'name', qtip : "菜单名称", vType : "chn", allowBlank : false}, {id : 'qtip', qtip : "提示信息", vType : "chn", allowBlank : true}, {id : 'image', qtip : "图片", vType : "alphanum", allowBlank : true, defValue : "user.gif"}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true} ]; // 创建树形 var lightTree = new Ext.lingo.JsonTree("lighttree", { metaData : metaData, dlgWidth : 500, dlgHeight : 300, dialogContent : "content" }); // 渲染树形 lightTree.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-13 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '部门管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1}, {id : 'name', qtip : "部门名称", vType : "chn", allowBlank : false}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true} ]; // 创建树形 var lightTree = new Ext.lingo.JsonTree("lighttree", { metaData : metaData, dlgWidth : 450, dlgHeight : 250, dialogContent : "content" }); // 渲染树形 lightTree.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-13 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '地区管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1}, {id : 'name', qtip : "地区名称", vType : "chn", allowBlank : false}, {id : 'descn', qtip : "描述", vType : "chn", allowBlank : true} ]; // 创建树形 var lightTree = new Ext.lingo.JsonTree("lighttree", { metaData : metaData, dlgWidth : 450, dlgHeight : 250, rootName : '管理地区', dialogContent : "content" }); // 渲染树形 lightTree.render(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-06 * http://code.google.com/p/anewssystem/ */ Ext.onReady(function(){ // 新节点的后缀 var cseed = 0, oseed = 0; var myPageSize = 20; // 打开提示功能 Ext.QuickTips.init(); // 为main-ct添加子无素 var cview = Ext.DomHelper.append('main-ct', {cn:[{id:'main-tb'},{id:'cbody'}]} ); var selectNode; // 查询表单 var searchForm = new Ext.form.Form({ //labelAlign: 'top' labelWidth: 90 }); // 确认行列大小 searchForm.column( {width:282,style:'margin-left:10px;margin-top:10px;'}, new Ext.form.TextField({ fieldLabel: '资源名称', name: 'name', id: 'name', width:170 }), new Ext.form.TextField({ fieldLabel: '资源类型', name: 'resType', id: 'resType', width:170 }), new Ext.form.DateField({ fieldLabel: '最后更新日期', name: 'lastChange', id: 'lastChange', width:170, format:'m/d/Y' }) ); // 自定义css样式,clear:true表示它是最后一列 searchForm.column( {width:272, style:'margin-left:10px;margin-top:10px;', clear:true}, new Ext.form.TextField({ fieldLabel: '资源地址', name: 'resString', id: 'resString', width:170 }), new Ext.form.TextField({ fieldLabel: '资源描述', name: 'descn', id: 'descn', width:170 }) ); var submit = searchForm.addButton({ text: '重置', //disabled:true, handler: function(){ searchForm.reset(); ds.clearFilter(); } }); var submit = searchForm.addButton({ text: '查询', //disabled:true, handler: submitSearchForm }); function submitSearchForm() { var fFields=searchForm.getValues(); ds.load({params:{start:0, limit:myPageSize,name:fFields['name'],type:fFields['type'],addr:fFields['addr']}}); } //----------END //建列表=========================== =========================================================== // 建一个资源数据映射数组 var recordType = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "resType", mapping:"resType", type: "string"}, {name: "name", mapping:"name", type: "string"}, {name: "resString", mapping:"resString", type: "string"}, {name: "descn", mapping:"descn", type: "string"} ]); //设置数据仓库,使用DWRProxy,ListRangeReader,recordType var ds = new Ext.data.Store({ proxy: new Ext.data.DWRProxy(ResourceHelper.pagedQuery, true), reader: new Ext.data.ListRangeReader({ totalProperty: 'totalCount', id: 'id' }, recordType), // 远端排序开关 remoteSort: false }); //创建表格头格式 var cm = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id: 'id', header: "编号", dataIndex: "id", width: 100, sortable: true, renderer: renderNamePlain, css: 'white-space:normal;' },{ id: 'name', header: "资源名称", dataIndex: "name", sortable: true, width: 150 , css: 'white-space:normal;' },{ id: 'resType', header: "资源类型", dataIndex: "resType", sortable: true, width: 150 },{ id: 'resString', header: "资源地址", dataIndex: "resString", sortable: true, width: 150 },{ id: 'descn', header: "资源描述", dataIndex: "descn", sortable: true, width: 150 }]); // 渲染表格的方法 function renderOP(value, p, record){ return String.format('<a href=# onclick="checkRoleForUser({0})">查看</a>',record.data['id']); } function renderName(value, p, record){ return String.format('<b>{0}</b><br>{1}', value, record.data['descn']==null?"":record.data['descn']); } function renderNamePlain(value){ return String.format('{0}', value); } function renderaddtime(value){ return String.format('<b>{0}</b>', typeof(value)=='string'?"":value.format('Y-m-d')); } //new一个表格实例 var grid = new Ext.grid.EditorGrid('main-tb', { ds: ds, cm: cm, selModel: new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock:false, loadMask: false }); // 实例化布局 var layout = new Ext.BorderLayout(document.body, { north: { titlebar: true, title: '请输入条件查询', collapsedTitle: '多条件查询选择==>', collapsible:true, collapsed:true, //hidden:true, margins:{left:3,top:3,right:3,bottom:0}, initialSize: 150, split:true }, center: { title:'资源列表', resizeTabs: true, margins:{left:5,right:0,bottom:5,top:5} } }, 'main-ct'); layout.batchAdd({ center : { el: cview, autoScroll:true, fitToFrame:true, resizeEl:'main-tb' } }); searchForm.render(layout.getRegion('north').bodyEl); //渲染表格 grid.render(); //取得表格的表脚 var gridFoot = grid.getView().getFooterPanel(true); // add a paging toolbar to the grid's footer var paging = new Ext.PagingToolbar(gridFoot, ds, { pageSize: myPageSize, displayInfo: true, displayMsg: '数据: {0} - {1} 共 {2}', emptyMsg: "没有找到相关数据" }); // 向表脚加视图按键 paging.add('-', { pressed: true, enableToggle:true, text: '详细信息', // cls: 'x-btn-text-icon details', toggleHandler: toggleDetails }); paging.add('-', { pressed: true, enableToggle:true, text: '新增', cls: '', toggleHandler: doAdd }, '-', { pressed: true, enableToggle:true, text: '修改', cls: '', toggleHandler: doSave }, '-', { pressed: true, enableToggle:true, text: '删除', cls: '', toggleHandler: doDel }); var gridHead = grid.getView().getHeaderPanel(true); var tb = new Ext.Toolbar(gridHead); filterButton = new Ext.Toolbar.MenuButton({ cls: 'x-btn-text-icon', text: '请选择', tooltip: '请选择...', menu: {items: [ new Ext.menu.CheckItem({ text: '名称', value: 'name', checked: true, group: 'filter', checkHandler: onItemCheck }) ]}, minWidth: 105 }); tb.add(filterButton); // 创建过滤器 var filter = Ext.get(tb.addDom({ //添加一个DomHelper配置工具条,然后返回对它的引用 tag: 'input', type: 'text', size: '30', value: '', style: 'background: #F0F0F9;' }).el); // 按键 filter.on('keypress', function(e) { // 监听回车按键 if(e.getKey() == e.ENTER && this.getValue().length > 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); filter.on('keyup', function(e) { // 监听空格 if(e.getKey() == e.BACKSPACE && this.getValue().length === 0) { ds.load({params:{start:0, limit:myPageSize}}); } }); // 更新查找按钮的值 function onItemCheck(item, checked) { if(checked) { filterButton.setText(item.text + ':'); } } ds.on('beforeload', function() { //表格加载前的动作! }); // 为表格加载数据 ds.load({params:{start:0, limit:myPageSize}}); function toggleDetails(btn, pressed){ cm.getColumnById('name').renderer = pressed ? renderNamePlain : renderName; grid.getView().refresh(); } // 更新对话框 function createNewDialog(dialogName) { var thisDialog = new Ext.LayoutDialog(dialogName, { modal:false, autoTabs:true, proxyDrag:true, resizable:true, width: 480, height: 302, shadow:true, center: { autoScroll: true, tabPosition: 'top', closeOnTab: true, alwaysShowTabs: false } }); thisDialog.addKeyListener(27, thisDialog.hide, thisDialog); thisDialog.addButton('关闭', function() {thisDialog.hide();}); return thisDialog; }; //----------------------Begin----------------添加表单动作(提交) function doAdd(){ var aAddInstanceDlg; if (!aAddInstanceDlg) { aAddInstanceDlg = createNewDialog("a-addInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { // 向服务器发送信息 if (form_instance_create.isValid()) { form_instance_create.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_create, action) { var info = Ext.MessageBox.alert('Error Message', action.result.errorInfo); }, success: function(form_instance_create, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('提示', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-addInstance-inner', {title: '添加资源'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } //End----------------------------------------------- //----------------------Begin----------------修改表单动作(提交) function doSave(){ var aAddInstanceDlg; if (!aAddInstanceDlg) { var m = grid.getSelections(); if(m.length!=1){ Ext.MessageBox.alert('Error', '只允许选择单行纪录进行修改!'); return; } id_show.setValue(m[0].get("id")); name_show.setValue(m[0].get("name")); resType_show.setValue(m[0].get("resType")); resString_show.setValue(m[0].get("resString")); descn_show.setValue(m[0].get("descn")); aAddInstanceDlg = createNewDialog("a-updateInstance-dlg"); aAddInstanceDlg.addButton('重置', resetForm, aAddInstanceDlg); aAddInstanceDlg.addButton('保存', function() { // submit now... all the form information are submit to the server // handle response after that... if (form_instance_update.isValid()) { form_instance_update.submit({ waitMsg:'数据提交中.....', reset: false, failure: function(form_instance_update, action) { alert(action.result); var info = Ext.MessageBox.alert('提示信息', action.result.errorInfo); }, success: function(form_instance_update, action) { Ext.MessageBox.alert('Confirm', action.result.info); aAddInstanceDlg.hide(); ds.load({params:{start:0, limit:myPageSize}}); } }); }else{ Ext.MessageBox.alert('提示', '输入的数据有误,请重新输入!'); } }); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('a-updateInstance-inner', {title: '资源更新'})); layout.endUpdate(); aAddInstanceDlg.show(); }; } function doAuth(){ var m = grid.getSelections(); if(m.length<=0){ Ext.MessageBox.alert('提示', '请选择需要授权的用户!'); return; } dsRole.load({params:{start:0, limit:myPageSize}}); var aAddInstanceDlg = createNewDialog("userAuthRole-dlg"); var layout = aAddInstanceDlg.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('userAuthRole-inner', {title: '用户授权'})); layout.endUpdate(); aAddInstanceDlg.show(); } //删除按钮方法 function doDel(){ var m = grid.getSelections(); if(m.length > 0) { Ext.MessageBox.confirm('提示', '确定要删除吗?' , doDel2); } else { Ext.MessageBox.alert('提示', '请选择要删除的数据行!'); } } //删除回调方法 function doDel2(btn) { if(btn=='yes'){ var m = grid.getSelections(); var rescid =new Array(); for(var i = 0, len = m.length; i < len; i++){ m[i].get("id"); rescid[i]=m[i].get("id"); ds.remove(m[i]);//从表格中删除 } Ext.Ajax.request({ url:'remove.htm?id=' + rescid, success:function(){ Ext.MessageBox.alert('提示', '删除成功!'); ds.load({params:{start:0, limit:myPageSize}}); }, failure:function(){Ext.MessageBox.alert('提示', '删除失败!');} }); }else{ return; } } // 提供校验功能 Ext.form.Field.prototype.msgTarget = 'side'; Ext.form.Field.prototype.height = 20; Ext.form.Field.prototype.fieldClass = 'text-field-default'; Ext.form.Field.prototype.focusClass = 'text-field-focus'; Ext.form.Field.prototype.invalidClass = 'text-field-invalid'; // 表单 var name_tf = new Ext.form.TextField({ fieldLabel: '资源名称', name: 'name', allowBlank:false }); var resType_tf = new Ext.form.TextField({ fieldLabel: '资源类型', name: 'resType', allowBlank:false }); var resString_tf = new Ext.form.TextField({ fieldLabel: '资源地址', name: 'resString', allowBlank:false }); var descn_tf = new Ext.form.TextField({ fieldLabel: '资源描述', name: 'descn', allowBlank:true }); var form_instance_create = new Ext.form.Form({ labelAlign: 'right', url:'insert.htm' }); form_instance_create.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_create.fieldset( {id:'addresc', legend:'添加资源----请填写数据:'}, name_tf, resType_tf, resString_tf, descn_tf ); form_instance_create.applyIfToFields({width:255}); form_instance_create.render('a-addInstance-form'); form_instance_create.end(); resetForm = function() { name_tf.setValue(''); resType_tf.setValue(''); resString_tf.setValue(''); descn_tf.setValue(''); }; // 更新资源 var id_show = new Ext.form.TextField({ // labelStyle: 'display: none', inputType: 'hidden', name: 'id', readOnly: true, allowBlank:false, labelStyle:'display: none' }); var name_show = new Ext.form.TextField({ fieldLabel: '资源名称', name: 'name', allowBlank:false }); var resType_show = new Ext.form.TextField({ fieldLabel: '资源类型', name: 'resType', allowBlank:false }); var resString_show = new Ext.form.TextField({ fieldLabel: '资源地址', name: 'resString', allowBlank:false }); var descn_show = new Ext.form.TextField({ fieldLabel: '资源描述', name: 'descn', allowBlank:true }); var form_instance_update = new Ext.form.Form({ labelAlign: 'right', url:'update.htm' }); form_instance_update.column({width: 430, labelWidth:120, style:'margin-left:8px;margin-top:8px'}); form_instance_update.fieldset({ id:'updateResc', legend:'更新资源----请填写数据:'}, name_show, resType_show, resString_show, descn_show, id_show ); form_instance_update.applyIfToFields({width:255}); form_instance_update.render('a-updateInstance-form'); form_instance_update.end(); });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license * * @author Lingo * @since 2007-09-21 * http://code.google.com/p/anewssystem/ */ UserGridPanel = function(container, config) { UserGridPanel.superclass.constructor.call(this, container, config); this.addMetaData = [ {id : 'dept', qtip : '部门', vType : 'treeField', url : "../dept/getChildren.htm", mapping : "dept.name"}, {id : 'username', qtip : "帐号", vType : "chn", allowBlank : false}, {id : 'password', qtip : '密码', vType : "passwordmeta", allowBlank : false}, {id : 'confirmpassword', qtip : '确认密码', vType : "password", allowBlank : false}, {id : 'truename', qtip : '姓名', vType : "chn"}, {id : 'sex', qtip : '性别', vType : "radio", values : [{id : '0', name : '男'}, {id : '1', name : '女'}], defValue : '0', renderer : Ext.lingo.FormUtils.renderSex}, {id : 'birthday', qtip : '生日', vType : "date"}, {id : 'tel', qtip : '电话', vType : "alphanum"}, {id : 'mobile', qtip : '手机', vType : "alphanum"}, {id : 'email', qtip : '邮箱', vType : "email"}, {id : 'duty', qtip : '职务', vType : "chn", allowBlank : true}, {id : 'descn', qtip : "备注", vType : "chn", allowBlank : true} ]; this.editMetaData = [ {id : 'id2', qtip : "ID", vType : "integer", defValue : -1, mapping : "id"}, {id : 'dept2', qtip : '部门', vType : 'treeField', url : "../dept/getChildren.htm", mapping : "dept.name"}, {id : 'username2', qtip : "帐号", vType : "chn", allowBlank : false, mapping : "username"}, {id : 'oldpassword2', qtip : '密码', vType : "password", allowBlank : true, mapping : "oldpassword2"}, {id : 'password2', qtip : '密码', vType : "passwordmeta", allowBlank : true, mapping : "password2"}, {id : 'confirmpassword2', qtip : '确认密码', vType : "password", allowBlank : true, mapping : "confirmpassword2"}, {id : 'truename2', qtip : '姓名', vType : "chn", mapping : "truename"}, {id : 'sex2', qtip : '性别', vType : "radio", values : [{id : '0', name : '男'}, {id : '1', name : '女'}], defValue : '0', renderer : Ext.lingo.FormUtils.renderSex, mapping : "sex"}, {id : 'birthday2', qtip : '生日', vType : "date", mapping : "birthday"}, {id : 'tel2', qtip : '电话', vType : "alphanum", mapping : "tel"}, {id : 'mobile2', qtip : '手机', vType : "alphanum", mapping : "mobile"}, {id : 'email2', qtip : '邮箱', vType : "email", mapping : "email"}, {id : 'duty2', qtip : '职务', vType : "chn", mapping : "duty", allowBlank : true}, {id : 'descn2', qtip : "备注", vType : "chn", mapping : "descn", allowBlank : true} ]; this.headers = ['id','dept','username','password','truename','sex','birthday','tel','mobile','email','duty','descn']; }; Ext.extend(UserGridPanel, Ext.lingo.JsonGrid, { // 添加 add : function() { this.createAddDialog(); this.columns = this.addcolumns; this.dialog = this.adddialog; this.metaData = this.addMetaData; UserGridPanel.superclass.add.call(this); } // 修改 , edit : function() { this.createEditDialog(); this.columns = this.editcolumns; this.dialog = this.editdialog; this.metaData = this.editMetaData; UserGridPanel.superclass.edit.call(this); } // 创建弹出式对话框 , createAddDialog : function() { if (this.adddialog) { return; } /////////////////////////////////////////////////// // add // this.adddialog = Ext.lingo.FormUtils.createTabedDialog('add-dialog', ['添加信息','帮助']); this.addyesBtn = this.adddialog.addButton("确定", function() { if (this.addcolumns.password.getValue() != this.addcolumns.confirmpassword.getValue()) { Ext.suggest.msg("错误", "两次输入的密码不一样"); this.addcolumns.confirmpassword.focus(); return; } var item = Ext.lingo.FormUtils.serialFields(this.addcolumns); if (!item) { return; } this.adddialog.el.mask('提交数据,请稍候...', 'x-mask-loading'); var addhide = function(data) { var json; try { json = Ext.decode(data.responseText); } catch (e) { json = {success:false,info:"服务器错误,请刷新页面。"}; } if (json.success) { this.adddialog.el.unmask(); this.adddialog.hide(); this.refresh.apply(this); } else { Ext.MessageBox.alert("错误", json.info); this.adddialog.el.unmask(); } }.createDelegate(this); Ext.lib.Ajax.request( 'POST', this.urlSave, {success:addhide,failure:addhide}, 'data=' + encodeURIComponent(Ext.encode(item)) ); }.createDelegate(this), this.adddialog); // 设置两个tab var addtabs = this.adddialog.getTabs(); addtabs.getTab(0).on("activate", function() { this.addyesBtn.show(); }, this, true); addtabs.getTab(1).on("activate", function(){ this.addyesBtn.hide(); }, this, true); addtabs.getTab(0).setContent(Ext.get("add-content").dom.innerHTML); document.body.removeChild(document.getElementById("add-content")); this.addcolumns = Ext.lingo.FormUtils.createAll(this.addMetaData); this.addnoBtn = this.adddialog.addButton("取消", this.adddialog.hide, this.adddialog); // 修改帐号后,监听blur事件,与后台交互,检测帐号是否已被其他人注册 this.addcolumns.username.on("blur", function() { var isUsernameValid = function(data) { var json = Ext.decode(data.responseText); try { json = Ext.decode(data.responseText); } catch (e) { json = {success:false}; } if (json.success) { document.getElementById("isUsernameValid").innerHTML = "<span style='font-weight:bold;color:green'>帐号可用。</span>"; } else { document.getElementById("isUsernameValid").innerHTML = "<span style='font-weight:bold;color:red'>帐号已被注册,请更换。</span>"; Ext.getCmp("username").focus(); } }; Ext.lib.Ajax.request( 'POST', "checkUsername.htm", {success:isUsernameValid,failure:isUsernameValid}, 'username=' + this.addcolumns.username.getValue() ); }.createDelegate(this)); } , createEditDialog : function() { if (this.editdialog) { return; } /////////////////////////////////////////////////// // edit // this.editdialog = Ext.lingo.FormUtils.createTabedDialog('edit-dialog', ['基本信息','详细信息','帮助']); this.edityesBtn = this.editdialog.addButton("确定", function() { if (this.editcolumns.oldpassword2.getValue() != "" && this.editcolumns.password2.getValue() != this.editcolumns.confirmpassword2.getValue()) { Ext.suggest.msg("错误", "两次输入的密码不一样"); this.editcolumns.confirmpassword2.focus(); return; } var item = Ext.lingo.FormUtils.serialFields(this.editcolumns); if (!item) { return } this.editdialog.el.mask('提交数据,请稍候...', 'x-mask-loading'); var edithide = function() { this.editdialog.el.unmask(); this.editdialog.hide(); this.refresh.apply(this); }.createDelegate(this); Ext.lib.Ajax.request( 'POST', this.urlSave, {success:edithide,failure:edithide}, 'data=' + encodeURIComponent(Ext.encode(item)) ); }.createDelegate(this), this.editdialog); // 设置三个tab var edittabs = this.editdialog.getTabs(); edittabs.getTab(0).on("activate", function() { this.edityesBtn.show(); }, this, true); edittabs.getTab(1).on("activate", function() { this.edityesBtn.show(); }, this, true); edittabs.getTab(2).on("activate", function(){ this.edityesBtn.hide(); }, this, true); edittabs.getTab(0).setContent(Ext.get("edit-base-content").dom.innerHTML); edittabs.getTab(1).setContent(Ext.get("edit-detail-content").dom.innerHTML); document.body.removeChild(document.getElementById("edit-base-content")); document.body.removeChild(document.getElementById("edit-detail-content")); this.editcolumns = Ext.lingo.FormUtils.createAll(this.editMetaData); this.editnoBtn = this.editdialog.addButton("取消", this.editdialog.hide, this.editdialog); } , applyElements : function() { // 重载父类方法,手工制作form } }); Ext.onReady(function(){ // 开启提示功能 Ext.QuickTips.init(); // 使用cookies保持状态 // TODO: 完全照抄,作用不明 Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); // 布局管理器 var layout = new Ext.BorderLayout(document.body, { center: { autoScroll : true, titlebar : false, tabPosition : 'top', closeOnTab : true, alwaysShowTabs : true, resizeTabs : true, fillToFrame : true } }); // 设置布局 layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('tab1', { title : '用户管理', toolbar : null, closable : false, fitToFrame : true })); layout.add('center', new Ext.ContentPanel('tab2', { title: "帮助", toolbar: null, closable: false, fitToFrame: true })); layout.restoreState(); layout.endUpdate(); layout.getRegion("center").showPanel("tab1"); // 默认需要id, name, theSort, parent, children // 其他随意定制 var metaData = [ {id : 'id', qtip : "ID", vType : "integer", allowBlank : true, defValue : -1, w:30}, {id : 'dept', qtip : '部门', vType : 'treeField', url : "../dept/getChildren.htm", mapping : "dept.name", w:60}, {id : 'username', qtip : "帐号", vType : "chn", allowBlank : false, w:60}, {id : 'password', qtip : '密码', vType : "password", allowBlank : false, w:60}, {id : 'truename', qtip : '姓名', vType : "chn", w:60}, {id : 'sex', qtip : '性别', vType : "radio", values : [{id : '0', name : '男'}, {id : '1', name : '女'}], defValue : '0', renderer : Ext.lingo.FormUtils.renderSex, w:30}, {id : 'birthday', qtip : '生日', vType : "date", w:60}, {id : 'tel', qtip : '电话', vType : "alphanum", w:60}, {id : 'mobile', qtip : '手机', vType : "alphanum", w:60}, {id : 'email', qtip : '邮箱', vType : "email"}, {id : 'duty', qtip : '职务', vType : "chn", w:50}, {id : 'status', qtip : '状态', vType : "integer", renderer : renderStatus, w:40}, {id : 'descn', qtip : "备注", vType : "chn"} ]; // 创建表格 var lightGrid = new UserGridPanel("lightgrid", { metaData : metaData, dialogContent : "content" }); // 渲染表格 lightGrid.render(); // ======================================================================== // ======================================================================== // 在工具栏上添两个按钮,开通和关闭用户 lightGrid.toolbar.insertButton(3, { icon : "../widgets/lingo/list-items.gif", id : 'openUser', text : '开通', cls : 'add', tooltip : '开通', handler : openUser }); lightGrid.toolbar.insertButton(4, { icon : "../widgets/lingo/list-items.gif", id : 'closeUser', text : '关闭', cls : 'add', tooltip : '关闭', handler : closeUser }); // 在工具栏上添一个按钮,选择角色 lightGrid.toolbar.insertButton(5, { icon : "../widgets/lingo/list-items.gif", id : 'config', text : '选择角色', cls : 'add', tooltip : '选择角色', handler : selectRole }); // 开通和关闭 function openUser() { var selections = lightGrid.grid.getSelections(); if (selections.length == 0) { Ext.MessageBox.alert("提示", "请选择希望开通的用户!"); return; } else { var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ selections[i].get("id"); ids[i] = selections[i].get("id"); } Ext.Ajax.request({ url : 'openUser.htm?ids=' + ids, success : function() { lightGrid.refresh(); }, failure : function(){Ext.MessageBox.alert('提示', '操作失败!');} }); } } function closeUser() { var selections = lightGrid.grid.getSelections(); if (selections.length == 0) { Ext.MessageBox.alert("提示", "请选择希望关闭的用户!"); return; } else { var ids = new Array(); for(var i = 0, len = selections.length; i < len; i++){ selections[i].get("id"); ids[i] = selections[i].get("id"); } Ext.Ajax.request({ url : 'closeUser.htm?ids=' + ids, success : function() { lightGrid.refresh(); }, failure : function(){Ext.MessageBox.alert('提示', '操作失败!');} }); } } // ======================================================================== // ======================================================================== // 渲染表格的方法 function renderRole(value, p, record){ if(record.data['authorized']==true){ return String.format("<b><font color=green>已分配</font></b>"); }else{ return String.format("<b><font color=red>未分配</font></b>"); } } function renderNamePlain(value){ return String.format('{0}', value); } function renderStatus(value) { if(value == 1){ return String.format("<b><font color=green>开通</font></b>"); }else{ return String.format("<b><font color=red>关闭</font></b>"); } } // 建一个资源数据映射数组 var roleRecord = Ext.data.Record.create([ {name: "id", mapping:"id", type: "int"}, {name: "name", mapping:"name", type: "string"}, {name: "descn", mapping:"descn", type: "string"}, {name: "authorized", mapping:"authorized", type: "boolean"} ]); // 配置资源 var roleStore = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({url:'getRoles.htm'}), reader : new Ext.data.JsonReader({},roleRecord), remoteSort : false }); var roleColumnModel = new Ext.grid.ColumnModel([{ // 设置了id值,我们就可以应用自定义样式 (比如 .x-grid-col-topic b { color:#333 }) id : 'id', header : "编号", dataIndex : "id", width : 80, sortable : true, renderer : renderNamePlain, css : 'white-space:normal;' }, { id : 'name', header : "角色名称", dataIndex : "name", sortable : true, width : 150 , css : 'white-space:normal;' }, { id : 'descn', header : "资源描述", dataIndex : "descn", sortable : true, width : 80 }, { id : 'authorized', header : "是否授权", dataIndex : "authorized", sortable : true, width : 80, renderer : renderRole }]); var roleGrid = new Ext.grid.EditorGrid('role-grid', { ds : roleStore, cm : roleColumnModel, selModel : new Ext.grid.RowSelectionModel({singleSelect:false}), enableColLock : false, loadMask : false }); // 渲染表格 roleGrid.render(); var roleFooter = roleGrid.getView().getFooterPanel(true); var rolePagging = new Ext.PagingToolbar(roleFooter, roleStore, { pageSize : 10, displayInfo : true, displayMsg : '显示: {0} - {1} 共 {2}', emptyMsg : "没有找到相关数据" }); rolePagging.add('-', { pressed : true, enableToggle : true, text : '授权', cls : '', toggleHandler : roleAuth }, '-', { pressed : true, enableToggle : true, text : '取消', cls : '', toggleHandler: roleCancel }); function roleAuth() { roleAuthDo(true); } function roleCancel() { roleAuthDo(false); } function roleAuthDo(isAuth) { //授权事件 var mRole = lightGrid.grid.getSelections(); var mResc = roleGrid.getSelections(); if(mResc.length <= 0) { Ext.MessageBox.alert('提示', '请选择至少一行纪录进行操作!'); return; } else { var ids = new Array(); for (var i = 0; i < mResc.length; i++) { var rescId = mResc[i].get('id'); ids[ids.length] = rescId; } var roleId = mRole[0].get('id'); Ext.lib.Ajax.request( 'POST', 'auth.htm', {success:end,failure:end}, 'ids=' + ids.join(",") + "&userId=" + roleId + "&isAuth=" + isAuth ); } roleStore.reload(); } function end() { Ext.Msg.alert("提示", "操作成功"); roleStore.reload(); } function selectRole() { var m = lightGrid.grid.getSelections(); if(m.length <= 0) { Ext.MessageBox.alert('提示', '请选择需要配置的用户!'); return; } // 读取数据需要的参数 roleStore.on('beforeload', function() { roleStore.baseParams = { id : lightGrid.grid.getSelections()[0].get('id') }; }); roleStore.load({params:{ start : 0, limit : 10 }}); var roleDialog = Ext.lingo.FormUtils.createLayoutDialog("role-dlg"); var layout = roleDialog.getLayout(); layout.beginUpdate(); layout.add('center', new Ext.ContentPanel('role-inner', {title: '选择角色'})); layout.endUpdate(); roleDialog.show(Ext.get("config")); } });
JavaScript
/** * Modify the details of the employee. * @param {object} employee The employee. * @param {integer} newDetails * @config {string} [title] The new job title. * @config {number} [salary] The new salary. */ function modify(employee, newDetails) { if (newDetails.title != undefined) employee.title = newDetails.title; if (newDetails.salary != undefined) employee.salary = newDetails.salary; }
JavaScript
document.write("<script src='test.js'></script>"); function testAdd() { assertEquals(add(1, 1), 2); }
JavaScript
/** * @param a 第一个加数 * @param b 第二个加数 * @returns 两个数的和 * @type Integer */ function add(a, b) { return a + b; alert('a'); }
JavaScript
/** * @param conf 初始化配置 */ Night = function(conf) { }; /** * @param a first * @param b second * @returns add result */ Night.prototype.add = function(a, b) { return a + b; };
JavaScript
// Author: Ilija Studen for the purposes of Uni–Form // Modified by Aris Karageorgos to use the parents function // Modified by Toni Karlheinz to support input fields' text // coloring and removal of their initial values on focus jQuery.fn.uniform = function(settings) { settings = jQuery.extend({ valid_class : 'valid', invalid_class : 'invalid', focused_class : 'focused', holder_class : 'element', field_selector : ':text, textarea', default_value_color: "#AFAFAF" }, settings); return this.each(function() { var form = jQuery(this); form.submit(function(){ form.find(settings.field_selector).each(function(){ if($(this).val() == $(this).attr("default_value")) $(this).val(""); }); }); // Select form fields and attach them higlighter functionality form.find(settings.field_selector).each(function(){ var default_value = $(this).val(); var default_color = $(this).css("color"); if($(this).val() == default_value){$(this).css("color",settings.default_value_color);}; $(this).attr("default_value", default_value); $(this).focus(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); $(this).parents().filter('.'+settings.holder_class+':first').addClass(settings.focused_class); if($(this).val() == default_value){ $(this).val("");$(this).css("color",default_color); }; }).blur(function() { form.find('.' + settings.focused_class).removeClass(settings.focused_class); if($(this).val() == ""){$(this).css("color",settings.default_value_color);$(this).val(default_value);}; }); }) }); }; // Auto set on page load... $(document).ready(function() { jQuery('form').uniform(); });
JavaScript
/** * jQuery jqGalScroll Plugin * Examples and documentation at: http://benjaminsterling.com/jquery-jqgalscroll-photo-gallery/ * * @author: Benjamin Sterling * @version: 2.1 * @copyright (c) 2007 Benjamin Sterling, KenzoMedia * @extendThanks Koesmanto Bong http://www.koesbong.com/ * Koes put a fire under my butt to improve this plugin * and when I took too long he took what I had and added * the horizontal scroll and in turn I ripped it from his * hands and made it better :) * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @requires jQuery v1.2.1 or later * @optional jQuery Easing v1.2 * * @name jqGalScroll * @example $('ul').jqGalScroll(); * * @Semantic requirements: * The structure fairly simple; the structure should consist * of a ul > li > img structure. * * <ul> * <li><img src="common/img/dsc_0003.thumbnail.JPG"/></li> * <li><img src="common/img/dsc_0012.thumbnail.JPG"/></li> * </ul> * * @param String ease * refer to http://gsgd.co.uk/sandbox/jquery.easing.php for values * * @example $('#gallery').jqGalScroll({speed:1000}); * @param String speed * fast, slow, 1000, ext.. * * @example $('#gallery').jqGalScroll({speed:1000}); * * @param String height * the default height of your wrapper * * @example $('#gallery').jqGalScroll({height:490}); * * @param String titleOpacity * the opacity of your title bar (if present) * * @example $('#gallery').jqGalScroll({titleOpacity:.70}); * * @param String direction * vertical horizontal diagonal * * @example $('#gallery').jqGalScroll({direction:'vertical'}); * */ (function($) { $.fn.jqGalScroll = function(options){ return this.each(function(i){ var el = this el.curImage = 0; el.jqthis = $(this).css({position:'relative'}); el.jqchildren = el.jqthis.children(); el.opts = $.extend({}, jqGalScroll, options); el.index = i; el.totalChildren = el.jqchildren.size(); var width,height; switch(el.opts.direction){ case 'horizontal': width = el.totalChildren *el.opts.width; height = el.opts.height; break; case 'vertical': width = el.opts.width; height = el.totalChildren *el.opts.height; break; default: width = el.totalChildren *el.opts.width; height = el.totalChildren *el.opts.height; break; }; el.container = $('<div id="jqGS'+i+'" class="jqGSContainer">').css({position:'relative'}); el.ImgContainer = $('<div class="jqGSImgContainer" style="height:'+el.opts.height+'px;position:relative;overflow:hidden">') .css({height:el.opts.height,width:el.opts.width,position:'relative',overflow:'hidden'}); el.jqthis.css({height:height,width:width}); el.jqthis.wrap(el.container); el.jqthis.wrap(el.ImgContainer); el.pagination = $('<div class="jqGSPagination">'); el.jqthis.parent().parent().append(el.pagination); var jqul = $('<ul>').appendTo(el.pagination); var pos = {x:0,y:0}; el.jqchildren .each(function(j){ var selected = ''; if(j == 0) selected = 'selected'; var $a = $('<a href="#'+(j)+'" class="'+selected+'">'+(j+1)+'</a>').click(function(){ var href = this.index;//href.replace(/^.*#/, ''); el.pagination.find('.selected').removeClass('selected'); $(this).addClass('selected'); var params = {}; if( el.opts.direction == 'diagonal'){ params = {right:(el.opts.width*href),bottom:(el.opts.height*href)} } else if( el.opts.direction == 'vertical'){ params = {bottom:(el.opts.height*href)} } else if( el.opts.direction == 'horizontal'){ params = {right:(el.opts.width*href)} }; el.jqthis.stop().animate(params,el.opts.speed, el.opts.ease); index = href; return false; }); var n = $a.get(0); n.index = j; $('<li>').appendTo(jqul).append($a); if( el.opts.direction == 'diagonal'){ pos.x = j * el.opts.width; pos.y = j * el.opts.height; } else if( el.opts.direction == 'horizontal'){ pos.x = j * el.opts.width; } else if( el.opts.direction == 'vertical'){ pos.y = j * el.opts.height; }; var jqchild = $(this).css({overflow:'auto', height:el.opts.height,width:el.opts.width,position:'absolute',left:pos.x, top:pos.y}); var jqimg = jqchild.find('img').hide() if(jqimg.parent().is('a')){ var p = jqimg.parent(); jqimg.get(0).linkHref = p.attr('href'); p.remove(); jqimg.appendTo(jqchild); }; jqimg.click(function(){ var next = n.index + 1; if((n.index + 1) == el.totalChildren ){ el.pagination.find('[href$=#0]').click(); } else{ el.pagination.find('[href$=#'+next+']').click(); } }); var $loader = $('<div class="jqGSLoader">').appendTo(jqchild); var $titleHolder = $('<div class="jqGSTitle">').appendTo(jqchild).css({opacity:el.opts.titleOpacity}).hide(); var image = new Image(); image.onload = function(){ image.onload = null; $loader.fadeOut(); jqimg.css({marginLeft:-image.width*.5,marginTop:-image.height*.5,position:'absolute',left:'50%',top:'50%'}).fadeIn(); var alt = jqimg.attr('alt'); if(typeof alt != 'undefined'){ $titleHolder.text(alt).fadeIn(); } }; image.src = jqimg.attr('src'); }); }); // end : this.each(function() }; // end : $.fn.jqGalScroll jqGalScroll = { ease: null, speed:0, height: 500, width: 500, titleOpacity : .60, direction : 'horizontal' // vertical horizontal diagonal }; })(jQuery);
JavaScript
/** * Loads the special study into an iframe */ (function() { var specialStudyLoginPage = '/specialStudyLogin'; var pageUrl, sessId, specialStudyLoc; var listener; function loadSpecialStudy(specialStudyLocation, sessionId, pageToView, theListener) { pageUrl = pageToView; sessId = sessionId; specialStudyLoc = specialStudyLocation; listener = theListener; $.ajax({ url: specialStudyLocation, complete: completeCallback, }); } function completeCallback(xhr, textStatus) { if (xhr.status === 200 || xhr.status === 302) { $('#specialStudyFrame').bind('load', loadingSpecialStudyComplete); $('#specialStudyFrame').attr('src', buildUrl()); } else { $('#specialStudySpan').html('Cannot load Household Characteristics'); $('#specialStudyFrame').height(50); if (listener && listener.onLoadFailure) { listener.onLoadFailure(); } } } function buildUrl() { var target = specialStudyLoc + specialStudyLoginPage + '?openhdsSessionId=' + sessId + '&targetUrl=' + pageUrl; return target; } function loadingSpecialStudyComplete() { var iframe = $('#specialStudyFrame').get(0); // resetting the height is required because on post back // (when user hits save) the details page is not as tall // as the create page. If the height is not reset, it will // always return the height set on the initial page load $('#specialStudyFrame').css('height', ''); var iframeHeight = $(iframe.contentDocument).height(); $('#specialStudyFrame').css('height', iframeHeight + 'px'); $('#specialStudySpan').remove(); $('#specialStudyFrame').css('visibility', 'visible'); $(iframe.contentDocument).find('input').first().focus(); } window.loadSpecialStudy = loadSpecialStudy; })();
JavaScript
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
JavaScript
try { var pageTracker = _gat._getTracker("UA-18761191-1"); pageTracker._trackPageview(); } catch(err) {}
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function(config) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.toolbar = 'MyToolbar'; config.language = 'zh-cn'; //配置语言 config.toolbar_MyToolbar = [ ['NewPage', 'Preview'], ['Cut', 'Copy', 'Paste'], 'PasteText', 'PasteFromWord', '-', 'Scayt'], ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'], ['Image', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'], '/', ['Format'], ['Bold', 'Italic', 'Strike'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'], ['Link', 'Unlink', 'Anchor'] ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList'], ['-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['-', 'SelectAll'] ]; };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('placeholder','he',{placeholder:{title:'מאפייני שומר מקום',toolbar:'צור שומר מקום',text:'תוכן שומר המקום',edit:'ערוך שומר מקום',textMissing:'שומר המקום חייב להכיל טקסט.'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/*! * MultiUpload for xheditor * @requires xhEditor * * @author Yanis.Wang<yanis.wang@gmail.com> * @site http://xheditor.com/ * @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php) * * @Version: 0.9.2 (build 100505) */ var swfu,selQueue=[],selectID,arrMsg=[],allSize=0,uploadSize=0; function removeFile() { var file; if(!selectID)return; for(var i in selQueue) { file=selQueue[i]; if(file.id==selectID) { selQueue.splice(i,1); allSize-=file.size; swfu.cancelUpload(file.id); $('#'+file.id).remove(); selectID=null; break; } } $('#btnClear').hide(); if(selQueue.length==0)$('#controlBtns').hide(); } function startUploadFiles() { if(swfu.getStats().files_queued>0) { $('#controlBtns').hide(); swfu.startUpload(); } else alert('上传前请先添加文件'); } function setFileState(fileid,txt) { $('#'+fileid+'_state').text(txt); } function fileQueued(file)//队列添加成功 { for(var i in selQueue)if(selQueue[i].name==file.name){swfu.cancelUpload(file.id);return false;}//防止同名文件重复添加 if(selQueue.length==0)$('#controlBtns').show(); selQueue.push(file); allSize+=file.size; $('#listBody').append('<tr id="'+file.id+'"><td>'+file.name+'</td><td>'+formatBytes(file.size)+'</td><td id="'+file.id+'_state">就绪</td></tr>'); $('#'+file.id).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');}) .click(function(){selectID=file.id;$('#listBody tr').removeClass('select');$(this).removeClass('hover').addClass('select');$('#btnClear').show();}) } function fileQueueError(file, errorCode, message)//队列添加失败 { var errorName=''; switch (errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: errorName = "只能同时上传 "+this.settings.file_upload_limit+" 个文件"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: errorName = "选择的文件超过了当前大小限制:"+this.settings.file_size_limit; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: errorName = "零大小文件"; break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: errorName = "文件扩展名必需为:"+this.settings.file_types_description+" ("+this.settings.file_types+")"; break; default: errorName = "未知错误"; break; } alert(errorName); } function uploadStart(file)//单文件上传开始 { setFileState(file.id,'上传中…'); } function uploadProgress(file, bytesLoaded, bytesTotal)//单文件上传进度 { var percent=Math.ceil((uploadSize+bytesLoaded)/allSize*100); $('#progressBar span').text(percent+'% ('+formatBytes(uploadSize+bytesLoaded)+' / '+formatBytes(allSize)+')'); $('#progressBar div').css('width',percent+'%'); } function uploadSuccess(file, serverData)//单文件上传成功 { var data=Object; try{eval("data=" + serverData);}catch(ex){}; if(data.err!=undefined&&data.msg!=undefined) { if(!data.err) { uploadSize+=file.size; arrMsg.push(data.msg); setFileState(file.id,'上传成功'); } else { setFileState(file.id,'上传失败'); alert(data.err); } } else setFileState(file.id,'上传失败!'); } function uploadError(file, errorCode, message)//单文件上传错误 { setFileState(file.id,'上传失败!'); } function uploadComplete(file)//文件上传周期结束 { if(swfu.getStats().files_queued>0)swfu.startUpload(); else uploadAllComplete(); } function uploadAllComplete()//全部文件上传成功 { callback(arrMsg); } function formatBytes(bytes) { var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB']; var e = Math.floor(Math.log(bytes)/Math.log(1024)); return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e]; }
JavaScript
/* * jQuery UI Accordion 1.6 * * Copyright (c) 2007 Jörn Zaefferer * * http://docs.jquery.com/UI/Accordion * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.accordion.js 4876 2008-03-08 11:49:04Z joern.zaefferer $ * */ ;(function($) { // If the UI scope is not available, add it $.ui = $.ui || {}; $.fn.extend({ accordion: function(options, data) { var args = Array.prototype.slice.call(arguments, 1); return this.each(function() { if (typeof options == "string") { var accordion = $.data(this, "ui-accordion"); accordion[options].apply(accordion, args); // INIT with optional options } else if (!$(this).is(".ui-accordion")) $.data(this, "ui-accordion", new $.ui.accordion(this, options)); }); }, // deprecated, use accordion("activate", index) instead activate: function(index) { return this.accordion("activate", index); } }); $.ui.accordion = function(container, options) { // setup configuration this.options = options = $.extend({}, $.ui.accordion.defaults, options); this.element = container; $(container).addClass("ui-accordion"); if ( options.navigation ) { var current = $(container).find("a").filter(options.navigationFilter); if ( current.length ) { if ( current.filter(options.header).length ) { options.active = current; } else { options.active = current.parent().parent().prev(); current.addClass("current"); } } } // calculate active if not specified, using the first header options.headers = $(container).find(options.header); options.active = findActive(options.headers, options.active); if ( options.fillSpace ) { var maxHeight = $(container).parent().height(); options.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; options.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(maxHeight - maxPadding); } else if ( options.autoheight ) { var maxHeight = 0; options.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } options.headers .not(options.active || "") .next() .hide(); options.active.parent().andSelf().addClass(options.selectedClass); if (options.event) $(container).bind((options.event) + ".ui-accordion", clickHandler); }; $.ui.accordion.prototype = { activate: function(index) { // call clickHandler with custom event clickHandler.call(this.element, { target: findActive( this.options.headers, index )[0] }); }, enable: function() { this.options.disabled = false; }, disable: function() { this.options.disabled = true; }, destroy: function() { this.options.headers.next().css("display", ""); if ( this.options.fillSpace || this.options.autoheight ) { this.options.headers.next().css("height", ""); } $.removeData(this.element, "ui-accordion"); $(this.element).removeClass("ui-accordion").unbind(".ui-accordion"); } } function scopeCallback(callback, scope) { return function() { return callback.apply(scope, arguments); }; } function completed(cancel) { // if removed while animated data can be empty if (!$.data(this, "ui-accordion")) return; var instance = $.data(this, "ui-accordion"); var options = instance.options; options.running = cancel ? 0 : --options.running; if ( options.running ) return; if ( options.clearStyle ) { options.toShow.add(options.toHide).css({ height: "", overflow: "" }); } $(this).triggerHandler("change.ui-accordion", [options.data], options.change); } function toggle(toShow, toHide, data, clickedActive, down) { var options = $.data(this, "ui-accordion").options; options.toShow = toShow; options.toHide = toHide; options.data = data; var complete = scopeCallback(completed, this); // count elements to animate options.running = toHide.size() == 0 ? toShow.size() : toHide.size(); if ( options.animated ) { if ( !options.alwaysOpen && clickedActive ) { $.ui.accordion.animations[options.animated]({ toShow: jQuery([]), toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } else { $.ui.accordion.animations[options.animated]({ toShow: toShow, toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } } else { if ( !options.alwaysOpen && clickedActive ) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } } function clickHandler(event) { var options = $.data(this, "ui-accordion").options; if (options.disabled) return false; // called only when using activate(false) to close all parts programmatically if ( !event.target && !options.alwaysOpen ) { options.active.parent().andSelf().toggleClass(options.selectedClass); var toHide = options.active.next(), data = { instance: this, options: options, newHeader: jQuery([]), oldHeader: options.active, newContent: jQuery([]), oldContent: toHide }, toShow = options.active = $([]); toggle.call(this, toShow, toHide, data ); return false; } // get the click target var clicked = $(event.target); // due to the event delegation model, we have to check if one // of the parent elements is our actual header, and find that if ( clicked.parents(options.header).length ) while ( !clicked.is(options.header) ) clicked = clicked.parent(); var clickedActive = clicked[0] == options.active[0]; // if animations are still active, or the active header is the target, ignore click if (options.running || (options.alwaysOpen && clickedActive)) return false; if (!clicked.is(options.header)) return; // switch classes options.active.parent().andSelf().toggleClass(options.selectedClass); if ( !clickedActive ) { clicked.parent().andSelf().addClass(options.selectedClass); } // find elements to show and hide var toShow = clicked.next(), toHide = options.active.next(), //data = [clicked, options.active, toShow, toHide], data = { instance: this, options: options, newHeader: clicked, oldHeader: options.active, newContent: toShow, oldContent: toHide }, down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] ); options.active = clickedActive ? $([]) : clicked; toggle.call(this, toShow, toHide, data, clickedActive, down ); return false; }; function findActive(headers, selector) { return selector != undefined ? typeof selector == "number" ? headers.filter(":eq(" + selector + ")") : headers.not(headers.not(selector)) : selector === false ? $([]) : headers.filter(":eq(0)"); } $.extend($.ui.accordion, { defaults: { selectedClass: "selected", alwaysOpen: true, animated: 'slide', event: "click", header: "a", autoheight: true, running: 0, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } var hideHeight = options.toHide.height(), showHeight = options.toShow.height(), difference = showHeight / hideHeight; options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{ step: function(now) { var current = (hideHeight - now) * difference; if ($.browser.msie || $.browser.opera) { current = Math.ceil(current); } options.toShow.height( current ); }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoheight ) { options.toShow.css("height", "auto"); } options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "bounceout" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }) } } }); })(jQuery);
JavaScript
/* * jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php * * Uses the built in easing capabilities added in jQuery 1.1 * to offer multiple easing options * * Copyright (c) 2007 George Smith * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ jQuery.extend(jQuery.easing, { easein: function(x, t, b, c, d) { return c*(t/=d)*t + b; // in }, easeinout: function(x, t, b, c, d) { if (t < d/2) return 2*c*t*t/(d*d) + b; var ts = t - d/2; return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b; }, easeout: function(x, t, b, c, d) { return -c*t*t/(d*d) + 2*c*t/d + b; }, expoin: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } return flip * (Math.exp(Math.log(c)/d * t)) + b; }, expoout: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b; }, expoinout: function(x, t, b, c, d) { var flip = 1; if (c < 0) { flip *= -1; c *= -1; } if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b; return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b; }, bouncein: function(x, t, b, c, d) { return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b; }, bounceout: function(x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, bounceinout: function(x, t, b, c, d) { if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b; return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b; }, elasin: function(x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, elasout: function(x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, elasinout: function(x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, backin: function(x, t, b, c, d) { var s=1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, backout: function(x, t, b, c, d) { var s=1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, backinout: function(x, t, b, c, d) { var s=1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; } });
JavaScript
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * $LastChangedDate: 2007-10-06 20:11:15 +0200 (Sa, 06 Okt 2007) $ * $Rev: 3581 $ * * Version: @VERSION * * Requires: jQuery 1.2+ */ (function($){ $.dimensions = { version: '@VERSION' }; // Create innerHeight, innerWidth, outerHeight and outerWidth methods $.each( [ 'Height', 'Width' ], function(i, name){ // innerHeight and innerWidth $.fn[ 'inner' + name ] = function() { if (!this[0]) return; var torl = name == 'Height' ? 'Top' : 'Left', // top or left borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right return num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr); }; // outerHeight and outerWidth $.fn[ 'outer' + name ] = function(options) { if (!this[0]) return; var torl = name == 'Height' ? 'Top' : 'Left', // top or left borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right options = $.extend({ margin: false }, options || {}); return num( this, name.toLowerCase() ) + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width') + num(this, 'padding' + torl) + num(this, 'padding' + borr) + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0); }; }); // Create scrollLeft and scrollTop methods $.each( ['Left', 'Top'], function(i, name) { $.fn[ 'scroll' + name ] = function(val) { if (!this[0]) return; return val != undefined ? // Set the scroll offset this.each(function() { this == window || this == document ? window.scrollTo( name == 'Left' ? val : $(window)[ 'scrollLeft' ](), name == 'Top' ? val : $(window)[ 'scrollTop' ]() ) : this[ 'scroll' + name ] = val; }) : // Return the scroll offset this[0] == window || this[0] == document ? self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] || $.boxModel && document.documentElement[ 'scroll' + name ] || document.body[ 'scroll' + name ] : this[0][ 'scroll' + name ]; }; }); $.fn.extend({ position: function() { var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results; if (elem) { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); parentOffset = offsetParent.offset(); // Subtract element margins offset.top -= num(elem, 'marginTop'); offset.left -= num(elem, 'marginLeft'); // Add offsetParent borders parentOffset.top += num(offsetParent, 'borderTopWidth'); parentOffset.left += num(offsetParent, 'borderLeftWidth'); // Subtract the two offsets results = { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } return results; }, offsetParent: function() { var offsetParent = this[0].offsetParent; while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') ) offsetParent = offsetParent.offsetParent; return $(offsetParent); } }); function num(el, prop) { return parseInt($.css(el.jquery?el[0]:el,prop))||0; }; })(jQuery);
JavaScript
 //表格的高亮显示效果 //此数组储存需要添加效果的Table.Id function trHightLight(tablesId) { for (i = 0; i < tablesId.length; i++) { $("#" + tablesId[i] + " tr").mouseover(function() { $(this).addClass("trHightLight"); }); $("#" + tablesId[i] + " tr").mouseout(function() { $(this).removeClass("trHightLight"); }); } }
JavaScript
jQuery().ready(function() { jQuery('#navigation').accordion({ header: '.head', navigation1: true, event: 'click', fillSpace: true, animated: 'bounceslide' }); }); //设置选择的菜单 function menuChange(activeid) { var obj = activeid var links = $("#navigation").find("a"); for (var i = 0; i < links.length; i++) { if (links[i].className == "Selected") { links[i].className = ""; } } obj.className = "Selected"; }
JavaScript
var mapWidth = 512; var mapHeight = 320; var mapType; var center_lat = 0; var center_lng = 0; var marker_lat = 0; var marker_lng = 0; var setZoom = 3; var map,marker; function initMap(zoom) { var mapOptions={zoom: 3,streetViewControl: false,scaleControl: true,mapTypeId: google.maps.MapTypeId.ROADMAP}; map = new google.maps.Map($('#mapArea')[0], mapOptions); google.maps.event.addListener(map, 'maptypeid_changed', function(event) { mapType=map.getMapTypeId(); }); google.maps.event.addListener(map, 'tilesloaded', function(event) { center_lat = map.getCenter().lat(); center_lng = map.getCenter().lng(); setZoom = map.getZoom(); }); google.maps.event.addListener(map, 'center_changed', function(event) { center_lat = map.getCenter().lat(); center_lng = map.getCenter().lng(); setZoom = map.getZoom(); }); marker = new google.maps.Marker({map:map,draggable:true}); google.maps.event.addListener(marker, 'dragend', function(event) { marker_lat = marker.getPosition().lat(); marker_lng = marker.getPosition().lng(); }); searchMap(); } function searchMap(zoom){ var address = $('#address').val(); var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var tlatlng=results[0].geometry.location; if(zoom)map.setZoom(zoom); map.setCenter(tlatlng); marker.setPosition(tlatlng); marker.setTitle(address); } else alert(address + " 地址错误,未找到当前地址"); }); } function pasteMap() { if (marker_lat == 0) marker_lat = center_lat; if (marker_lng == 0) marker_lng = center_lng; callback("http://maps.google.com/maps/api/staticmap?center=" + center_lat + ',' + center_lng + "&zoom=" + setZoom + "&size=" + mapWidth + 'x' + mapHeight + "&maptype=" + mapType + "&markers=" + marker_lat + ',' + marker_lng + "&sensor=false"); } function pageInit() { $('#address').keypress(function(ev){if(ev.which==13)searchMap(10);}); $('#mapsearch').click(function(){searchMap(10);}); $('#addMap').click(pasteMap); } $(pageInit);
JavaScript
/** * password_strength_plugin.js * Copyright (c) 2009 myPocket technologies (www.mypocket-technologies.com) * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * View the GNU General Public License <http://www.gnu.org/licenses/>. * @author Darren Mason (djmason9@gmail.com) * @date 3/13/2009 * @projectDescription Password Strength Meter is a jQuery plug-in provide you smart algorithm to detect a password strength. Based on Firas Kassem orginal plugin - http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/ * @version 1.0.1 * * @requires jquery.js (tested with 1.3.2) * @param shortPass: "shortPass", //optional * @param badPass: "badPass", //optional * @param goodPass: "goodPass", //optional * @param strongPass: "strongPass", //optional * @param baseStyle: "testresult", //optional * @param userid: "", //required override * @param messageloc: 1 //before == 0 or after == 1 * */ (function($){ $.fn.shortPass = 'Too short'; $.fn.badPass = 'Weak'; $.fn.goodPass = 'Good'; $.fn.strongPass = 'Strong'; $.fn.samePassword = 'Username and Password identical.'; $.fn.resultStyle = ""; $.fn.passStrength = function(options) { var defaults = { shortPass: "shortPass", //optional badPass: "badPass", //optional goodPass: "goodPass", //optional strongPass: "strongPass", //optional baseStyle: "testresult", //optional userid: "", //required override messageloc: 1 //before == 0 or after == 1 }; var opts = $.extend(defaults, options); return this.each(function() { var obj = $(this); $(obj).unbind().keyup(function() { var results = $.fn.teststrength($(this).val(),$(opts.userid).val(),opts); if(opts.messageloc === 1) { $(this).next("." + opts.baseStyle).remove(); $(this).after("<span class=\""+opts.baseStyle+"\"><span></span></span>"); $(this).next("." + opts.baseStyle).addClass($(this).resultStyle).find("span").text(results); } else { $(this).prev("." + opts.baseStyle).remove(); $(this).before("<span class=\""+opts.baseStyle+"\"><span></span></span>"); $(this).prev("." + opts.baseStyle).addClass($(this).resultStyle).find("span").text(results); } }); //FUNCTIONS $.fn.teststrength = function(password,username,option){ var score = 0; //password < 4 if (password.length < 4 ) { this.resultStyle = option.shortPass;return $(this).shortPass; } //password == user name if (password.toLowerCase()==username.toLowerCase()){this.resultStyle = option.badPass;return $(this).samePassword;} //password length score += password.length * 4; score += ( $.fn.checkRepetition(1,password).length - password.length ) * 1; score += ( $.fn.checkRepetition(2,password).length - password.length ) * 1; score += ( $.fn.checkRepetition(3,password).length - password.length ) * 1; score += ( $.fn.checkRepetition(4,password).length - password.length ) * 1; //password has 3 numbers if (password.match(/(.*[0-9].*[0-9].*[0-9])/)){ score += 5;} //password has 2 symbols if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){ score += 5 ;} //password has Upper and Lower chars if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){ score += 10;} //password has number and chars if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){ score += 15;} // //password has number and symbol if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/)){ score += 15;} //password has char and symbol if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/)){score += 15;} //password is just a numbers or chars if (password.match(/^\w+$/) || password.match(/^\d+$/) ){ score -= 10;} //verifying 0 < score < 100 if ( score < 0 ){score = 0;} if ( score > 100 ){ score = 100;} if (score < 34 ){ this.resultStyle = option.badPass; return $(this).badPass;} if (score < 68 ){ this.resultStyle = option.goodPass;return $(this).goodPass;} this.resultStyle= option.strongPass; return $(this).strongPass; }; }); }; })(jQuery); $.fn.checkRepetition = function(pLen,str) { var res = ""; for (var i=0; i<str.length ; i++ ) { var repeated=true; for (var j=0;j < pLen && (j+i+pLen) < str.length;j++){ repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen)); } if (j<pLen){repeated=false;} if (repeated) { i+=pLen-1; repeated=false; } else { res+=str.charAt(i); } } return res; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to deal with WebGL * programs. */ tdl.provide('tdl.programs'); tdl.require('tdl.log'); tdl.require('tdl.string'); tdl.require('tdl.webgl'); /** * A module for programs. * @namespace */ tdl.programs = tdl.programs || {}; /** * Loads a program from script tags. * @param {string} vertexShaderId The id of the script tag that contains the * vertex shader source. * @param {string} fragmentShaderId The id of the script tag that contains the * fragment shader source. * @return {tdl.programs.Program} The created program. */ tdl.programs.loadProgramFromScriptTags = function( vertexShaderId, fragmentShaderId) { var vertElem = document.getElementById(vertexShaderId); var fragElem = document.getElementById(fragmentShaderId); if (!vertElem) { throw("Can't find vertex program tag: " + vertexShaderId); } if (!fragElem) { throw("Can't find fragment program tag: " + fragmentShaderId); } return tdl.programs.loadProgram( document.getElementById(vertexShaderId).text, document.getElementById(fragmentShaderId).text); }; tdl.programs.makeProgramId = function(vertexShader, fragmentShader) { return vertexShader + fragmentShader; }; /** * Loads a program. * @param {string} vertexShader The vertex shader source. * @param {string} fragmentShader The fragment shader source. * @param {!function(error)) opt_asyncCallback. Called with * undefined if success or string if failure. * @return {tdl.programs.Program} The created program. */ tdl.programs.loadProgram = function(vertexShader, fragmentShader, opt_asyncCallback) { var id = tdl.programs.makeProgramId(vertexShader, fragmentShader); tdl.programs.init_(); var program = gl.tdl.programs.programDB[id]; if (program) { if (opt_asyncCallback) { setTimeout(function() { opt_asyncCallback(); }, 1); } return program; } try { program = new tdl.programs.Program(vertexShader, fragmentShader, opt_asyncCallback); } catch (e) { tdl.error(e); return null; } if (!opt_asyncCallback) { gl.tdl.programs.programDB[id] = program; } return program; }; /** * A object to manage a WebGLProgram. * @constructor * @param {string} vertexShader The vertex shader source. * @param {string} fragmentShader The fragment shader source. * @param {!function(error)) opt_asyncCallback. Called with * undefined if success or string if failure. */ tdl.programs.Program = function(vertexShader, fragmentShader, opt_asyncCallback) { var that = this; this.programId = tdl.programs.makeProgramId(vertexShader, fragmentShader); this.asyncCallback = opt_asyncCallback; var shaderId; var program; var vs; var fs; /** * Loads a shader. * @param {!WebGLContext} gl The WebGLContext to use. * @param {string} shaderSource The shader source. * @param {number} shaderType The type of shader. * @return {!WebGLShader} The created shader. */ var loadShader = function(gl, shaderSource, shaderType) { shaderId = shaderSource + shaderType; tdl.programs.init_(); var shader = gl.tdl.programs.shaderDB[shaderId]; if (shader) { return shader; } // Create the shader object var shader = gl.createShader(shaderType); // Load the shader source gl.shaderSource(shader, shaderSource); // Compile the shader gl.compileShader(shader); // Check the compile status if (!that.asyncCallback) { checkShader(shader); } return shader; } var checkShader = function(shader) { var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled && !gl.isContextLost()) { // Something went wrong during compilation; get the error tdl.programs.lastError = gl.getShaderInfoLog(shader); gl.deleteShader(shader); throw("*** Error compiling shader :" + tdl.programs.lastError); } gl.tdl.programs.shaderDB[shaderId] = shader; }; /** * Loads shaders from script tags, creates a program, attaches the shaders and * links. * @param {!WebGLContext} gl The WebGLContext to use. * @param {string} vertexShader The vertex shader. * @param {string} fragmentShader The fragment shader. * @return {!WebGLProgram} The created program. */ var loadProgram = function(gl, vertexShader, fragmentShader) { var e; try { vs = loadShader(gl, vertexShader, gl.VERTEX_SHADER); fs = loadShader(gl, fragmentShader, gl.FRAGMENT_SHADER); program = gl.createProgram(); gl.attachShader(program, vs); gl.attachShader(program, fs); linkProgram(gl, program); } catch (e) { deleteAll(e); } return program; }; var deleteAll = function(e) { if (vs) { gl.deleteShader(vs) } if (fs) { gl.deleteShader(fs) } if (program) { gl.deleteProgram(program) } throw e; }; /** * Links a WebGL program, throws if there are errors. * @param {!WebGLContext} gl The WebGLContext to use. * @param {!WebGLProgram} program The WebGLProgram to link. */ var linkProgram = function(gl, program) { // Link the program gl.linkProgram(program); // Check the link status if (!that.asyncCallback) { checkProgram(program); } }; var checkProgram = function(program) { var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked && !gl.isContextLost()) { // something went wrong with the link tdl.programs.lastError = gl.getProgramInfoLog (program); throw("*** Error in program linking:" + tdl.programs.lastError); } }; // Compile shaders var program = loadProgram(gl, vertexShader, fragmentShader); if (!program && !gl.isContextLost()) { throw ("could not compile program"); } // TODO(gman): remove the need for this. function flatten(array){ var flat = []; for (var i = 0, l = array.length; i < l; i++) { var type = Object.prototype.toString.call(array[i]).split(' ').pop().split(']').shift().toLowerCase(); if (type) { flat = flat.concat(/^(array|collection|arguments|object)$/.test(type) ? flatten(array[i]) : array[i]); } } return flat; } function createSetters(program) { // Look up attribs. var attribs = { }; // Also make a plain table of the locs. var attribLocs = { }; function createAttribSetter(info, index) { if (info.size != 1) { throw("arrays of attribs not handled"); } return function(b) { gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer()); gl.enableVertexAttribArray(index); gl.vertexAttribPointer( index, b.numComponents(), b.type(), b.normalize(), b.stride(), b.offset()); }; } var numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); for (var ii = 0; ii < numAttribs; ++ii) { var info = gl.getActiveAttrib(program, ii); if (!info) { break; } var name = info.name; if (tdl.string.endsWith(name, "[0]")) { name = name.substr(0, name.length - 3); } var index = gl.getAttribLocation(program, info.name); attribs[name] = createAttribSetter(info, index); attribLocs[name] = index } // Look up uniforms var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); var uniforms = { }; var textureUnit = 0; function createUniformSetter(info) { var loc = gl.getUniformLocation(program, info.name); var type = info.type; if (info.size > 1 && tdl.string.endsWith(info.name, "[0]")) { // It's an array. if (type == gl.FLOAT) return function() { var old; return function(v) { if (v !== old) { old = v; gl.uniform1fv(loc, v); } }; }(); if (type == gl.FLOAT_VEC2) return function() { // I hope they don't use -1,-1 as their first draw var old = new Float32Array([-1, -1]); return function(v) { if (v[0] != old[0] || v[1] != old[1]) { gl.uniform2fv(loc, v); } }; }(); if (type == gl.FLOAT_VEC3) return function() { // I hope they don't use -1,-1,-1 as their first draw var old = new Float32Array([-1, -1, -1]); return function(v) { if (v[0] != old[0] || v[1] != old[1] || v[2] != old[2]) { gl.uniform3fv(loc, v); } }; }(); if (type == gl.FLOAT_VEC4) return function(v) { gl.uniform4fv(loc, v); }; if (type == gl.INT) return function(v) { gl.uniform1iv(loc, v); }; if (type == gl.INT_VEC2) return function(v) { gl.uniform2iv(loc, v); }; if (type == gl.INT_VEC3) return function(v) { gl.uniform3iv(loc, v); }; if (type == gl.INT_VEC4) return function(v) { gl.uniform4iv(loc, v); }; if (type == gl.BOOL) return function(v) { gl.uniform1iv(loc, v); }; if (type == gl.BOOL_VEC2) return function(v) { gl.uniform2iv(loc, v); }; if (type == gl.BOOL_VEC3) return function(v) { gl.uniform3iv(loc, v); }; if (type == gl.BOOL_VEC4) return function(v) { gl.uniform4iv(loc, v); }; if (type == gl.FLOAT_MAT2) return function(v) { gl.uniformMatrix2fv(loc, false, v); }; if (type == gl.FLOAT_MAT3) return function(v) { gl.uniformMatrix3fv(loc, false, v); }; if (type == gl.FLOAT_MAT4) return function(v) { gl.uniformMatrix4fv(loc, false, v); }; if (type == gl.SAMPLER_2D || type == gl.SAMPLER_CUBE) { var units = []; for (var ii = 0; ii < info.size; ++ii) { units.push(textureUnit++); } return function(units) { return function(v) { gl.uniform1iv(loc, units); v.bindToUnit(units); }; }(units); } throw ("unknown type: 0x" + type.toString(16)); } else { if (type == gl.FLOAT) return function(v) { gl.uniform1f(loc, v); }; if (type == gl.FLOAT_VEC2) return function(v) { gl.uniform2fv(loc, v); }; if (type == gl.FLOAT_VEC3) return function(v) { gl.uniform3fv(loc, v); }; if (type == gl.FLOAT_VEC4) return function(v) { gl.uniform4fv(loc, v); }; if (type == gl.INT) return function(v) { gl.uniform1i(loc, v); }; if (type == gl.INT_VEC2) return function(v) { gl.uniform2iv(loc, v); }; if (type == gl.INT_VEC3) return function(v) { gl.uniform3iv(loc, v); }; if (type == gl.INT_VEC4) return function(v) { gl.uniform4iv(loc, v); }; if (type == gl.BOOL) return function(v) { gl.uniform1i(loc, v); }; if (type == gl.BOOL_VEC2) return function(v) { gl.uniform2iv(loc, v); }; if (type == gl.BOOL_VEC3) return function(v) { gl.uniform3iv(loc, v); }; if (type == gl.BOOL_VEC4) return function(v) { gl.uniform4iv(loc, v); }; if (type == gl.FLOAT_MAT2) return function(v) { gl.uniformMatrix2fv(loc, false, v); }; if (type == gl.FLOAT_MAT3) return function(v) { gl.uniformMatrix3fv(loc, false, v); }; if (type == gl.FLOAT_MAT4) return function(v) { gl.uniformMatrix4fv(loc, false, v); }; if (type == gl.SAMPLER_2D || type == gl.SAMPLER_CUBE) { return function(unit) { return function(v) { gl.uniform1i(loc, unit); v.bindToUnit(unit); }; }(textureUnit++); } throw ("unknown type: 0x" + type.toString(16)); } } var textures = {}; for (var ii = 0; ii < numUniforms; ++ii) { var info = gl.getActiveUniform(program, ii); if (!info) { break; } name = info.name; if (tdl.string.endsWith(name, "[0]")) { name = name.substr(0, name.length - 3); } var setter = createUniformSetter(info); uniforms[name] = setter; if (info.type == gl.SAMPLER_2D || info.type == gl.SAMPLER_CUBE) { textures[name] = setter; } } that.textures = textures; that.attrib = attribs; that.attribLoc = attribLocs; that.uniform = uniforms; } createSetters(program); this.loadNewShaders = function(vertexShaderSource, fragmentShaderSource) { var program = loadProgram(gl, vertexShaderSource, fragmentShaderSource); if (!program && !gl.isContextLost()) { throw ("could not compile program"); } that.program = program; createSetters(); }; this.program = program; this.good = this.asyncCallback ? false : true; var checkLater = function() { var e; try { checkShader(vs); checkShader(fs); checkProgram(program); } catch (e) { that.asyncCallback(e.toString()); return; } gl.tdl.programs.programDB[that.programId] = this; that.asyncCallback(); }; if (this.asyncCallback) { setTimeout(checkLater, 1000); } }; tdl.programs.handleContextLost_ = function() { if (gl.tdl && gl.tdl.programs && gl.tdl.programs.shaderDB) { delete gl.tdl.programs.shaderDB; delete gl.tdl.programs.programDB; } }; tdl.programs.init_ = function() { if (!gl.tdl.programs) { gl.tdl.programs = { }; tdl.webgl.registerContextLostHandler(gl.canvas, tdl.programs.handleContextLost_, true); } if (!gl.tdl.programs.shaderDB) { gl.tdl.programs.shaderDB = { }; gl.tdl.programs.programDB = { }; } }; tdl.programs.Program.prototype.use = function() { gl.useProgram(this.program); }; //function dumpValue(msg, name, value) { // var str; // if (value.length) { // str = value[0].toString(); // for (var ii = 1; ii < value.length; ++ii) { // str += "," + value[ii]; // } // } else { // str = value.toString(); // } // tdl.log(msg + name + ": " + str); //} tdl.programs.Program.prototype.setUniform = function(uniform, value) { var func = this.uniform[uniform]; if (func) { //dumpValue("SET UNI:", uniform, value); func(value); } };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to deal with basic webgl stuff. */ tdl.provide('tdl.webgl'); tdl.require('tdl.log'); tdl.require('tdl.misc'); /** * A module for log. * @namespace */ tdl.webgl = tdl.webgl || {}; /** * The current GL context * @type {WebGLRenderingContext} */ gl = null; tdl.webgl.makeCurrent = function(context) { gl = context; } /** * Creates the HTLM for a failure message * @param {string} canvasContainerId id of container of th * canvas. * @return {string} The html. */ tdl.webgl.makeFailHTML = function(msg) { return '' + '<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>' + '<td align="center">' + '<div style="display: table-cell; vertical-align: middle;">' + '<div style="">' + msg + '</div>' + '</div>' + '</td></tr></table>'; }; /** * Mesasge for getting a webgl browser * @type {string} */ tdl.webgl.GET_A_WEBGL_BROWSER = '' + 'This page requires a browser that supports WebGL.<br/>' + '<a href="http://get.webgl.org">Click here to upgrade your browser.</a>'; /** * Mesasge for need better hardware * @type {string} */ tdl.webgl.OTHER_PROBLEM = '' + "It does not appear your computer supports WebGL.<br/>" + '<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>'; /** * Creates a webgl context. * @param {Element} canvas. The canvas element to create a * context from. * @param {WebGLContextCreationAttirbutes} opt_attribs Any * creation attributes you want to pass in. * @param {function:(msg)} opt_onError An function to call * if there is an error during creation. * @return {!WebGLRenderingContext} The created context. */ tdl.webgl.setupWebGL = function(canvas, opt_attribs, opt_onError) { function handleCreationError(msg) { var container = canvas.parentNode; if (container) { var str = window.WebGLRenderingContext ? tdl.webgl.OTHER_PROBLEM : tdl.webgl.GET_A_WEBGL_BROWSER; if (msg) { str += "<br/><br/>Status: " + msg; } container.innerHTML = tdl.webgl.makeFailHTML(str); } }; opt_onError = opt_onError || handleCreationError; if (canvas.addEventListener) { canvas.addEventListener("webglcontextcreationerror", function(event) { opt_onError(event.statusMessage); }, false); } var context = tdl.webgl.create3DContext(canvas, opt_attribs); if (context) { if (canvas.addEventListener) { canvas.addEventListener("webglcontextlost", function(event) { //tdl.log("call tdl.webgl.handleContextLost"); event.preventDefault(); tdl.webgl.handleContextLost(canvas); }, false); canvas.addEventListener("webglcontextrestored", function(event) { //tdl.log("call tdl.webgl.handleContextRestored"); tdl.webgl.handleContextRestored(canvas); }, false); } } else { if (!window.WebGLRenderingContext) { opt_onError(""); } } return context; }; /** * Creates a webgl context. * @param {!Canvas} canvas The canvas tag to get context * from. If one is not passed in one will be created. * @return {!WebGLRenderingContext} The created context. */ tdl.webgl.create3DContext = function(canvas, opt_attribs) { if (opt_attribs === undefined) { opt_attribs = {alpha:false}; tdl.misc.applyUrlSettings(opt_attribs, 'webgl'); } var names = ["webgl", "experimental-webgl"]; var context = null; for (var ii = 0; ii < names.length; ++ii) { try { context = canvas.getContext(names[ii], opt_attribs); } catch(e) {} if (context) { break; } } if (context) { if (!tdl.webgl.glEnums) { tdl.webgl.init(context); } tdl.webgl.makeCurrent(context); tdl.webgl.setupCanvas_(canvas); context.tdl = {}; context.tdl.depthTexture = tdl.webgl.getExtensionWithKnownPrefixes("WEBGL_depth_texture"); // Disallow selection by default. This keeps the cursor from changing to an // I-beam when the user clicks and drags. It's easier on the eyes. function returnFalse() { return false; } canvas.onselectstart = returnFalse; canvas.onmousedown = returnFalse; } return context; }; tdl.webgl.setupCanvas_ = function(canvas) { if (!canvas.tdl) { canvas.tdl = {}; } }; /** * Browser prefixes for extensions. * @type {!Array.<string>} */ tdl.webgl.browserPrefixes_ = [ "", "MOZ_", "OP_", "WEBKIT_" ]; /** * Given an extension name like WEBGL_compressed_texture_s3tc * returns the supported version extension, like * WEBKIT_WEBGL_compressed_teture_s3tc * @param {string} name Name of extension to look for * @return {WebGLExtension} The extension or undefined if not * found. */ tdl.webgl.getExtensionWithKnownPrefixes = function(name) { for (var ii = 0; ii < tdl.webgl.browserPrefixes_.length; ++ii) { var prefixedName = tdl.webgl.browserPrefixes_[ii] + name; var ext = gl.getExtension(prefixedName); if (ext) { return ext; } } }; tdl.webgl.runHandlers_ = function(handlers) { //tdl.log("run handlers: " + handlers.length); var handlersCopy = handlers.slice(); for (var ii = 0; ii < handlersCopy.length; ++ii) { //tdl.log("run: " + ii); handlersCopy[ii](); } }; tdl.webgl.registerContextLostHandler = function( canvas, handler, opt_sysHandler) { tdl.webgl.setupCanvas_(canvas); if (!canvas.tdl.contextLostHandlers) { canvas.tdl.contextLostHandlers = [[],[]]; } var a = canvas.tdl.contextLostHandlers[opt_sysHandler ? 0 : 1]; a.push(handler); }; tdl.webgl.registerContextRestoredHandler = function( canvas, handler, opt_sysHandler) { tdl.webgl.setupCanvas_(canvas); if (!canvas.tdl.contextRestoredHandlers) { canvas.tdl.contextRestoredHandlers = [[],[]]; } var a = canvas.tdl.contextRestoredHandlers[opt_sysHandler ? 0 : 1]; a.push(handler); }; tdl.webgl.handleContextLost = function(canvas) { // first run tdl's handlers then the user's //tdl.log("tdl.webgl.handleContextLost"); if (canvas.tdl.contextLostHandlers) { tdl.webgl.runHandlers_(canvas.tdl.contextLostHandlers[0]); tdl.webgl.runHandlers_(canvas.tdl.contextLostHandlers[1]); } }; tdl.webgl.handleContextRestored = function(canvas) { // first run tdl's handlers then the user's //tdl.log("tdl.webgl.handleContextRestored"); if (canvas.tdl.contextRestoredHandlers) { tdl.webgl.runHandlers_(canvas.tdl.contextRestoredHandlers[0]); tdl.webgl.runHandlers_(canvas.tdl.contextRestoredHandlers[1]); } }; /** * Which arguements are enums. * @type {!Object.<number, string>} */ tdl.webgl.glValidEnumContexts = { // Generic setters and getters 'enable': { 0:true }, 'disable': { 0:true }, 'getParameter': { 0:true }, // Rendering 'drawArrays': { 0:true }, 'drawElements': { 0:true, 2:true }, // Shaders 'createShader': { 0:true }, 'getShaderParameter': { 1:true }, 'getProgramParameter': { 1:true }, // Vertex attributes 'getVertexAttrib': { 1:true }, 'vertexAttribPointer': { 2:true }, // Textures 'bindTexture': { 0:true }, 'activeTexture': { 0:true }, 'getTexParameter': { 0:true, 1:true }, 'texParameterf': { 0:true, 1:true }, 'texParameteri': { 0:true, 1:true, 2:true }, 'texImage2D': { 0:true, 2:true, 6:true, 7:true }, 'texSubImage2D': { 0:true, 6:true, 7:true }, 'copyTexImage2D': { 0:true, 2:true }, 'copyTexSubImage2D': { 0:true }, 'generateMipmap': { 0:true }, // Buffer objects 'bindBuffer': { 0:true }, 'bufferData': { 0:true, 2:true }, 'bufferSubData': { 0:true }, 'getBufferParameter': { 0:true, 1:true }, // Renderbuffers and framebuffers 'pixelStorei': { 0:true, 1:true }, 'readPixels': { 4:true, 5:true }, 'bindRenderbuffer': { 0:true }, 'bindFramebuffer': { 0:true }, 'checkFramebufferStatus': { 0:true }, 'framebufferRenderbuffer': { 0:true, 1:true, 2:true }, 'framebufferTexture2D': { 0:true, 1:true, 2:true }, 'getFramebufferAttachmentParameter': { 0:true, 1:true, 2:true }, 'getRenderbufferParameter': { 0:true, 1:true }, 'renderbufferStorage': { 0:true, 1:true }, // Frame buffer operations (clear, blend, depth test, stencil) 'clear': { 0:true }, 'depthFunc': { 0:true }, 'blendFunc': { 0:true, 1:true }, 'blendFuncSeparate': { 0:true, 1:true, 2:true, 3:true }, 'blendEquation': { 0:true }, 'blendEquationSeparate': { 0:true, 1:true }, 'stencilFunc': { 0:true }, 'stencilFuncSeparate': { 0:true, 1:true }, 'stencilMaskSeparate': { 0:true }, 'stencilOp': { 0:true, 1:true, 2:true }, 'stencilOpSeparate': { 0:true, 1:true, 2:true, 3:true }, // Culling 'cullFace': { 0:true }, 'frontFace': { 0:true } }; /** * Map of numbers to names. * @type {Object} */ tdl.webgl.glEnums = null; /** * Initializes this module. Safe to call more than once. * @param {!WebGLRenderingContext} ctx A WebGL context. If * you have more than one context it doesn't matter which one * you pass in, it is only used to pull out constants. */ tdl.webgl.init = function(ctx) { if (tdl.webgl.glEnums == null) { tdl.webgl.glEnums = { }; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'number') { tdl.webgl.glEnums[ctx[propertyName]] = propertyName; } } } }; /** * Checks the utils have been initialized. */ tdl.webgl.checkInit = function() { if (tdl.webgl.glEnums == null) { throw 'tdl.webgl.init(ctx) not called'; } }; /** * Returns true or false if value matches any WebGL enum * @param {*} value Value to check if it might be an enum. * @return {boolean} True if value matches one of the WebGL defined enums */ tdl.webgl.mightBeEnum = function(value) { tdl.webgl.checkInit(); return (tdl.webgl.glEnums[value] !== undefined); } /** * Gets an string version of an WebGL enum. * * Example: * var str = WebGLDebugUtil.glEnumToString(ctx.getError()); * * @param {number} value Value to return an enum for * @return {string} The string version of the enum. */ tdl.webgl.glEnumToString = function(value) { tdl.webgl.checkInit(); if (value === undefined) { return "undefined"; } var name = tdl.webgl.glEnums[value]; return (name !== undefined) ? name : ("*UNKNOWN WebGL ENUM (0x" + value.toString(16) + ")"); }; /** * Returns the string version of a WebGL argument. * Attempts to convert enum arguments to strings. * @param {string} functionName the name of the WebGL function. * @param {number} argumentIndx the index of the argument. * @param {*} value The value of the argument. * @return {string} The value as a string. */ tdl.webgl.glFunctionArgToString = function(functionName, argumentIndex, value) { var funcInfo = tdl.webgl.glValidEnumContexts[functionName]; if (funcInfo !== undefined) { if (funcInfo[argumentIndex]) { return tdl.webgl.glEnumToString(value); } } if (value === null) { return "null"; } else if (value === undefined) { return "undefined"; } else { return value.toString(); } }; /** * Converts the arguments of a WebGL function to a string. * Attempts to convert enum arguments to strings. * * @param {string} functionName the name of the WebGL function. * @param {number} args The arguments. * @return {string} The arguments as a string. */ tdl.webgl.glFunctionArgsToString = function(functionName, args) { // apparently we can't do args.join(","); var argStr = ""; for (var ii = 0; ii < args.length; ++ii) { argStr += ((ii == 0) ? '' : ', ') + tdl.webgl.glFunctionArgToString(functionName, ii, args[ii]); } return argStr; }; /** * Given a WebGL context returns a wrapped context that calls * gl.getError after every command and calls a function if the * result is not gl.NO_ERROR. * * @param {!WebGLRenderingContext} ctx The webgl context to * wrap. * @param {!function(err, funcName, args): void} opt_onErrorFunc * The function to call when gl.getError returns an * error. If not specified the default function calls * console.log with a message. * @param {!function(funcName, args): void} opt_onFunc The * function to call when each webgl function is called. * You can use this to log all calls for example. */ tdl.webgl.makeDebugContext = function(ctx, opt_onErrorFunc, opt_onFunc) { tdl.webgl.init(ctx); opt_onErrorFunc = opt_onErrorFunc || function(err, functionName, args) { tdl.error( "WebGL error "+ tdl.webgl.glEnumToString(err) + " in " + functionName + "(" + tdl.webgl.glFunctionArgsToString( functionName, args) + ")"); }; // Holds booleans for each GL error so after we get the error ourselves // we can still return it to the client app. var glErrorShadow = { }; // Makes a function that calls a WebGL function and then calls getError. function makeErrorWrapper(ctx, functionName) { return function() { if (opt_onFunc) { opt_onFunc(functionName, arguments); } try { var result = ctx[functionName].apply(ctx, arguments); } catch (e) { opt_onErrorFunc(ctx.NO_ERROR, functionName, arguments); throw(e); } var err = ctx.getError(); if (err != 0) { glErrorShadow[err] = true; opt_onErrorFunc(err, functionName, arguments); } return result; }; } function makePropertyWrapper(wrapper, original, propertyName) { wrapper.__defineGetter__(propertyName, function() { return original[propertyName]; }); // TODO(gmane): this needs to handle properties that take more than // one value? wrapper.__defineSetter__(propertyName, function(value) { original[propertyName] = value; }); } // Make a an object that has a copy of every property of the WebGL context // but wraps all functions. var wrapper = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'function') { wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); } else { makePropertyWrapper(wrapper, ctx, propertyName); } } // Override the getError function with one that returns our saved results. wrapper.getError = function() { for (var err in glErrorShadow) { if (glErrorShadow[err]) { glErrorShadow[err] = false; return err; } } return ctx.NO_ERROR; }; return wrapper; }; /** * Provides requestAnimationFrame in a cross browser way. * @param {function(RequestAnimationEvent): void} callback. Callback that will * be called when a frame is ready. * @param {!Element} element Element to request an animation frame for. * @return {number} request id. */ tdl.webgl.requestAnimationFrame = function(callback, element) { if (!tdl.webgl.requestAnimationFrameImpl_) { tdl.webgl.requestAnimationFrameImpl_ = function() { var functionNames = [ "requestAnimationFrame", "webkitRequestAnimationFrame", "mozRequestAnimationFrame", "oRequestAnimationFrame", "msRequestAnimationFrame" ]; for (var jj = 0; jj < functionNames.length; ++jj) { var functionName = functionNames[jj]; if (window[functionName]) { tdl.log("using ", functionName); return function(name) { return function(callback, element) { return window[name].call(window, callback, element); }; }(functionName); } } tdl.log("using window.setTimeout"); return function(callback, element) { return window.setTimeout(callback, 1000 / 70); }; }(); } return tdl.webgl.requestAnimationFrameImpl_(callback, element); }; /** * Provides cancelRequestAnimationFrame in a cross browser way. * @param {number} requestId. */ tdl.webgl.cancelRequestAnimationFrame = function(requestId) { if (!tdl.webgl.cancelRequestAnimationFrameImpl_) { tdl.webgl.cancelRequestAnimationFrameImpl_ = function() { var functionNames = [ "cancelRequestAnimationFrame", "webkitCancelRequestAnimationFrame", "mozCancelRequestAnimationFrame", "oCancelRequestAnimationFrame", "msCancelRequestAnimationFrame" ]; for (var jj = 0; jj < functionNames.length; ++jj) { var functionName = functionNames[jj]; if (window[functionName]) { return function(name) { return function(requestId) { window[name].call(window, requestId); }; }(functionName); } } return function(requestId) { window.clearTimeout(requestId); }; }(); } tdl.webgl.cancelRequestAnimationFrameImpl_(requestId); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains various functions for quaternion arithmetic * and converting between rotation matrices and quaternions. It adds them to * the "quaternions" module on the tdl object. Javascript arrays with * four entries are used to represent quaternions, and functions are provided * for doing operations on those. * * Operations are done assuming quaternions are of the form: * q[0] + q[1]i + q[2]j + q[3]k and using the hamiltonian rules for * multiplication as described on Brougham Bridge: * i^2 = j^2 = k^2 = ijk = -1. * */ tdl.provide('tdl.quaternions'); /** * A Module for quaternion math. * @namespace */ tdl.quaternions = tdl.quaternions || {}; /** * A Quaternion. * @type {!Array.<number>} */ tdl.quaternions.Quaternion = goog.typedef; /** * Quickly determines if the object a is a scalar or a quaternion; * assumes that the argument is either a number (scalar), or an array of * numbers. * @param {(number|!tdl.quaternions.Quaternion)} a A number or array the type * of which is in question. * @return {string} Either the string 'Scalar' or 'Quaternion'. */ tdl.quaternions.mathType = function(a) { if (typeof(a) === 'number') return 'Scalar'; return 'Quaternion'; }; /** * Creates an identity quaternion. * @return {!tdl.quaternions.Quaternion} The identity quaternion. */ tdl.quaternions.identity = function() { return [ 0, 0, 0, 1 ]; }; /** * Copies a quaternion. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.quaternions.Quaternion} A new quaternion identical to q. */ tdl.quaternions.copy = function(q) { return q.slice(); }; /** * Negates a quaternion. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.quaternions.Quaternion} -q. */ tdl.quaternions.negative = function(q) { return [-q[0], -q[1], -q[2], -q[3]]; }; /** * Adds two Quaternions. * @param {!tdl.quaternions.Quaternion} a Operand Quaternion. * @param {!tdl.quaternions.Quaternion} b Operand Quaternion. * @return {!tdl.quaternions.Quaternion} The sum of a and b. */ tdl.quaternions.addQuaternionQuaternion = function(a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]; }; /** * Adds a quaternion to a scalar. * @param {!tdl.quaternions.Quaternion} a Operand Quaternion. * @param {number} b Operand Scalar. * @return {!tdl.quaternions.Quaternion} The sum of a and b. */ tdl.quaternions.addQuaternionScalar = function(a, b) { return a.slice(0, 3).concat(a[3] + b); }; /** * Adds a scalar to a quaternion. * @param {number} a Operand scalar. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The sum of a and b. */ tdl.quaternions.addScalarQuaternion = function(a, b) { return b.slice(0, 3).concat(a + b[3]); }; /** * Subtracts two quaternions. * @param {!tdl.quaternions.Quaternion} a Operand quaternion. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The difference a - b. */ tdl.quaternions.subQuaternionQuaternion = function(a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2], a[3] - b[3]]; }; /** * Subtracts a scalar from a quaternion. * @param {!tdl.quaternions.Quaternion} a Operand quaternion. * @param {number} b Operand scalar. * @return {!tdl.quaternions.Quaternion} The difference a - b. */ tdl.quaternions.subQuaternionScalar = function(a, b) { return a.slice(0, 3).concat(a[3] - b); }; /** * Subtracts a quaternion from a scalar. * @param {number} a Operand scalar. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The difference a - b. */ tdl.quaternions.subScalarQuaternion = function(a, b) { return [-b[0], -b[1], -b[2], a - b[3]]; }; /** * Multiplies a scalar by a quaternion. * @param {number} k The scalar. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.quaternions.Quaternion} The product of k and q. */ tdl.quaternions.mulScalarQuaternion = function(k, q) { return [k * q[0], k * q[1], k * q[2], k * q[3]]; }; /** * Multiplies a quaternion by a scalar. * @param {!tdl.quaternions.Quaternion} q The Quaternion. * @param {number} k The scalar. * @return {!tdl.quaternions.Quaternion} The product of k and v. */ tdl.quaternions.mulQuaternionScalar = function(q, k) { return [k * q[0], k * q[1], k * q[2], k * q[3]]; }; /** * Multiplies two quaternions. * @param {!tdl.quaternions.Quaternion} a Operand quaternion. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The quaternion product a * b. */ tdl.quaternions.mulQuaternionQuaternion = function(a, b) { var aX = a[0]; var aY = a[1]; var aZ = a[2]; var aW = a[3]; var bX = b[0]; var bY = b[1]; var bZ = b[2]; var bW = b[3]; return [ aW * bX + aX * bW + aY * bZ - aZ * bY, aW * bY + aY * bW + aZ * bX - aX * bZ, aW * bZ + aZ * bW + aX * bY - aY * bX, aW * bW - aX * bX - aY * bY - aZ * bZ]; }; /** * Divides two quaternions; assumes the convention that a/b = a*(1/b). * @param {!tdl.quaternions.Quaternion} a Operand quaternion. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The quaternion quotient a / b. */ tdl.quaternions.divQuaternionQuaternion = function(a, b) { var aX = a[0]; var aY = a[1]; var aZ = a[2]; var aW = a[3]; var bX = b[0]; var bY = b[1]; var bZ = b[2]; var bW = b[3]; var d = 1 / (bW * bW + bX * bX + bY * bY + bZ * bZ); return [ (aX * bW - aW * bX - aY * bZ + aZ * bY) * d, (aX * bZ - aW * bY + aY * bW - aZ * bX) * d, (aY * bX + aZ * bW - aW * bZ - aX * bY) * d, (aW * bW + aX * bX + aY * bY + aZ * bZ) * d]; }; /** * Divides a Quaternion by a scalar. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @param {number} k The scalar. * @return {!tdl.quaternions.Quaternion} q The quaternion q divided by k. */ tdl.quaternions.divQuaternionScalar = function(q, k) { return [q[0] / k, q[1] / k, q[2] / k, q[3] / k]; }; /** * Divides a scalar by a quaternion. * @param {number} a Operand scalar. * @param {!tdl.quaternions.Quaternion} b Operand quaternion. * @return {!tdl.quaternions.Quaternion} The quaternion product. */ tdl.quaternions.divScalarQuaternion = function(a, b) { var b0 = b[0]; var b1 = b[1]; var b2 = b[2]; var b3 = b[3]; var d = 1 / (b0 * b0 + b1 * b1 + b2 * b2 + b3 * b3); return [-a * b0 * d, -a * b1 * d, -a * b2 * d, a * b3 * d]; }; /** * Computes the multiplicative inverse of a quaternion. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.quaternions.Quaternion} The multiplicative inverse of q. */ tdl.quaternions.inverse = function(q) { var q0 = q[0]; var q1 = q[1]; var q2 = q[2]; var q3 = q[3]; var d = 1 / (q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); return [-q0 * d, -q1 * d, -q2 * d, q3 * d]; }; /** * Multiplies two objects which are either scalars or quaternions. * @param {(!tdl.quaternions.Quaternion|number)} a Operand. * @param {(!tdl.quaternions.Quaternion|number)} b Operand. * @return {(!tdl.quaternions.Quaternion|number)} The product of a and b. */ tdl.quaternions.mul = function(a, b) { return tdl.quaternions['mul' + tdl.quaternions.mathType(a) + tdl.quaternions.mathType(b)](a, b); }; /** * Divides two objects which are either scalars or quaternions. * @param {(!tdl.quaternions.Quaternion|number)} a Operand. * @param {(!tdl.quaternions.Quaternion|number)} b Operand. * @return {(!tdl.quaternions.Quaternion|number)} The quotient of a and b. */ tdl.quaternions.div = function(a, b) { return tdl.quaternions['div' + tdl.quaternions.mathType(a) + tdl.quaternions.mathType(b)](a, b); }; /** * Adds two objects which are either scalars or quaternions. * @param {(!tdl.quaternions.Quaternion|number)} a Operand. * @param {(!tdl.quaternions.Quaternion|number)} b Operand. * @return {(!tdl.quaternions.Quaternion|number)} The sum of a and b. */ tdl.quaternions.add = function(a, b) { return tdl.quaternions['add' + tdl.quaternions.mathType(a) + tdl.quaternions.mathType(b)](a, b); }; /** * Subtracts two objects which are either scalars or quaternions. * @param {(!tdl.quaternions.Quaternion|number)} a Operand. * @param {(!tdl.quaternions.Quaternion|number)} b Operand. * @return {(!tdl.quaternions.Quaternion|number)} The difference of a and b. */ tdl.quaternions.sub = function(a, b) { return tdl.quaternions['sub' + tdl.quaternions.mathType(a) + tdl.quaternions.mathType(b)](a, b); }; /** * Computes the length of a Quaternion, i.e. the square root of the * sum of the squares of the coefficients. * @param {!tdl.quaternions.Quaternion} a The Quaternion. * @return {number} The length of a. */ tdl.quaternions.length = function(a) { return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]); }; /** * Computes the square of the length of a quaternion, i.e. the sum of the * squares of the coefficients. * @param {!tdl.quaternions.Quaternion} a The quaternion. * @return {number} The square of the length of a. */ tdl.quaternions.lengthSquared = function(a) { return a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]; }; /** * Divides a Quaternion by its length and returns the quotient. * @param {!tdl.quaternions.Quaternion} a The Quaternion. * @return {!tdl.quaternions.Quaternion} A unit length quaternion pointing in * the same direction as a. */ tdl.quaternions.normalize = function(a) { var d = 1 / Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2] + a[3] * a[3]); return [a[0] * d, a[1] * d, a[2] * d, a[3] * d]; }; /** * Computes the conjugate of the given quaternion. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.quaternions.Quaternion} The conjugate of q. */ tdl.quaternions.conjugate = function(q) { return [-q[0], -q[1], -q[2], q[3]]; }; /** * Creates a quaternion which rotates around the x-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.quaternions.Quaternion} The quaternion. */ tdl.quaternions.rotationX = function(angle) { return [Math.sin(angle / 2), 0, 0, Math.cos(angle / 2)]; }; /** * Creates a quaternion which rotates around the y-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.quaternions.Quaternion} The quaternion. */ tdl.quaternions.rotationY = function(angle) { return [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)]; }; /** * Creates a quaternion which rotates around the z-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.quaternions.Quaternion} The quaternion. */ tdl.quaternions.rotationZ = function(angle) { return [0, 0, Math.sin(angle / 2), Math.cos(angle / 2)]; }; /** * Creates a quaternion which rotates around the given axis by the given * angle. * @param {!tdl.math.Vector3} axis The axis about which to rotate. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.quaternions.Quaternion} A quaternion which rotates angle * radians around the axis. */ tdl.quaternions.axisRotation = function(axis, angle) { var d = 1 / Math.sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]); var sin = Math.sin(angle / 2); var cos = Math.cos(angle / 2); return [sin * axis[0] * d, sin * axis[1] * d, sin * axis[2] * d, cos]; }; /** * Computes a 4-by-4 rotation matrix (with trivial translation component) * given a quaternion. We assume the convention that to rotate a vector v by * a quaternion r means to express that vector as a quaternion q by letting * q = [v[0], v[1], v[2], 0] and then obtain the rotated vector by evaluating * the expression (r * q) / r. * @param {!tdl.quaternions.Quaternion} q The quaternion. * @return {!tdl.math.Matrix4} A 4-by-4 rotation matrix. */ tdl.quaternions.quaternionToRotation = function(q) { var qX = q[0]; var qY = q[1]; var qZ = q[2]; var qW = q[3]; var qWqW = qW * qW; var qWqX = qW * qX; var qWqY = qW * qY; var qWqZ = qW * qZ; var qXqW = qX * qW; var qXqX = qX * qX; var qXqY = qX * qY; var qXqZ = qX * qZ; var qYqW = qY * qW; var qYqX = qY * qX; var qYqY = qY * qY; var qYqZ = qY * qZ; var qZqW = qZ * qW; var qZqX = qZ * qX; var qZqY = qZ * qY; var qZqZ = qZ * qZ; var d = qWqW + qXqX + qYqY + qZqZ; return [ [(qWqW + qXqX - qYqY - qZqZ) / d, 2 * (qWqZ + qXqY) / d, 2 * (qXqZ - qWqY) / d, 0], [2 * (qXqY - qWqZ) / d, (qWqW - qXqX + qYqY - qZqZ) / d, 2 * (qWqX + qYqZ) / d, 0], [2 * (qWqY + qXqZ) / d, 2 * (qYqZ - qWqX) / d, (qWqW - qXqX - qYqY + qZqZ) / d, 0], [0, 0, 0, 1]]; }; /** * Computes a quaternion whose rotation is equivalent to the given matrix. * @param {(!tdl.math.Matrix4|!tdl.math.Matrix3)} m A 3-by-3 or 4-by-4 * rotation matrix. * @return {!tdl.quaternions.Quaternion} A quaternion q such that * quaternions.quaternionToRotation(q) is m. */ tdl.quaternions.rotationToQuaternion = function(m) { var u; var v; var w; // Choose u, v, and w such that u is the index of the biggest diagonal entry // of m, and u v w is an even permutation of 0 1 and 2. if (m[0][0] > m[1][1] && m[0][0] > m[2][2]) { u = 0; v = 1; w = 2; } else if (m[1][1] > m[0][0] && m[1][1] > m[2][2]) { u = 1; v = 2; w = 0; } else { u = 2; v = 0; w = 1; } var r = Math.sqrt(1 + m[u][u] - m[v][v] - m[w][w]); var q = []; q[u] = 0.5 * r; q[v] = 0.5 * (m[v][u] + m[u][v]) / r; q[w] = 0.5 * (m[u][w] + m[w][u]) / r; q[3] = 0.5 * (m[v][w] - m[w][v]) / r; return q; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to sync app settings across * browsers. */ tdl.provide('tdl.sync'); tdl.require('tdl.log'); tdl.require('tdl.io'); tdl.require('tdl.misc'); /** * A module for sync. * @namespace */ tdl.sync = tdl.sync || {}; /** * Manages synchronizing settings across browsers. Requires a server * running to support it. Note that even if you don't want to sync * across browsers you can still use the SyncManager. * * @constructor * @param {!Object} settings The object that contains the settings you * want kept in sync. */ tdl.sync.SyncManager = function(settings, opt_callback) { this.settings = settings; this.putCount = 0; this.getCount = 0; this.callback = opt_callback || function() {}; // This probably should not be here. tdl.misc.applyUrlSettings(settings); } /** * Initialize the sync manager to start syncing settings with a server. * @param {string} server domain name of server. * @param {number} port port of server. * @param {boolean} slave true if this page is a slave. Slaves only receive * settings from the server. Non slaves send settings the server. */ tdl.sync.SyncManager.prototype.init = function(url, slave) { var that = this; this.sync = true; this.slave = slave; this.socket = new WebSocket(url); this.opened = false; this.queued = []; this.socket.onopen = function(event) { tdl.log("SOCKET OPENED!"); that.opened = true; for (var ii = 0; ii < that.queued.length; ++ii) { var settings = that.queued[ii]; ++that.putCount; tdl.log("--PUT:[", that.putCount, "]-------------"); tdl.log(settings); that.socket.send(settings); } that.queued = []; }; this.socket.onerror = function(event) { tdl.log("SOCKET ERROR!"); }; this.socket.onclose = function(event) { tdl.log("SOCKET CLOSED!"); }; this.socket.onmessage = function(event) { ++that.getCount; tdl.log("--GET:[", g_getCount, ":", event.type, "]-------------"); var obj = JSON.parse(event.data); tdl.dumpObj(obj); tdl.misc.copyProperties(obj, that.settings); that.callback(obj); }; }; /** * Sets the settings. * * If we are synchronizing settings the settings are sent to the server. * Otherwise they are applied directy. * * @param {!Object} settings Object with new settings. */ tdl.sync.SyncManager.prototype.setSettings = function(settings) { if (this.sync) { if (!this.slave) { if (this.socket) { if (!this.opened) { this.queued.push(JSON.stringify(settings)); } else { ++this.putCount; tdl.log("--PUT:[", this.putCount, "]-------------"); tdl.dumpObj(settings); this.socket.send(JSON.stringify(settings)); } } } } else { tdl.misc.copyProperties(settings, this.settings); this.callback(settings); } };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to measure frames * per second. */ tdl.provide('tdl.fps'); /** * A module for fps. * @namespace */ tdl.fps = tdl.fps || {}; /** * Number of frames to average over for computing FPS. * @type {number} */ tdl.fps.NUM_FRAMES_TO_AVERAGE = 16; /** * Measures frames per second. * @constructor */ tdl.fps.FPSTimer = function() { // total time spent for last N frames. this.totalTime_ = tdl.fps.NUM_FRAMES_TO_AVERAGE; // elapsed time for last N frames. this.timeTable_ = []; // where to record next elapsed time. this.timeTableCursor_ = 0; // Initialize the FPS elapsed time history table. for (var tt = 0; tt < tdl.fps.NUM_FRAMES_TO_AVERAGE; ++tt) { this.timeTable_[tt] = 1.0; } }; /** * Updates the fps measurement. You must call this in your * render loop. * * @param {number} elapsedTime The elasped time in seconds * since the last frame. */ tdl.fps.FPSTimer.prototype.update = function(elapsedTime) { // Keep the total time and total active time for the last N frames. this.totalTime_ += elapsedTime - this.timeTable_[this.timeTableCursor_]; // Save off the elapsed time for this frame so we can subtract it later. this.timeTable_[this.timeTableCursor_] = elapsedTime; // Wrap the place to store the next time sample. ++this.timeTableCursor_; if (this.timeTableCursor_ == tdl.fps.NUM_FRAMES_TO_AVERAGE) { this.timeTableCursor_ = 0; } this.instantaneousFPS = Math.floor(1.0 / elapsedTime + 0.5); this.averageFPS = Math.floor( (1.0 / (this.totalTime_ / tdl.fps.NUM_FRAMES_TO_AVERAGE)) + 0.5); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects strings. */ tdl.provide('tdl.string'); /** * A module for string. * @namespace */ tdl.string = tdl.string || {}; /** * Whether a haystack ends with a needle. * @param {string} haystack String to search * @param {string} needle String to search for. * @param {boolean} True if haystack ends with needle. */ tdl.string.endsWith = function(haystack, needle) { return haystack.substr(haystack.length - needle.length) === needle; }; /** * Whether a haystack starts with a needle. * @param {string} haystack String to search * @param {string} needle String to search for. * @param {boolean} True if haystack starts with needle. */ tdl.string.startsWith = function(haystack, needle) { return haystack.substr(0, needle.length) === needle; }; /** * Converts a non-homogenious array into a string. * @param {!Array.<*>} args Args to turn into a string */ tdl.string.argsToString = function(args) { var lastArgWasNumber = false; var numArgs = args.length; var strs = []; for (var ii = 0; ii < numArgs; ++ii) { var arg = args[ii]; if (arg === undefined) { strs.push('undefined'); } else if (typeof arg == 'number') { if (lastArgWasNumber) { strs.push(", "); } if (arg == Math.floor(arg)) { strs.push(arg.toFixed(0)); } else { strs.push(arg.toFixed(3)); } lastArgWasNumber = true; } else if (window.Float32Array && arg instanceof Float32Array) { // TODO(gman): Make this handle other types of arrays. strs.push(tdl.string.argsToString(arg)); } else { strs.push(arg.toString()); lastArgWasNumber = false; } } return strs.join(""); }; /** * Converts an object into a string. Similar to JSON.stringify but just used * for debugging. */ tdl.string.objToString = function(obj, opt_prefix) { var strs = []; function objToString(obj, opt_prefix) { opt_prefix = opt_prefix || ""; if (typeof obj == 'object') { if (obj.length !== undefined) { for (var ii = 0; ii < obj.length; ++ii) { objToString(obj[ii], opt_prefix + "[" + ii + "]"); } } else { for (var name in obj) { objToString(obj[name], opt_prefix + "." + name); } } } else { strs.push(tdl.string.argsToString([opt_prefix, ": ", obj])); } } objToString(obj); return strs.join("\n"); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains various functions and classes for rendering * gpu based particles. */ tdl.provide('tdl.particles'); tdl.require('tdl.math'); tdl.require('tdl.shader'); /** * A Module with various io functions and classes. * @namespace */ tdl.particles = tdl.particles || {}; /** * Enum for pre-made particle states. * @enum */ tdl.particles.ParticleStateIds = { BLEND: 0, ADD: 1, BLEND_PREMULTIPLY: 2, BLEND_NO_ALPHA: 3, SUBTRACT: 4, INVERSE: 5}; /** * Vertex and fragment program strings for 2D and 3D particles. * @private * @type {!Array.<string>} */ tdl.particles.SHADER_STRINGS = [ // 3D (oriented) vertex shader 'uniform mat4 worldViewProjection;\n' + 'uniform mat4 world;\n' + 'uniform vec3 worldVelocity;\n' + 'uniform vec3 worldAcceleration;\n' + 'uniform float timeRange;\n' + 'uniform float time;\n' + 'uniform float timeOffset;\n' + 'uniform float frameDuration;\n' + 'uniform float numFrames;\n' + '\n' + '// Incoming vertex attributes\n' + 'attribute vec4 uvLifeTimeFrameStart; // uv, lifeTime, frameStart\n' + 'attribute vec4 positionStartTime; // position.xyz, startTime\n' + 'attribute vec4 velocityStartSize; // velocity.xyz, startSize\n' + 'attribute vec4 accelerationEndSize; // acceleration.xyz, endSize\n' + 'attribute vec4 spinStartSpinSpeed; // spinStart.x, spinSpeed.y\n' + 'attribute vec4 orientation; // orientation quaternion\n' + 'attribute vec4 colorMult; // multiplies color and ramp textures\n' + '\n' + '// Outgoing variables to fragment shader\n' + 'varying vec2 outputTexcoord;\n' + 'varying float outputPercentLife;\n' + 'varying vec4 outputColorMult;\n' + '\n' + 'void main() {\n' + ' vec2 uv = uvLifeTimeFrameStart.xy;\n' + ' float lifeTime = uvLifeTimeFrameStart.z;\n' + ' float frameStart = uvLifeTimeFrameStart.w;\n' + ' vec3 position = positionStartTime.xyz;\n' + ' float startTime = positionStartTime.w;\n' + ' vec3 velocity = (world * vec4(velocityStartSize.xyz,\n' + ' 0.)).xyz + worldVelocity;\n' + ' float startSize = velocityStartSize.w;\n' + ' vec3 acceleration = (world * vec4(accelerationEndSize.xyz,\n' + ' 0)).xyz + worldAcceleration;\n' + ' float endSize = accelerationEndSize.w;\n' + ' float spinStart = spinStartSpinSpeed.x;\n' + ' float spinSpeed = spinStartSpinSpeed.y;\n' + '\n' + ' float localTime = mod((time - timeOffset - startTime), timeRange);\n' + ' float percentLife = localTime / lifeTime;\n' + '\n' + ' float frame = mod(floor(localTime / frameDuration + frameStart),\n' + ' numFrames);\n' + ' float uOffset = frame / numFrames;\n' + ' float u = uOffset + (uv.x + 0.5) * (1. / numFrames);\n' + '\n' + ' outputTexcoord = vec2(u, uv.y + 0.5);\n' + ' outputColorMult = colorMult;\n' + '\n' + ' float size = mix(startSize, endSize, percentLife);\n' + ' size = (percentLife < 0. || percentLife > 1.) ? 0. : size;\n' + ' float s = sin(spinStart + spinSpeed * localTime);\n' + ' float c = cos(spinStart + spinSpeed * localTime);\n' + '\n' + ' vec4 rotatedPoint = vec4((uv.x * c + uv.y * s) * size, 0., \n' + ' (uv.x * s - uv.y * c) * size, 1.);\n' + ' vec3 center = velocity * localTime +\n' + ' acceleration * localTime * localTime + \n' + ' position;\n' + '\n' + ' vec4 q2 = orientation + orientation;\n' + ' vec4 qx = orientation.xxxw * q2.xyzx;\n' + ' vec4 qy = orientation.xyyw * q2.xyzy;\n' + ' vec4 qz = orientation.xxzw * q2.xxzz;\n' + '\n' + ' mat4 localMatrix = mat4(\n' + ' (1.0 - qy.y) - qz.z, \n' + ' qx.y + qz.w, \n' + ' qx.z - qy.w,\n' + ' 0,\n' + '\n' + ' qx.y - qz.w, \n' + ' (1.0 - qx.x) - qz.z, \n' + ' qy.z + qx.w,\n' + ' 0,\n' + '\n' + ' qx.z + qy.w, \n' + ' qy.z - qx.w, \n' + ' (1.0 - qx.x) - qy.y,\n' + ' 0,\n' + '\n' + ' center.x, center.y, center.z, 1);\n' + ' rotatedPoint = localMatrix * rotatedPoint;\n' + ' outputPercentLife = percentLife;\n' + ' gl_Position = worldViewProjection * rotatedPoint;\n' + '}\n', // 2D (billboarded) vertex shader 'uniform mat4 viewProjection;\n' + 'uniform mat4 world;\n' + 'uniform mat4 viewInverse;\n' + 'uniform vec3 worldVelocity;\n' + 'uniform vec3 worldAcceleration;\n' + 'uniform float timeRange;\n' + 'uniform float time;\n' + 'uniform float timeOffset;\n' + 'uniform float frameDuration;\n' + 'uniform float numFrames;\n' + '\n' + '// Incoming vertex attributes\n' + 'attribute vec4 uvLifeTimeFrameStart; // uv, lifeTime, frameStart\n' + 'attribute vec4 positionStartTime; // position.xyz, startTime\n' + 'attribute vec4 velocityStartSize; // velocity.xyz, startSize\n' + 'attribute vec4 accelerationEndSize; // acceleration.xyz, endSize\n' + 'attribute vec4 spinStartSpinSpeed; // spinStart.x, spinSpeed.y\n' + 'attribute vec4 colorMult; // multiplies color and ramp textures\n' + '\n' + '// Outgoing variables to fragment shader\n' + 'varying vec2 outputTexcoord;\n' + 'varying float outputPercentLife;\n' + 'varying vec4 outputColorMult;\n' + '\n' + 'void main() {\n' + ' vec2 uv = uvLifeTimeFrameStart.xy;\n' + ' float lifeTime = uvLifeTimeFrameStart.z;\n' + ' float frameStart = uvLifeTimeFrameStart.w;\n' + ' vec3 position = positionStartTime.xyz;\n' + // ' vec3 position = (world * vec4(positionStartTime.xyz, 1.0)).xyz;\n' + ' float startTime = positionStartTime.w;\n' + ' vec3 velocity = (world * vec4(velocityStartSize.xyz,\n' + ' 0.)).xyz + worldVelocity;\n' + ' float startSize = velocityStartSize.w;\n' + ' vec3 acceleration = (world * vec4(accelerationEndSize.xyz,\n' + ' 0)).xyz + worldAcceleration;\n' + ' float endSize = accelerationEndSize.w;\n' + ' float spinStart = spinStartSpinSpeed.x;\n' + ' float spinSpeed = spinStartSpinSpeed.y;\n' + '\n' + ' float localTime = mod((time - timeOffset - startTime), timeRange);\n' + ' float percentLife = localTime / lifeTime;\n' + '\n' + ' float frame = mod(floor(localTime / frameDuration + frameStart),\n' + ' numFrames);\n' + ' float uOffset = frame / numFrames;\n' + ' float u = uOffset + (uv.x + 0.5) * (1. / numFrames);\n' + '\n' + ' outputTexcoord = vec2(u, uv.y + 0.5);\n' + ' outputColorMult = colorMult;\n' + '\n' + ' vec3 basisX = viewInverse[0].xyz;\n' + ' vec3 basisZ = viewInverse[1].xyz;\n' + '\n' + ' float size = mix(startSize, endSize, percentLife);\n' + ' size = (percentLife < 0. || percentLife > 1.) ? 0. : size;\n' + ' float s = sin(spinStart + spinSpeed * localTime);\n' + ' float c = cos(spinStart + spinSpeed * localTime);\n' + '\n' + ' vec2 rotatedPoint = vec2(uv.x * c + uv.y * s, \n' + ' -uv.x * s + uv.y * c);\n' + ' vec3 localPosition = vec3(basisX * rotatedPoint.x +\n' + ' basisZ * rotatedPoint.y) * size +\n' + ' velocity * localTime +\n' + ' acceleration * localTime * localTime + \n' + ' position;\n' + '\n' + ' outputPercentLife = percentLife;\n' + ' gl_Position = viewProjection * vec4(localPosition + world[3].xyz, 1.);\n' + '}\n', // Fragment shader used by both 2D and 3D vertex shaders '#ifdef GL_ES\n' + 'precision highp float;\n' + '#endif\n' + 'uniform sampler2D rampSampler;\n' + 'uniform sampler2D colorSampler;\n' + '\n' + '// Incoming variables from vertex shader\n' + 'varying vec2 outputTexcoord;\n' + 'varying float outputPercentLife;\n' + 'varying vec4 outputColorMult;\n' + '\n' + 'void main() {\n' + ' vec4 colorMult = texture2D(rampSampler, \n' + ' vec2(outputPercentLife, 0.5)) *\n' + ' outputColorMult;\n' + ' gl_FragColor = texture2D(colorSampler, outputTexcoord) * colorMult;\n' + // For debugging: requires setup of some uniforms and vertex // attributes to be commented out to avoid GL errors // ' gl_FragColor = vec4(1., 0., 0., 1.);\n' + '}\n' ]; /** * Corner values. * @private * @type {!Array.<!Array.<number>>} */ tdl.particles.CORNERS_ = [ [-0.5, -0.5], [+0.5, -0.5], [+0.5, +0.5], [-0.5, +0.5]]; /** * Creates a particle system. * You only need one of these to run multiple emitters of different types * of particles. * @constructor * @param {!WebGLRenderingContext} gl The WebGLRenderingContext * into which the particles will be rendered. * @param {!function(): number} opt_clock A function that returns the * number of seconds elapsed. The "time base" does not matter; it is * corrected for internally in the particle system. If not supplied, * wall clock time defined by the JavaScript Date API will be used. * @param {!function(): number} opt_randomFunction A function that returns * a random number between 0.0 and 1.0. This allows you to pass in a * pseudo random function if you need particles that are reproducible. */ tdl.particles.ParticleSystem = function(gl, opt_clock, opt_randomFunction) { this.gl = gl; // Entities which can be drawn -- emitters or OneShots this.drawables_ = []; var shaders = []; shaders.push(new tdl.shader.Shader(gl, tdl.particles.SHADER_STRINGS[0], tdl.particles.SHADER_STRINGS[2])); shaders.push(new tdl.shader.Shader(gl, tdl.particles.SHADER_STRINGS[1], tdl.particles.SHADER_STRINGS[2])); var blendFuncs = {}; blendFuncs[tdl.particles.ParticleStateIds.BLEND] = { src: gl.SRC_ALPHA, dest: gl.ONE_MINUS_SRC_ALPHA }; blendFuncs[tdl.particles.ParticleStateIds.ADD] = { src: gl.SRC_ALPHA, dest: gl.ONE }; blendFuncs[tdl.particles.ParticleStateIds.BLEND_PREMULTIPLY] = { src: gl.ONE, dest: gl.ONE_MINUS_SRC_ALPHA }; blendFuncs[tdl.particles.ParticleStateIds.BLEND_NO_ALPHA] = { src: gl.SRC_COLOR, dest: gl.ONE_MINUS_SRC_COLOR }; blendFuncs[tdl.particles.ParticleStateIds.SUBTRACT] = { src: gl.SRC_ALPHA, dest: gl.ONE_MINUS_SRC_ALPHA, eq: gl.FUNC_REVERSE_SUBTRACT }; blendFuncs[tdl.particles.ParticleStateIds.INVERSE] = { src: gl.ONE_MINUS_DST_COLOR, dest: gl.ONE_MINUS_SRC_COLOR }; this.blendFuncs_ = blendFuncs; var pixelBase = [0, 0.20, 0.70, 1, 0.70, 0.20, 0, 0]; var pixels = []; for (var yy = 0; yy < 8; ++yy) { for (var xx = 0; xx < 8; ++xx) { var pixel = pixelBase[xx] * pixelBase[yy]; pixels.push(pixel, pixel, pixel, pixel); } } var colorTexture = this.createTextureFromFloats(8, 8, pixels); // Note difference in texture size from O3D sample to avoid NPOT // texture creation var rampTexture = this.createTextureFromFloats(2, 1, [1, 1, 1, 1, 1, 1, 1, 0]); this.now_ = new Date(); this.timeBase_ = new Date(); if (opt_clock) { this.timeSource_ = opt_clock; } else { this.timeSource_ = tdl.particles.createDefaultClock_(this); } this.randomFunction_ = opt_randomFunction || function() { return Math.random(); }; // This FloatArray is used to store a single particle's data // in the VBO. As of this writing there wasn't a way to store less // than a full WebGLArray's data in a bufferSubData call. this.singleParticleArray_ = new Float32Array(4 * tdl.particles.LAST_IDX); /** * The shaders for particles. * @type {!Array.<!Shader>} */ this.shaders = shaders; /** * The default color texture for particles. * @type {!o3d.Texture2D} */ this.defaultColorTexture = colorTexture; /** * The default ramp texture for particles. * @type {!o3d.Texture2D} */ this.defaultRampTexture = rampTexture; }; tdl.particles.createDefaultClock_ = function(particleSystem) { return function() { var now = particleSystem.now_; var base = particleSystem.timeBase_; return (now.getTime() - base.getTime()) / 1000.0; } } /** * Creates an OpenGL texture from an array of floating point values. * @private */ tdl.particles.ParticleSystem.prototype.createTextureFromFloats = function(width, height, pixels, opt_texture) { var gl = this.gl; var texture = null; if (opt_texture != null) { texture = opt_texture; } else { texture = gl.createTexture(); } // = opt_texture || gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // FIXME: this is not 100% correct; will end up extending the ends // of the range too far out toward the edge. Really need to pull in // the texture coordinates used to sample this texture by half a // texel. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); var data = new Uint8Array(pixels.length); for (var i = 0; i < pixels.length; i++) { var t = pixels[i] * 255.; data[i] = t; } gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); return texture; } /** * A ParticleSpec specifies how to emit particles. * * NOTE: For all particle functions you can specific a ParticleSpec as a * Javascript object, only specifying the fields that you care about. * * <pre> * emitter.setParameters({ * numParticles: 40, * lifeTime: 2, * timeRange: 2, * startSize: 50, * endSize: 90, * positionRange: [10, 10, 10], * velocity:[0, 0, 60], velocityRange: [15, 15, 15], * acceleration: [0, 0, -20], * spinSpeedRange: 4} * ); * </pre> * * Many of these parameters are in pairs. For paired paramters each particle * specfic value is set like this * * particle.field = value + Math.random() - 0.5 * valueRange * 2; * * or in English * * particle.field = value plus or minus valueRange. * * So for example, if you wanted a value from 10 to 20 you'd pass 15 for value * and 5 for valueRange because * * 15 + or - 5 = (10 to 20) * * @constructor */ tdl.particles.ParticleSpec = function() { /** * The number of particles to emit. * @type {number} */ this.numParticles = 1; /** * The number of frames in the particle texture. * @type {number} */ this.numFrames = 1; /** * The frame duration at which to animate the particle texture in seconds per * frame. * @type {number} */ this.frameDuration = 1; /** * The initial frame to display for a particular particle. * @type {number} */ this.frameStart = 0; /** * The frame start range. * @type {number} */ this.frameStartRange = 0; /** * The life time of the entire particle system. * To make a particle system be continuous set this to match the lifeTime. * @type {number} */ this.timeRange = 99999999; /** * The startTime of a particle. * @type {?number} */ this.startTime = null; // TODO: Describe what happens if this is not set. I still have some // work to do there. /** * The lifeTime of a particle. * @type {number} */ this.lifeTime = 1; /** * The lifeTime range. * @type {number} */ this.lifeTimeRange = 0; /** * The starting size of a particle. * @type {number} */ this.startSize = 1; /** * The starting size range. * @type {number} */ this.startSizeRange = 0; /** * The ending size of a particle. * @type {number} */ this.endSize = 1; /** * The ending size range. * @type {number} */ this.endSizeRange = 0; /** * The starting position of a particle in local space. * @type {!tdl.math.Vector3} */ this.position = [0, 0, 0]; /** * The starting position range. * @type {!tdl.math.Vector3} */ this.positionRange = [0, 0, 0]; /** * The velocity of a paritcle in local space. * @type {!tdl.math.Vector3} */ this.velocity = [0, 0, 0]; /** * The velocity range. * @type {!tdl.math.Vector3} */ this.velocityRange = [0, 0, 0]; /** * The acceleration of a particle in local space. * @type {!tdl.math.Vector3} */ this.acceleration = [0, 0, 0]; /** * The accleration range. * @type {!tdl.math.Vector3} */ this.accelerationRange = [0, 0, 0]; /** * The starting spin value for a particle in radians. * @type {number} */ this.spinStart = 0; /** * The spin start range. * @type {number} */ this.spinStartRange = 0; /** * The spin speed of a particle in radians. * @type {number} */ this.spinSpeed = 0; /** * The spin speed range. * @type {number} */ this.spinSpeedRange = 0; /** * The color multiplier of a particle. * @type {!tdl.math.Vector4} */ this.colorMult = [1, 1, 1, 1]; /** * The color multiplier range. * @type {!tdl.math.Vector4} */ this.colorMultRange = [0, 0, 0, 0]; /** * The velocity of all paritcles in world space. * @type {!tdl.math.Vector3} */ this.worldVelocity = [0, 0, 0]; /** * The acceleration of all paritcles in world space. * @type {!tdl.math.Vector3} */ this.worldAcceleration = [0, 0, 0]; /** * Whether these particles are oriented in 2d or 3d. true = 2d, false = 3d. * @type {boolean} */ this.billboard = true; /** * The orientation of a particle. This is only used if billboard is false. * @type {!tdl.quaternions.Quaternion} */ this.orientation = [0, 0, 0, 1]; }; /** * Creates a particle emitter. * @param {!o3d.Texture} opt_texture The texture to use for the particles. * If you don't supply a texture a default is provided. * @param {!function(): number} opt_clock A ParamFloat to be the clock for * the emitter. * @return {!tdl.particles.ParticleEmitter} The new emitter. */ tdl.particles.ParticleSystem.prototype.createParticleEmitter = function(opt_texture, opt_clock) { var emitter = new tdl.particles.ParticleEmitter(this, opt_texture, opt_clock); this.drawables_.push(emitter); return emitter; }; /** * Creates a Trail particle emitter. * You can use this for jet exhaust, etc... * @param {!o3d.Transform} parent Transform to put emitter on. * @param {number} maxParticles Maximum number of particles to appear at once. * @param {!tdl.particles.ParticleSpec} parameters The parameters used to * generate particles. * @param {!o3d.Texture} opt_texture The texture to use for the particles. * If you don't supply a texture a default is provided. * @param {!function(number, !tdl.particles.ParticleSpec): void} * opt_perParticleParamSetter A function that is called for each particle to * allow it's parameters to be adjusted per particle. The number is the * index of the particle being created, in other words, if numParticles is * 20 this value will be 0 to 19. The ParticleSpec is a spec for this * particular particle. You can set any per particle value before returning. * @param {!function(): number} opt_clock A function to be the clock for * the emitter. * @return {!tdl.particles.Trail} A Trail object. */ tdl.particles.ParticleSystem.prototype.createTrail = function( maxParticles, parameters, opt_texture, opt_perParticleParamSetter, opt_clock) { var trail = new tdl.particles.Trail( this, maxParticles, parameters, opt_texture, opt_perParticleParamSetter, opt_clock); this.drawables_.push(trail); return trail; }; /** * Draws all of the particle emitters managed by this ParticleSystem. * This modifies the depth mask, depth test, blend function and its * enabling, array buffer binding, element array buffer binding, the * textures bound to texture units 0 and 1, and which is the active * texture unit. * @param {!Matrix4x4} viewProjection The viewProjection matrix. * @param {!Matrix4x4} world The world matrix. * @param {!Matrix4x4} viewInverse The viewInverse matrix. */ tdl.particles.ParticleSystem.prototype.draw = function(viewProjection, world, viewInverse) { // Update notion of current time this.now_ = new Date(); // Set up global state var gl = this.gl; gl.depthMask(false); gl.enable(gl.DEPTH_TEST); // Set up certain uniforms once per shader per draw. var shader = this.shaders[1]; shader.bind(); gl.uniformMatrix4fv(shader.viewProjectionLoc, false, viewProjection); gl.uniformMatrix4fv(shader.viewInverseLoc, false, viewInverse); // Draw all emitters // FIXME: this is missing O3D's z-sorting logic from the // zOrderedDrawList for (var ii = 0; ii < this.drawables_.length; ++ii) { this.drawables_[ii].draw(world, viewProjection, 0); } }; // Base element indices for the interleaved floating point data. // Each of the four corners of the particle has four floats for each // of these pieces of information. tdl.particles.UV_LIFE_TIME_FRAME_START_IDX = 0; tdl.particles.POSITION_START_TIME_IDX = 4; tdl.particles.VELOCITY_START_SIZE_IDX = 8; tdl.particles.ACCELERATION_END_SIZE_IDX = 12; tdl.particles.SPIN_START_SPIN_SPEED_IDX = 16; tdl.particles.ORIENTATION_IDX = 20; tdl.particles.COLOR_MULT_IDX = 24; tdl.particles.LAST_IDX = 28; /** * A ParticleEmitter * @private * @constructor * @param {!tdl.particles.ParticleSystem} particleSystem The particle system * to manage this emitter. * @param {!o3d.Texture} opt_texture The texture to use for the particles. * If you don't supply a texture a default is provided. * @param {!function(): number} opt_clock (optional) A function that * returns the number of seconds elapsed. A function, returning * seconds elapsed, to be the time source for the emitter. */ tdl.particles.ParticleEmitter = function(particleSystem, opt_texture, opt_clock) { opt_clock = opt_clock || particleSystem.timeSource_; this.gl = particleSystem.gl; this.createdParticles_ = false; this.tmpWorld_ = new Float32Array(16); // This Float32Array is used to store a single particle's data // in the VBO. As of this writing there wasn't a way to store less // than a full WebGLArray's data in a bufferSubData call. this.singleParticleArray_ = new Float32Array(4 * tdl.particles.LAST_IDX); // The VBO holding the particles' data, (re-)allocated in // allocateParticles_(). this.particleBuffer_ = gl.createBuffer(); // The buffer object holding the particles' indices, (re-)allocated // in allocateParticles_(). this.indexBuffer_ = gl.createBuffer(); // The number of particles that are stored in the particle buffer. this.numParticles_ = 0; this.rampTexture_ = particleSystem.defaultRampTexture; this.colorTexture_ = opt_texture || particleSystem.defaultColorTexture; /** * The particle system managing this emitter. * @type {!tdl.particles.ParticleSystem} */ this.particleSystem = particleSystem; /** * A function that is the source for the time for this emitter. * @private * @type {!function(): number} */ this.timeSource_ = opt_clock; /** * The translation for this ParticleEmitter. (FIXME: generalize.) * @private * @type {!tdl.math.Vector3} */ this.translation_ = [0, 0, 0]; // Set up the blend functions for drawing the particles. this.setState(tdl.particles.ParticleStateIds.BLEND); }; /** * Sets the world translation for this ParticleEmitter. * @param {!tdl.math.Vector3} translation The translation for this emitter. */ tdl.particles.ParticleEmitter.prototype.setTranslation = function(x, y, z) { this.translation_[0] = x; this.translation_[1] = y; this.translation_[2] = z; }; /** * Sets the blend state for the particles. * You can use this to set the emitter to draw with BLEND, ADD, SUBTRACT, etc. * @param {ParticleStateIds} stateId The state you want. */ tdl.particles.ParticleEmitter.prototype.setState = function(stateId) { this.blendFunc_ = this.particleSystem.blendFuncs_[stateId]; }; /** * Sets the colorRamp for the particles. * The colorRamp is used as a multiplier for the texture. When a particle * starts it is multiplied by the first color, as it ages to progressed * through the colors in the ramp. * * <pre> * particleEmitter.setColorRamp([ * 1, 0, 0, 1, // red * 0, 1, 0, 1, // green * 1, 0, 1, 0]); // purple but with zero alpha * </pre> * * The code above sets the particle to start red, change to green then * fade out while changing to purple. * * @param {!Array.<number>} colorRamp An array of color values in * the form RGBA. */ tdl.particles.ParticleEmitter.prototype.setColorRamp = function(colorRamp) { var width = colorRamp.length / 4; if (width % 1 != 0) { throw 'colorRamp must have multiple of 4 entries'; } var gl = this.gl; if (this.rampTexture_ == this.particleSystem.defaultRampTexture) { this.rampTexture_ = null; } this.rampTexture_ = this.particleSystem.createTextureFromFloats(width, 1, colorRamp, this.rampTexture_); }; /** * Validates and adds missing particle parameters. * @param {!tdl.particles.ParticleSpec} parameters The parameters to validate. */ tdl.particles.ParticleEmitter.prototype.validateParameters = function( parameters) { var defaults = new tdl.particles.ParticleSpec(); for (var key in parameters) { if (typeof defaults[key] === 'undefined') { throw 'unknown particle parameter "' + key + '"'; } } for (var key in defaults) { if (typeof parameters[key] === 'undefined') { parameters[key] = defaults[key]; } } }; /** * Creates particles. * @private * @param {number} firstParticleIndex Index of first particle to create. * @param {number} numParticles The number of particles to create. * @param {!tdl.particles.ParticleSpec} parameters The parameters for the * emitters. * @param {!function(number, !tdl.particles.ParticleSpec): void} * opt_perParticleParamSetter A function that is called for each particle to * allow it's parameters to be adjusted per particle. The number is the * index of the particle being created, in other words, if numParticles is * 20 this value will be 0 to 19. The ParticleSpec is a spec for this * particular particle. You can set any per particle value before returning. */ tdl.particles.ParticleEmitter.prototype.createParticles_ = function( firstParticleIndex, numParticles, parameters, opt_perParticleParamSetter) { var singleParticleArray = this.particleSystem.singleParticleArray_; var gl = this.gl; // Set the globals. this.billboard_ = parameters.billboard; this.timeRange_ = parameters.timeRange; this.numFrames_ = parameters.numFrames; this.frameDuration_ = parameters.frameDuration; this.worldVelocity_ = [ parameters.worldVelocity[0], parameters.worldVelocity[1], parameters.worldVelocity[2] ]; this.worldAcceleration_ = [ parameters.worldAcceleration[0], parameters.worldAcceleration[1], parameters.worldAcceleration[2] ]; var random = this.particleSystem.randomFunction_; var plusMinus = function(range) { return (random() - 0.5) * range * 2; }; // TODO: change to not allocate. var plusMinusVector = function(range) { var v = []; for (var ii = 0; ii < range.length; ++ii) { v.push(plusMinus(range[ii])); } return v; }; gl.bindBuffer(gl.ARRAY_BUFFER, this.particleBuffer_); for (var ii = 0; ii < numParticles; ++ii) { if (opt_perParticleParamSetter) { opt_perParticleParamSetter(ii, parameters); } var pLifeTime = parameters.lifeTime; var pStartTime = (parameters.startTime === null) ? (ii * parameters.lifeTime / numParticles) : parameters.startTime; var pFrameStart = parameters.frameStart + plusMinus(parameters.frameStartRange); var pPosition = tdl.math.addVector( parameters.position, plusMinusVector(parameters.positionRange)); var pVelocity = tdl.math.addVector( parameters.velocity, plusMinusVector(parameters.velocityRange)); var pAcceleration = tdl.math.addVector( parameters.acceleration, plusMinusVector(parameters.accelerationRange)); var pColorMult = tdl.math.addVector( parameters.colorMult, plusMinusVector(parameters.colorMultRange)); var pSpinStart = parameters.spinStart + plusMinus(parameters.spinStartRange); var pSpinSpeed = parameters.spinSpeed + plusMinus(parameters.spinSpeedRange); var pStartSize = parameters.startSize + plusMinus(parameters.startSizeRange); var pEndSize = parameters.endSize + plusMinus(parameters.endSizeRange); var pOrientation = parameters.orientation; // make each corner of the particle. for (var jj = 0; jj < 4; ++jj) { var offset0 = tdl.particles.LAST_IDX * jj; var offset1 = offset0 + 1; var offset2 = offset0 + 2; var offset3 = offset0 + 3; singleParticleArray[tdl.particles.UV_LIFE_TIME_FRAME_START_IDX + offset0] = tdl.particles.CORNERS_[jj][0]; singleParticleArray[tdl.particles.UV_LIFE_TIME_FRAME_START_IDX + offset1] = tdl.particles.CORNERS_[jj][1]; singleParticleArray[tdl.particles.UV_LIFE_TIME_FRAME_START_IDX + offset2] = pLifeTime; singleParticleArray[tdl.particles.UV_LIFE_TIME_FRAME_START_IDX + offset3] = pFrameStart; singleParticleArray[tdl.particles.POSITION_START_TIME_IDX + offset0] = pPosition[0]; singleParticleArray[tdl.particles.POSITION_START_TIME_IDX + offset1] = pPosition[1]; singleParticleArray[tdl.particles.POSITION_START_TIME_IDX + offset2] = pPosition[2]; singleParticleArray[tdl.particles.POSITION_START_TIME_IDX + offset3] = pStartTime; singleParticleArray[tdl.particles.VELOCITY_START_SIZE_IDX + offset0] = pVelocity[0]; singleParticleArray[tdl.particles.VELOCITY_START_SIZE_IDX + offset1] = pVelocity[1]; singleParticleArray[tdl.particles.VELOCITY_START_SIZE_IDX + offset2] = pVelocity[2]; singleParticleArray[tdl.particles.VELOCITY_START_SIZE_IDX + offset3] = pStartSize; singleParticleArray[tdl.particles.ACCELERATION_END_SIZE_IDX + offset0] = pAcceleration[0]; singleParticleArray[tdl.particles.ACCELERATION_END_SIZE_IDX + offset1] = pAcceleration[1]; singleParticleArray[tdl.particles.ACCELERATION_END_SIZE_IDX + offset2] = pAcceleration[2]; singleParticleArray[tdl.particles.ACCELERATION_END_SIZE_IDX + offset3] = pEndSize; singleParticleArray[tdl.particles.SPIN_START_SPIN_SPEED_IDX + offset0] = pSpinStart; singleParticleArray[tdl.particles.SPIN_START_SPIN_SPEED_IDX + offset1] = pSpinSpeed; singleParticleArray[tdl.particles.SPIN_START_SPIN_SPEED_IDX + offset2] = 0; singleParticleArray[tdl.particles.SPIN_START_SPIN_SPEED_IDX + offset3] = 0; singleParticleArray[tdl.particles.ORIENTATION_IDX + offset0] = pOrientation[0]; singleParticleArray[tdl.particles.ORIENTATION_IDX + offset1] = pOrientation[1]; singleParticleArray[tdl.particles.ORIENTATION_IDX + offset2] = pOrientation[2]; singleParticleArray[tdl.particles.ORIENTATION_IDX + offset3] = pOrientation[3]; singleParticleArray[tdl.particles.COLOR_MULT_IDX + offset0] = pColorMult[0]; singleParticleArray[tdl.particles.COLOR_MULT_IDX + offset1] = pColorMult[1]; singleParticleArray[tdl.particles.COLOR_MULT_IDX + offset2] = pColorMult[2]; singleParticleArray[tdl.particles.COLOR_MULT_IDX + offset3] = pColorMult[3]; } // Upload this particle's information into the VBO. // FIXME: probably want to make fewer bufferSubData calls gl.bufferSubData(gl.ARRAY_BUFFER, singleParticleArray.byteLength * (ii + firstParticleIndex), singleParticleArray); } this.createdParticles_ = true; }; /** * Allocates particles. * @private * @param {number} numParticles Number of particles to allocate. */ tdl.particles.ParticleEmitter.prototype.allocateParticles_ = function( numParticles) { if (this.numParticles_ != numParticles) { var gl = this.gl; gl.bindBuffer(gl.ARRAY_BUFFER, this.particleBuffer_); gl.bufferData(gl.ARRAY_BUFFER, numParticles * this.particleSystem.singleParticleArray_.byteLength, gl.DYNAMIC_DRAW); var numIndices = 6 * numParticles; if (numIndices > 65536) { throw "can't have more than 10922 particles per emitter"; } var indices = new Uint16Array(numIndices); var idx = 0; for (var ii = 0; ii < numParticles; ++ii) { // Make 2 triangles for the quad. var startIndex = ii * 4; indices[idx++] = startIndex + 0; indices[idx++] = startIndex + 1; indices[idx++] = startIndex + 2; indices[idx++] = startIndex + 0; indices[idx++] = startIndex + 2; indices[idx++] = startIndex + 3; } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer_); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); this.numParticles_ = numParticles; } }; /** * Sets the parameters of the particle emitter. * * Each of these parameters are in pairs. The used to create a table * of particle parameters. For each particle a specfic value is * set like this * * particle.field = value + Math.random() - 0.5 * valueRange * 2; * * or in English * * particle.field = value plus or minus valueRange. * * So for example, if you wanted a value from 10 to 20 you'd pass 15 for value * and 5 for valueRange because * * 15 + or - 5 = (10 to 20) * * @param {!tdl.particles.ParticleSpec} parameters The parameters for the * emitters. * @param {!function(number, !tdl.particles.ParticleSpec): void} * opt_perParticleParamSetter A function that is called for each particle to * allow it's parameters to be adjusted per particle. The number is the * index of the particle being created, in other words, if numParticles is * 20 this value will be 0 to 19. The ParticleSpec is a spec for this * particular particle. You can set any per particle value before returning. */ tdl.particles.ParticleEmitter.prototype.setParameters = function( parameters, opt_perParticleParamSetter) { this.validateParameters(parameters); var numParticles = parameters.numParticles; this.allocateParticles_(numParticles); this.createParticles_( 0, numParticles, parameters, opt_perParticleParamSetter); }; tdl.particles.ParticleEmitter.prototype.draw = function(world, viewProjection, timeOffset) { if (!this.createdParticles_) { return; } var gl = this.gl; // Set up blend function gl.enable(gl.BLEND); var blendFunc = this.blendFunc_; gl.blendFunc(blendFunc.src, blendFunc.dest); if (blendFunc.eq) { gl.blendEquation(blendFunc.eq); } else { gl.blendEquation(gl.FUNC_ADD); } var shader = this.particleSystem.shaders[this.billboard_ ? 1 : 0]; shader.bind(); var tmpWorld = this.tmpWorld_; tdl.fast.matrix4.copy(tmpWorld, world); tdl.fast.matrix4.translate(tmpWorld, this.translation_); gl.uniformMatrix4fv(shader.worldLoc, false, tmpWorld); if (!this.billboard_) { var worldViewProjection = new Float32Array(16); tdl.fast.matrix4.mul.mulMatrixMatrix4(worldViewProjection, tmpWorld, viewProjection); gl.uniformMatrix4fv(shader.worldViewProjectionLoc, false, worldViewProjection); } gl.uniform3f(shader.worldVelocityLoc, this.worldVelocity_[0], this.worldVelocity_[1], this.worldVelocity_[2]); gl.uniform3f(shader.worldAccelerationLoc, this.worldAcceleration_[0], this.worldAcceleration_[1], this.worldAcceleration_[2]); gl.uniform1f(shader.timeRangeLoc, this.timeRange_); gl.uniform1f(shader.numFramesLoc, this.numFrames_); gl.uniform1f(shader.frameDurationLoc, this.frameDuration_); // Compute and set time var curTime = this.timeSource_(); gl.uniform1f(shader.timeLoc, curTime); // This is non-zero only for OneShots gl.uniform1f(shader.timeOffsetLoc, timeOffset); // Set up textures gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.rampTexture_); gl.uniform1i(shader.rampSamplerLoc, 0); gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, this.colorTexture_); gl.uniform1i(shader.colorSamplerLoc, 1); gl.activeTexture(gl.TEXTURE0); // Set up vertex attributes var sizeofFloat = 4; var stride = sizeofFloat * tdl.particles.LAST_IDX; gl.bindBuffer(gl.ARRAY_BUFFER, this.particleBuffer_); gl.vertexAttribPointer(shader.uvLifeTimeFrameStartLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.UV_LIFE_TIME_FRAME_START_IDX); gl.enableVertexAttribArray(shader.uvLifeTimeFrameStartLoc); gl.vertexAttribPointer(shader.positionStartTimeLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.POSITION_START_TIME_IDX); gl.enableVertexAttribArray(shader.positionStartTimeLoc); gl.vertexAttribPointer(shader.velocityStartSizeLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.VELOCITY_START_SIZE_IDX); gl.enableVertexAttribArray(shader.velocityStartSizeLoc); gl.vertexAttribPointer(shader.accelerationEndSizeLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.ACCELERATION_END_SIZE_IDX); gl.enableVertexAttribArray(shader.accelerationEndSizeLoc); gl.vertexAttribPointer(shader.spinStartSpinSpeedLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.SPIN_START_SPIN_SPEED_IDX); gl.enableVertexAttribArray(shader.spinStartSpinSpeedLoc); // Only for non-billboarded, i.e., 3D, particles if (shader.orientationLoc != undefined) { gl.vertexAttribPointer(shader.orientationLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.ORIENTATION_IDX); gl.enableVertexAttribArray(shader.orientationLoc); } // NOTE: comment out the next two calls if using debug shader which // only outputs red. gl.vertexAttribPointer(shader.colorMultLoc, 4, gl.FLOAT, false, stride, sizeofFloat * tdl.particles.COLOR_MULT_IDX); gl.enableVertexAttribArray(shader.colorMultLoc); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer_); gl.drawElements(gl.TRIANGLES, this.numParticles_ * 6, gl.UNSIGNED_SHORT, 0); gl.disableVertexAttribArray(shader.uvLifeTimeFrameStartLoc); gl.disableVertexAttribArray(shader.positionStartTimeLoc); gl.disableVertexAttribArray(shader.velocityStartSizeLoc); gl.disableVertexAttribArray(shader.accelerationEndSizeLoc); gl.disableVertexAttribArray(shader.spinStartSpinSpeedLoc); // FIXME: only for billboarded, i.e., 3D, particles? if (shader.orientationLoc != undefined) { gl.disableVertexAttribArray(shader.orientationLoc); } gl.disableVertexAttribArray(shader.colorMultLoc); }; /** * Creates a OneShot particle emitter instance. * You can use this for dust puffs, explosions, fireworks, etc... * @return {!tdl.particles.OneShot} A OneShot object. */ tdl.particles.ParticleEmitter.prototype.createOneShot = function() { return new tdl.particles.OneShot(this); }; /** * An object to manage a particle emitter instance as a one * shot. Examples of one shot effects are things like an explosion, * some fireworks. Note that once a OneShot has been created for a * given emitter, that emitter can only be treated as containing one * or more OneShots. * @private * @constructor * @param {!tdl.particles.ParticleEmitter} emitter The emitter to use for the * one shot. * @param {!o3d.Transform} opt_parent The parent for this one shot. */ tdl.particles.OneShot = function(emitter) { this.emitter_ = emitter; /** * Translation for OneShot. * @type {!tdl.math.Vector3} */ this.world_ = tdl.fast.matrix4.translation(new Float32Array(16), [0, 0, 0]); this.tempWorld_ = tdl.fast.matrix4.translation(new Float32Array(16), [0, 0, 0]); this.timeOffset_ = 0; this.visible_ = false; // Remove the parent emitter from the particle system's drawable // list (if it's still there) and add ourselves instead. var particleSystem = emitter.particleSystem; var idx = particleSystem.drawables_.indexOf(emitter); if (idx >= 0) { particleSystem.drawables_.splice(idx, 1); } particleSystem.drawables_.push(this); }; /** * Triggers the oneshot. * * Note: You must have set the parent either at creation, with setParent, or by * passing in a parent here. * * @param {!tdl.math.Vector3} opt_position The position of the one shot * relative to its parent. */ tdl.particles.OneShot.prototype.trigger = function(opt_world) { if (opt_world) { this.world_.set(opt_world) } this.visible_ = true; this.timeOffset_ = this.emitter_.timeSource_(); }; /** * Draws the oneshot. * * @private */ tdl.particles.OneShot.prototype.draw = function(world, viewProjection, timeOffset) { if (this.visible_) { tdl.fast.matrix4.mul(this.tempWorld_, this.world_, world); this.emitter_.draw(this.tempWorld_, viewProjection, this.timeOffset_); } }; /** * A type of emitter to use for particle effects that leave trails like exhaust. * @constructor * @extends {tdl.particles.ParticleEmitter} * @param {!tdl.particles.ParticleSystem} particleSystem The particle system * to manage this emitter. * @param {!o3d.Transform} parent Transform to put emitter on. * @param {number} maxParticles Maximum number of particles to appear at once. * @param {!tdl.particles.ParticleSpec} parameters The parameters used to * generate particles. * @param {!o3d.Texture} opt_texture The texture to use for the particles. * If you don't supply a texture a default is provided. * @param {!function(number, !tdl.particles.ParticleSpec): void} * opt_perParticleParamSetter A function that is called for each particle to * allow it's parameters to be adjusted per particle. The number is the * index of the particle being created, in other words, if numParticles is * 20 this value will be 0 to 19. The ParticleSpec is a spec for this * particular particle. You can set any per particle value before returning. * @param {!function(): number} opt_clock A function to be the clock for * the emitter. */ tdl.particles.Trail = function( particleSystem, maxParticles, parameters, opt_texture, opt_perParticleParamSetter, opt_clock) { tdl.particles.ParticleEmitter.call( this, particleSystem, opt_texture, opt_clock); this.allocateParticles_(maxParticles); this.validateParameters(parameters); this.parameters = parameters; this.perParticleParamSetter = opt_perParticleParamSetter; this.birthIndex_ = 0; this.maxParticles_ = maxParticles; }; tdl.base.inherit(tdl.particles.Trail, tdl.particles.ParticleEmitter); /** * Births particles from this Trail. * @param {!tdl.math.Vector3} position Position to birth particles at. */ tdl.particles.Trail.prototype.birthParticles = function(position) { var numParticles = this.parameters.numParticles; this.parameters.startTime = this.timeSource_(); this.parameters.position = position; while (this.birthIndex_ + numParticles >= this.maxParticles_) { var numParticlesToEnd = this.maxParticles_ - this.birthIndex_; this.createParticles_(this.birthIndex_, numParticlesToEnd, this.parameters, this.perParticleParamSetter); numParticles -= numParticlesToEnd; this.birthIndex_ = 0; } this.createParticles_(this.birthIndex_, numParticles, this.parameters, this.perParticleParamSetter); this.birthIndex_ += numParticles; }; tdl.particles.OneShotManager = function(emitter, numOneshots) { this.numOneshots = numOneshots; this.oneshotIndex = 0; this.oneshots = []; for (var ii = 0; ii < numOneshots; ++ii) { this.oneshots.push(emitter.createOneShot()); } }; tdl.particles.OneShotManager.prototype.startOneShot = function(worldMatrix) { this.oneshots[this.oneshotIndex].trigger(worldMatrix); this.oneshotIndex = (this.oneshotIndex + 1) % this.numOneshots; }; tdl.particles.createOneShotManager = function(emitter, numOneshots) { return new tdl.particles.OneShotManager(emitter, numOneshots); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains matrix/vector math functions. */ tdl.provide('tdl.fast'); /** * A module for math for tdl.fast. * @namespace */ tdl.fast = tdl.fast || {}; if (!window.Float32Array) { // This just makes some errors go away when there is no WebGL. window.Float32Array = function() { }; } tdl.fast.temp0v3_ = new Float32Array(3); tdl.fast.temp1v3_ = new Float32Array(3); tdl.fast.temp2v3_ = new Float32Array(3); tdl.fast.temp0v4_ = new Float32Array(4); tdl.fast.temp1v4_ = new Float32Array(4); tdl.fast.temp2v4_ = new Float32Array(4); tdl.fast.temp0m4_ = new Float32Array(16); tdl.fast.temp1m4_ = new Float32Array(16); tdl.fast.temp2m4_ = new Float32Array(16); /** * Functions which deal with 4-by-4 transformation matrices are kept in their * own namespsace. * @namespace */ tdl.fast.matrix4 = tdl.fast.matrix4 || {}; /** * Functions that are specifically row major are kept in their own namespace. * @namespace */ tdl.fast.rowMajor = tdl.fast.rowMajor || {}; /** * Functions that are specifically column major are kept in their own namespace. * @namespace */ tdl.fast.columnMajor = tdl.fast.columnMajor || {}; /** * An Array of 2 floats * @type {!Float32Array} */ tdl.fast.Vector2 = goog.typedef; /** * An Array of 3 floats * @type {!Float32Array} */ tdl.fast.Vector3 = goog.typedef; /** * An Array of 4 floats * @type {!Float32Array} */ tdl.fast.Vector4 = goog.typedef; /** * An Array of floats. * @type {!Float32Array} */ tdl.fast.Vector = goog.typedef; /** * A 2x2 Matrix of floats * @type {!Float32Array} */ tdl.fast.Matrix2 = goog.typedef; /** * A 3x3 Matrix of floats * @type {!Float32Array} */ tdl.fast.Matrix3 = goog.typedef; /** * A 4x4 Matrix of floats * @type {!Float32Array} */ tdl.fast.Matrix4 = goog.typedef; /** * A arbitrary size Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.fast.Matrix = goog.typedef; /** * Adds two vectors; assumes a and b have the same dimension. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. */ tdl.fast.addVector = function(dst, a, b) { var aLength = a.length; for (var i = 0; i < aLength; ++i) dst[i] = a[i] + b[i]; return dst; }; /** * Subtracts two vectors. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. */ tdl.fast.subVector = function(dst, a, b) { var aLength = a.length; for (var i = 0; i < aLength; ++i) dst[i] = a[i] - b[i]; return dst; }; /** * Performs linear interpolation on two vectors. * Given vectors a and b and interpolation coefficient t, returns * (1 - t) * a + t * b. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. * @param {number} t Interpolation coefficient. */ tdl.fast.lerpVector = function(dst, a, b, t) { var aLength = a.length; for (var i = 0; i < aLength; ++i) dst[i] = (1 - t) * a[i] + t * b[i]; return dst; }; /** * Divides a vector by a scalar. * @param {!tdl.fast.Vector} dst The vector. * @param {!tdl.fast.Vector} v The vector. * @param {number} k The scalar. * @return {!tdl.fast.Vector} dst. */ tdl.fast.divVectorScalar = function(dst, v, k) { var vLength = v.length; for (var i = 0; i < vLength; ++i) dst[i] = v[i] / k; return dst; }; /** * Computes the cross product of two vectors; assumes both vectors have * three entries. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. * @return {!tdl.fast.Vector} The vector a cross b. */ tdl.fast.cross = function(dst, a, b) { dst[0] = a[1] * b[2] - a[2] * b[1]; dst[1] = a[2] * b[0] - a[0] * b[2]; dst[2] = a[0] * b[1] - a[1] * b[0]; return dst; }; /** * Computes the dot product of two vectors; assumes both vectors have * three entries. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. * @return {number} dot product */ tdl.fast.dot = function(a, b) { return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]); }; /** * Divides a vector by its Euclidean length and returns the quotient. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a The vector. * @return {!tdl.fast.Vector} The normalized vector. */ tdl.fast.normalize = function(dst, a) { var n = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) n += a[i] * a[i]; n = Math.sqrt(n); if (n > 0.00001) { for (var i = 0; i < aLength; ++i) dst[i] = a[i] / n; } else { for (var i = 0; i < aLength; ++i) dst[i] = 0; } return dst; }; /** * Negates a vector. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} -v. */ tdl.fast.negativeVector = function(dst, v) { var vLength = v.length; for (var i = 0; i < vLength; ++i) { dst[i] = -v[i]; } return dst; }; /** * Negates a matrix. * @param {!tdl.fast.Matrix} dst matrix. * @param {!tdl.fast.Matrix} v The matrix. * @return {!tdl.fast.Matrix} -v. */ tdl.fast.negativeMatrix = function(dst, v) { var vLength = v.length; for (var i = 0; i < vLength; ++i) { dst[i] = -v[i]; } return dst; }; /** * Copies a vector. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} A copy of v. */ tdl.fast.copyVector = function(dst, v) { dst.set(v); return dst; }; /** * Copies a matrix. * @param {!tdl.fast.Matrix} m The matrix. * @return {!tdl.fast.Matrix} A copy of m. */ tdl.fast.copyMatrix = function(dst, m) { dst.set(m); return dst; }; /** * Multiplies a scalar by a vector. * @param {!tdl.fast.Vector} dst vector. * @param {number} k The scalar. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} The product of k and v. */ tdl.fast.mulScalarVector = function(dst, k, v) { var vLength = v.length; for (var i = 0; i < vLength; ++i) { dst[i] = k * v[i]; } return dst; }; /** * Multiplies a vector by a scalar. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} v The vector. * @param {number} k The scalar. * @return {!tdl.fast.Vector} The product of k and v. */ tdl.fast.mulVectorScalar = function(dst, v, k) { return tdl.fast.mulScalarVector(dst, k, v); }; /** * Multiplies a scalar by a matrix. * @param {!tdl.fast.Matrix} dst matrix. * @param {number} k The scalar. * @param {!tdl.fast.Matrix} m The matrix. * @return {!tdl.fast.Matrix} The product of m and k. */ tdl.fast.mulScalarMatrix = function(dst, k, m) { var mLength = m.length; for (var i = 0; i < mLength; ++i) { dst[i] = k * m[i]; } return dst; }; /** * Multiplies a matrix by a scalar. * @param {!tdl.fast.Matrix} dst matrix. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} k The scalar. * @return {!tdl.fast.Matrix} The product of m and k. */ tdl.fast.mulMatrixScalar = function(dst, m, k) { return tdl.fast.mulScalarMatrix(dst, k, m); }; /** * Multiplies a vector by another vector (component-wise); assumes a and * b have the same length. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. * @return {!tdl.fast.Vector} The vector of products of entries of a and * b. */ tdl.fast.mulVectorVector = function(dst, a, b) { var aLength = a.length; for (var i = 0; i < aLength; ++i) dst[i] = a[i] * b[i]; return dst; }; /** * Divides a vector by another vector (component-wise); assumes a and * b have the same length. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} a Operand vector. * @param {!tdl.fast.Vector} b Operand vector. * @return {!tdl.fast.Vector} The vector of quotients of entries of a and * b. */ tdl.fast.divVectorVector = function(dst, a, b) { var aLength = a.length; for (var i = 0; i < aLength; ++i) dst[i] = a[i] / b[i]; return dst; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector; assumes * matrix entries are accessed in [row][column] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} v The vector. * @param {!tdl.fast.Matrix} m The matrix. * @return {!tdl.fast.Vector} The product of v and m as a row vector. */ tdl.fast.rowMajor.mulVectorMatrix4 = function(dst, v, m) { for (var i = 0; i < 4; ++i) { dst[i] = 0.0; for (var j = 0; j < 4; ++j) dst[i] += v[j] * m[j * 4 + i]; } return dst; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector; assumes * matrix entries are accessed in [column][row] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Vector} v The vector. * @param {!tdl.fast.Matrix} m The matrix. * @return {!tdl.fast.Vector} The product of v and m as a row vector. */ tdl.fast.columnMajor.mulVectorMatrix4 = function(dst, v, m) { var mLength = m.length; var vLength = v.length; for (var i = 0; i < 4; ++i) { dst[i] = 0.0; var col = i * 4; for (var j = 0; j < 4; ++j) dst[i] += v[j] * m[col + j]; } return dst; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} The product of m and v as a row vector. */ tdl.fast.mulVectorMatrix4 = null; /** * Multiplies a matrix by a vector; treats the vector as a column vector. * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} The product of m and v as a column vector. */ tdl.fast.rowMajor.mulMatrix4Vector = function(dst, m, v) { for (var i = 0; i < 4; ++i) { dst[i] = 0.0; var row = i * 4; for (var j = 0; j < 4; ++j) dst[i] += m[row + j] * v[j]; } return dst; }; /** * Multiplies a matrix by a vector; treats the vector as a column vector; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} The product of m and v as a column vector. */ tdl.fast.columnMajor.mulMatrix4Vector = function(dst, m, v) { for (var i = 0; i < 4; ++i) { dst[i] = 0.0; for (var j = 0; j < 4; ++j) dst[i] += v[j] * m[j * 4 + i]; } return dst; }; /** * Multiplies a matrix by a vector; treats the vector as a column vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {!tdl.fast.Vector} v The vector. * @return {!tdl.fast.Vector} The product of m and v as a column vector. */ tdl.fast.mulMatrix4Vector = null; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3; * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.fast.Matrix3} dst matrix. * @param {!tdl.fast.Matrix3} a The matrix on the left. * @param {!tdl.fast.Matrix3} b The matrix on the right. * @return {!tdl.fast.Matrix3} The matrix product of a and b. */ tdl.fast.rowMajor.mulMatrixMatrix3 = function(dst, a, b) { var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3 + 0]; var a11 = a[3 + 1]; var a12 = a[3 + 2]; var a20 = a[6 + 0]; var a21 = a[6 + 1]; var a22 = a[6 + 2]; var b00 = b[0]; var b01 = b[1]; var b02 = b[2]; var b10 = b[3 + 0]; var b11 = b[3 + 1]; var b12 = b[3 + 2]; var b20 = b[6 + 0]; var b21 = b[6 + 1]; var b22 = b[6 + 2]; dst[0] = a00 * b00 + a01 * b10 + a02 * b20; dst[1] = a00 * b01 + a01 * b11 + a02 * b21; dst[2] = a00 * b02 + a01 * b12 + a02 * b22; dst[3] = a10 * b00 + a11 * b10 + a12 * b20; dst[4] = a10 * b01 + a11 * b11 + a12 * b21; dst[5] = a10 * b02 + a11 * b12 + a12 * b22; dst[6] = a20 * b00 + a21 * b10 + a22 * b20; dst[7] = a20 * b01 + a21 * b11 + a22 * b21; dst[8] = a20 * b02 + a21 * b12 + a22 * b22; return dst; }; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.fast.Matrix3} dst matrix. * @param {!tdl.fast.Matrix3} a The matrix on the left. * @param {!tdl.fast.Matrix3} b The matrix on the right. * @return {!tdl.fast.Matrix3} The matrix product of a and b. */ tdl.fast.columnMajor.mulMatrixMatrix3 = function(dst, a, b) { var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a10 = a[3 + 0]; var a11 = a[3 + 1]; var a12 = a[3 + 2]; var a20 = a[6 + 0]; var a21 = a[6 + 1]; var a22 = a[6 + 2]; var b00 = b[0]; var b01 = b[1]; var b02 = b[2]; var b10 = b[3 + 0]; var b11 = b[3 + 1]; var b12 = b[3 + 2]; var b20 = b[6 + 0]; var b21 = b[6 + 1]; var b22 = b[6 + 2]; dst[0] = a00 * b00 + a10 * b01 + a20 * b02; dst[1] = a01 * b00 + a11 * b01 + a21 * b02; dst[2] = a02 * b00 + a12 * b01 + a22 * b02; dst[3] = a00 * b10 + a10 * b11 + a20 * b12; dst[4] = a01 * b10 + a11 * b11 + a21 * b12; dst[5] = a02 * b10 + a12 * b11 + a22 * b12; dst[6] = a00 * b20 + a10 * b21 + a20 * b22; dst[7] = a01 * b20 + a11 * b21 + a21 * b22; dst[8] = a02 * b20 + a12 * b21 + a22 * b22; return dst; }; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3. * @param {!tdl.fast.Matrix3} a The matrix on the left. * @param {!tdl.fast.Matrix3} b The matrix on the right. * @return {!tdl.fast.Matrix3} The matrix product of a and b. */ tdl.fast.mulMatrixMatrix3 = null; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4; * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.fast.Matrix4} dst matrix. * @param {!tdl.fast.Matrix4} a The matrix on the left. * @param {!tdl.fast.Matrix4} b The matrix on the right. * @return {!tdl.fast.Matrix4} The matrix product of a and b. */ tdl.fast.rowMajor.mulMatrixMatrix4 = function(dst, a, b) { var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[ 4 + 0]; var a11 = a[ 4 + 1]; var a12 = a[ 4 + 2]; var a13 = a[ 4 + 3]; var a20 = a[ 8 + 0]; var a21 = a[ 8 + 1]; var a22 = a[ 8 + 2]; var a23 = a[ 8 + 3]; var a30 = a[12 + 0]; var a31 = a[12 + 1]; var a32 = a[12 + 2]; var a33 = a[12 + 3]; var b00 = b[0]; var b01 = b[1]; var b02 = b[2]; var b03 = b[3]; var b10 = b[ 4 + 0]; var b11 = b[ 4 + 1]; var b12 = b[ 4 + 2]; var b13 = b[ 4 + 3]; var b20 = b[ 8 + 0]; var b21 = b[ 8 + 1]; var b22 = b[ 8 + 2]; var b23 = b[ 8 + 3]; var b30 = b[12 + 0]; var b31 = b[12 + 1]; var b32 = b[12 + 2]; var b33 = b[12 + 3]; dst[ 0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30; dst[ 1] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31; dst[ 2] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32; dst[ 3] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33; dst[ 4] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30; dst[ 5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31; dst[ 6] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32; dst[ 7] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33; dst[ 8] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30; dst[ 9] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31; dst[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32; dst[11] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33; dst[12] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30; dst[13] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31; dst[14] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32; dst[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33; return dst; }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.fast.Matrix4} dst matrix. * @param {!tdl.fast.Matrix4} a The matrix on the left. * @param {!tdl.fast.Matrix4} b The matrix on the right. * @return {!tdl.fast.Matrix4} The matrix product of a and b. */ tdl.fast.columnMajor.mulMatrixMatrix4 = function(dst, a, b) { var a00 = a[0]; var a01 = a[1]; var a02 = a[2]; var a03 = a[3]; var a10 = a[ 4 + 0]; var a11 = a[ 4 + 1]; var a12 = a[ 4 + 2]; var a13 = a[ 4 + 3]; var a20 = a[ 8 + 0]; var a21 = a[ 8 + 1]; var a22 = a[ 8 + 2]; var a23 = a[ 8 + 3]; var a30 = a[12 + 0]; var a31 = a[12 + 1]; var a32 = a[12 + 2]; var a33 = a[12 + 3]; var b00 = b[0]; var b01 = b[1]; var b02 = b[2]; var b03 = b[3]; var b10 = b[ 4 + 0]; var b11 = b[ 4 + 1]; var b12 = b[ 4 + 2]; var b13 = b[ 4 + 3]; var b20 = b[ 8 + 0]; var b21 = b[ 8 + 1]; var b22 = b[ 8 + 2]; var b23 = b[ 8 + 3]; var b30 = b[12 + 0]; var b31 = b[12 + 1]; var b32 = b[12 + 2]; var b33 = b[12 + 3]; dst[ 0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03; dst[ 1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03; dst[ 2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03; dst[ 3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03; dst[ 4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13; dst[ 5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13; dst[ 6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13; dst[ 7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13; dst[ 8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23; dst[ 9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23; dst[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23; dst[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23; dst[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33; dst[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33; dst[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33; dst[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33; return dst; }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4. * @param {!tdl.fast.Matrix4} a The matrix on the left. * @param {!tdl.fast.Matrix4} b The matrix on the right. * @return {!tdl.fast.Matrix4} The matrix product of a and b. */ tdl.fast.mulMatrixMatrix4 = null; /** * Gets the jth column of the given matrix m; assumes matrix entries are * accessed in [row][column] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.fast.Vector} The jth column of m as a vector. */ tdl.fast.rowMajor.column4 = function(dst, m, j) { for (var i = 0; i < 4; ++i) { dst[i] = m[i * 4 + j]; } return dst; }; /** * Gets the jth column of the given matrix m; assumes matrix entries are * accessed in [column][row] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.fast.Vector} The jth column of m as a vector. */ tdl.fast.columnMajor.column4 = function(dst, m, j) { var off = j * 4; dst[0] = m[off + 0]; dst[1] = m[off + 1]; dst[2] = m[off + 2]; dst[3] = m[off + 3]; return dst; }; /** * Gets the jth column of the given matrix m. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.fast.Vector} The jth column of m as a vector. */ tdl.fast.column4 = null; /** * Gets the ith row of the given matrix m; assumes matrix entries are * accessed in [row][column] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} i The index of the desired row. * @return {!tdl.fast.Vector} The ith row of m. */ tdl.fast.rowMajor.row4 = function(dst, m, i) { var off = i * 4; dst[0] = m[off + 0]; dst[1] = m[off + 1]; dst[2] = m[off + 2]; dst[3] = m[off + 3]; return dst; }; /** * Gets the ith row of the given matrix m; assumes matrix entries are * accessed in [column][row] fashion. * @param {!tdl.fast.Vector} dst vector. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} i The index of the desired row. * @return {!tdl.fast.Vector} The ith row of m. */ tdl.fast.columnMajor.row4 = function(dst, m, i) { for (var j = 0; j < 4; ++j) { dst[j] = m[j * 4 + i]; } return dst; }; /** * Gets the ith row of the given matrix m. * @param {!tdl.fast.Matrix} m The matrix. * @param {number} i The index of the desired row. * @return {!tdl.fast.Vector} The ith row of m. */ tdl.fast.row4 = null; /** * Creates an n-by-n identity matrix. * * @param {!tdl.fast.Matrix} dst matrix. * @return {!tdl.fast.Matrix} An n-by-n identity matrix. */ tdl.fast.identity4 = function(dst) { dst[ 0] = 1; dst[ 1] = 0; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = 1; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = 0; dst[ 9] = 0; dst[10] = 1; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Takes the transpose of a matrix. * @param {!tdl.fast.Matrix} dst matrix. * @param {!tdl.fast.Matrix} m The matrix. * @return {!tdl.fast.Matrix} The transpose of m. */ tdl.fast.transpose4 = function(dst, m) { if (dst === m) { var t; t = m[1]; m[1] = m[4]; m[4] = t; t = m[2]; m[2] = m[8]; m[8] = t; t = m[3]; m[3] = m[12]; m[12] = t; t = m[6]; m[6] = m[9]; m[9] = t; t = m[7]; m[7] = m[13]; m[13] = t; t = m[11]; m[11] = m[14]; m[14] = t; return dst; } var m00 = m[0 * 4 + 0]; var m01 = m[0 * 4 + 1]; var m02 = m[0 * 4 + 2]; var m03 = m[0 * 4 + 3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; dst[ 0] = m00; dst[ 1] = m10; dst[ 2] = m20; dst[ 3] = m30; dst[ 4] = m01; dst[ 5] = m11; dst[ 6] = m21; dst[ 7] = m31; dst[ 8] = m02; dst[ 9] = m12; dst[10] = m22; dst[11] = m32; dst[12] = m03; dst[13] = m13; dst[14] = m23; dst[15] = m33; return dst; }; /** * Computes the inverse of a 4-by-4 matrix. * @param {!tdl.fast.Matrix4} dst matrix. * @param {!tdl.fast.Matrix4} m The matrix. * @return {!tdl.fast.Matrix4} The inverse of m. */ tdl.fast.inverse4 = function(dst, m) { var m00 = m[0 * 4 + 0]; var m01 = m[0 * 4 + 1]; var m02 = m[0 * 4 + 2]; var m03 = m[0 * 4 + 3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; var tmp_0 = m22 * m33; var tmp_1 = m32 * m23; var tmp_2 = m12 * m33; var tmp_3 = m32 * m13; var tmp_4 = m12 * m23; var tmp_5 = m22 * m13; var tmp_6 = m02 * m33; var tmp_7 = m32 * m03; var tmp_8 = m02 * m23; var tmp_9 = m22 * m03; var tmp_10 = m02 * m13; var tmp_11 = m12 * m03; var tmp_12 = m20 * m31; var tmp_13 = m30 * m21; var tmp_14 = m10 * m31; var tmp_15 = m30 * m11; var tmp_16 = m10 * m21; var tmp_17 = m20 * m11; var tmp_18 = m00 * m31; var tmp_19 = m30 * m01; var tmp_20 = m00 * m21; var tmp_21 = m20 * m01; var tmp_22 = m00 * m11; var tmp_23 = m10 * m01; var t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) - (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31); var t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) - (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31); var t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) - (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31); var t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) - (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21); var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3); dst[ 0] = d * t0; dst[ 1] = d * t1; dst[ 2] = d * t2; dst[ 3] = d * t3; dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) - (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30)); dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) - (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30)); dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) - (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30)); dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) - (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20)); dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) - (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33)); dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) - (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33)); dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) - (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33)); dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) - (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23)); dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) - (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22)); dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) - (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02)); dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) - (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12)); dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) - (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02)); return dst; }; /** * Computes the inverse of a 4-by-4 matrix. * Note: It is faster to call this than tdl.fast.inverse. * @param {!tdl.fast.Matrix4} m The matrix. * @return {!tdl.fast.Matrix4} The inverse of m. */ tdl.fast.matrix4.inverse = function(dst,m) { return tdl.fast.inverse4(dst,m); }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4. * Note: It is faster to call this than tdl.fast.mul. * @param {!tdl.fast.Matrix4} a The matrix on the left. * @param {!tdl.fast.Matrix4} b The matrix on the right. * @return {!tdl.fast.Matrix4} The matrix product of a and b. */ tdl.fast.matrix4.mul = function(dst, a, b) { return tdl.fast.mulMatrixMatrix4(dst, a, b); }; /** * Copies a Matrix4. * Note: It is faster to call this than tdl.fast.copy. * @param {!tdl.fast.Matrix4} m The matrix. * @return {!tdl.fast.Matrix4} A copy of m. */ tdl.fast.matrix4.copy = function(dst, m) { return tdl.fast.copyMatrix(dst, m); }; /** * Sets the translation component of a 4-by-4 matrix to the given * vector. * @param {!tdl.fast.Matrix4} a The matrix. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} v The vector. * @return {!tdl.fast.Matrix4} a once modified. */ tdl.fast.matrix4.setTranslation = function(a, v) { a[12] = v[0]; a[13] = v[1]; a[14] = v[2]; a[15] = 1; return a; }; /** * Returns the translation component of a 4-by-4 matrix as a vector with 3 * entries. * @return {!tdl.fast.Vector3} dst vector.. * @param {!tdl.fast.Matrix4} m The matrix. * @return {!tdl.fast.Vector3} The translation component of m. */ tdl.fast.matrix4.getTranslation = function(dst, m) { dst[0] = m[12]; dst[1] = m[13]; dst[2] = m[14]; return dst; }; /** * Creates a 4-by-4 identity matrix. * @param {!tdl.fast.Matrix4} dst matrix. * @return {!tdl.fast.Matrix4} The 4-by-4 identity. */ tdl.fast.matrix4.identity = function(dst) { return tdl.fast.identity4(dst); }; tdl.fast.matrix4.getAxis = function(dst, m, axis) { var off = axis * 4; dst[0] = m[off + 0]; dst[1] = m[off + 1]; dst[2] = m[off + 2]; return dst; }; /** * Computes a 4-by-4 perspective transformation matrix given the angular height * of the frustum, the aspect ratio, and the near and far clipping planes. The * arguments define a frustum extending in the negative z direction. The given * angle is the vertical angle of the frustum, and the horizontal angle is * determined to produce the given aspect ratio. The arguments near and far are * the distances to the near and far clipping planes. Note that near and far * are not z coordinates, but rather they are distances along the negative * z-axis. The matrix generated sends the viewing frustum to the unit box. * We assume a unit box extending from -1 to 1 in the x and y dimensions and * from 0 to 1 in the z dimension. * @param {!tdl.fast.Matrix4} dst matrix. * @param {number} angle The camera angle from top to bottom (in radians). * @param {number} aspect The aspect ratio width / height. * @param {number} zNear The depth (negative z coordinate) * of the near clipping plane. * @param {number} zFar The depth (negative z coordinate) * of the far clipping plane. * @return {!tdl.fast.Matrix4} The perspective matrix. */ tdl.fast.matrix4.perspective = function(dst, angle, aspect, zNear, zFar) { var f = Math.tan(Math.PI * 0.5 - 0.5 * angle); var rangeInv = 1.0 / (zNear - zFar); dst[0] = f / aspect; dst[1] = 0; dst[2] = 0; dst[3] = 0; dst[4] = 0; dst[5] = f; dst[6] = 0; dst[7] = 0; dst[8] = 0; dst[9] = 0; dst[10] = (zNear + zFar) * rangeInv; dst[11] = -1; dst[12] = 0; dst[13] = 0; dst[14] = zNear * zFar * rangeInv * 2; dst[15] = 0; return dst; }; /** * Computes a 4-by-4 othogonal transformation matrix given the left, right, * bottom, and top dimensions of the near clipping plane as well as the * near and far clipping plane distances. * @param {!tdl.fast.Matrix4} dst Output matrix. * @param {number} left Left side of the near clipping plane viewport. * @param {number} right Right side of the near clipping plane viewport. * @param {number} top Top of the near clipping plane viewport. * @param {number} bottom Bottom of the near clipping plane viewport. * @param {number} near The depth (negative z coordinate) * of the near clipping plane. * @param {number} far The depth (negative z coordinate) * of the far clipping plane. * @return {!tdl.fast.Matrix4} The perspective matrix. */ tdl.fast.matrix4.ortho = function(dst, left, right, bottom, top, near, far) { dst[0] = 2 / (right - left); dst[1] = 0; dst[2] = 0; dst[3] = 0; dst[4] = 0; dst[5] = 2 / (top - bottom); dst[6] = 0; dst[7] = 0; dst[8] = 0; dst[9] = 0; dst[10] = -1 / (far - near); dst[11] = 0; dst[12] = (right + left) / (left - right); dst[13] = (top + bottom) / (bottom - top); dst[14] = -near / (near - far); dst[15] = 1; return dst; } /** * Computes a 4-by-4 perspective transformation matrix given the left, right, * top, bottom, near and far clipping planes. The arguments define a frustum * extending in the negative z direction. The arguments near and far are the * distances to the near and far clipping planes. Note that near and far are not * z coordinates, but rather they are distances along the negative z-axis. The * matrix generated sends the viewing frustum to the unit box. We assume a unit * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z * dimension. * @param {number} left The x coordinate of the left plane of the box. * @param {number} right The x coordinate of the right plane of the box. * @param {number} bottom The y coordinate of the bottom plane of the box. * @param {number} top The y coordinate of the right plane of the box. * @param {number} near The negative z coordinate of the near plane of the box. * @param {number} far The negative z coordinate of the far plane of the box. * @return {!tdl.fast.Matrix4} The perspective projection matrix. */ tdl.fast.matrix4.frustum = function(dst, left, right, bottom, top, near, far) { var dx = (right - left); var dy = (top - bottom); var dz = (near - far); dst[ 0] = 2 * near / dx; dst[ 1] = 0; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = 2 * near / dy; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = (left + right) / dx; dst[ 9] = (top + bottom) / dy; dst[10] = far / dz; dst[11] = -1; dst[12] = 0; dst[13] = 0; dst[14] = near * far / dz; dst[15] = 0; return dst; }; /** * Computes a 4-by-4 look-at transformation. The transformation generated is * an orthogonal rotation matrix with translation component. The translation * component sends the eye to the origin. The rotation component sends the * vector pointing from the eye to the target to a vector pointing in the * negative z direction, and also sends the up vector into the upper half of * the yz plane. * @return {!tdl.fast.Matrix4} dst matrix. * @param {(!tdl.fast.Vector3} eye The * position of the eye. * @param {(!tdl.fast.Vector3} target The * position meant to be viewed. * @param {(!tdl.fast.Vector3} up A vector * pointing up. * @return {!tdl.fast.Matrix4} The look-at matrix. */ tdl.fast.matrix4.lookAt = function(dst, eye, target, up) { var t0 = tdl.fast.temp0v3_; var t1 = tdl.fast.temp1v3_; var t2 = tdl.fast.temp2v3_; var vz = tdl.fast.normalize(t0, tdl.fast.subVector(t0, eye, target)); var vx = tdl.fast.normalize(t1, tdl.fast.cross(t1, up, vz)); var vy = tdl.fast.cross(t2, vz, vx); dst[ 0] = vx[0]; dst[ 1] = vy[0]; dst[ 2] = vz[0]; dst[ 3] = 0; dst[ 4] = vx[1]; dst[ 5] = vy[1]; dst[ 6] = vz[1]; dst[ 7] = 0; dst[ 8] = vx[2]; dst[ 9] = vy[2]; dst[10] = vz[2]; dst[11] = 0; dst[12] = -tdl.fast.dot(vx, eye); dst[13] = -tdl.fast.dot(vy, eye); dst[14] = -tdl.fast.dot(vz, eye); dst[15] = 1; return dst; }; /** * Computes a 4-by-4 camera look-at transformation. This is the * inverse of lookAt The transformation generated is an * orthogonal rotation matrix with translation component. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} eye The position * of the eye. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} target The * position meant to be viewed. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} up A vector * pointing up. * @return {!tdl.fast.Matrix4} The camera look-at matrix. */ tdl.fast.matrix4.cameraLookAt = function(dst, eye, target, up) { var t0 = tdl.fast.temp0v3_; var t1 = tdl.fast.temp1v3_; var t2 = tdl.fast.temp2v3_; var vz = tdl.fast.normalize(t0, tdl.fast.subVector(t0, eye, target)); var vx = tdl.fast.normalize(t1, tdl.fast.cross(t1, up, vz)); var vy = tdl.fast.cross(t2, vz, vx); dst[ 0] = vx[0]; dst[ 1] = vx[1]; dst[ 2] = vx[2]; dst[ 3] = 0; dst[ 4] = vy[0]; dst[ 5] = vy[1]; dst[ 6] = vy[2]; dst[ 7] = 0; dst[ 8] = vz[0]; dst[ 9] = vz[1]; dst[10] = vz[2]; dst[11] = 0; dst[12] = eye[0]; dst[13] = eye[1]; dst[14] = eye[2]; dst[15] = 1; return dst; }; /** * Creates a 4-by-4 matrix which translates by the given vector v. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} v The vector by * which to translate. * @return {!tdl.fast.Matrix4} The translation matrix. */ tdl.fast.matrix4.translation = function(dst, v) { dst[ 0] = 1; dst[ 1] = 0; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = 1; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = 0; dst[ 9] = 0; dst[10] = 1; dst[11] = 0; dst[12] = v[0]; dst[13] = v[1]; dst[14] = v[2]; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix by translation by the given vector v. * @param {!tdl.fast.Matrix4} m The matrix. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} v The vector by * which to translate. * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.translate = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; var m00 = m[0]; var m01 = m[1]; var m02 = m[2]; var m03 = m[3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; m[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30; m[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31; m[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32; m[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33; return m; }; tdl.fast.matrix4.transpose = tdl.fast.transpose4; /** * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} The rotation matrix. */ tdl.fast.matrix4.rotationX = function(dst, angle) { var c = Math.cos(angle); var s = Math.sin(angle); dst[ 0] = 1; dst[ 1] = 0; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = c; dst[ 6] = s; dst[ 7] = 0; dst[ 8] = 0; dst[ 9] = -s; dst[10] = c; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix by a rotation around the x-axis by the given * angle. * @param {!tdl.fast.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.rotateX = function(m, angle) { var m10 = m[4]; var m11 = m[5]; var m12 = m[6]; var m13 = m[7]; var m20 = m[8]; var m21 = m[9]; var m22 = m[10]; var m23 = m[11]; var c = Math.cos(angle); var s = Math.sin(angle); m[4] = c * m10 + s * m20; m[5] = c * m11 + s * m21; m[6] = c * m12 + s * m22; m[7] = c * m13 + s * m23; m[8] = c * m20 - s * m10; m[9] = c * m21 - s * m11; m[10] = c * m22 - s * m12; m[11] = c * m23 - s * m13; return m; }; /** * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} The rotation matrix. */ tdl.fast.matrix4.rotationY = function(dst, angle) { var c = Math.cos(angle); var s = Math.sin(angle); dst[ 0] = c; dst[ 1] = 0; dst[ 2] = -s; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = 1; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = s; dst[ 9] = 0; dst[10] = c; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix by a rotation around the y-axis by the given * angle. * @param {!tdl.fast.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.rotateY = function(m, angle) { var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var c = Math.cos(angle); var s = Math.sin(angle); m[ 0] = c * m00 - s * m20; m[ 1] = c * m01 - s * m21; m[ 2] = c * m02 - s * m22; m[ 3] = c * m03 - s * m23; m[ 8] = c * m20 + s * m00; m[ 9] = c * m21 + s * m01; m[10] = c * m22 + s * m02; m[11] = c * m23 + s * m03; return m; }; /** * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} The rotation matrix. */ tdl.fast.matrix4.rotationZ = function(dst, angle) { var c = Math.cos(angle); var s = Math.sin(angle); dst[ 0] = c; dst[ 1] = s; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = -s; dst[ 5] = c; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = 0; dst[ 9] = 0; dst[10] = 1; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix by a rotation around the z-axis by the given * angle. * @param {!tdl.fast.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.rotateZ = function(m, angle) { var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var c = Math.cos(angle); var s = Math.sin(angle); m[ 0] = c * m00 + s * m10; m[ 1] = c * m01 + s * m11; m[ 2] = c * m02 + s * m12; m[ 3] = c * m03 + s * m13; m[ 4] = c * m10 - s * m00; m[ 5] = c * m11 - s * m01; m[ 6] = c * m12 - s * m02; m[ 7] = c * m13 - s * m03; return m; }; /** * Creates a 4-by-4 matrix which rotates around the given axis by the given * angle. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} axis The axis * about which to rotate. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} A matrix which rotates angle radians * around the axis. */ tdl.fast.matrix4.axisRotation = function(dst, axis, angle) { var x = axis[0]; var y = axis[1]; var z = axis[2]; var n = Math.sqrt(x * x + y * y + z * z); x /= n; y /= n; z /= n; var xx = x * x; var yy = y * y; var zz = z * z; var c = Math.cos(angle); var s = Math.sin(angle); var oneMinusCosine = 1 - c; dst[ 0] = xx + (1 - xx) * c; dst[ 1] = x * y * oneMinusCosine + z * s; dst[ 2] = x * z * oneMinusCosine - y * s; dst[ 3] = 0; dst[ 4] = x * y * oneMinusCosine - z * s; dst[ 5] = yy + (1 - yy) * c; dst[ 6] = y * z * oneMinusCosine + x * s; dst[ 7] = 0; dst[ 8] = x * z * oneMinusCosine + y * s; dst[ 9] = y * z * oneMinusCosine - x * s; dst[10] = zz + (1 - zz) * c; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix by rotation around the given axis by the * given angle. * @param {!tdl.fast.Matrix4} m The matrix. * @param {(!tdl.fast.Vector3|!tdl.fast.Vector4)} axis The axis * about which to rotate. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.axisRotate = function(m, axis, angle) { var x = axis[0]; var y = axis[1]; var z = axis[2]; var n = Math.sqrt(x * x + y * y + z * z); x /= n; y /= n; z /= n; var xx = x * x; var yy = y * y; var zz = z * z; var c = Math.cos(angle); var s = Math.sin(angle); var oneMinusCosine = 1 - c; var r00 = xx + (1 - xx) * c; var r01 = x * y * oneMinusCosine + z * s; var r02 = x * z * oneMinusCosine - y * s; var r10 = x * y * oneMinusCosine - z * s; var r11 = yy + (1 - yy) * c; var r12 = y * z * oneMinusCosine + x * s; var r20 = x * z * oneMinusCosine + y * s; var r21 = y * z * oneMinusCosine - x * s; var r22 = zz + (1 - zz) * c; var m00 = m[0]; var m01 = m[1]; var m02 = m[2]; var m03 = m[3]; var m10 = m[4]; var m11 = m[5]; var m12 = m[6]; var m13 = m[7]; var m20 = m[8]; var m21 = m[9]; var m22 = m[10]; var m23 = m[11]; var m30 = m[12]; var m31 = m[13]; var m32 = m[14]; var m33 = m[15]; m[ 0] = r00 * m00 + r01 * m10 + r02 * m20; m[ 1] = r00 * m01 + r01 * m11 + r02 * m21; m[ 2] = r00 * m02 + r01 * m12 + r02 * m22; m[ 3] = r00 * m03 + r01 * m13 + r02 * m23; m[ 4] = r10 * m00 + r11 * m10 + r12 * m20; m[ 5] = r10 * m01 + r11 * m11 + r12 * m21; m[ 6] = r10 * m02 + r11 * m12 + r12 * m22; m[ 7] = r10 * m03 + r11 * m13 + r12 * m23; m[ 8] = r20 * m00 + r21 * m10 + r22 * m20; m[ 9] = r20 * m01 + r21 * m11 + r22 * m21; m[10] = r20 * m02 + r21 * m12 + r22 * m22; m[11] = r20 * m03 + r21 * m13 + r22 * m23; return m; }; /** * Creates a 4-by-4 matrix which scales in each dimension by an amount given by * the corresponding entry in the given vector; assumes the vector has three * entries. * @param {!tdl.fast.Vector3} v A vector of * three entries specifying the factor by which to scale in each dimension. * @return {!tdl.fast.Matrix4} The scaling matrix. */ tdl.fast.matrix4.scaling = function(dst, v) { dst[ 0] = v[0]; dst[ 1] = 0; dst[ 2] = 0; dst[ 3] = 0; dst[ 4] = 0; dst[ 5] = v[1]; dst[ 6] = 0; dst[ 7] = 0; dst[ 8] = 0; dst[ 9] = 0; dst[10] = v[2]; dst[11] = 0; dst[12] = 0; dst[13] = 0; dst[14] = 0; dst[15] = 1; return dst; }; /** * Modifies the given 4-by-4 matrix, scaling in each dimension by an amount * given by the corresponding entry in the given vector; assumes the vector has * three entries. * @param {!tdl.fast.Matrix4} m The matrix to be modified. * @param {!tdl.fast.Vector3} v A vector of three entries specifying the * factor by which to scale in each dimension. * @return {!tdl.fast.Matrix4} m once modified. */ tdl.fast.matrix4.scale = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; m[0] = v0 * m[0*4+0]; m[1] = v0 * m[0*4+1]; m[2] = v0 * m[0*4+2]; m[3] = v0 * m[0*4+3]; m[4] = v1 * m[1*4+0]; m[5] = v1 * m[1*4+1]; m[6] = v1 * m[1*4+2]; m[7] = v1 * m[1*4+3]; m[8] = v2 * m[2*4+0]; m[9] = v2 * m[2*4+1]; m[10] = v2 * m[2*4+2]; m[11] = v2 * m[2*4+3]; return m; }; /** * Sets each function in the namespace tdl.fast to the row major * version in tdl.fast.rowMajor (provided such a function exists in * tdl.fast.rowMajor). Call this function to establish the row major * convention. */ tdl.fast.installRowMajorFunctions = function() { for (var f in tdl.fast.rowMajor) { tdl.fast[f] = tdl.fast.rowMajor[f]; } }; /** * Sets each function in the namespace tdl.fast to the column major * version in tdl.fast.columnMajor (provided such a function exists in * tdl.fast.columnMajor). Call this function to establish the column * major convention. */ tdl.fast.installColumnMajorFunctions = function() { for (var f in tdl.fast.columnMajor) { tdl.fast[f] = tdl.fast.columnMajor[f]; } }; // By default, install the row-major functions. tdl.fast.installRowMajorFunctions();
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains various functions and class for io. */ tdl.provide('tdl.io'); /** * A Module with various io functions and classes. * @namespace */ tdl.io = tdl.io || {}; /** * Creates a LoadInfo object. * @param {XMLHttpRequest} opt_request * The request to watch. * @return {!tdl.io.LoadInfo} The new LoadInfo. * @see tdl.io.LoadInfo */ tdl.io.createLoadInfo = function(opt_request) { return new tdl.io.LoadInfo(opt_request); }; /** * A class to help with progress reporting for most loading utilities. * * Example: * <pre> * var g_loadInfo = null; * g_id = window.setInterval(statusUpdate, 500); * g_loadInfo = tdl.scene.loadScene('http://google.com/somescene.js', * callback); * * function callback(exception) { * g_loadInfo = null; * window.clearInterval(g_id); * if (!exception) { * // do something with scene just loaded * } * } * * function statusUpdate() { * if (g_loadInfo) { * var progress = g_loadInfo.getKnownProgressInfoSoFar(); * document.getElementById('loadstatus').innerHTML = progress.percent; * } * } * </pre> * * @constructor * @param {XMLHttpRequest} opt_request * The request to watch. * @see tdl.loader.Loader */ tdl.io.LoadInfo = function(opt_request) { this.request_ = opt_request; this.streamLength_ = 0; // because the request may have been freed. this.children_ = []; }; /** * Adds another LoadInfo as a child of this LoadInfo so they can be * managed as a group. * @param {!tdl.io.LoadInfo} loadInfo The child LoadInfo. */ tdl.io.LoadInfo.prototype.addChild = function(loadInfo) { this.children_.push(loadInfo); }; /** * Marks this LoadInfo as finished. */ tdl.io.LoadInfo.prototype.finish = function() { if (this.request_) { if (this.hasStatus_) { this.streamLength_ = this.request_.streamLength; } this.request_ = null; } }; /** * Gets the total bytes that will be streamed known so far. * If you are only streaming 1 file then this will be the info for that file but * if you have queued up many files using an tdl.loader.Loader only a couple of * files are streamed at a time meaning that the size is not known for files * that have yet started to download. * * If you are downloading many files for your application and you want to * provide a progress status you have about 4 options * * 1) Use LoadInfo.getTotalBytesDownloaded() / * LoadInfo.getTotalKnownBytesToStreamSoFar() and just be aware the bar will * grown and then shrink as new files start to download and their lengths * become known. * * 2) Use LoadInfo.getTotalRequestsDownloaded() / * LoadInfo.getTotalKnownRequestsToStreamSoFar() and be aware the granularity * is not all that great since it only reports fully downloaded files. If you * are downloading a bunch of small files this might be ok. * * 3) Put all your files in one archive. Then there will be only one file and * method 1 will work well. * * 4) Figure out the total size in bytes of the files you will download and put * that number in your application, then use LoadInfo.getTotalBytesDownloaded() * / MY_APPS_TOTAL_BYTES_TO_DOWNLOAD. * * @return {number} The total number of currently known bytes to be streamed. */ tdl.io.LoadInfo.prototype.getTotalKnownBytesToStreamSoFar = function() { //if (!this.streamLength_ && this.request_ && this.hasStatus_) { // // // //this.streamLength_ = this.request_.streamLength; //} var total = this.streamLength_; for (var cc = 0; cc < this.children_.length; ++cc) { total += this.children_[cc].getTotalKnownBytesToStreamSoFar(); } return total; }; /** * Gets the total bytes downloaded so far. * @return {number} The total number of currently known bytes to be streamed. */ tdl.io.LoadInfo.prototype.getTotalBytesDownloaded = function() { var total = (this.request_ && this.hasStatus_) ? this.request_.bytesReceived : this.streamLength_; for (var cc = 0; cc < this.children_.length; ++cc) { total += this.children_[cc].getTotalBytesDownloaded(); } return total; }; /** * Gets the total streams that will be download known so far. * We can't know all the streams since you could use an tdl.loader.Loader * object, request some streams, then call this function, then request some * more. * * See LoadInfo.getTotalKnownBytesToStreamSoFar for details. * @return {number} The total number of requests currently known to be streamed. * @see tdl.io.LoadInfo.getTotalKnownBytesToStreamSoFar */ tdl.io.LoadInfo.prototype.getTotalKnownRequestsToStreamSoFar = function() { var total = 1; for (var cc = 0; cc < this.children_.length; ++cc) { total += this.children_[cc].getTotalKnownRequestToStreamSoFar(); } return total; }; /** * Gets the total requests downloaded so far. * @return {number} The total requests downloaded so far. */ tdl.io.LoadInfo.prototype.getTotalRequestsDownloaded = function() { var total = this.request_ ? 0 : 1; for (var cc = 0; cc < this.children_.length; ++cc) { total += this.children_[cc].getTotalRequestsDownloaded(); } return total; }; /** * Gets progress info. * This is commonly formatted version of the information available from a * LoadInfo. * * See LoadInfo.getTotalKnownBytesToStreamSoFar for details. * @return {{percent: number, downloaded: string, totalBytes: string, * base: number, suffix: string}} progress info. * @see tdl.io.LoadInfo.getTotalKnownBytesToStreamSoFar */ tdl.io.LoadInfo.prototype.getKnownProgressInfoSoFar = function() { var percent = 0; var bytesToDownload = this.getTotalKnownBytesToStreamSoFar(); var bytesDownloaded = this.getTotalBytesDownloaded(); if (bytesToDownload > 0) { percent = Math.floor(bytesDownloaded / bytesToDownload * 100); } var base = (bytesToDownload < 1024 * 1024) ? 1024 : (1024 * 1024); return { percent: percent, downloaded: (bytesDownloaded / base).toFixed(2), totalBytes: (bytesToDownload / base).toFixed(2), base: base, suffix: (base == 1024 ? 'kb' : 'mb')} }; /** * Loads text from an external file. This function is synchronous. * @param {string} url The url of the external file. * @return {string} the loaded text if the request is synchronous. */ tdl.io.loadTextFileSynchronous = function(url) { var error = 'loadTextFileSynchronous failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/plain'); } } else if (window.ActiveXObject) { request = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } else { throw 'XMLHttpRequest is disabled'; } request.open('GET', url, false); request.send(null); if (request.readyState != 4) { throw error; } return request.responseText; }; /** * Loads text from an external file. This function is asynchronous. * @param {string} url The url of the external file. * @param {function(string, *): void} callback A callback passed the loaded * string and an exception which will be null on success. * @return {!tdl.io.LoadInfo} A LoadInfo to track progress. */ tdl.io.loadTextFile = function(url, callback) { var error = 'loadTextFile failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/plain; charset=utf-8'); } } else if (window.ActiveXObject) { request = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } else { throw 'XMLHttpRequest is disabled'; } var loadInfo = tdl.io.createLoadInfo(request, false); request.open('GET', url, true); var finish = function() { if (request.readyState == 4) { var text = ''; // HTTP reports success with a 200 status. The file protocol reports // success with zero. HTTP does not use zero as a status code (they // start at 100). // https://developer.mozilla.org/En/Using_XMLHttpRequest var success = request.status == 200 || request.status == 0; if (success) { text = request.responseText; } loadInfo.finish(); callback(text, success ? null : 'could not load: ' + url); } }; request.onreadystatechange = finish; request.send(null); return loadInfo; }; /** * Loads a file from an external file. This function is * asynchronous. * @param {string} url The url of the external file. * @param {function(string, *): void} callback A callback passed the loaded * ArrayBuffer and an exception which will be null on * success. * @return {!tdl.io.LoadInfo} A LoadInfo to track progress. */ tdl.io.loadArrayBuffer = function(url, callback) { var error = 'loadArrayBuffer failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); } else { throw 'XMLHttpRequest is disabled'; } var loadInfo = tdl.io.createLoadInfo(request, false); request.open('GET', url, true); var finish = function() { if (request.readyState == 4) { var text = ''; // HTTP reports success with a 200 status. The file protocol reports // success with zero. HTTP does not use zero as a status code (they // start at 100). // https://developer.mozilla.org/En/Using_XMLHttpRequest var success = request.status == 200 || request.status == 0; if (success) { arrayBuffer = request.response; } loadInfo.finish(); callback(arrayBuffer, success ? null : 'could not load: ' + url); } }; request.onreadystatechange = finish; if (request.responseType === undefined) { throw 'no support for binary files'; } request.responseType = "arraybuffer"; request.send(null); return loadInfo; }; /** * Loads JSON from an external file. This function is asynchronous. * @param {string} url The url of the external file. * @param {function(jsonObject, *): void} callback A callback passed the loaded * json and an exception which will be null on success. * @return {!tdl.io.LoadInfo} A LoadInfo to track progress. */ tdl.io.loadJSON = function(url, callback) { var error = 'loadJSON failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/plain'); } } else if (window.ActiveXObject) { request = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } else { throw 'XMLHttpRequest is disabled'; } var loadInfo = tdl.io.createLoadInfo(request, false); request.open('GET', url, true); var finish = function() { if (request.readyState == 4) { var json = undefined; // HTTP reports success with a 200 status. The file protocol reports // success with zero. HTTP does not use zero as a status code (they // start at 100). // https://developer.mozilla.org/En/Using_XMLHttpRequest var success = request.status == 200 || request.status == 0; if (success) { try { json = JSON.parse(request.responseText); } catch (e) { success = false; } } loadInfo.finish(); callback(json, success ? null : 'could not load: ' + url); } }; try { request.onreadystatechange = finish; request.send(null); } catch (e) { callback(null, 'could not load: ' + url); } return loadInfo; }; /** * Sends an object. This function is asynchronous. * @param {string} url The url of the external file. * @param {function(jsonObject, *): void} callback A callback passed the loaded * json and an exception which will be null on success. * @return {!tdl.io.LoadInfo} A LoadInfo to track progress. */ tdl.io.sendJSON = function(url, jsonObject, callback) { var error = 'sendJSON failed to load url "' + url + '"'; var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/plain'); } } else if (window.ActiveXObject) { request = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } else { throw 'XMLHttpRequest is disabled'; } var loadInfo = tdl.io.createLoadInfo(request, false); request.open('POST', url, true); var js = JSON.stringify(jsonObject); var finish = function() { if (request.readyState == 4) { var json = undefined; // HTTP reports success with a 200 status. The file protocol reports // success with zero. HTTP does not use zero as a status code (they // start at 100). // https://developer.mozilla.org/En/Using_XMLHttpRequest var success = request.status == 200 || request.status == 0; if (success) { try { json = JSON.parse(request.responseText); } catch (e) { success = false; } } loadInfo.finish(); callback(json, success ? null : 'could not load: ' + url); } }; try { request.onreadystatechange = finish; request.setRequestHeader("Content-type", "application/json"); request.send(js); } catch (e) { callback(null, 'could not load: ' + url); } return loadInfo; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to manage models. */ tdl.provide('tdl.models'); tdl.require('tdl.buffers'); /** * A module for models. * @namespace */ tdl.models = tdl.models || {}; /** * Manages a program, buffers and textures for easier drawing. * @constructor * @param {!tdl.programs.Program} program The program to render * this model with * @param {!Object.<string, AttribBuffer>} arrays The * AttribBuffers to bind to draw this model. * @param {!Object.<string, Texture>} textures The textures to * bind to draw this model. * @param {number} opt_mode Mode to call drawElements with. Default = * gl.TRIANGLES */ tdl.models.Model = function(program, arrays, textures, opt_mode) { this.buffers = { }; this.setBuffers(arrays); var textureUnits = { } var unit = 0; for (var texture in program.textures) { textureUnits[texture] = unit++; } this.mode = (opt_mode === undefined) ? gl.TRIANGLES : opt_mode; this.textures = textures; this.textureUnits = textureUnits; this.setProgram(program); } tdl.models.Model.prototype.setProgram = function(program) { this.program = program; } tdl.models.Model.prototype.setBuffer = function(name, array, opt_newBuffer) { var target = (name == 'indices') ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; var b = this.buffers[name]; if (!b || opt_newBuffer) { b = new tdl.buffers.Buffer(array, target); } else { b.set(array); } this.buffers[name] = b; }; tdl.models.Model.prototype.setBuffers = function(arrays, opt_newBuffers) { var that = this; for (var name in arrays) { this.setBuffer(name, arrays[name], opt_newBuffers); } if (this.buffers.indices) { this.baseBuffer = this.buffers.indices; this.drawFunc = function(totalComponents, startOffset) { gl.drawElements(that.mode, totalComponents, gl.UNSIGNED_SHORT, startOffset); } } else { for (var key in this.buffers) { this.baseBuffer = this.buffers[key]; break; } this.drawFunc = function(totalComponents, startOffset) { gl.drawArrays(that.mode, startOffset, totalComponents); } } }; tdl.models.Model.prototype.applyUniforms_ = function(opt_uniforms) { if (opt_uniforms) { var program = this.program; for (var uniform in opt_uniforms) { program.setUniform(uniform, opt_uniforms[uniform]); } } }; /** * Sets up the shared parts of drawing this model. Uses the * program, binds the buffers, sets the textures. * * @param {!Object.<string, *>} opt_uniforms An object of names to * values to set on this models uniforms. * @param {!Object.<string, *>} opt_textures An object of names to * textures to set on this models uniforms. */ tdl.models.Model.prototype.drawPrep = function() { var program = this.program; var buffers = this.buffers; var textures = this.textures; program.use(); for (var buffer in buffers) { var b = buffers[buffer]; if (buffer == 'indices') { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b.buffer()); } else { var attrib = program.attrib[buffer]; if (attrib) { attrib(b); } } } this.applyUniforms_(textures); for (var ii = 0; ii < arguments.length; ++ii) { this.applyUniforms_(arguments[ii]); } }; /** * Draws this model. * * After calling tdl.models.Model.drawPrep you can call this * function multiple times to draw this model. * * @param {!Object.<string, *>} opt_uniforms An object of names to * values to set on this models uniforms. * @param {!Object.<string, *>} opt_textures An object of names to * textures to set on this models uniforms. */ tdl.models.Model.prototype.draw = function() { var buffers = this.buffers; var totalComponents = buffers.indices.totalComponents(); var startOffset = 0; for (var ii = 0; ii < arguments.length; ++ii) { var arg = arguments[ii]; if (typeof arg == 'number') { switch (ii) { case 0: totalComponents = arg; break; case 1: startOffset = arg; break; default: throw 'unvalid argument'; } } else { this.applyUniforms_(arg); } } this.drawFunc(totalComponents, startOffset); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains various functions for managing a clock */ tdl.provide('tdl.clock'); tdl.require('tdl.io'); tdl.require('tdl.log'); /** * Creates a clock. Optionally synced to a server * @param {number} opt_syncRate. If passed, this is the number of seconds * between syncing to the server. If not passed the local clock is used. * Note: If the client is faster than the server this means it's possible * the clock will report a certain time and then later a previous time. */ tdl.clock.createClock = function(opt_syncRate, opt_url) { if (opt_syncRate) { return new tdl.clock.SyncedClock(opt_syncRate, opt_url); } else { return new tdl.clock.LocalClock(); } }; /** * A clock that gets the local current time in seconds. * @private */ tdl.clock.LocalClock = function() { } /** * Gets the current time in seconds. * @private */ tdl.clock.LocalClock.prototype.getTime = function() { return (new Date()).getTime() * 0.001; } /** * A clock that gets the current time in seconds attempting to eep the clock * synced to the server. * @private */ tdl.clock.SyncedClock = function(opt_syncRate, opt_url) { this.url = opt_url || window.location.href; this.syncRate = opt_syncRate || 10; this.timeOffset = 0; this.syncToServer(); } tdl.clock.SyncedClock.prototype.getLocalTime_ = function() { return (new Date()).getTime() * 0.001; } tdl.clock.SyncedClock.prototype.syncToServer = function() { var that = this; var sendTime = this.getLocalTime_(); tdl.io.sendJSON(this.url, {cmd: 'time'}, function(obj, exception) { if (exception) { tdl.log("error: syncToServer: " + exception); } else { var receiveTime = that.getLocalTime_(); var duration = receiveTime - sendTime; var serverTime = obj.time + duration * 0.5; that.timeOffset = serverTime - receiveTime; tdl.log("new timeoffset: " + that.timeOffset); } setTimeout(function() { that.syncToServer(); }, that.syncRate * 1000); }); }; /** * Gets the current time in seconds. * @private */ tdl.clock.SyncedClock.prototype.getTime = function() { return (new Date()).getTime() * 0.001 + this.timeOffset; }
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Base for all tdl sample utilties. * * The main point of this module is to provide a central place to * have an init function to register an tdl namespace object because many other * modules need access to it. */ /** * A namespace for all the tdl utility libraries. * @namespace */ var tdl = tdl || {}; /** * Define this because the Google internal JSCompiler needs goog.typedef below. */ var goog = goog || {}; if (!window.Int32Array) { window.Int32Array = function() { }; window.Float32Array = function() { }; window.Uint16Array = function() { }; } /** * A macro for defining composite types. * * By assigning goog.typedef to a name, this tells Google internal JSCompiler * that this is not the name of a class, but rather it's the name of a composite * type. * * For example, * /** @type {Array|NodeList} / goog.ArrayLike = goog.typedef; * will tell JSCompiler to replace all appearances of goog.ArrayLike in type * definitions with the union of Array and NodeList. * * Does nothing in uncompiled code. */ goog.typedef = true; /** * Reference to the global context. In most cases this will be 'window'. */ tdl.global = this; /** * Some javascripts don't support __defineGetter__ or __defineSetter__ * so we define some here so at least we don't get compile errors. * We expect the initialzation code will check and complain. This stubs * are just here to make sure we can actually get to the initialization code. */ //if (!Object.prototype.__defineSetter__) { // Object.prototype.__defineSetter__ = function() {} // Object.prototype.__defineGetter__ = function() {} //} // /** * Flag used to force a function to run in the browser when it is called * from V8. * @type {boolean} */ tdl.BROWSER_ONLY = true; /** * Array of namespaces that have been provided. * @private * @type {!Array.<string>} */ tdl.provided_ = []; /** * Creates object stubs for a namespace. When present in a file, * tdl.provide also indicates that the file defines the indicated * object. * @param {string} name name of the object that this file defines. */ tdl.provide = function(name) { // Ensure that the same namespace isn't provided twice. if (tdl.getObjectByName(name) && !tdl.implicitNamespaces_[name]) { throw 'Namespace "' + name + '" already declared.'; } var namespace = name; while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) { tdl.implicitNamespaces_[namespace] = true; } tdl.exportPath_(name); tdl.provided_.push(name); }; /** * Namespaces implicitly defined by tdl.provide. For example, * tdl.provide('tdl.events.Event') implicitly declares * that 'tdl' and 'tdl.events' must be namespaces. * * @type {Object} * @private */ tdl.implicitNamespaces_ = {}; /** * Builds an object structure for the provided namespace path, * ensuring that names that already exist are not overwritten. For * example: * "a.b.c" -> a = {};a.b={};a.b.c={}; * Used by tdl.provide and tdl.exportSymbol. * @param {string} name name of the object that this file defines. * @param {Object} opt_object the object to expose at the end of the path. * @param {Object} opt_objectToExportTo The object to add the path to; default * is |tdl.global|. * @private */ tdl.exportPath_ = function(name, opt_object, opt_objectToExportTo) { var parts = name.split('.'); var cur = opt_objectToExportTo || tdl.global; var part; // Internet Explorer exhibits strange behavior when throwing errors from // methods externed in this manner. See the testExportSymbolExceptions in // base_test.html for an example. if (!(parts[0] in cur) && cur.execScript) { cur.execScript('var ' + parts[0]); } // Parentheses added to eliminate strict JS warning in Firefox. while (parts.length && (part = parts.shift())) { if (!parts.length && tdl.isDef(opt_object)) { // last part and we have an object; use it. cur[part] = opt_object; } else if (cur[part]) { cur = cur[part]; } else { cur = cur[part] = {}; } } }; /** * Returns an object based on its fully qualified external name. If you are * using a compilation pass that renames property names beware that using this * function will not find renamed properties. * * @param {string} name The fully qualified name. * @param {Object} opt_obj The object within which to look; default is * |tdl.global|. * @return {Object} The object or, if not found, null. */ tdl.getObjectByName = function(name, opt_obj) { var parts = name.split('.'); var cur = opt_obj || tdl.global; for (var pp = 0; pp < parts.length; ++pp) { var part = parts[pp]; if (cur[part]) { cur = cur[part]; } else { return null; } } return cur; }; /** * Implements a system for the dynamic resolution of dependencies. * @param {string} rule Rule to include, in the form tdl.package.part. */ tdl.require = function(rule) { // TODO(gman): For some unknown reason, when we call // tdl.util.getScriptTagText_ it calls // document.getElementsByTagName('script') and for some reason the scripts do // not always show up. Calling it here seems to fix that as long as we // actually ask for the length, at least in FF 3.5.1 It would be nice to // figure out why. var dummy = document.getElementsByTagName('script').length; // if the object already exists we do not need do do anything if (tdl.getObjectByName(rule)) { return; } var path = tdl.getPathFromRule_(rule); if (path) { tdl.included_[path] = true; tdl.writeScripts_(); } else { throw new Error('tdl.require could not find: ' + rule); } }; /** * Path for included scripts. * @type {string} */ tdl.basePath = ''; /** * Object used to keep track of urls that have already been added. This * record allows the prevention of circular dependencies. * @type {Object} * @private */ tdl.included_ = {}; /** * This object is used to keep track of dependencies and other data that is * used for loading scripts. * @private * @type {Object} */ tdl.dependencies_ = { visited: {}, // used when resolving dependencies to prevent us from // visiting the file twice. written: {} // used to keep track of script files we have written. }; /** * Tries to detect the base path of the tdl-base.js script that * bootstraps the tdl libraries. * @private */ tdl.findBasePath_ = function() { var doc = tdl.global.document; if (typeof doc == 'undefined') { return; } if (tdl.global.BASE_PATH) { tdl.basePath = tdl.global.BASE_PATH; return; } else { // HACKHACK to hide compiler warnings :( tdl.global.BASE_PATH = null; } var expectedBase = 'tdl/base.js'; var scripts = doc.getElementsByTagName('script'); for (var script, i = 0; script = scripts[i]; i++) { var src = script.src; var l = src.length; if (src.substr(l - expectedBase.length) == expectedBase) { tdl.basePath = src.substr(0, l - expectedBase.length); return; } } }; /** * Writes a script tag if, and only if, that script hasn't already been added * to the document. (Must be called at execution time.) * @param {string} src Script source. * @private */ tdl.writeScriptTag_ = function(src) { var doc = tdl.global.document; if (typeof doc != 'undefined' && !tdl.dependencies_.written[src]) { tdl.dependencies_.written[src] = true; var html = '<script type="text/javascript" src="' + src + '"></' + 'script>' doc.write(html); } }; /** * Resolves dependencies based on the dependencies added using addDependency * and calls writeScriptTag_ in the correct order. * @private */ tdl.writeScripts_ = function() { // the scripts we need to write this time. var scripts = []; var seenScript = {}; var deps = tdl.dependencies_; function visitNode(path) { if (path in deps.written) { return; } // we have already visited this one. We can get here if we have cyclic // dependencies. if (path in deps.visited) { if (!(path in seenScript)) { seenScript[path] = true; scripts.push(path); } return; } deps.visited[path] = true; if (!(path in seenScript)) { seenScript[path] = true; scripts.push(path); } } for (var path in tdl.included_) { if (!deps.written[path]) { visitNode(path); } } for (var i = 0; i < scripts.length; i++) { if (scripts[i]) { tdl.writeScriptTag_(tdl.basePath + scripts[i]); } else { throw Error('Undefined script input'); } } }; /** * Looks at the dependency rules and tries to determine the script file that * fulfills a particular rule. * @param {string} rule In the form tdl.namespace.Class or * project.script. * @return {string?} Url corresponding to the rule, or null. * @private */ tdl.getPathFromRule_ = function(rule) { var parts = rule.split('.'); return parts.join('/') + '.js'; }; tdl.findBasePath_(); /** * Returns true if the specified value is not |undefined|. * WARNING: Do not use this to test if an object has a property. Use the in * operator instead. * @param {*} val Variable to test. * @return {boolean} Whether variable is defined. */ tdl.isDef = function(val) { return typeof val != 'undefined'; }; /** * Exposes an unobfuscated global namespace path for the given object. * Note that fields of the exported object *will* be obfuscated, * unless they are exported in turn via this function or * tdl.exportProperty. * * <p>Also handy for making public items that are defined in anonymous * closures. * * ex. tdl.exportSymbol('Foo', Foo); * * ex. tdl.exportSymbol('public.path.Foo.staticFunction', * Foo.staticFunction); * public.path.Foo.staticFunction(); * * ex. tdl.exportSymbol('public.path.Foo.prototype.myMethod', * Foo.prototype.myMethod); * new public.path.Foo().myMethod(); * * @param {string} publicPath Unobfuscated name to export. * @param {Object} object Object the name should point to. * @param {Object} opt_objectToExportTo The object to add the path to; default * is |tdl.global|. */ tdl.exportSymbol = function(publicPath, object, opt_objectToExportTo) { tdl.exportPath_(publicPath, object, opt_objectToExportTo); }; tdl.provide('tdl.base'); /** * The base module for tdl. * @namespace */ tdl.base = tdl.base || {}; /** * Determine whether a value is an array. Do not use instanceof because that * will not work for V8 arrays (the browser thinks they are Objects). * @param {*} value A value. * @return {boolean} Whether the value is an array. */ tdl.base.isArray = function(value) { var valueAsObject = /** @type {!Object} */ (value); return typeof(value) === 'object' && value !== null && 'length' in valueAsObject && 'splice' in valueAsObject; }; /** * A stub for later optionally converting obfuscated names * @private * @param {string} name Name to un-obfuscate. * @return {string} un-obfuscated name. */ tdl.base.maybeDeobfuscateFunctionName_ = function(name) { return name; }; /** * Makes one class inherit from another. * @param {!Object} subClass Class that wants to inherit. * @param {!Object} superClass Class to inherit from. */ tdl.base.inherit = function(subClass, superClass) { /** * TmpClass. * @ignore * @constructor */ var TmpClass = function() { }; TmpClass.prototype = superClass.prototype; subClass.prototype = new TmpClass(); }; /** * Parses an error stack from an exception * @param {!Exception} excp The exception to get a stack trace from. * @return {!Array.<string>} An array of strings of the stack trace. */ tdl.base.parseErrorStack = function(excp) { var stack = []; var name; var line; if (!excp || !excp.stack) { return stack; } var stacklist = excp.stack.split('\n'); for (var i = 0; i < stacklist.length - 1; i++) { var framedata = stacklist[i]; name = framedata.match(/^([a-zA-Z0-9_$]*)/)[1]; if (name) { name = tdl.base.maybeDeobfuscateFunctionName_(name); } else { name = 'anonymous'; } var result = framedata.match(/(.*:[0-9]+)$/); line = result && result[1]; if (!line) { line = '(unknown)'; } stack[stack.length] = name + ' : ' + line } // remove top level anonymous functions to match IE var omitRegexp = /^anonymous :/; while (stack.length && omitRegexp.exec(stack[stack.length - 1])) { stack.length = stack.length - 1; } return stack; }; /** * Gets a function name from a function object. * @param {!function(...): *} aFunction The function object to try to get a * name from. * @return {string} function name or 'anonymous' if not found. */ tdl.base.getFunctionName = function(aFunction) { var regexpResult = aFunction.toString().match(/function(\s*)(\w*)/); if (regexpResult && regexpResult.length >= 2 && regexpResult[2]) { return tdl.base.maybeDeobfuscateFunctionName_(regexpResult[2]); } return 'anonymous'; }; /** * Pretty prints an exception's stack, if it has one. * @param {Array.<string>} stack An array of errors. * @return {string} The pretty stack. */ tdl.base.formatErrorStack = function(stack) { var result = ''; for (var i = 0; i < stack.length; i++) { result += '> ' + stack[i] + '\n'; } return result; }; /** * Gets a stack trace as a string. * @param {number} stripCount The number of entries to strip from the top of the * stack. Example: Pass in 1 to remove yourself from the stack trace. * @return {string} The stack trace. */ tdl.base.getStackTrace = function(stripCount) { var result = ''; if (typeof(arguments.caller) != 'undefined') { // IE, not ECMA for (var a = arguments.caller; a != null; a = a.caller) { result += '> ' + tdl.base.getFunctionName(a.callee) + '\n'; if (a.caller == a) { result += '*'; break; } } } else { // Mozilla, not ECMA // fake an exception so we can get Mozilla's error stack var testExcp; try { eval('var var;'); } catch (testExcp) { var stack = tdl.base.parseErrorStack(testExcp); result += tdl.base.formatErrorStack(stack.slice(3 + stripCount, stack.length)); } } return result; }; /** * Returns true if the user's browser is Microsoft IE. * @return {boolean} true if the user's browser is Microsoft IE. */ tdl.base.IsMSIE = function() { var ua = navigator.userAgent.toLowerCase(); var msie = /msie/.test(ua) && !/opera/.test(ua); return msie; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains a loader class for helping to load * muliple assets in an asynchronous manner. */ tdl.provide('tdl.loader'); tdl.require('tdl.io'); /** * A Module with a loader class for helping to load muliple assets in an * asynchronous manner. * @namespace */ tdl.loader = tdl.loader || {}; /** * A simple Loader class to call some callback when everything has loaded. * @constructor * @param {!function(): void} onFinished Function to call when final item has * loaded. */ tdl.loader.Loader = function(onFinished) { this.count_ = 1; this.onFinished_ = onFinished; /** * The LoadInfo for this loader you can use to track progress. * @type {!tdl.io.LoadInfo} */ this.loadInfo = tdl.io.createLoadInfo(); }; /** * Creates a Loader for helping to load a bunch of items asychronously. * * The way you use this is as follows. * * <pre> * var loader = tdl.loader.createLoader(myFinishedCallback); * loader.loadTextFile(text1Url, callbackForText); * loader.loadTextFile(text2Url, callbackForText); * loader.loadTextFile(text3Url, callbackForText); * loader.finish(); * </pre> * * The loader guarantees that myFinishedCallback will be called after * all the items have been loaded. * * @param {!function(): void} onFinished Function to call when final item has * loaded. * @return {!tdl.loader.Loader} A Loader Object. */ tdl.loader.createLoader = function(onFinished) { return new tdl.loader.Loader(onFinished); }; /** * Loads a text file. * @param {string} url URL of scene to load. * @param {!function(string, *): void} onTextLoaded Function to call when * the file is loaded. It will be passed the contents of the file as a * string and an exception which is null on success. */ tdl.loader.Loader.prototype.loadTextFile = function(url, onTextLoaded) { var that = this; // so the function below can see "this". ++this.count_; var loadInfo = tdl.io.loadTextFile(url, function(string, exception) { onTextLoaded(string, exception); that.countDown_(); }); this.loadInfo.addChild(loadInfo); }; /** * Creates a loader that is tracked by this loader so that when the new loader * is finished it will be reported to this loader. * @param {!function(): void} onFinished Function to be called when everything * loaded with this loader has finished. * @return {!tdl.loader.Loader} The new Loader. */ tdl.loader.Loader.prototype.createLoader = function(onFinished) { var that = this; ++this.count_; var loader = tdl.loader.createLoader(function() { onFinished(); that.countDown_(); }); this.loadInfo.addChild(loader.loadInfo); return loader; }; /** * Counts down the internal count and if it gets to zero calls the callback. * @private */ tdl.loader.Loader.prototype.countDown_ = function() { --this.count_; if (this.count_ === 0) { this.onFinished_(); } }; /** * Finishes the loading process. * Actually this just calls countDown_ to account for the count starting at 1. */ tdl.loader.Loader.prototype.finish = function() { this.countDown_(); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains matrix/vector math functions. * It adds them to the "math" module on the tdl object. * * tdl.math supports a row-major and a column-major mode. In both * modes, vectors are stored as arrays of numbers, and matrices are stored as * arrays of arrays of numbers. * * In row-major mode: * * - Rows of a matrix are sub-arrays. * - Individual entries of a matrix M get accessed in M[row][column] fashion. * - Tuples of coordinates are interpreted as row-vectors. * - A vector v gets transformed by a matrix M by multiplying in the order v*M. * * In column-major mode: * * - Columns of a matrix are sub-arrays. * - Individual entries of a matrix M get accessed in M[column][row] fashion. * - Tuples of coordinates are interpreted as column-vectors. * - A matrix M transforms a vector v by multiplying in the order M*v. * * When a function in tdl.math requires separate row-major and * column-major versions, a function with the same name gets added to each of * the namespaces tdl.math.rowMajor and tdl.math.columnMajor. The * function installRowMajorFunctions() or the function * installColumnMajorFunctions() should get called during initialization to * establish the mode. installRowMajorFunctions() works by iterating through * the tdl.math.rowMajor namespace and for each function foo, setting * tdl.math.foo equal to tdl.math.rowMajor.foo. * installRowMajorFunctions() works the same way, iterating over the columnMajor * namespace. At the end of this file, we call installRowMajorFunctions(). * * Switching modes changes two things. It changes how a matrix is encoded as an * array, and it changes how the entries of a matrix get interpreted. Because * those two things change together, the matrix representing a given * transformation of space is the same JavaScript object in either mode. * One consequence of this is that very few functions require separate row-major * and column-major versions. Typically, a function requires separate versions * only if it makes matrix multiplication order explicit, like * mulMatrixMatrix(), mulMatrixVector(), or mulVectorMatrix(). Functions which * create a new matrix, like scaling(), rotationZYX(), and translation() return * the same JavaScript object in either mode, and functions which implicitly * multiply like scale(), rotateZYX() and translate() modify the matrix in the * same way in either mode. * * The convention choice made for math functions in this library is independent * of the convention choice for how matrices get loaded into shaders. That * convention is determined on a per-shader basis. * * Other utilities in tdl should avoid making calls to functions that make * multiplication order explicit. Instead they should appeal to functions like: * * tdl.math.matrix4.transformPoint * tdl.math.matrix4.transformDirection * tdl.math.matrix4.transformNormal * tdl.math.matrix4.transformVector4 * tdl.math.matrix4.composition * tdl.math.matrix4.compose * * These functions multiply matrices implicitly and internally choose the * multiplication order to get the right result. That way, utilities which use * tdl.math work in either major mode. Note that this does not necessarily * mean all sample code will work even if a line is added which switches major * modes, but it does mean that calls to tdl still do what they are supposed * to. * */ tdl.provide('tdl.math'); /** * A module for math for tdl.math. * @namespace */ tdl.math = tdl.math || {}; /** * A random seed for the pseudoRandom function. * @private * @type {number} */ tdl.math.randomSeed_ = 0; /** * A constant for the pseudoRandom function * @private * @type {number} */ tdl.math.RANDOM_RANGE_ = Math.pow(2, 32); /** * Functions which deal with 4-by-4 transformation matrices are kept in their * own namespsace. * @namespace */ tdl.math.matrix4 = tdl.math.matrix4 || {}; /** * Functions that are specifically row major are kept in their own namespace. * @namespace */ tdl.math.rowMajor = tdl.math.rowMajor || {}; /** * Functions that are specifically column major are kept in their own namespace. * @namespace */ tdl.math.columnMajor = tdl.math.columnMajor || {}; /** * An Array of 2 floats * @type {!Array.<number>} */ tdl.math.Vector2 = goog.typedef; /** * An Array of 3 floats * @type {!Array.<number>} */ tdl.math.Vector3 = goog.typedef; /** * An Array of 4 floats * @type {!Array.<number>} */ tdl.math.Vector4 = goog.typedef; /** * An Array of floats. * @type {!Array.<number>} */ tdl.math.Vector = goog.typedef; /** * A 1x1 Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.math.Matrix1 = goog.typedef; /** * A 2x2 Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.math.Matrix2 = goog.typedef; /** * A 3x3 Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.math.Matrix3 = goog.typedef; /** * A 4x4 Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.math.Matrix4 = goog.typedef; /** * A arbitrary size Matrix of floats * @type {!Array.<!Array.<number>>} */ tdl.math.Matrix = goog.typedef; /** * Returns a deterministic pseudorandom number between 0 and 1 * @return {number} a random number between 0 and 1 */ tdl.math.pseudoRandom = function() { var math = tdl.math; return (math.randomSeed_ = (134775813 * math.randomSeed_ + 1) % math.RANDOM_RANGE_) / math.RANDOM_RANGE_; }; /** * Resets the pseudoRandom function sequence. */ tdl.math.resetPseudoRandom = function() { tdl.math.randomSeed_ = 0; }; /** * Return a random integer between 0 and n-1 * @param {number} n */ tdl.math.randomInt = function(n) { return Math.floor(Math.random() * n); } /** * Converts degrees to radians. * @param {number} degrees A value in degrees. * @return {number} the value in radians. */ tdl.math.degToRad = function(degrees) { return degrees * Math.PI / 180; }; /** * Converts radians to degrees. * @param {number} radians A value in radians. * @return {number} the value in degrees. */ tdl.math.radToDeg = function(radians) { return radians * 180 / Math.PI; }; /** * Performs linear interpolation on two scalars. * Given scalars a and b and interpolation coefficient t, returns * (1 - t) * a + t * b. * @param {number} a Operand scalar. * @param {number} b Operand scalar. * @param {number} t Interpolation coefficient. * @return {number} The weighted sum of a and b. */ tdl.math.lerpScalar = function(a, b, t) { return (1 - t) * a + t * b; }; /** * Adds two vectors; assumes a and b have the same dimension. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {!tdl.math.Vector} The sum of a and b. */ tdl.math.addVector = function(a, b) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) r[i] = a[i] + b[i]; return r; }; /** * Subtracts two vectors. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {!tdl.math.Vector} The difference of a and b. */ tdl.math.subVector = function(a, b) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) r[i] = a[i] - b[i]; return r; }; /** * Performs linear interpolation on two vectors. * Given vectors a and b and interpolation coefficient t, returns * (1 - t) * a + t * b. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @param {number} t Interpolation coefficient. * @return {!tdl.math.Vector} The weighted sum of a and b. */ tdl.math.lerpVector = function(a, b, t) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) r[i] = (1 - t) * a[i] + t * b[i]; return r; }; /** * Clamps a value between 0 and range using a modulo. * @param {number} v Value to clamp mod. * @param {number} range Range to clamp to. * @param {number} opt_rangeStart start of range. Default = 0. * @return {number} Clamp modded value. */ tdl.math.modClamp = function(v, range, opt_rangeStart) { var start = opt_rangeStart || 0; if (range < 0.00001) { return start; } v -= start; if (v < 0) { v -= Math.floor(v / range) * range; } else { v = v % range; } return v + start; }; /** * Lerps in a circle. * Does a lerp between a and b but inside range so for example if * range is 100, a is 95 and b is 5 lerping will go in the positive direction. * @param {number} a Start value. * @param {number} b Target value. * @param {number} t Amount to lerp (0 to 1). * @param {number} range Range of circle. * @return {number} lerped result. */ tdl.math.lerpCircular = function(a, b, t, range) { a = tdl.math.modClamp(a, range); b = tdl.math.modClamp(b, range); var delta = b - a; if (Math.abs(delta) > range * 0.5) { if (delta > 0) { b -= range; } else { b += range; } } return tdl.math.modClamp(tdl.math.lerpScalar(a, b, t), range); }; /** * Lerps radians. * @param {number} a Start value. * @param {number} b Target value. * @param {number} t Amount to lerp (0 to 1). * @return {number} lerped result. */ tdl.math.lerpRadian = function(a, b, t) { return tdl.math.lerpCircular(a, b, t, Math.PI * 2); }; /** * Divides a vector by a scalar. * @param {!tdl.math.Vector} v The vector. * @param {number} k The scalar. * @return {!tdl.math.Vector} v The vector v divided by k. */ tdl.math.divVectorScalar = function(v, k) { var r = []; var vLength = v.length; for (var i = 0; i < vLength; ++i) r[i] = v[i] / k; return r; }; /** * Computes the dot product of two vectors; assumes that a and b have * the same dimension. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {number} The dot product of a and b. */ tdl.math.dot = function(a, b) { var r = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) r += a[i] * b[i]; return r; }; /** * Computes the cross product of two vectors; assumes both vectors have * three entries. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {!tdl.math.Vector} The vector a cross b. */ tdl.math.cross = function(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; }; /** * Computes the Euclidean length of a vector, i.e. the square root of the * sum of the squares of the entries. * @param {!tdl.math.Vector} a The vector. * @return {number} The length of a. */ tdl.math.length = function(a) { var r = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) r += a[i] * a[i]; return Math.sqrt(r); }; /** * Computes the square of the Euclidean length of a vector, i.e. the sum * of the squares of the entries. * @param {!tdl.math.Vector} a The vector. * @return {number} The square of the length of a. */ tdl.math.lengthSquared = function(a) { var r = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) r += a[i] * a[i]; return r; }; /** * Computes the Euclidean distance between two vectors. * @param {!tdl.math.Vector} a A vector. * @param {!tdl.math.Vector} b A vector. * @return {number} The distance between a and b. */ tdl.math.distance = function(a, b) { var r = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) { var t = a[i] - b[i]; r += t * t; } return Math.sqrt(r); }; /** * Computes the square of the Euclidean distance between two vectors. * @param {!tdl.math.Vector} a A vector. * @param {!tdl.math.Vector} b A vector. * @return {number} The distance between a and b. */ tdl.math.distanceSquared = function(a, b) { var r = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) { var t = a[i] - b[i]; r += t * t; } return r; }; /** * Divides a vector by its Euclidean length and returns the quotient. * @param {!tdl.math.Vector} a The vector. * @return {!tdl.math.Vector} The normalized vector. */ tdl.math.normalize = function(a) { var r = []; var n = 0.0; var aLength = a.length; for (var i = 0; i < aLength; ++i) n += a[i] * a[i]; n = Math.sqrt(n); if (n > 0.00001) { for (var i = 0; i < aLength; ++i) r[i] = a[i] / n; } else { r = [0,0,0]; } return r; }; /** * Adds two matrices; assumes a and b are the same size. * @param {!tdl.math.Matrix} a Operand matrix. * @param {!tdl.math.Matrix} b Operand matrix. * @return {!tdl.math.Matrix} The sum of a and b. */ tdl.math.addMatrix = function(a, b) { var r = []; var aLength = a.length; var a0Length = a[0].length; for (var i = 0; i < aLength; ++i) { var row = []; var ai = a[i]; var bi = b[i]; for (var j = 0; j < a0Length; ++j) row[j] = ai[j] + bi[j]; r[i] = row; } return r; }; /** * Subtracts two matrices; assumes a and b are the same size. * @param {!tdl.math.Matrix} a Operand matrix. * @param {!tdl.math.Matrix} b Operand matrix. * @return {!tdl.math.Matrix} The sum of a and b. */ tdl.math.subMatrix = function(a, b) { var r = []; var aLength = a.length; var a0Length = a[0].length; for (var i = 0; i < aLength; ++i) { var row = []; var ai = a[i]; var bi = b[i]; for (var j = 0; j < a0Length; ++j) row[j] = ai[j] - bi[j]; r[i] = row; } return r; }; /** * Performs linear interpolation on two matrices. * Given matrices a and b and interpolation coefficient t, returns * (1 - t) * a + t * b. * @param {!tdl.math.Matrix} a Operand matrix. * @param {!tdl.math.Matrix} b Operand matrix. * @param {number} t Interpolation coefficient. * @return {!tdl.math.Matrix} The weighted of a and b. */ tdl.math.lerpMatrix = function(a, b, t) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) { r[i] = (1 - t) * a[i] + t * b[i]; } return r; }; /** * Divides a matrix by a scalar. * @param {!tdl.math.Matrix} m The matrix. * @param {number} k The scalar. * @return {!tdl.math.Matrix} The matrix m divided by k. */ tdl.math.divMatrixScalar = function(m, k) { var r = []; var mLength = m.length; for (var i = 0; i < mLength; ++i) { r[i] = m[i] / k; } return r; }; /** * Negates a scalar. * @param {number} a The scalar. * @return {number} -a. */ tdl.math.negativeScalar = function(a) { return -a; }; /** * Negates a vector. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} -v. */ tdl.math.negativeVector = function(v) { var r = []; var vLength = v.length; for (var i = 0; i < vLength; ++i) { r[i] = -v[i]; } return r; }; /** * Negates a matrix. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} -m. */ tdl.math.negativeMatrix = function(m) { var r = []; var mLength = m.length; for (var i = 0; i < mLength; ++i) { r[i] = -m[i]; } return r; }; /** * Copies a scalar. * @param {number} a The scalar. * @return {number} a. */ tdl.math.copyScalar = function(a) { return a; }; /** * Copies a vector. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} A copy of v. */ tdl.math.copyVector = function(v) { var r = []; for (var i = 0; i < v.length; i++) r[i] = v[i]; return r; }; /** * Copies a matrix. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} A copy of m. */ tdl.math.copyMatrix = function(m) { var r = []; var mLength = m.length; for (var i = 0; i < mLength; ++i) { r[i] = m[i]; } return r; }; /** * Multiplies two scalars. * @param {number} a Operand scalar. * @param {number} b Operand scalar. * @return {number} The product of a and b. */ tdl.math.mulScalarScalar = function(a, b) { return a * b; }; /** * Multiplies a scalar by a vector. * @param {number} k The scalar. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} The product of k and v. */ tdl.math.mulScalarVector = function(k, v) { var r = []; var vLength = v.length; for (var i = 0; i < vLength; ++i) { r[i] = k * v[i]; } return r; }; /** * Multiplies a vector by a scalar. * @param {!tdl.math.Vector} v The vector. * @param {number} k The scalar. * @return {!tdl.math.Vector} The product of k and v. */ tdl.math.mulVectorScalar = function(v, k) { return tdl.math.mulScalarVector(k, v); }; /** * Multiplies a scalar by a matrix. * @param {number} k The scalar. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} The product of m and k. */ tdl.math.mulScalarMatrix = function(k, m) { var r = []; var mLength = m.length; for (var i = 0; i < mLength; ++i) { r[i] = k * m[i]; } return r; }; /** * Multiplies a matrix by a scalar. * @param {!tdl.math.Matrix} m The matrix. * @param {number} k The scalar. * @return {!tdl.math.Matrix} The product of m and k. */ tdl.math.mulMatrixScalar = function(m, k) { return tdl.math.mulScalarMatrix(k, m); }; /** * Multiplies a vector by another vector (component-wise); assumes a and * b have the same length. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {!tdl.math.Vector} The vector of products of entries of a and * b. */ tdl.math.mulVectorVector = function(a, b) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) r[i] = a[i] * b[i]; return r; }; /** * Divides a vector by another vector (component-wise); assumes a and * b have the same length. * @param {!tdl.math.Vector} a Operand vector. * @param {!tdl.math.Vector} b Operand vector. * @return {!tdl.math.Vector} The vector of quotients of entries of a and * b. */ tdl.math.divVectorVector = function(a, b) { var r = []; var aLength = a.length; for (var i = 0; i < aLength; ++i) r[i] = a[i] / b[i]; return r; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector; assumes * matrix entries are accessed in [row][column] fashion. * @param {!tdl.math.Vector} v The vector. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Vector} The product of v and m as a row vector. */ tdl.math.rowMajor.mulVectorMatrix4 = function(v, m) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = 0.0; for (var j = 0; j < 4; ++j) r[i] += v[j] * m[j * 4 + i]; } return r; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector; assumes * matrix entries are accessed in [column][row] fashion. * @param {!tdl.math.Vector} v The vector. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Vector} The product of v and m as a row vector. */ tdl.math.columnMajor.mulVectorMatrix = function(v, m) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = 0.0; for (var j = 0; j < 4; ++j) r[i] += v[j] * r[i * 4 + j]; } return r; }; /** * Multiplies a vector by a matrix; treats the vector as a row vector. * @param {!tdl.math.Matrix} m The matrix. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} The product of m and v as a row vector. */ tdl.math.mulVectorMatrix = null; /** * Multiplies a matrix by a vector; treats the vector as a column vector. * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} The product of m and v as a column vector. */ tdl.math.rowMajor.mulMatrixVector = function(m, v) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = 0.0; for (var j = 0; j < 4; ++j) r[i] += m[i * 4 + j] * v[j]; } return r; }; /** * Multiplies a matrix by a vector; treats the vector as a column vector; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} The product of m and v as a column vector. */ tdl.math.columnMajor.mulMatrixVector = function(m, v) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = 0.0; for (var j = 0; j < 4; ++j) r[i] += v[j] * m[j * 4 + i]; } return r; }; /** * Multiplies a matrix by a vector; treats the vector as a column vector. * @param {!tdl.math.Matrix} m The matrix. * @param {!tdl.math.Vector} v The vector. * @return {!tdl.math.Vector} The product of m and v as a column vector. */ tdl.math.mulMatrixVector = null; /** * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2; * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.math.Matrix2} a The matrix on the left. * @param {!tdl.math.Matrix2} b The matrix on the right. * @return {!tdl.math.Matrix2} The matrix product of a and b. */ tdl.math.rowMajor.mulMatrixMatrix2 = function(a, b) { var a00 = a[0*2+0]; var a01 = a[0*2+1]; var a10 = a[1*2+0]; var a11 = a[1*2+1]; var b00 = b[0*2+0]; var b01 = b[0*2+1]; var b10 = b[1*2+0]; var b11 = b[1*2+1]; return [a00 * b00 + a01 * b10, a00 * b01 + a01 * b11, a10 * b00 + a11 * b10, a10 * b01 + a11 * b11]; }; /** * Multiplies two 2-by-2 matrices; assumes that the given matrices are 2-by-2; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.math.Matrix2} a The matrix on the left. * @param {!tdl.math.Matrix2} b The matrix on the right. * @return {!tdl.math.Matrix2} The matrix product of a and b. */ tdl.math.columnMajor.mulMatrixMatrix2 = function(a, b) { var a00 = a[0*2+0]; var a01 = a[0*2+1]; var a10 = a[1*2+0]; var a11 = a[1*2+1]; var b00 = b[0*2+0]; var b01 = b[0*2+1]; var b10 = b[1*2+0]; var b11 = b[1*2+1]; return [a00 * b00 + a10 * b01, a01 * b00 + a11 * b01, a00 * b10 + a10 * b11, a01 * b10 + a11 * b11]; }; /** * Multiplies two 2-by-2 matrices. * @param {!tdl.math.Matrix2} a The matrix on the left. * @param {!tdl.math.Matrix2} b The matrix on the right. * @return {!tdl.math.Matrix2} The matrix product of a and b. */ tdl.math.mulMatrixMatrix2 = null; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3; * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.math.Matrix3} a The matrix on the left. * @param {!tdl.math.Matrix3} b The matrix on the right. * @return {!tdl.math.Matrix3} The matrix product of a and b. */ tdl.math.rowMajor.mulMatrixMatrix3 = function(a, b) { var a00 = a[0*3+0]; var a01 = a[0*3+1]; var a02 = a[0*3+2]; var a10 = a[1*3+0]; var a11 = a[1*3+1]; var a12 = a[1*3+2]; var a20 = a[2*3+0]; var a21 = a[2*3+1]; var a22 = a[2*3+2]; var b00 = b[0*3+0]; var b01 = b[0*3+1]; var b02 = b[0*3+2]; var b10 = b[1*3+0]; var b11 = b[1*3+1]; var b12 = b[1*3+2]; var b20 = b[2*3+0]; var b21 = b[2*3+1]; var b22 = b[2*3+2]; return [a00 * b00 + a01 * b10 + a02 * b20, a00 * b01 + a01 * b11 + a02 * b21, a00 * b02 + a01 * b12 + a02 * b22, a10 * b00 + a11 * b10 + a12 * b20, a10 * b01 + a11 * b11 + a12 * b21, a10 * b02 + a11 * b12 + a12 * b22, a20 * b00 + a21 * b10 + a22 * b20, a20 * b01 + a21 * b11 + a22 * b21, a20 * b02 + a21 * b12 + a22 * b22]; }; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.math.Matrix3} a The matrix on the left. * @param {!tdl.math.Matrix3} b The matrix on the right. * @return {!tdl.math.Matrix3} The matrix product of a and b. */ tdl.math.columnMajor.mulMatrixMatrix3 = function(a, b) { var a00 = a[0*3+0]; var a01 = a[0*3+1]; var a02 = a[0*3+2]; var a10 = a[1*3+0]; var a11 = a[1*3+1]; var a12 = a[1*3+2]; var a20 = a[2*3+0]; var a21 = a[2*3+1]; var a22 = a[2*3+2]; var b00 = b[0*3+0]; var b01 = b[0*3+1]; var b02 = b[0*3+2]; var b10 = b[1*3+0]; var b11 = b[1*3+1]; var b12 = b[1*3+2]; var b20 = b[2*3+0]; var b21 = b[2*3+1]; var b22 = b[2*3+2]; return [a00 * b00 + a10 * b01 + a20 * b02, a01 * b00 + a11 * b01 + a21 * b02, a02 * b00 + a12 * b01 + a22 * b02, a00 * b10 + a10 * b11 + a20 * b12, a01 * b10 + a11 * b11 + a21 * b12, a02 * b10 + a12 * b11 + a22 * b12, a00 * b20 + a10 * b21 + a20 * b22, a01 * b20 + a11 * b21 + a21 * b22, a02 * b20 + a12 * b21 + a22 * b22]; }; /** * Multiplies two 3-by-3 matrices; assumes that the given matrices are 3-by-3. * @param {!tdl.math.Matrix3} a The matrix on the left. * @param {!tdl.math.Matrix3} b The matrix on the right. * @return {!tdl.math.Matrix3} The matrix product of a and b. */ tdl.math.mulMatrixMatrix3 = null; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4; * assumes matrix entries are accessed in [row][column] fashion. * @param {!tdl.math.Matrix4} a The matrix on the left. * @param {!tdl.math.Matrix4} b The matrix on the right. * @return {!tdl.math.Matrix4} The matrix product of a and b. */ tdl.math.rowMajor.mulMatrixMatrix4 = function(a, b) { var a00 = a[0*4+0]; var a01 = a[0*4+1]; var a02 = a[0*4+2]; var a03 = a[0*4+3]; var a10 = a[1*4+0]; var a11 = a[1*4+1]; var a12 = a[1*4+2]; var a13 = a[1*4+3]; var a20 = a[2*4+0]; var a21 = a[2*4+1]; var a22 = a[2*4+2]; var a23 = a[2*4+3]; var a30 = a[3*4+0]; var a31 = a[3*4+1]; var a32 = a[3*4+2]; var a33 = a[3*4+3]; var b00 = b[0*4+0]; var b01 = b[0*4+1]; var b02 = b[0*4+2]; var b03 = b[0*4+3]; var b10 = b[1*4+0]; var b11 = b[1*4+1]; var b12 = b[1*4+2]; var b13 = b[1*4+3]; var b20 = b[2*4+0]; var b21 = b[2*4+1]; var b22 = b[2*4+2]; var b23 = b[2*4+3]; var b30 = b[3*4+0]; var b31 = b[3*4+1]; var b32 = b[3*4+2]; var b33 = b[3*4+3]; return [a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30, a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31, a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32, a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33, a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30, a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31, a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32, a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33, a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30, a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31, a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32, a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33, a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30, a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31, a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32, a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33]; }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4; * assumes matrix entries are accessed in [column][row] fashion. * @param {!tdl.math.Matrix4} a The matrix on the left. * @param {!tdl.math.Matrix4} b The matrix on the right. * @return {!tdl.math.Matrix4} The matrix product of a and b. */ tdl.math.columnMajor.mulMatrixMatrix4 = function(a, b) { var a00 = a[0*4+0]; var a01 = a[0*4+1]; var a02 = a[0*4+2]; var a03 = a[0*4+3]; var a10 = a[1*4+0]; var a11 = a[1*4+1]; var a12 = a[1*4+2]; var a13 = a[1*4+3]; var a20 = a[2*4+0]; var a21 = a[2*4+1]; var a22 = a[2*4+2]; var a23 = a[2*4+3]; var a30 = a[3*4+0]; var a31 = a[3*4+1]; var a32 = a[3*4+2]; var a33 = a[3*4+3]; var b00 = b[0*4+0]; var b01 = b[0*4+1]; var b02 = b[0*4+2]; var b03 = b[0*4+3]; var b10 = b[1*4+0]; var b11 = b[1*4+1]; var b12 = b[1*4+2]; var b13 = b[1*4+3]; var b20 = b[2*4+0]; var b21 = b[2*4+1]; var b22 = b[2*4+2]; var b23 = b[2*4+3]; var b30 = b[3*4+0]; var b31 = b[3*4+1]; var b32 = b[3*4+2]; var b33 = b[3*4+3]; return [a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03, a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03, a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03, a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03, a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13, a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13, a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13, a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13, a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23, a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23, a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23, a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23, a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33, a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33, a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33, a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33]; }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4. * @param {!tdl.math.Matrix4} a The matrix on the left. * @param {!tdl.math.Matrix4} b The matrix on the right. * @return {!tdl.math.Matrix4} The matrix product of a and b. */ tdl.math.mulMatrixMatrix4 = null; /** * Multiplies two matrices; assumes that the sizes of the matrices are * appropriately compatible; assumes matrix entries are accessed in * [row][column] fashion. * @param {!tdl.math.Matrix} a The matrix on the left. * @param {!tdl.math.Matrix} b The matrix on the right. * @return {!tdl.math.Matrix} The matrix product of a and b. */ tdl.math.rowMajor.mulMatrixMatrix = function(a, b) { var r = []; for (var i = 0; i < 4; ++i) { for (var j = 0; j < 4; ++j) { r[i*4+j] = 0.0; for (var k = 0; k < 4; ++k) r[i*4+j] += a[i*4+k] * b[k*4+j]; // kth row, jth column. } } return r; }; /** * Multiplies two matrices; assumes that the sizes of the matrices are * appropriately compatible; assumes matrix entries are accessed in * [row][column] fashion. * @param {!tdl.math.Matrix} a The matrix on the left. * @param {!tdl.math.Matrix} b The matrix on the right. * @return {!tdl.math.Matrix} The matrix product of a and b. */ tdl.math.columnMajor.mulMatrixMatrix = function(a, b) { var r = []; for (var i = 0; i < 4; ++i) { for (var j = 0; j < 4; ++j) { r[i*4+j] = 0.0; for (var k = 0; k < 4; ++k) r[i*4+j] += b[i*4+k] * a[k*4+j]; // kth column, jth row. } } return r; }; /** * Multiplies two matrices; assumes that the sizes of the matrices are * appropriately compatible. * @param {!tdl.math.Matrix} a The matrix on the left. * @param {!tdl.math.Matrix} b The matrix on the right. * @return {!tdl.math.Matrix} The matrix product of a and b. */ tdl.math.mulMatrixMatrix = null; /** * Gets the jth column of the given matrix m; assumes matrix entries are * accessed in [row][column] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.math.Vector} The jth column of m as a vector. */ tdl.math.rowMajor.column = function(m, j) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = m[i*4+j]; } return r; }; /** * Gets the jth column of the given matrix m; assumes matrix entries are * accessed in [column][row] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.math.Vector} The jth column of m as a vector. */ tdl.math.columnMajor.column = function(m, j) { var r = []; for (var i = 0; i < 4; ++i) { r[i] = m[j*4+i]; } return r; }; /** * Gets the jth column of the given matrix m. * @param {!tdl.math.Matrix} m The matrix. * @param {number} j The index of the desired column. * @return {!tdl.math.Vector} The jth column of m as a vector. */ tdl.math.column = null; /** * Gets the ith row of the given matrix m; assumes matrix entries are * accessed in [row][column] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {number} i The index of the desired row. * @return {!tdl.math.Vector} The ith row of m. */ tdl.math.rowMajor.row = function(m, i) { var r = []; for (var j = 0; j < 4; ++j) { r[i] = m[i*4+j]; } return r; }; /** * Gets the ith row of the given matrix m; assumes matrix entries are * accessed in [column][row] fashion. * @param {!tdl.math.Matrix} m The matrix. * @param {number} i The index of the desired row. * @param {number} opt_size Unknown (to dkogan) * @return {!tdl.math.Vector} The ith row of m. */ tdl.math.columnMajor.row = function(m, i, opt_size) { opt_size = opt_size || 4; var r = []; for (var j = 0; j < opt_size; ++j) { r[j] = m[j*opt_size+i]; } return r; }; /** * Gets the ith row of the given matrix m. * @param {!tdl.math.Matrix} m The matrix. * @param {number} i The index of the desired row. * @return {!tdl.math.Vector} The ith row of m. */ tdl.math.row = null; /** * Takes the transpose of a matrix. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} The transpose of m. */ tdl.math.transpose = function(m) { var r = []; var m00 = m[0 * 4 + 0]; var m01 = m[0 * 4 + 1]; var m02 = m[0 * 4 + 2]; var m03 = m[0 * 4 + 3]; var m10 = m[1 * 4 + 0]; var m11 = m[1 * 4 + 1]; var m12 = m[1 * 4 + 2]; var m13 = m[1 * 4 + 3]; var m20 = m[2 * 4 + 0]; var m21 = m[2 * 4 + 1]; var m22 = m[2 * 4 + 2]; var m23 = m[2 * 4 + 3]; var m30 = m[3 * 4 + 0]; var m31 = m[3 * 4 + 1]; var m32 = m[3 * 4 + 2]; var m33 = m[3 * 4 + 3]; r[ 0] = m00; r[ 1] = m10; r[ 2] = m20; r[ 3] = m30; r[ 4] = m01; r[ 5] = m11; r[ 6] = m21; r[ 7] = m31; r[ 8] = m02; r[ 9] = m12; r[10] = m22; r[11] = m32; r[12] = m03; r[13] = m13; r[14] = m23; r[15] = m33; return r; }; /** * Computes the trace (sum of the diagonal entries) of a square matrix; * assumes m is square. * @param {!tdl.math.Matrix} m The matrix. * @return {number} The trace of m. */ tdl.math.trace = function(m) { var r = 0.0; for (var i = 0; i < 4; ++i) r += m[i*4+i]; return r; }; /** * Computes the determinant of a 1-by-1 matrix. * @param {!tdl.math.Matrix1} m The matrix. * @return {number} The determinant of m. */ tdl.math.det1 = function(m) { return m[0]; }; /** * Computes the determinant of a 2-by-2 matrix. * @param {!tdl.math.Matrix2} m The matrix. * @return {number} The determinant of m. */ tdl.math.det2 = function(m) { return m[0*2+0] * m[1*2+1] - m[0*2+1] * m[1*2+0]; }; /** * Computes the determinant of a 3-by-3 matrix. * @param {!tdl.math.Matrix3} m The matrix. * @return {number} The determinant of m. */ tdl.math.det3 = function(m) { return m[2*3+2] * (m[0*3+0] * m[1*3+1] - m[0*3+1] * m[1*3+0]) - m[2*3+1] * (m[0*3+0] * m[1*3+2] - m[0*3+2] * m[1*3+0]) + m[2*3+0] * (m[0*3+1] * m[1*3+2] - m[0*3+2] * m[1*3+1]); }; /** * Computes the determinant of a 4-by-4 matrix. * @param {!tdl.math.Matrix4} m The matrix. * @return {number} The determinant of m. */ tdl.math.det4 = function(m) { var t01 = m[0*4+0] * m[1*4+1] - m[0*4+1] * m[1*4+0]; var t02 = m[0*4+0] * m[1*4+2] - m[0*4+2] * m[1*4+0]; var t03 = m[0*4+0] * m[1*4+3] - m[0*4+3] * m[1*4+0]; var t12 = m[0*4+1] * m[1*4+2] - m[0*4+2] * m[1*4+1]; var t13 = m[0*4+1] * m[1*4+3] - m[0*4+3] * m[1*4+1]; var t23 = m[0*4+2] * m[1*4+3] - m[0*4+3] * m[1*4+2]; return m[3*4+3] * (m[2*4+2] * t01 - m[2*4+1] * t02 + m[2*4+0] * t12) - m[3*4+2] * (m[2*4+3] * t01 - m[2*4+1] * t03 + m[2*4+0] * t13) + m[3*4+1] * (m[2*4+3] * t02 - m[2*4+2] * t03 + m[2*4+0] * t23) - m[3*4+0] * (m[2*4+3] * t12 - m[2*4+2] * t13 + m[2*4+1] * t23); }; /** * Computes the inverse of a 1-by-1 matrix. * @param {!tdl.math.Matrix1} m The matrix. * @return {!tdl.math.Matrix1} The inverse of m. */ tdl.math.inverse1 = function(m) { return [[1.0 / m[0]]]; }; /** * Computes the inverse of a 2-by-2 matrix. * @param {!tdl.math.Matrix2} m The matrix. * @return {!tdl.math.Matrix2} The inverse of m. */ tdl.math.inverse2 = function(m) { var d = 1.0 / (m[0*2+0] * m[1*2+1] - m[0*2+1] * m[1*2+0]); return [d * m[1*2+1], -d * m[0*2+1], -d * m[1*2+0], d * m[0*2+0]]; }; /** * Computes the inverse of a 3-by-3 matrix. * @param {!tdl.math.Matrix3} m The matrix. * @return {!tdl.math.Matrix3} The inverse of m. */ tdl.math.inverse3 = function(m) { var t00 = m[1*3+1] * m[2*3+2] - m[1*3+2] * m[2*3+1]; var t10 = m[0*3+1] * m[2*3+2] - m[0*3+2] * m[2*3+1]; var t20 = m[0*3+1] * m[1*3+2] - m[0*3+2] * m[1*3+1]; var d = 1.0 / (m[0*3+0] * t00 - m[1*3+0] * t10 + m[2*3+0] * t20); return [ d * t00, -d * t10, d * t20, -d * (m[1*3+0] * m[2*3+2] - m[1*3+2] * m[2*3+0]), d * (m[0*3+0] * m[2*3+2] - m[0*3+2] * m[2*3+0]), -d * (m[0*3+0] * m[1*3+2] - m[0*3+2] * m[1*3+0]), d * (m[1*3+0] * m[2*3+1] - m[1*3+1] * m[2*3+0]), -d * (m[0*3+0] * m[2*3+1] - m[0*3+1] * m[2*3+0]), d * (m[0*3+0] * m[1*3+1] - m[0*3+1] * m[1*3+0])]; }; /** * Computes the inverse of a 4-by-4 matrix. * @param {!tdl.math.Matrix4} m The matrix. * @return {!tdl.math.Matrix4} The inverse of m. */ tdl.math.inverse4 = function(m) { var tmp_0 = m[2*4+2] * m[3*4+3]; var tmp_1 = m[3*4+2] * m[2*4+3]; var tmp_2 = m[1*4+2] * m[3*4+3]; var tmp_3 = m[3*4+2] * m[1*4+3]; var tmp_4 = m[1*4+2] * m[2*4+3]; var tmp_5 = m[2*4+2] * m[1*4+3]; var tmp_6 = m[0*4+2] * m[3*4+3]; var tmp_7 = m[3*4+2] * m[0*4+3]; var tmp_8 = m[0*4+2] * m[2*4+3]; var tmp_9 = m[2*4+2] * m[0*4+3]; var tmp_10 = m[0*4+2] * m[1*4+3]; var tmp_11 = m[1*4+2] * m[0*4+3]; var tmp_12 = m[2*4+0] * m[3*4+1]; var tmp_13 = m[3*4+0] * m[2*4+1]; var tmp_14 = m[1*4+0] * m[3*4+1]; var tmp_15 = m[3*4+0] * m[1*4+1]; var tmp_16 = m[1*4+0] * m[2*4+1]; var tmp_17 = m[2*4+0] * m[1*4+1]; var tmp_18 = m[0*4+0] * m[3*4+1]; var tmp_19 = m[3*4+0] * m[0*4+1]; var tmp_20 = m[0*4+0] * m[2*4+1]; var tmp_21 = m[2*4+0] * m[0*4+1]; var tmp_22 = m[0*4+0] * m[1*4+1]; var tmp_23 = m[1*4+0] * m[0*4+1]; var t0 = (tmp_0 * m[1*4+1] + tmp_3 * m[2*4+1] + tmp_4 * m[3*4+1]) - (tmp_1 * m[1*4+1] + tmp_2 * m[2*4+1] + tmp_5 * m[3*4+1]); var t1 = (tmp_1 * m[0*4+1] + tmp_6 * m[2*4+1] + tmp_9 * m[3*4+1]) - (tmp_0 * m[0*4+1] + tmp_7 * m[2*4+1] + tmp_8 * m[3*4+1]); var t2 = (tmp_2 * m[0*4+1] + tmp_7 * m[1*4+1] + tmp_10 * m[3*4+1]) - (tmp_3 * m[0*4+1] + tmp_6 * m[1*4+1] + tmp_11 * m[3*4+1]); var t3 = (tmp_5 * m[0*4+1] + tmp_8 * m[1*4+1] + tmp_11 * m[2*4+1]) - (tmp_4 * m[0*4+1] + tmp_9 * m[1*4+1] + tmp_10 * m[2*4+1]); var d = 1.0 / (m[0*4+0] * t0 + m[1*4+0] * t1 + m[2*4+0] * t2 + m[3*4+0] * t3); return [d * t0, d * t1, d * t2, d * t3, d * ((tmp_1 * m[1*4+0] + tmp_2 * m[2*4+0] + tmp_5 * m[3*4+0]) - (tmp_0 * m[1*4+0] + tmp_3 * m[2*4+0] + tmp_4 * m[3*4+0])), d * ((tmp_0 * m[0*4+0] + tmp_7 * m[2*4+0] + tmp_8 * m[3*4+0]) - (tmp_1 * m[0*4+0] + tmp_6 * m[2*4+0] + tmp_9 * m[3*4+0])), d * ((tmp_3 * m[0*4+0] + tmp_6 * m[1*4+0] + tmp_11 * m[3*4+0]) - (tmp_2 * m[0*4+0] + tmp_7 * m[1*4+0] + tmp_10 * m[3*4+0])), d * ((tmp_4 * m[0*4+0] + tmp_9 * m[1*4+0] + tmp_10 * m[2*4+0]) - (tmp_5 * m[0*4+0] + tmp_8 * m[1*4+0] + tmp_11 * m[2*4+0])), d * ((tmp_12 * m[1*4+3] + tmp_15 * m[2*4+3] + tmp_16 * m[3*4+3]) - (tmp_13 * m[1*4+3] + tmp_14 * m[2*4+3] + tmp_17 * m[3*4+3])), d * ((tmp_13 * m[0*4+3] + tmp_18 * m[2*4+3] + tmp_21 * m[3*4+3]) - (tmp_12 * m[0*4+3] + tmp_19 * m[2*4+3] + tmp_20 * m[3*4+3])), d * ((tmp_14 * m[0*4+3] + tmp_19 * m[1*4+3] + tmp_22 * m[3*4+3]) - (tmp_15 * m[0*4+3] + tmp_18 * m[1*4+3] + tmp_23 * m[3*4+3])), d * ((tmp_17 * m[0*4+3] + tmp_20 * m[1*4+3] + tmp_23 * m[2*4+3]) - (tmp_16 * m[0*4+3] + tmp_21 * m[1*4+3] + tmp_22 * m[2*4+3])), d * ((tmp_14 * m[2*4+2] + tmp_17 * m[3*4+2] + tmp_13 * m[1*4+2]) - (tmp_16 * m[3*4+2] + tmp_12 * m[1*4+2] + tmp_15 * m[2*4+2])), d * ((tmp_20 * m[3*4+2] + tmp_12 * m[0*4+2] + tmp_19 * m[2*4+2]) - (tmp_18 * m[2*4+2] + tmp_21 * m[3*4+2] + tmp_13 * m[0*4+2])), d * ((tmp_18 * m[1*4+2] + tmp_23 * m[3*4+2] + tmp_15 * m[0*4+2]) - (tmp_22 * m[3*4+2] + tmp_14 * m[0*4+2] + tmp_19 * m[1*4+2])), d * ((tmp_22 * m[2*4+2] + tmp_16 * m[0*4+2] + tmp_21 * m[1*4+2]) - (tmp_20 * m[1*4+2] + tmp_23 * m[2*4+2] + tmp_17 * m[0*4+2]))]; }; /** * Computes the determinant of the cofactor matrix obtained by removal * of a specified row and column. This is a helper function for the general * determinant and matrix inversion functions. * @param {!tdl.math.Matrix} a The original matrix. * @param {number} x The row to be removed. * @param {number} y The column to be removed. * @return {number} The determinant of the matrix obtained by removing * row x and column y from a. */ tdl.math.codet = function(a, x, y) { var size = 4; var b = []; var ai = 0; for (var bi = 0; bi < size - 1; ++bi) { if (ai == x) ai++; var aj = 0; for (var bj = 0; bj < size - 1; ++bj) { if (aj == y) aj++; b[bi*4+bj] = a[ai*4+aj]; aj++; } ai++; } return tdl.math.det(b); }; /** * Computes the determinant of an arbitrary square matrix. * @param {!tdl.math.Matrix} m The matrix. * @return {number} the determinant of m. */ tdl.math.det = function(m) { var d = 4; if (d <= 4) { return tdl.math['det' + d](m); } var r = 0.0; var sign = 1; var row = m[0]; var mLength = m.length; for (var y = 0; y < mLength; y++) { r += sign * row[y] * tdl.math.codet(m, 0, y); sign *= -1; } return r; }; /** * Computes the inverse of an arbitrary square matrix. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} The inverse of m. */ tdl.math.inverse = function(m) { var d = 4; if (d <= 4) { return tdl.math['inverse' + d](m); } var r = []; var size = m.length; for (var j = 0; j < size; ++j) { r[j] = []; for (var i = 0; i < size; ++i) r[j][i] = ((i + j) % 2 ? -1 : 1) * tdl.math.codet(m, i, j); } return tdl.math.divMatrixScalar(r, tdl.math.det(m)); }; /** * Performs Graham-Schmidt orthogonalization on the vectors which make up the * given matrix and returns the result in the rows of a new matrix. When * multiplying many orthogonal matrices together, errors can accumulate causing * the product to fail to be orthogonal. This function can be used to correct * that. * @param {!tdl.math.Matrix} m The matrix. * @return {!tdl.math.Matrix} A matrix whose rows are obtained from the * rows of m by the Graham-Schmidt process. */ tdl.math.orthonormalize = function(m) { // var r = []; // for (var i = 0; i < 4; ++i) { // var v = m[i]; // for (var j = 0; j < i; ++j) { // v = tdl.math.subVector(v, tdl.math.mulScalarVector( // tdl.math.dot(r[j], m[i]), r[j])); // } // r[i] = tdl.math.normalize(v); // } // return r; }; /** * Computes the inverse of a 4-by-4 matrix. * Note: It is faster to call this than tdl.math.inverse. * @param {!tdl.math.Matrix4} m The matrix. * @return {!tdl.math.Matrix4} The inverse of m. */ tdl.math.matrix4.inverse = function(m) { return tdl.math.inverse4(m); }; /** * Multiplies two 4-by-4 matrices; assumes that the given matrices are 4-by-4. * Note: It is faster to call this than tdl.math.mul. * @param {!tdl.math.Matrix4} a The matrix on the left. * @param {!tdl.math.Matrix4} b The matrix on the right. * @return {!tdl.math.Matrix4} The matrix product of a and b. */ tdl.math.matrix4.mul = function(a, b) { return tdl.math.mulMatrixMatrix4(a, b); }; /** * Computes the determinant of a 4-by-4 matrix. * Note: It is faster to call this than tdl.math.det. * @param {!tdl.math.Matrix4} m The matrix. * @return {number} The determinant of m. */ tdl.math.matrix4.det = function(m) { return tdl.math.det4(m); }; /** * Copies a Matrix4. * Note: It is faster to call this than tdl.math.copy. * @param {!tdl.math.Matrix4} m The matrix. * @return {!tdl.math.Matrix4} A copy of m. */ tdl.math.matrix4.copy = function(m) { return tdl.math.copyMatrix(m); }; tdl.math.matrix4.transpose = tdl.math.transpose; /** * Sets the upper 3-by-3 block of matrix a to the upper 3-by-3 block of matrix * b; assumes that a and b are big enough to contain an upper 3-by-3 block. * @param {!tdl.math.Matrix4} a A matrix. * @param {!tdl.math.Matrix3} b A 3-by-3 matrix. * @return {!tdl.math.Matrix4} a once modified. */ tdl.math.matrix4.setUpper3x3 = function(a, b) { a[0*4+0] = b[0*3+0]; a[0*4+1] = b[0*3+1]; a[0*4+2] = b[0*3+2]; a[1*4+0] = b[1*3+0]; a[1*4+1] = b[1*3+1]; a[1*4+2] = b[1*3+2]; a[2*4+0] = b[2*3+0]; a[2*4+1] = b[2*3+1]; a[2*4+2] = b[2*3+2]; return a; }; /** * Returns a 3-by-3 matrix mimicking the upper 3-by-3 block of m; assumes m * is big enough to contain an upper 3-by-3 block. * @param {!tdl.math.Matrix4} m The matrix. * @return {!tdl.math.Matrix3} The upper 3-by-3 block of m. */ tdl.math.matrix4.getUpper3x3 = function(m) { return [ m[0*4+0], m[0*4+1], m[0*4+2], m[1*4+0], m[1*4+1], m[1*4+2], m[2*4+0], m[2*4+1], m[2*4+2] ]; }; /** * Sets the translation component of a 4-by-4 matrix to the given * vector. * @param {!tdl.math.Matrix4} a The matrix. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} v The vector. * @return {!tdl.math.Matrix4} a once modified. */ tdl.math.matrix4.setTranslation = function(a, v) { a[12] = v[0]; a[13] = v[1]; a[14] = v[2]; a[15] = 1; return a; }; /** * Returns the translation component of a 4-by-4 matrix as a vector with 3 * entries. * @param {!tdl.math.Matrix4} m The matrix. * @return {!tdl.math.Vector3} The translation component of m. */ tdl.math.matrix4.getTranslation = function(m) { return [m[12], m[13], m[14], m[15]]; }; /** * Takes a 4-by-4 matrix and a vector with 3 entries, * interprets the vector as a point, transforms that point by the matrix, and * returns the result as a vector with 3 entries. * @param {!tdl.math.Matrix4} m The matrix. * @param {!tdl.math.Vector3} v The point. * @return {!tdl.math.Vector3} The transformed point. */ tdl.math.matrix4.transformPoint = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; var d = v0 * m[0*4+3] + v1 * m[1*4+3] + v2 * m[2*4+3] + m[3*4+3]; return [(v0 * m[0*4+0] + v1 * m[1*4+0] + v2 * m[2*4+0] + m[3*4+0]) / d, (v0 * m[0*4+1] + v1 * m[1*4+1] + v2 * m[2*4+1] + m[3*4+1]) / d, (v0 * m[0*4+2] + v1 * m[1*4+2] + v2 * m[2*4+2] + m[3*4+2]) / d]; }; /** * Takes a 4-by-4 matrix and a vector with 4 entries, transforms that vector by * the matrix, and returns the result as a vector with 4 entries. * @param {!tdl.math.Matrix4} m The matrix. * @param {!tdl.math.Vector4} v The point in homogenous coordinates. * @return {!tdl.math.Vector4} The transformed point in homogenous * coordinates. */ tdl.math.matrix4.transformVector4 = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; var v3 = v[3]; return [v0 * m[0*4+0] + v1 * m[1*4+0] + v2 * m[2*4+0] + v3 * m[3*4+0], v0 * m[0*4+1] + v1 * m[1*4+1] + v2 * m[2*4+1] + v3 * m[3*4+1], v0 * m[0*4+2] + v1 * m[1*4+2] + v2 * m[2*4+2] + v3 * m[3*4+2], v0 * m[0*4+3] + v1 * m[1*4+3] + v2 * m[2*4+3] + v3 * m[3*4+3]]; }; /** * Takes a 4-by-4 matrix and a vector with 3 entries, interprets the vector as a * direction, transforms that direction by the matrix, and returns the result; * assumes the transformation of 3-dimensional space represented by the matrix * is parallel-preserving, i.e. any combination of rotation, scaling and * translation, but not a perspective distortion. Returns a vector with 3 * entries. * @param {!tdl.math.Matrix4} m The matrix. * @param {!tdl.math.Vector3} v The direction. * @return {!tdl.math.Vector3} The transformed direction. */ tdl.math.matrix4.transformDirection = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; return [v0 * m[0*4+0] + v1 * m[1*4+0] + v2 * m[2*4+0], v0 * m[0*4+1] + v1 * m[1*4+1] + v2 * m[2*4+1], v0 * m[0*4+2] + v1 * m[1*4+2] + v2 * m[2*4+2]]; }; /** * Takes a 4-by-4 matrix m and a vector v with 3 entries, interprets the vector * as a normal to a surface, and computes a vector which is normal upon * transforming that surface by the matrix. The effect of this function is the * same as transforming v (as a direction) by the inverse-transpose of m. This * function assumes the transformation of 3-dimensional space represented by the * matrix is parallel-preserving, i.e. any combination of rotation, scaling and * translation, but not a perspective distortion. Returns a vector with 3 * entries. * @param {!tdl.math.Matrix4} m The matrix. * @param {!tdl.math.Vector3} v The normal. * @return {!tdl.math.Vector3} The transformed normal. */ tdl.math.matrix4.transformNormal = function(m, v) { var mi = tdl.math.inverse4(m); var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; return [v0 * mi[0*4+0] + v1 * mi[0*4+1] + v2 * mi[0*4+2], v0 * mi[1*4+0] + v1 * mi[1*4+1] + v2 * mi[1*4+2], v0 * mi[2*4+0] + v1 * mi[2*4+1] + v2 * mi[2*4+2]]; }; /** * Creates a 4-by-4 identity matrix. * @return {!tdl.math.Matrix4} The 4-by-4 identity. */ tdl.math.matrix4.identity = function() { return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; }; /** * Sets the given 4-by-4 matrix to the identity matrix. * @param {!tdl.math.Matrix4} m The matrix to set to identity. * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.setIdentity = function(m) { for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { if (i == j) { m[i*4+j] = 1; } else { m[i*4+j] = 0; } } } return m; }; /** * Computes a 4-by-4 perspective transformation matrix given the angular height * of the frustum, the aspect ratio, and the near and far clipping planes. The * arguments define a frustum extending in the negative z direction. The given * angle is the vertical angle of the frustum, and the horizontal angle is * determined to produce the given aspect ratio. The arguments near and far are * the distances to the near and far clipping planes. Note that near and far * are not z coordinates, but rather they are distances along the negative * z-axis. The matrix generated sends the viewing frustum to the unit box. * We assume a unit box extending from -1 to 1 in the x and y dimensions and * from 0 to 1 in the z dimension. * @param {number} angle The camera angle from top to bottom (in radians). * @param {number} aspect The aspect ratio width / height. * @param {number} zNear The depth (negative z coordinate) * of the near clipping plane. * @param {number} zFar The depth (negative z coordinate) * of the far clipping plane. * @return {!tdl.math.Matrix4} The perspective matrix. */ tdl.math.matrix4.perspective = function(angle, aspect, zNear, zFar) { var f = Math.tan(Math.PI * 0.5 - 0.5 * angle); var rangeInv = 1.0 / (zNear - zFar); return [ f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (zNear + zFar) * rangeInv, -1, 0, 0, zNear * zFar * rangeInv * 2, 0 ]; }; /** * Computes a 4-by-4 orthographic projection matrix given the coordinates of the * planes defining the axis-aligned, box-shaped viewing volume. The matrix * generated sends that box to the unit box. Note that although left and right * are x coordinates and bottom and top are y coordinates, near and far * are not z coordinates, but rather they are distances along the negative * z-axis. We assume a unit box extending from -1 to 1 in the x and y * dimensions and from 0 to 1 in the z dimension. * @param {number} left The x coordinate of the left plane of the box. * @param {number} right The x coordinate of the right plane of the box. * @param {number} bottom The y coordinate of the bottom plane of the box. * @param {number} top The y coordinate of the right plane of the box. * @param {number} near The negative z coordinate of the near plane of the box. * @param {number} far The negative z coordinate of the far plane of the box. * @return {!tdl.math.Matrix4} The orthographic projection matrix. */ tdl.math.matrix4.orthographic = function(left, right, bottom, top, near, far) { return [ 2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, 1 / (near - far), 0, (left + right) / (left - right), (bottom + top) / (bottom - top), near / (near - far), 1 ]; }; /** * Computes a 4-by-4 perspective transformation matrix given the left, right, * top, bottom, near and far clipping planes. The arguments define a frustum * extending in the negative z direction. The arguments near and far are the * distances to the near and far clipping planes. Note that near and far are not * z coordinates, but rather they are distances along the negative z-axis. The * matrix generated sends the viewing frustum to the unit box. We assume a unit * box extending from -1 to 1 in the x and y dimensions and from 0 to 1 in the z * dimension. * @param {number} left The x coordinate of the left plane of the box. * @param {number} right The x coordinate of the right plane of the box. * @param {number} bottom The y coordinate of the bottom plane of the box. * @param {number} top The y coordinate of the right plane of the box. * @param {number} near The negative z coordinate of the near plane of the box. * @param {number} far The negative z coordinate of the far plane of the box. * @return {!tdl.math.Matrix4} The perspective projection matrix. */ tdl.math.matrix4.frustum = function(left, right, bottom, top, near, far) { var dx = (right - left); var dy = (top - bottom); var dz = (near - far); return [ 2 * near / dx, 0, 0, 0, 0, 2 * near / dy, 0, 0, (left + right) / dx, (top + bottom) / dy, far / dz, -1, 0, 0, near * far / dz, 0]; }; /** * Computes a 4-by-4 look-at transformation. The transformation generated is * an orthogonal rotation matrix with translation component. The translation * component sends the eye to the origin. The rotation component sends the * vector pointing from the eye to the target to a vector pointing in the * negative z direction, and also sends the up vector into the upper half of * the yz plane. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} eye The position * of the eye. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} target The * position meant to be viewed. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} up A vector * pointing up. * @return {!tdl.math.Matrix4} The look-at matrix. */ tdl.math.matrix4.lookAt = function(eye, target, up) { return tdl.math.inverse(tdl.math.matrix4.cameraLookAt( eye, target, up)); }; /** * Computes a 4-by-4 camera look-at transformation. This is the * inverse of lookAt The transformation generated is an * orthogonal rotation matrix with translation component. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} eye The position * of the eye. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} target The * position meant to be viewed. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} up A vector * pointing up. * @return {!tdl.math.Matrix4} The camera look-at matrix. */ tdl.math.matrix4.cameraLookAt = function(eye, target, up) { var vz = tdl.math.normalize( tdl.math.subVector(eye, target)); var vx = tdl.math.normalize( tdl.math.cross(up, vz)); var vy = tdl.math.cross(vz, vx); return tdl.math.inverse([ vx[0], vx[1], vx[2], 0, vy[0], vy[1], vy[2], 0, vz[0], vz[1], vz[2], 0, -tdl.math.dot(vx, eye), -tdl.math.dot(vy, eye), -tdl.math.dot(vz, eye), 1]); }; /** * Takes two 4-by-4 matrices, a and b, and computes the product in the order * that pre-composes b with a. In other words, the matrix returned will * transform by b first and then a. Note this is subtly different from just * multiplying the matrices together. For given a and b, this function returns * the same object in both row-major and column-major mode. * @param {!tdl.math.Matrix4} a A 4-by-4 matrix. * @param {!tdl.math.Matrix4} b A 4-by-4 matrix. * @return {!tdl.math.Matrix4} the composition of a and b, b first then a. */ tdl.math.matrix4.composition = function(a, b) { var a00 = a[0*4+0]; var a01 = a[0*4+1]; var a02 = a[0*4+2]; var a03 = a[0*4+3]; var a10 = a[1*4+0]; var a11 = a[1*4+1]; var a12 = a[1*4+2]; var a13 = a[1*4+3]; var a20 = a[2*4+0]; var a21 = a[2*4+1]; var a22 = a[2*4+2]; var a23 = a[2*4+3]; var a30 = a[3*4+0]; var a31 = a[3*4+1]; var a32 = a[3*4+2]; var a33 = a[3*4+3]; var b00 = b[0*4+0]; var b01 = b[0*4+1]; var b02 = b[0*4+2]; var b03 = b[0*4+3]; var b10 = b[1*4+0]; var b11 = b[1*4+1]; var b12 = b[1*4+2]; var b13 = b[1*4+3]; var b20 = b[2*4+0]; var b21 = b[2*4+1]; var b22 = b[2*4+2]; var b23 = b[2*4+3]; var b30 = b[3*4+0]; var b31 = b[3*4+1]; var b32 = b[3*4+2]; var b33 = b[3*4+3]; return [a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03, a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03, a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03, a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03, a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13, a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13, a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13, a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13, a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23, a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23, a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23, a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23, a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33, a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33, a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33, a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33]; }; /** * Takes two 4-by-4 matrices, a and b, and modifies a to be the product in the * order that pre-composes b with a. The matrix a, upon modification will * transform by b first and then a. Note this is subtly different from just * multiplying the matrices together. For given a and b, a, upon modification, * will be the same object in both row-major and column-major mode. * @param {!tdl.math.Matrix4} a A 4-by-4 matrix. * @param {!tdl.math.Matrix4} b A 4-by-4 matrix. * @return {!tdl.math.Matrix4} a once modified. */ tdl.math.matrix4.compose = function(a, b) { var a00 = a[0*4+0]; var a01 = a[0*4+1]; var a02 = a[0*4+2]; var a03 = a[0*4+3]; var a10 = a[1*4+0]; var a11 = a[1*4+1]; var a12 = a[1*4+2]; var a13 = a[1*4+3]; var a20 = a[2*4+0]; var a21 = a[2*4+1]; var a22 = a[2*4+2]; var a23 = a[2*4+3]; var a30 = a[3*4+0]; var a31 = a[3*4+1]; var a32 = a[3*4+2]; var a33 = a[3*4+3]; var b00 = b[0*4+0]; var b01 = b[0*4+1]; var b02 = b[0*4+2]; var b03 = b[0*4+3]; var b10 = b[1*4+0]; var b11 = b[1*4+1]; var b12 = b[1*4+2]; var b13 = b[1*4+3]; var b20 = b[2*4+0]; var b21 = b[2*4+1]; var b22 = b[2*4+2]; var b23 = b[2*4+3]; var b30 = b[3*4+0]; var b31 = b[3*4+1]; var b32 = b[3*4+2]; var b33 = b[3*4+3]; a[ 0] = a00 * b00 + a10 * b01 + a20 * b02 + a30 * b03; a[ 1] = a01 * b00 + a11 * b01 + a21 * b02 + a31 * b03; a[ 2] = a02 * b00 + a12 * b01 + a22 * b02 + a32 * b03; a[ 3] = a03 * b00 + a13 * b01 + a23 * b02 + a33 * b03; a[ 4] = a00 * b10 + a10 * b11 + a20 * b12 + a30 * b13; a[ 5] = a01 * b10 + a11 * b11 + a21 * b12 + a31 * b13; a[ 6] = a02 * b10 + a12 * b11 + a22 * b12 + a32 * b13; a[ 7] = a03 * b10 + a13 * b11 + a23 * b12 + a33 * b13; a[ 8] = a00 * b20 + a10 * b21 + a20 * b22 + a30 * b23; a[ 9] = a01 * b20 + a11 * b21 + a21 * b22 + a31 * b23; a[10] = a02 * b20 + a12 * b21 + a22 * b22 + a32 * b23; a[11] = a03 * b20 + a13 * b21 + a23 * b22 + a33 * b23; a[12] = a00 * b30 + a10 * b31 + a20 * b32 + a30 * b33; a[13] = a01 * b30 + a11 * b31 + a21 * b32 + a31 * b33; a[14] = a02 * b30 + a12 * b31 + a22 * b32 + a32 * b33; a[15] = a03 * b30 + a13 * b31 + a23 * b32 + a33 * b33; return a; }; /** * Creates a 4-by-4 matrix which translates by the given vector v. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} v The vector by * which to translate. * @return {!tdl.math.Matrix4} The translation matrix. */ tdl.math.matrix4.translation = function(v) { return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, v[0], v[1], v[2], 1 ]; }; /** * Modifies the given 4-by-4 matrix by translation by the given vector v. * @param {!tdl.math.Matrix4} m The matrix. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} v The vector by * which to translate. * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.translate = function(m, v) { var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var m30 = m[3*4+0]; var m31 = m[3*4+1]; var m32 = m[3*4+2]; var m33 = m[3*4+3]; var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; m[12] = m00 * v0 + m10 * v1 + m20 * v2 + m30; m[13] = m01 * v0 + m11 * v1 + m21 * v2 + m31; m[14] = m02 * v0 + m12 * v1 + m22 * v2 + m32; m[15] = m03 * v0 + m13 * v1 + m23 * v2 + m33; return m; }; /** * Creates a 4-by-4 matrix which scales in each dimension by an amount given by * the corresponding entry in the given vector; assumes the vector has three * entries. * @param {!tdl.math.Vector3} v A vector of * three entries specifying the factor by which to scale in each dimension. * @return {!tdl.math.Matrix4} The scaling matrix. */ tdl.math.matrix4.scaling = function(v) { return [ v[0], 0, 0, 0, 0, v[1], 0, 0, 0, 0, v[2], 0, 0, 0, 0, 1 ]; }; /** * Modifies the given 4-by-4 matrix, scaling in each dimension by an amount * given by the corresponding entry in the given vector; assumes the vector has * three entries. * @param {!tdl.math.Matrix4} m The matrix to be modified. * @param {!tdl.math.Vector3} v A vector of three entries specifying the * factor by which to scale in each dimension. * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.scale = function(m, v) { var v0 = v[0]; var v1 = v[1]; var v2 = v[2]; m[0] = v0 * m[0*4+0]; m[1] = v0 * m[0*4+1]; m[2] = v0 * m[0*4+2]; m[3] = v0 * m[0*4+3]; m[4] = v1 * m[1*4+0]; m[5] = v1 * m[1*4+1]; m[6] = v1 * m[1*4+2]; m[7] = v1 * m[1*4+3]; m[8] = v2 * m[2*4+0]; m[9] = v2 * m[2*4+1]; m[10] = v2 * m[2*4+2]; m[11] = v2 * m[2*4+3]; return m; }; /** * Creates a 4-by-4 matrix which rotates around the x-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} The rotation matrix. */ tdl.math.matrix4.rotationX = function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); return [ 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 ]; }; /** * Modifies the given 4-by-4 matrix by a rotation around the x-axis by the given * angle. * @param {!tdl.math.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.rotateX = function(m, angle) { var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var c = Math.cos(angle); var s = Math.sin(angle); m[4] = c * m10 + s * m20; m[5] = c * m11 + s * m21; m[6] = c * m12 + s * m22; m[7] = c * m13 + s * m23; m[8] = c * m20 - s * m10; m[9] = c * m21 - s * m11; m[10] = c * m22 - s * m12; m[11] = c * m23 - s * m13; return m; }; /** * Creates a 4-by-4 matrix which rotates around the y-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} The rotation matrix. */ tdl.math.matrix4.rotationY = function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); return [ c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 ]; }; /** * Modifies the given 4-by-4 matrix by a rotation around the y-axis by the given * angle. * @param {!tdl.math.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.rotateY = function(m, angle) { var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var c = Math.cos(angle); var s = Math.sin(angle); m[ 0] = c * m00 - s * m20; m[ 1] = c * m01 - s * m21; m[ 2] = c * m02 - s * m22; m[ 3] = c * m03 - s * m23; m[ 8] = c * m20 + s * m00; m[ 9] = c * m21 + s * m01; m[10] = c * m22 + s * m02; m[11] = c * m23 + s * m03; return m; }; /** * Creates a 4-by-4 matrix which rotates around the z-axis by the given angle. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} The rotation matrix. */ tdl.math.matrix4.rotationZ = function(angle) { var c = Math.cos(angle); var s = Math.sin(angle); return [ c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; }; /** * Modifies the given 4-by-4 matrix by a rotation around the z-axis by the given * angle. * @param {!tdl.math.Matrix4} m The matrix. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.rotateZ = function(m, angle) { var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var c = Math.cos(angle); var s = Math.sin(angle); m[ 0] = c * m00 + s * m10; m[ 1] = c * m01 + s * m11; m[ 2] = c * m02 + s * m12; m[ 3] = c * m03 + s * m13; m[ 4] = c * m10 - s * m00; m[ 5] = c * m11 - s * m01; m[ 6] = c * m12 - s * m02; m[ 7] = c * m13 - s * m03; return m; }; /** * Creates a 4-by-4 rotation matrix. Interprets the entries of the given * vector as angles by which to rotate around the x, y and z axes, returns a * a matrix which rotates around the x-axis first, then the y-axis, then the * z-axis. * @param {!tdl.math.Vector3} v A vector of angles (in radians). * @return {!tdl.math.Matrix4} The rotation matrix. */ tdl.math.matrix4.rotationZYX = function(v) { var sinx = Math.sin(v[0]); var cosx = Math.cos(v[0]); var siny = Math.sin(v[1]); var cosy = Math.cos(v[1]); var sinz = Math.sin(v[2]); var cosz = Math.cos(v[2]); var coszsiny = cosz * siny; var sinzsiny = sinz * siny; return [ cosz * cosy, sinz * cosy, -siny, 0, coszsiny * sinx - sinz * cosx, sinzsiny * sinx + cosz * cosx, cosy * sinx, 0, coszsiny * cosx + sinz * sinx, sinzsiny * cosx - cosz * sinx, cosy * cosx, 0, 0, 0, 0, 1 ]; }; /** * Modifies a 4-by-4 matrix by a rotation. Interprets the coordinates of the * given vector as angles by which to rotate around the x, y and z axes, rotates * around the x-axis first, then the y-axis, then the z-axis. * @param {!tdl.math.Matrix4} m The matrix. * @param {!tdl.math.Vector3} v A vector of angles (in radians). * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.rotateZYX = function(m, v) { var sinX = Math.sin(v[0]); var cosX = Math.cos(v[0]); var sinY = Math.sin(v[1]); var cosY = Math.cos(v[1]); var sinZ = Math.sin(v[2]); var cosZ = Math.cos(v[2]); var cosZSinY = cosZ * sinY; var sinZSinY = sinZ * sinY; var r00 = cosZ * cosY; var r01 = sinZ * cosY; var r02 = -sinY; var r10 = cosZSinY * sinX - sinZ * cosX; var r11 = sinZSinY * sinX + cosZ * cosX; var r12 = cosY * sinX; var r20 = cosZSinY * cosX + sinZ * sinX; var r21 = sinZSinY * cosX - cosZ * sinX; var r22 = cosY * cosX; var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var m30 = m[3*4+0]; var m31 = m[3*4+1]; var m32 = m[3*4+2]; var m33 = m[3*4+3]; m[ 0] = r00 * m00 + r01 * m10 + r02 * m20; m[ 1] = r00 * m01 + r01 * m11 + r02 * m21; m[ 2] = r00 * m02 + r01 * m12 + r02 * m22; m[ 3] = r00 * m03 + r01 * m13 + r02 * m23; m[ 4] = r10 * m00 + r11 * m10 + r12 * m20; m[ 5] = r10 * m01 + r11 * m11 + r12 * m21; m[ 6] = r10 * m02 + r11 * m12 + r12 * m22; m[ 7] = r10 * m03 + r11 * m13 + r12 * m23; m[ 8] = r20 * m00 + r21 * m10 + r22 * m20; m[ 9] = r20 * m01 + r21 * m11 + r22 * m21; m[10] = r20 * m02 + r21 * m12 + r22 * m22; m[11] = r20 * m03 + r21 * m13 + r22 * m23; return m; }; /** * Creates a 4-by-4 matrix which rotates around the given axis by the given * angle. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} axis The axis * about which to rotate. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} A matrix which rotates angle radians * around the axis. */ tdl.math.matrix4.axisRotation = function(axis, angle) { var x = axis[0]; var y = axis[1]; var z = axis[2]; var n = Math.sqrt(x * x + y * y + z * z); x /= n; y /= n; z /= n; var xx = x * x; var yy = y * y; var zz = z * z; var c = Math.cos(angle); var s = Math.sin(angle); var oneMinusCosine = 1 - c; return [ xx + (1 - xx) * c, x * y * oneMinusCosine + z * s, x * z * oneMinusCosine - y * s, 0, x * y * oneMinusCosine - z * s, yy + (1 - yy) * c, y * z * oneMinusCosine + x * s, 0, x * z * oneMinusCosine + y * s, y * z * oneMinusCosine - x * s, zz + (1 - zz) * c, 0, 0, 0, 0, 1 ]; }; /** * Modifies the given 4-by-4 matrix by rotation around the given axis by the * given angle. * @param {!tdl.math.Matrix4} m The matrix. * @param {(!tdl.math.Vector3|!tdl.math.Vector4)} axis The axis * about which to rotate. * @param {number} angle The angle by which to rotate (in radians). * @return {!tdl.math.Matrix4} m once modified. */ tdl.math.matrix4.axisRotate = function(m, axis, angle) { var x = axis[0]; var y = axis[1]; var z = axis[2]; var n = Math.sqrt(x * x + y * y + z * z); x /= n; y /= n; z /= n; var xx = x * x; var yy = y * y; var zz = z * z; var c = Math.cos(angle); var s = Math.sin(angle); var oneMinusCosine = 1 - c; var r00 = xx + (1 - xx) * c; var r01 = x * y * oneMinusCosine + z * s; var r02 = x * z * oneMinusCosine - y * s; var r10 = x * y * oneMinusCosine - z * s; var r11 = yy + (1 - yy) * c; var r12 = y * z * oneMinusCosine + x * s; var r20 = x * z * oneMinusCosine + y * s; var r21 = y * z * oneMinusCosine - x * s; var r22 = zz + (1 - zz) * c; var m00 = m[0*4+0]; var m01 = m[0*4+1]; var m02 = m[0*4+2]; var m03 = m[0*4+3]; var m10 = m[1*4+0]; var m11 = m[1*4+1]; var m12 = m[1*4+2]; var m13 = m[1*4+3]; var m20 = m[2*4+0]; var m21 = m[2*4+1]; var m22 = m[2*4+2]; var m23 = m[2*4+3]; var m30 = m[3*4+0]; var m31 = m[3*4+1]; var m32 = m[3*4+2]; var m33 = m[3*4+3]; m[ 0] = r00 * m00 + r01 * m10 + r02 * m20; m[ 1] = r00 * m01 + r01 * m11 + r02 * m21; m[ 2] = r00 * m02 + r01 * m12 + r02 * m22; m[ 3] = r00 * m03 + r01 * m13 + r02 * m23; m[ 4] = r10 * m00 + r11 * m10 + r12 * m20; m[ 5] = r10 * m01 + r11 * m11 + r12 * m21; m[ 6] = r10 * m02 + r11 * m12 + r12 * m22; m[ 7] = r10 * m03 + r11 * m13 + r12 * m23; m[ 8] = r20 * m00 + r21 * m10 + r22 * m20; m[ 9] = r20 * m01 + r21 * m11 + r22 * m21; m[10] = r20 * m02 + r21 * m12 + r22 * m22; m[11] = r20 * m03 + r21 * m13 + r22 * m23; return m; }; /** * Sets each function in the namespace tdl.math to the row major * version in tdl.math.rowMajor (provided such a function exists in * tdl.math.rowMajor). Call this function to establish the row major * convention. */ tdl.math.installRowMajorFunctions = function() { for (var f in tdl.math.rowMajor) { tdl.math[f] = tdl.math.rowMajor[f]; } }; /** * Sets each function in the namespace tdl.math to the column major * version in tdl.math.columnMajor (provided such a function exists in * tdl.math.columnMajor). Call this function to establish the column * major convention. */ tdl.math.installColumnMajorFunctions = function() { for (var f in tdl.math.columnMajor) { tdl.math[f] = tdl.math.columnMajor[f]; } }; /** * Sets each function in the namespace tdl.math to the error checking * version in tdl.math.errorCheck (provided such a function exists in * tdl.math.errorCheck). */ tdl.math.installErrorCheckFunctions = function() { for (var f in tdl.math.errorCheck) { tdl.math[f] = tdl.math.errorCheck[f]; } }; /** * Sets each function in the namespace tdl.math to the error checking free * version in tdl.math.errorCheckFree (provided such a function exists in * tdl.math.errorCheckFree). */ tdl.math.installErrorCheckFreeFunctions = function() { for (var f in tdl.math.errorCheckFree) { tdl.math[f] = tdl.math.errorCheckFree[f]; } } // By default, install the row-major functions. tdl.math.installRowMajorFunctions(); // By default, install prechecking. tdl.math.installErrorCheckFunctions();
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains misc functions that don't fit elsewhere. */ tdl.provide('tdl.misc'); tdl.require('tdl.log'); /** * A module for misc. * @namespace */ tdl.misc = tdl.misc || {}; tdl.misc.applyUrlSettings = function(obj, opt_argumentName) { var argumentName = opt_argumentName || 'settings'; try { var s = window.location.href; var q = s.indexOf("?"); var e = s.indexOf("#"); if (e < 0) { e = s.length; } var query = s.substring(q + 1, e); //tdl.log("query:", query); var pairs = query.split("&"); //tdl.log("pairs:", pairs.length); for (var ii = 0; ii < pairs.length; ++ii) { var keyValue = pairs[ii].split("="); var key = keyValue[0]; var value = decodeURIComponent(keyValue[1]); //tdl.log(ii, ":", key, "=", value); switch (key) { case argumentName: //tdl.log(value); var settings = eval("(" + value + ")"); //tdl.log("settings:", settings); tdl.misc.copyProperties(settings, obj); break; } } } catch (e) { tdl.error(e); tdl.error("settings:", settings); return; } }; /** * Copies properties from obj to dst recursively. * @private * @param {!Object} obj Object with new settings. * @param {!Object} dst Object to receive new settings. */ tdl.misc.copyProperties = function(obj, dst) { for (var name in obj) { var value = obj[name]; if (value instanceof Array) { //tdl.log("apply->: ", name, "[]"); var newDst = dst[name]; if (!newDst) { newDst = []; dst[name] = newDst; } tdl.misc.copyProperties(value, newDst); } else if (typeof value == 'object') { //tdl.log("apply->: ", name); var newDst = dst[name]; if (!newDst) { newDst = {}; dst[name] = newDst; } tdl.misc.copyProperties(value, newDst); } else { //tdl.log("apply: ", name, "=", value); dst[name] = value; } } };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to make primitives. */ tdl.provide('tdl.primitives'); tdl.require('tdl.math'); tdl.require('tdl.log'); /** * A module for primitives. * @namespace */ tdl.primitives = tdl.primitives || {}; /** * AttribBuffer manages a TypedArray as an array of vectors. * * @param {number} numComponents Number of components per * vector. * @param {number|!Array.<number>} numElements Number of vectors or the data. * @param {string} opt_type The type of the TypedArray to * create. Default = 'Float32Array'. * @param {!Array.<number>} opt_data The data for the array. */ tdl.primitives.AttribBuffer = function( numComponents, numElements, opt_type) { opt_type = opt_type || 'Float32Array'; var type = window[opt_type]; if (numElements.length) { this.buffer = new type(numElements); numElements = this.buffer.length / numComponents; this.cursor = numElements; } else { this.buffer = new type(numComponents * numElements); this.cursor = 0; } this.numComponents = numComponents; this.numElements = numElements; this.type = opt_type; }; tdl.primitives.AttribBuffer.prototype.stride = function() { return 0; }; tdl.primitives.AttribBuffer.prototype.offset = function() { return 0; }; tdl.primitives.AttribBuffer.prototype.getElement = function(index) { var offset = index * this.numComponents; var value = []; for (var ii = 0; ii < this.numComponents; ++ii) { value.push(this.buffer[offset + ii]); } return value; }; tdl.primitives.AttribBuffer.prototype.setElement = function(index, value) { var offset = index * this.numComponents; for (var ii = 0; ii < this.numComponents; ++ii) { this.buffer[offset + ii] = value[ii]; } }; tdl.primitives.AttribBuffer.prototype.fillRange = function(index, count, value) { var offset = index * this.numComponents; for (var jj = 0; jj < count; ++jj) { for (var ii = 0; ii < this.numComponents; ++ii) { this.buffer[offset++] = value[ii]; } } }; tdl.primitives.AttribBuffer.prototype.clone = function() { var copy = new tdl.primitives.AttribBuffer( this.numComponents, this.numElements, this.type); copy.pushArray(this); return copy; } tdl.primitives.AttribBuffer.prototype.push = function(value) { this.setElement(this.cursor++, value); }; tdl.primitives.AttribBuffer.prototype.pushArray = function(array) { // this.buffer.set(array, this.cursor * this.numComponents); // this.cursor += array.numElements; for (var ii = 0; ii < array.numElements; ++ii) { this.push(array.getElement(ii)); } }; tdl.primitives.AttribBuffer.prototype.pushArrayWithOffset = function(array, offset) { for (var ii = 0; ii < array.numElements; ++ii) { var elem = array.getElement(ii); for (var jj = 0; jj < offset.length; ++jj) { elem[jj] += offset[jj]; } this.push(elem); } }; /** * Computes the extents * @param {!AttribBuffer} positions The positions * @return {!{min: !tdl.math.Vector3, max:!tdl.math.Vector3}} * The min and max extents. */ tdl.primitives.AttribBuffer.prototype.computeExtents = function() { var numElements = this.numElements; var numComponents = this.numComponents; var minExtent = this.getElement(0); var maxExtent = this.getElement(0); for (var ii = 1; ii < numElements; ++ii) { var element = this.getElement(ii); for (var jj = 0; jj < numComponents; ++jj) { minExtent[jj] = Math.min(minExtent[jj], element[jj]); maxExtent[jj] = Math.max(maxExtent[jj], element[jj]); } } return {min: minExtent, max: maxExtent}; }; /** * Reorients positions by the given matrix. In other words, it * multiplies each vertex by the given matrix. * @param {!tdl.primitives.AttribBuffer} array AttribBuffer to * reorient. * @param {!tdl.math.Matrix4} matrix Matrix by which to * multiply. */ tdl.primitives.mulComponents = function(array, multiplier) { var numElements = array.numElements; var numComponents = array.numComponents; for (var ii = 0; ii < numElements; ++ii) { var element = array.getElement(ii); for (var jj = 0; jj < numComponents; ++jj) { element[jj] *= multiplier[jj]; } array.setElement(ii, element); } }; /** * Reorients positions by the given matrix. In other words, it * multiplies each vertex by the given matrix. * @param {!tdl.primitives.AttribBuffer} array AttribBuffer to * reorient. * @param {!tdl.math.Matrix4} matrix Matrix by which to * multiply. */ tdl.primitives.reorientPositions = function(array, matrix) { var math = tdl.math; var numElements = array.numElements; for (var ii = 0; ii < numElements; ++ii) { array.setElement(ii, math.matrix4.transformPoint(matrix, array.getElement(ii))); } }; /** * Reorients normals by the inverse-transpose of the given * matrix.. * @param {!tdl.primitives.AttribBuffer} array AttribBuffer to * reorient. * @param {!tdl.math.Matrix4} matrix Matrix by which to * multiply. */ tdl.primitives.reorientNormals = function(array, matrix) { var math = tdl.math; var numElements = array.numElements; for (var ii = 0; ii < numElements; ++ii) { array.setElement(ii, math.matrix4.transformNormal(matrix, array.getElement(ii))); } }; /** * Reorients directions by the given matrix.. * @param {!tdl.primitives.AttribBuffer} array AttribBuffer to * reorient. * @param {!tdl.math.Matrix4} matrix Matrix by which to * multiply. */ tdl.primitives.reorientDirections = function(array, matrix) { var math = tdl.math; var numElements = array.numElements; for (var ii = 0; ii < numElements; ++ii) { array.setElement(ii, math.matrix4.transformDirection(matrix, array.getElement(ii))); } }; /** * Reorients arrays by the given matrix. Assumes arrays have * names that start with 'position', 'normal', 'tangent', * 'binormal' * * @param {!Object.<string, !tdl.primitive.AttribBuffer>} arrays * The arrays to remap. * @param {!tdl.math.Matrix4} matrix The matrix to remap by */ tdl.primitives.reorient = function(arrays, matrix) { for (var array in arrays) { if (array.match(/^position/)) { tdl.primitives.reorientPositions(arrays[array], matrix); } else if (array.match(/^normal/)) { tdl.primitives.reorientNormals(arrays[array], matrix); } else if (array.match(/^tangent/) || array.match(/^binormal/)) { tdl.primitives.reorientDirections(arrays[array], matrix); } } }; /** * Creates tangents and normals. * * @param {!AttibArray} positionArray Positions * @param {!AttibArray} normalArray Normals * @param {!AttibArray} normalMapUVArray UVs for the normal map. * @param {!AttibArray} triangles The indicies of the trianlges. * @returns {!{tangent: {!AttribArray}, * binormal: {!AttribArray}} */ tdl.primitives.createTangentsAndBinormals = function( positionArray, normalArray, normalMapUVArray, triangles) { var math = tdl.math; // Maps from position, normal key to tangent and binormal matrix. var tangentFrames = {}; // Rounds a vector to integer components. function roundVector(v) { return [Math.round(v[0]), Math.round(v[1]), Math.round(v[2])]; } // Generates a key for the tangentFrames map from a position and normal // vector. Rounds position and normal to allow some tolerance. function tangentFrameKey(position, normal) { return roundVector(math.mulVectorScalar(position, 100)) + ',' + roundVector(math.mulVectorScalar(normal, 100)); } // Accumulates into the tangent and binormal matrix at the approximate // position and normal. function addTangentFrame(position, normal, tangent, binormal) { var key = tangentFrameKey(position, normal); var frame = tangentFrames[key]; if (!frame) { frame = [[0, 0, 0], [0, 0, 0]]; } frame[0] = math.addVector(frame[0], tangent); frame[1] = math.addVector(frame[1], binormal); tangentFrames[key] = frame; } // Get the tangent and binormal matrix at the approximate position and // normal. function getTangentFrame(position, normal) { var key = tangentFrameKey(position, normal); return tangentFrames[key]; } var numTriangles = triangles.numElements; for (var triangleIndex = 0; triangleIndex < numTriangles; ++triangleIndex) { // Get the vertex indices, uvs and positions for the triangle. var vertexIndices = triangles.getElement(triangleIndex); var uvs = []; var positions = []; var normals = []; for (var i = 0; i < 3; ++i) { var vertexIndex = vertexIndices[i]; uvs[i] = normalMapUVArray.getElement(vertexIndex); positions[i] = positionArray.getElement(vertexIndex); normals[i] = normalArray.getElement(vertexIndex); } // Calculate the tangent and binormal for the triangle using method // described in Maya documentation appendix A: tangent and binormal // vectors. var tangent = [0, 0, 0]; var binormal = [0, 0, 0]; for (var axis = 0; axis < 3; ++axis) { var edge1 = [positions[1][axis] - positions[0][axis], uvs[1][0] - uvs[0][0], uvs[1][1] - uvs[0][1]]; var edge2 = [positions[2][axis] - positions[0][axis], uvs[2][0] - uvs[0][0], uvs[2][1] - uvs[0][1]]; var edgeCross = math.normalize(math.cross(edge1, edge2)); if (edgeCross[0] == 0) { edgeCross[0] = 1; } tangent[axis] = -edgeCross[1] / edgeCross[0]; binormal[axis] = -edgeCross[2] / edgeCross[0]; } // Normalize the tangent and binornmal. var tangentLength = math.length(tangent); if (tangentLength > 0.00001) { tangent = math.mulVectorScalar(tangent, 1 / tangentLength); } var binormalLength = math.length(binormal); if (binormalLength > 0.00001) { binormal = math.mulVectorScalar(binormal, 1 / binormalLength); } // Accumulate the tangent and binormal into the tangent frame map. for (var i = 0; i < 3; ++i) { addTangentFrame(positions[i], normals[i], tangent, binormal); } } // Add the tangent and binormal streams. var numVertices = positionArray.numElements; var tangents = new tdl.primitives.AttribBuffer(3, numVertices); var binormals = new tdl.primitives.AttribBuffer(3, numVertices); // Extract the tangent and binormal for each vertex. for (var vertexIndex = 0; vertexIndex < numVertices; ++vertexIndex) { var position = positionArray.getElement(vertexIndex); var normal = normalArray.getElement(vertexIndex); var frame = getTangentFrame(position, normal); // Orthonormalize the tangent with respect to the normal. var tangent = frame[0]; tangent = math.subVector( tangent, math.mulVectorScalar(normal, math.dot(normal, tangent))); var tangentLength = math.length(tangent); if (tangentLength > 0.00001) { tangent = math.mulVectorScalar(tangent, 1 / tangentLength); } // Orthonormalize the binormal with respect to the normal and the tangent. var binormal = frame[1]; binormal = math.subVector( binormal, math.mulVectorScalar(tangent, math.dot(tangent, binormal))); binormal = math.subVector( binormal, math.mulVectorScalar(normal, math.dot(normal, binormal))); var binormalLength = math.length(binormal); if (binormalLength > 0.00001) { binormal = math.mulVectorScalar(binormal, 1 / binormalLength); } tangents.push(tangent); binormals.push(binormal); } return { tangent: tangents, binormal: binormals}; }; /** * Adds tangents and binormals. * * @param {!Object.<string,!AttibArray>} arrays Arrays containing position, * normal and texCoord. */ tdl.primitives.addTangentsAndBinormals = function(arrays) { var bn = tdl.primitives.createTangentsAndBinormals( arrays.position, arrays.normal, arrays.texCoord, arrays.indices); arrays.tangent = bn.tangent; arrays.binormal = bn.binormal; return arrays; }; tdl.primitives.clone = function(arrays) { var newArrays = { }; for (var array in arrays) { newArrays[array] = arrays[array].clone(); } return newArrays; }; /** * Concats 2 or more sets of arrays. Assumes each set of arrays has arrays that * match the other sets. * @param {!Array<!Object.<string, !AttribBuffer>>} arrays Arrays to concat * @return {!Object.<string, !AttribBuffer>} concatenated result. */ tdl.primitives.concat = function(arrayOfArrays) { var names = {}; var baseName; // get names of all arrays. for (var ii = 0; ii < arrayOfArrays.length; ++ii) { var arrays = arrayOfArrays[ii]; for (var name in arrays) { if (!names[name]) { names[name] = []; } if (!baseName && name != 'indices') { baseName = name; } var array = arrays[name]; names[name].push(array.numElements); } } var base = names[baseName]; var newArrays = {}; for (var name in names) { var numElements = 0; var numComponents; var type; for (var ii = 0; ii < arrayOfArrays.length; ++ii) { var arrays = arrayOfArrays[ii]; var array = arrays[name]; numElements += array.numElements; numComponents = array.numComponents; type = array.type; } var newArray = new tdl.primitives.AttribBuffer( numComponents, numElements, type); var baseIndex = 0; for (var ii = 0; ii < arrayOfArrays.length; ++ii) { var arrays = arrayOfArrays[ii]; var array = arrays[name]; if (name == 'indices') { newArray.pushArrayWithOffset( array, [baseIndex, baseIndex, baseIndex]); baseIndex += base[ii]; } else { newArray.pushArray(array); } } newArrays[name] = newArray; } return newArrays; }; /** * Same as tdl.primitives.concat except this one returns an array * of arrays if the models have indices. This is because WebGL can only handle * 16bit indices (ie, < 65536) So, as it is concatenating, if the data would * make indices > 65535 it starts a new set of arrays. * * @param {!Array<!Object.<string, !AttribBuffer>>} arrays Arrays to concat * @return {!{arrays:{!Array<{!Object.<string, !AttribBuffer>>, * instances:{!Array<{firstVertex:number, numVertices:number, arrayIndex: * number}>}} object result. */ // tdl.primitives.concatLarge = function(arrayOfArrays) { // Step 2: convert instances to expanded geometry var instances = []; var expandedArrays = []; var expandedArray; var totalElements = 0; for (var ii = 0; ii < arrayOfArrays.length; ++ii) { // WebGL can only handle 65536 indexed vertices so check if this // geometry can fit the current model var array = arrayOfArrays[ii]; if (!expandedArray || totalElements + array.position.numElements > 65536) { // Start a new array. totalElements = 0; expandedArray = [array]; expandedArrays.push(expandedArray); } else { // Add our new stuff on to the old one. expandedArray.push(array); } instances.push({ firstVertex: totalElements, numVertices: array.position.numElements, arrayIndex: expandedArrays.length - 1 }); totalElements += array.position.numElements; } for (var ii = 0; ii < expandedArrays.length; ++ii) { //tdl.log("concat:", ii, " of ", expandedArrays.length); expandedArrays[ii] = tdl.primitives.concat(expandedArrays[ii]); } return { arrays: expandedArrays, instances: instances }; }; /** * Applies planar UV mapping in the XZ plane. * @param {!AttribBuffer} positions The positions * @param {!AttribBuffer} texCoords The texCoords */ tdl.primitives.applyPlanarUVMapping = function(positions, texCoords) { // compute the extents var extents = positions.computeExtents(); var ranges = tdl.math.subVector(extents.max, extents.min); var numElements = positions.numElements; for (var ii = 0; ii < numElements; ++ii) { var position = positions.getElement(ii); var u = (position[0] - extents.min[0]) / ranges[0]; var v = (position[2] - extents.min[2]) / ranges[2]; texCoords.setElement(ii, [u, v]); } }; /** * Takes a bunch of instances of geometry and converts them * to 1 or more geometries that represent all the instances. * * In other words, if make a cube * * var cube = tdl.primitives.createCube(1); * * And you put 4 of those in an array * * var instances = [cube, cube, cube, cube] * * Then if you call this function it will return a mesh that contains * all 4 cubes. it * * @author gman (4/19/2011) * * @param instances */ tdl.primitives.expandInstancesToGeometry = function(instances) { }; /** * Creates sphere vertices. * The created sphere has position, normal and uv streams. * * @param {number} radius radius of the sphere. * @param {number} subdivisionsAxis number of steps around the sphere. * @param {number} subdivisionsHeight number of vertically on the sphere. * @param {number} opt_startLatitudeInRadians where to start the * top of the sphere. Default = 0. * @param {number} opt_endLatitudeInRadians Where to end the * bottom of the sphere. Default = Math.PI. * @param {number} opt_startLongitudeInRadians where to start * wrapping the sphere. Default = 0. * @param {number} opt_endLongitudeInRadians where to end * wrapping the sphere. Default = 2 * Math.PI. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createSphere = function( radius, subdivisionsAxis, subdivisionsHeight, opt_startLatitudeInRadians, opt_endLatitudeInRadians, opt_startLongitudeInRadians, opt_endLongitudeInRadians) { if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) { throw Error('subdivisionAxis and subdivisionHeight must be > 0'); } var math = tdl.math; opt_startLatitudeInRadians = opt_startLatitudeInRadians || 0; opt_endLatitudeInRadians = opt_endLatitudeInRadians || Math.PI; opt_startLongitudeInRadians = opt_startLongitudeInRadians || 0; opt_endLongitudeInRadians = opt_endLongitudeInRadians || (Math.PI * 2); var latRange = opt_endLatitudeInRadians - opt_startLatitudeInRadians; var longRange = opt_endLongitudeInRadians - opt_startLongitudeInRadians; // We are going to generate our sphere by iterating through its // spherical coordinates and generating 2 triangles for each quad on a // ring of the sphere. var numVertices = (subdivisionsAxis + 1) * (subdivisionsHeight + 1); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); // Generate the individual vertices in our vertex buffer. for (var y = 0; y <= subdivisionsHeight; y++) { for (var x = 0; x <= subdivisionsAxis; x++) { // Generate a vertex based on its spherical coordinates var u = x / subdivisionsAxis; var v = y / subdivisionsHeight; var theta = longRange * u; var phi = latRange * v; var sinTheta = Math.sin(theta); var cosTheta = Math.cos(theta); var sinPhi = Math.sin(phi); var cosPhi = Math.cos(phi); var ux = cosTheta * sinPhi; var uy = cosPhi; var uz = sinTheta * sinPhi; positions.push([radius * ux, radius * uy, radius * uz]); normals.push([ux, uy, uz]); texCoords.push([1 - u, v]); } } var numVertsAround = subdivisionsAxis + 1; var indices = new tdl.primitives.AttribBuffer( 3, subdivisionsAxis * subdivisionsHeight * 2, 'Uint16Array'); for (var x = 0; x < subdivisionsAxis; x++) { for (var y = 0; y < subdivisionsHeight; y++) { // Make triangle 1 of quad. indices.push([ (y + 0) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x]); // Make triangle 2 of quad. indices.push([ (y + 1) * numVertsAround + x, (y + 0) * numVertsAround + x + 1, (y + 1) * numVertsAround + x + 1]); } } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Creates cresent vertices. The created sphere has position, normal and uv * streams. * * @param {number} verticalRadius The vertical radius of the cresent. * @param {number} outerRadius The outer radius of the cresent. * @param {number} innerRadius The inner radius of the cresent. * @param {number} thickness The thickness of the cresent. * @param {number} subdivisionsDown number of steps around the sphere. * @param {number} subdivisionsThick number of vertically on the sphere. * @param {number} opt_startOffset Where to start arc Default 0. * @param {number} opt_endOffset Where to end arg Default 1. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createCresent = function( verticalRadius, outerRadius, innerRadius, thickness, subdivisionsDown, opt_startOffset, opt_endOffset) { if (subdivisionsDown <= 0) { throw Error('subdivisionDown must be > 0'); } var math = tdl.math; opt_startOffset = opt_startOffset || 0; opt_endOffset = opt_endOffset || 1; var subdivisionsThick = 2; var offsetRange = opt_endOffset - opt_startOffset; var numVertices = (subdivisionsDown + 1) * 2 * (2 + subdivisionsThick); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); function createArc(arcRadius, x, normalMult, normalAdd, uMult, uAdd) { for (var z = 0; z <= subdivisionsDown; z++) { var uBack = x / (subdivisionsThick - 1); var v = z / subdivisionsDown; var xBack = (uBack - 0.5) * 2; var angle = (opt_startOffset + (v * offsetRange)) * Math.PI; var s = Math.sin(angle); var c = Math.cos(angle); var radius = math.lerpScalar(verticalRadius, arcRadius, s); var px = xBack * thickness; var py = c * verticalRadius; var pz = s * radius; positions.push([px, py, pz]); // TODO(gman): fix! This is not correct. var n = math.addVector( math.mulVectorVector([0, s, c], normalMult), normalAdd); normals.push(n); texCoords.push([uBack * uMult + uAdd, v]); } } // Generate the individual vertices in our vertex buffer. for (var x = 0; x < subdivisionsThick; x++) { var uBack = (x / (subdivisionsThick - 1) - 0.5) * 2; createArc(outerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0); createArc(outerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 0); createArc(innerRadius, x, [1, 1, 1], [0, 0, 0], 1, 0); createArc(innerRadius, x, [0, 0, 0], [uBack, 0, 0], 0, 1); } // Do outer surface. var indices = new tdl.primitives.AttribBuffer( 3, (subdivisionsDown * 2) * (2 + subdivisionsThick), 'Uint16Array'); function createSurface(leftArcOffset, rightArcOffset) { for (var z = 0; z < subdivisionsDown; ++z) { // Make triangle 1 of quad. indices.push([ leftArcOffset + z + 0, leftArcOffset + z + 1, rightArcOffset + z + 0]); // Make triangle 2 of quad. indices.push([ leftArcOffset + z + 1, rightArcOffset + z + 1, rightArcOffset + z + 0]); } } var numVerticesDown = subdivisionsDown + 1; // front createSurface(numVerticesDown * 0, numVerticesDown * 4); // right createSurface(numVerticesDown * 5, numVerticesDown * 7); // back createSurface(numVerticesDown * 6, numVerticesDown * 2); // left createSurface(numVerticesDown * 3, numVerticesDown * 1); return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Creates XZ plane vertices. * The created plane has position, normal and uv streams. * * @param {number} width Width of the plane. * @param {number} depth Depth of the plane. * @param {number} subdivisionsWidth Number of steps across the plane. * @param {number} subdivisionsDepth Number of steps down the plane. * @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply * all the vertices. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createPlane = function( width, depth, subdivisionsWidth, subdivisionsDepth) { if (subdivisionsWidth <= 0 || subdivisionsDepth <= 0) { throw Error('subdivisionWidth and subdivisionDepth must be > 0'); } var math = tdl.math; var numVertices = (subdivisionsWidth + 1) * (subdivisionsDepth + 1); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); for (var z = 0; z <= subdivisionsDepth; z++) { for (var x = 0; x <= subdivisionsWidth; x++) { var u = x / subdivisionsWidth; var v = z / subdivisionsDepth; positions.push([ width * u - width * 0.5, 0, depth * v - depth * 0.5]); normals.push([0, 1, 0]); texCoords.push([u, v]); } } var numVertsAcross = subdivisionsWidth + 1; var indices = new tdl.primitives.AttribBuffer( 3, subdivisionsWidth * subdivisionsDepth * 2, 'Uint16Array'); for (var z = 0; z < subdivisionsDepth; z++) { for (var x = 0; x < subdivisionsWidth; x++) { // Make triangle 1 of quad. indices.push([ (z + 0) * numVertsAcross + x, (z + 1) * numVertsAcross + x, (z + 0) * numVertsAcross + x + 1]); // Make triangle 2 of quad. indices.push([ (z + 1) * numVertsAcross + x, (z + 1) * numVertsAcross + x + 1, (z + 0) * numVertsAcross + x + 1]); } } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Array of the indices of corners of each face of a cube. * @private * @type {!Array.<!Array.<number>>} */ tdl.primitives.CUBE_FACE_INDICES_ = [ [3, 7, 5, 1], // right [6, 2, 0, 4], // left [6, 7, 3, 2], // ?? [0, 1, 5, 4], // ?? [7, 6, 4, 5], // front [2, 3, 1, 0] // back ]; /** * Creates the vertices and indices for a cube. The * cube will be created around the origin. (-size / 2, size / 2) * * @param {number} size Width, height and depth of the cube. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createCube = function(size) { var k = size / 2; var cornerVertices = [ [-k, -k, -k], [+k, -k, -k], [-k, +k, -k], [+k, +k, -k], [-k, -k, +k], [+k, -k, +k], [-k, +k, +k], [+k, +k, +k] ]; var faceNormals = [ [+1, +0, +0], [-1, +0, +0], [+0, +1, +0], [+0, -1, +0], [+0, +0, +1], [+0, +0, -1] ]; var uvCoords = [ [1, 0], [0, 0], [0, 1], [1, 1] ]; var numVertices = 6 * 4; var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); var indices = new tdl.primitives.AttribBuffer(3, 6 * 2, 'Uint16Array'); for (var f = 0; f < 6; ++f) { var faceIndices = tdl.primitives.CUBE_FACE_INDICES_[f]; for (var v = 0; v < 4; ++v) { var position = cornerVertices[faceIndices[v]]; var normal = faceNormals[f]; var uv = uvCoords[v]; // Each face needs all four vertices because the normals and texture // coordinates are not all the same. positions.push(position); normals.push(normal); texCoords.push(uv); } // Two triangles make a square face. var offset = 4 * f; indices.push([offset + 0, offset + 1, offset + 2]); indices.push([offset + 0, offset + 2, offset + 3]); } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Creates the vertices and indices for a flared cube (extrude the edges). * The U texture coordinate will be a gradient 0-1 from inside out. Use * the vertex shader to distort using U as an angle for fun effects. * * @param {number} size Width, height and depth of the cube. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createFlaredCube = function(innerSize, outerSize, layerCount) { var numVertices = 2 * (layerCount + 1); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); var indices = new tdl.primitives.AttribBuffer( 3, layerCount * 2, 'Uint16Array'); // make a trapazoid plane. for (var z = 0; z <= layerCount; z++) { for (var x = 0; x <= 1; x++) { var u = x; var v = z / layerCount; var width = tdl.math.lerpScalar(innerSize, outerSize, v); positions.push([ width * u - width * 0.5, 0, tdl.math.lerpScalar(innerSize, outerSize, v) * 0.7 ]); normals.push([0, 1, 0]); texCoords.push([v, u]); } } var numVertsAcross = 2; for (var z = 0; z < layerCount; z++) { // Make triangle 1 of quad. indices.push([ (z + 0) * numVertsAcross, (z + 1) * numVertsAcross, (z + 0) * numVertsAcross + 1]); // Make triangle 2 of quad. indices.push([ (z + 1) * numVertsAcross, (z + 1) * numVertsAcross + 1, (z + 0) * numVertsAcross + 1]); } var arrays = { position: positions, normal: normals, texCoord: texCoords, indices: indices }; // rotate it 45 degrees tdl.primitives.reorient(arrays, tdl.math.matrix4.rotationX(Math.PI / 4)); // make 3 copies of plane each rotated 90 var planes = [arrays]; for (var ii = 0; ii < 3; ++ii) { var clone = tdl.primitives.clone(arrays); tdl.primitives.reorient(clone, tdl.math.matrix4.rotationZ(Math.PI * (ii + 1) / 2)); planes.push(clone); } // concat 4 planes to make a cone var arrays = tdl.primitives.concat(planes); // make 3 copies of cone each rotated 90 var cones = [arrays]; for (var ii = 0; ii < 3; ++ii) { var clone = tdl.primitives.clone(arrays); tdl.primitives.reorient(clone, tdl.math.matrix4.rotationY(Math.PI * (ii + 1) / 2)); cones.push(clone); } // concat 4 cones to make flared cube var arrays = tdl.primitives.concat(cones); return arrays; }; /** * Creates vertices for a truncated cone, which is like a cylinder * except that it has different top and bottom radii. A truncated cone * can also be used to create cylinders and regular cones. The * truncated cone will be created centered about the origin, with the * y axis as its vertical axis. The created cone has position, normal * and uv streams. * * @param {number} bottomRadius Bottom radius of truncated cone. * @param {number} topRadius Top radius of truncated cone. * @param {number} height Height of truncated cone. * @param {number} radialSubdivisions The number of subdivisions around the * truncated cone. * @param {number} verticalSubdivisions The number of subdivisions down the * truncated cone. * @param {boolean} opt_topCap Create top cap. Default = true. * @param {boolean} opt_bottomCap Create bottom cap. Default = * true. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createTruncatedCone = function( bottomRadius, topRadius, height, radialSubdivisions, verticalSubdivisions, opt_topCap, opt_bottomCap) { if (radialSubdivisions < 3) { throw Error('radialSubdivisions must be 3 or greater'); } if (verticalSubdivisions < 1) { throw Error('verticalSubdivisions must be 1 or greater'); } var topCap = (opt_topCap === undefined) ? true : opt_topCap; var bottomCap = (opt_bottomCap === undefined) ? true : opt_bottomCap; var extra = (topCap ? 2 : 0) + (bottomCap ? 2 : 0); var numVertices = (radialSubdivisions + 1) * (verticalSubdivisions + 1 + extra); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); var indices = new tdl.primitives.AttribBuffer( 3, radialSubdivisions * (verticalSubdivisions + extra) * 2, 'Uint16Array'); var vertsAroundEdge = radialSubdivisions + 1; // The slant of the cone is constant across its surface var slant = Math.atan2(bottomRadius - topRadius, height); var cosSlant = Math.cos(slant); var sinSlant = Math.sin(slant); var start = topCap ? -2 : 0; var end = verticalSubdivisions + (bottomCap ? 2 : 0); for (var yy = start; yy <= end; ++yy) { var v = yy / verticalSubdivisions var y = height * v; var ringRadius; if (yy < 0) { y = 0; v = 1; ringRadius = bottomRadius; } else if (yy > verticalSubdivisions) { y = height; v = 1; ringRadius = topRadius; } else { ringRadius = bottomRadius + (topRadius - bottomRadius) * (yy / verticalSubdivisions); } if (yy == -2 || yy == verticalSubdivisions + 2) { ringRadius = 0; v = 0; } y -= height / 2; for (var ii = 0; ii < vertsAroundEdge; ++ii) { var sin = Math.sin(ii * Math.PI * 2 / radialSubdivisions); var cos = Math.cos(ii * Math.PI * 2 / radialSubdivisions); positions.push([sin * ringRadius, y, cos * ringRadius]); normals.push([ (yy < 0 || yy > verticalSubdivisions) ? 0 : (sin * cosSlant), (yy < 0) ? -1 : (yy > verticalSubdivisions ? 1 : sinSlant), (yy < 0 || yy > verticalSubdivisions) ? 0 : (cos * cosSlant)]); texCoords.push([(ii / radialSubdivisions), 1 - v]); } } for (var yy = 0; yy < verticalSubdivisions + extra; ++yy) { for (var ii = 0; ii < radialSubdivisions; ++ii) { indices.push([vertsAroundEdge * (yy + 0) + 0 + ii, vertsAroundEdge * (yy + 0) + 1 + ii, vertsAroundEdge * (yy + 1) + 1 + ii]); indices.push([vertsAroundEdge * (yy + 0) + 0 + ii, vertsAroundEdge * (yy + 1) + 1 + ii, vertsAroundEdge * (yy + 1) + 0 + ii]); } } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Creates cylinder vertices. The cylinder will be created around the origin * along the y-axis. The created cylinder has position, normal and uv streams. * * @param {number} radius Radius of cylinder. * @param {number} height Height of cylinder. * @param {number} radialSubdivisions The number of subdivisions around the * cylinder. * @param {number} verticalSubdivisions The number of subdivisions down the * cylinder. * @param {boolean} opt_topCap Create top cap. Default = true. * @param {boolean} opt_bottomCap Create bottom cap. Default = * true. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created plane vertices. */ tdl.primitives.createCylinder = function( radius, height, radialSubdivisions, verticalSubdivisions, opt_topCap, opt_bottomCap) { return tdl.primitives.createTruncatedCone( radius, radius, height, radialSubdivisions, verticalSubdivisions, opt_topCap, opt_bottomCap); }; /** * Creates vertices for a torus, The created cone has position, normal * and texCoord streams. * * @param {number} radius radius of center of torus circle. * @param {number} thickness radius of torus ring. * @param {number} radialSubdivisions The number of subdivisions around the * torus. * @param {number} bodySubdivisions The number of subdivisions around the * body torus. * @param {boolean} opt_startAngle start angle in radians. Default = 0. * @param {boolean} opt_endAngle end angle in radians. Default = Math.PI * 2. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created torus vertices. */ tdl.primitives.createTorus = function( radius, thickness, radialSubdivisions, bodySubdivisions, opt_startAngle, opt_endAngle) { if (radialSubdivisions < 3) { throw Error('radialSubdivisions must be 3 or greater'); } if (bodySubdivisions < 3) { throw Error('verticalSubdivisions must be 3 or greater'); } var startAngle = opt_startAngle || 0; var endAngle = opt_endAngle || Math.PI * 2; var range = endAngle - startAngle; // TODO(gman): cap the ends if not a full circle. var numVertices = (radialSubdivisions) * (bodySubdivisions); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); var indices = new tdl.primitives.AttribBuffer( 3, (radialSubdivisions) * (bodySubdivisions) * 2, 'Uint16Array'); for (var slice = 0; slice < bodySubdivisions; ++slice) { var v = slice / bodySubdivisions; var sliceAngle = v * Math.PI * 2; var sliceSin = Math.sin(sliceAngle); var ringRadius = radius + sliceSin * thickness; var ny = Math.cos(sliceAngle); var y = ny * thickness; for (var ring = 0; ring < radialSubdivisions; ++ring) { var u = ring / radialSubdivisions; var ringAngle = startAngle + u * range; var xSin = Math.sin(ringAngle); var zCos = Math.cos(ringAngle); var x = xSin * ringRadius; var z = zCos * ringRadius; var nx = xSin * sliceSin; var nz = zCos * sliceSin; positions.push([x, y, z]); normals.push([nx, ny, nz]); texCoords.push([u, 1 - v]); } } for (var slice = 0; slice < bodySubdivisions; ++slice) { for (var ring = 0; ring < radialSubdivisions; ++ring) { var nextRingIndex = (1 + ring) % radialSubdivisions; var nextSliceIndex = (1 + slice) % bodySubdivisions; indices.push([radialSubdivisions * slice + ring, radialSubdivisions * nextSliceIndex + ring, radialSubdivisions * slice + nextRingIndex]); indices.push([radialSubdivisions * nextSliceIndex + ring, radialSubdivisions * nextSliceIndex + nextRingIndex, radialSubdivisions * slice + nextRingIndex]); } } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Creates a disc. The disc will be in the xz plane, centered at * the origin. When creating, at least 3 divisions, or pie * pieces, need to be specified, otherwise the triangles making * up the disc will be degenerate. You can also specify the * number of radial pieces (opt_stacks). A value of 1 for * opt_stacks will give you a simple disc of pie pieces. If you * want to create an annulus you can set opt_innerRadius to a * value > 0. Finally, stackPower allows you to have the widths * increase or decrease as you move away from the center. This * is particularly useful when using the disc as a ground plane * with a fixed camera such that you don't need the resolution * of small triangles near the perimeter. For example, a value * of 2 will produce stacks whose ouside radius increases with * the square of the stack index. A value of 1 will give uniform * stacks. * * @param {number} radius Radius of the ground plane. * @param {number} divisions Number of triangles in the ground plane * (at least 3). * @param {number} opt_stacks Number of radial divisions (default=1). * @param {number} opt_innerRadius. Default 0. * @param {number} opt_stackPower Power to raise stack size to for decreasing * width. * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The * created vertices. */ tdl.primitives.createDisc = function( radius, divisions, opt_stacks, opt_innerRadius, opt_stackPower) { if (divisions < 3) { throw Error('divisions must be at least 3'); } var stacks = opt_stacks ? opt_stacks : 1; var stackPower = opt_stackPower ? opt_stackPower : 1; var innerRadius = opt_innerRadius ? opt_innerRadius : 0; // Note: We don't share the center vertex because that would // mess up texture coordinates. var numVertices = (divisions) * (stacks + 1); var positions = new tdl.primitives.AttribBuffer(3, numVertices); var normals = new tdl.primitives.AttribBuffer(3, numVertices); var texCoords = new tdl.primitives.AttribBuffer(2, numVertices); var indices = new tdl.primitives.AttribBuffer( 3, stacks * divisions * 2, 'Uint16Array'); var firstIndex = 0; var radiusSpan = radius - innerRadius; // Build the disk one stack at a time. for (var stack = 0; stack <= stacks; ++stack) { var stackRadius = innerRadius + radiusSpan * Math.pow(stack / stacks, stackPower); for (var i = 0; i < divisions; ++i) { var theta = 2.0 * Math.PI * i / divisions; var x = stackRadius * Math.cos(theta); var z = stackRadius * Math.sin(theta); positions.push([x, 0, z]); normals.push([0, 1, 0]); texCoords.push([1 - (i / divisions), stack / stacks]); if (stack > 0) { // a, b, c and d are the indices of the vertices of a quad. unless // the current stack is the one closest to the center, in which case // the vertices a and b connect to the center vertex. var a = firstIndex + (i + 1) % divisions; var b = firstIndex + i; var c = firstIndex + i - divisions; var d = firstIndex + (i + 1) % divisions - divisions; // Make a quad of the vertices a, b, c, d. indices.push([a, b, c]); indices.push([a, c, d]); } } firstIndex += divisions; } return { position: positions, normal: normals, texCoord: texCoords, indices: indices}; }; /** * Interleaves vertex information into one large buffer * @param {Array of <string, tdl.primitives.AttribBuffer>} * @param {Object.<string, tdl.primitives.AttribBuffer>} */ tdl.primitives.interleaveVertexData = function(vertexDataArray) { var stride = 0; for (var s = 0; s < vertexDataArray.length; s++) { stride += vertexDataArray[s].numComponents; } // This assumes the first element is always positions. var numVertices = vertexDataArray[0].numElements; var vertexData = new Float32Array(stride * numVertices); var count = 0; for (var v = 0; v< numVertices; v++) { for (var i = 0; i < vertexDataArray.length; i++) { var element = vertexDataArray[i].getElement(v); for (var d = 0; d < vertexDataArray[i].numComponents; d++) { vertexData[count++] = element[d]; } } } return vertexData; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains misc functions to deal with * fullscreen. */ tdl.provide('tdl.fullscreen'); /** * A module for misc. * @namespace */ tdl.fullscreen = tdl.fullscreen || {}; tdl.fullscreen.requestFullScreen = function(element) { if (element.webkitRequestFullScreen) { element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } }; tdl.fullscreen.cancelFullScreen = function(element) { if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } }; tdl.fullscreen.onFullScreenChange = function(element, callback) { element.addEventListener('fullscreenchange', function(event) { callback(document.fullscreenEnabled); }); element.addEventListener('webkitfullscreenchange', function(event) { var fullscreenEnabled = document.webkitFullscreenEnabled; if (fullscreenEnabled === undefined) { fullscreenEnabled = document.webkitIsFullScreen; } callback(fullscreenEnabled); }); element.addEventListener('mozfullscreenchange', function(event) { var fullscreenEnabled = document.mozFullscreenEnabled; if (fullscreenEnabled === undefined) { fullscreenEnabled = document.mozFullScreen; } callback(fullscreenEnabled); }); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to manage * framebuffers. */ tdl.provide('tdl.framebuffers'); tdl.require('tdl.textures'); /** * A module for textures. * @namespace */ tdl.framebuffers = tdl.framebuffers || {}; tdl.framebuffers.createFramebuffer = function(width, height, opt_depth) { return new tdl.framebuffers.Framebuffer(width, height, opt_depth); }; tdl.framebuffers.createCubeFramebuffer = function(size, opt_depth) { return new tdl.framebuffers.CubeFramebuffer(size, opt_depth); }; tdl.framebuffers.BackBuffer = function(canvas) { this.depth = true; this.buffer = null; }; tdl.framebuffers.BackBuffer.prototype.bind = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, this.width, this.height); }; if (Object.prototype.__defineSetter__) { tdl.framebuffers.BackBuffer.prototype.__defineGetter__( 'width', function () { return gl.drawingBufferWidth || gl.canvas.width; } ); tdl.framebuffers.BackBuffer.prototype.__defineGetter__( 'height', function () { return gl.drawingBufferHeight || gl.canvas.height; } ); } // Use this where you need to pass in a framebuffer, but you really // mean the backbuffer, so that binding it works as expected. tdl.framebuffers.getBackBuffer = function(canvas) { return new tdl.framebuffers.BackBuffer(canvas) }; tdl.framebuffers.Framebuffer = function(width, height, opt_depth) { this.width = width; this.height = height; this.depth = opt_depth; this.recoverFromLostContext(); }; tdl.framebuffers.Framebuffer.prototype.bind = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); gl.viewport(0, 0, this.width, this.height); }; tdl.framebuffers.Framebuffer.unbind = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport( 0, 0, gl.drawingBufferWidth || gl.canvas.width, gl.drawingBufferHeight || gl.canvas.height); }; tdl.framebuffers.Framebuffer.prototype.unbind = function() { tdl.framebuffers.Framebuffer.unbind(); }; tdl.framebuffers.Framebuffer.prototype.recoverFromLostContext = function() { var tex = new tdl.textures.SolidTexture([0,0,0,0]); this.initializeTexture(tex); var fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex.texture, 0); if (this.depth) { if (gl.tdl.depthTexture) { var dt = new tdl.textures.DepthTexture(this.width, this.height); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, dt.texture, 0); this.depthTexture = dt; } else { var db = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, db); gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.width, this.height); gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, db); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.depthRenderbuffer = db; } } var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status != gl.FRAMEBUFFER_COMPLETE && !gl.isContextLost()) { throw("gl.checkFramebufferStatus() returned " + tdl.webgl.glEnumToString(status)); } this.framebuffer = fb; this.texture = tex; gl.bindFramebuffer(gl.FRAMEBUFFER, null); }; tdl.framebuffers.Framebuffer.prototype.initializeTexture = function(tex) { gl.bindTexture(gl.TEXTURE_2D, tex.texture); tex.setParameter(gl.TEXTURE_MIN_FILTER, gl.LINEAR); tex.setParameter(gl.TEXTURE_MAG_FILTER, gl.LINEAR); tex.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); tex.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, // level gl.RGBA, // internalFormat this.width, // width this.height, // height 0, // border gl.RGBA, // format gl.UNSIGNED_BYTE, // type null); // data }; tdl.framebuffers.CubeFramebuffer = function(size, opt_depth) { this.size = size; this.depth = opt_depth; this.recoverFromLostContext(); }; tdl.framebuffers.CubeFramebuffer.prototype.bind = function(face) { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[face]); gl.viewport(0, 0, this.size, this.size); }; tdl.framebuffers.CubeFramebuffer.unbind = function() { gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport( 0, 0, gl.drawingBufferWidth || gl.canvas.width, gl.drawingBufferHeight || gl.canvas.height); }; tdl.framebuffers.CubeFramebuffer.prototype.unbind = function() { tdl.framebuffers.CubeFramebuffer.unbind(); }; tdl.framebuffers.CubeFramebuffer.prototype.recoverFromLostContext = function() { var tex = new tdl.textures.CubeMap(this.size); gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex.texture); tex.setParameter(gl.TEXTURE_MIN_FILTER, gl.LINEAR); tex.setParameter(gl.TEXTURE_MAG_FILTER, gl.LINEAR); tex.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); tex.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); for (var ff = 0; ff < 6; ++ff) { gl.texImage2D(tdl.textures.CubeMap.faceTargets[ff], 0, // level gl.RGBA, // internalFormat this.size, // width this.size, // height 0, // border gl.RGBA, // format gl.UNSIGNED_BYTE, // type null); // data } if (this.depth) { var db = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, db); gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.size, this.size); } this.framebuffers = []; for (var ff = 0; ff < 6; ++ff) { var fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, tdl.textures.CubeMap.faceTargets[ff], tex.texture, 0); if (this.depth) { gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, db); } var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status != gl.FRAMEBUFFER_COMPLETE) { throw("gl.checkFramebufferStatus() returned " + WebGLDebugUtils.glEnumToString(status)); } this.framebuffers.push(fb); } gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.texture = tex; }; tdl.framebuffers.Float32Framebuffer = function(width, height, opt_depth) { if (!gl.getExtension("OES_texture_float")) { throw("Requires OES_texture_float extension"); } tdl.framebuffers.Framebuffer.call(this, width, height, opt_depth); }; tdl.base.inherit(tdl.framebuffers.Float32Framebuffer, tdl.framebuffers.Framebuffer); tdl.framebuffers.Float32Framebuffer.prototype.initializeTexture = function(tex) { gl.bindTexture(gl.TEXTURE_2D, tex.texture); tex.setParameter(gl.TEXTURE_MIN_FILTER, gl.NEAREST); tex.setParameter(gl.TEXTURE_MAG_FILTER, gl.NEAREST); tex.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); tex.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, // level gl.RGBA, // internalFormat this.width, // width this.height, // height 0, // border gl.RGBA, // format gl.FLOAT, // type null); // data };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains a class which assists with the * loading of GLSL shaders. */ tdl.provide('tdl.shader'); /** * A module for shaders. * @namespace */ tdl.shader = tdl.shader || {}; /** * Loads a shader from vertex and fragment programs specified in * "script" nodes in the HTML page. This provides a convenient * mechanism for writing GLSL snippets without the burden of * additional syntax like per-line quotation marks. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext * into which the shader will be loaded. * @param {!string} vertexScriptName The name of the HTML Script node * containing the vertex program. * @param {!string} fragmentScriptName The name of the HTML Script node * containing the fragment program. */ tdl.shader.loadFromScriptNodes = function(gl, vertexScriptName, fragmentScriptName) { var vertexScript = document.getElementById(vertexScriptName); var fragmentScript = document.getElementById(fragmentScriptName); if (!vertexScript || !fragmentScript) return null; return new tdl.shader.Shader(gl, vertexScript.text, fragmentScript.text); } /** * Helper which convers GLSL names to JavaScript names. * @private */ tdl.shader.glslNameToJs_ = function(name) { return name.replace(/_(.)/g, function(_, p1) { return p1.toUpperCase(); }); } /** * Creates a new Shader object, loading and linking the given vertex * and fragment shaders into a program. * @param {!WebGLRenderingContext} gl The WebGLRenderingContext * into which the shader will be loaded. * @param {!string} vertex The vertex shader. * @param {!string} fragment The fragment shader. */ tdl.shader.Shader = function(gl, vertex, fragment) { this.program = gl.createProgram(); this.gl = gl; var vs = this.loadShader(this.gl.VERTEX_SHADER, vertex); if (!vs) { tdl.log("couldn't load shader") } this.gl.attachShader(this.program, vs); this.gl.deleteShader(vs); var fs = this.loadShader(this.gl.FRAGMENT_SHADER, fragment); if (!fs) { tdl.log("couldn't load shader") } this.gl.attachShader(this.program, fs); this.gl.deleteShader(fs); this.gl.linkProgram(this.program); this.gl.useProgram(this.program); // Check the link status var linked = this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS); if (!linked && !this.gl.isContextLost()) { var infoLog = this.gl.getProgramInfoLog(this.program); tdl.error("Error linking program:\n" + infoLog); this.gl.deleteProgram(this.program); this.program = null; return; } // find uniforms and attributes var re = /(uniform|attribute)\s+\S+\s+(\S+)\s*;/g; var match = null; while ((match = re.exec(vertex + '\n' + fragment)) != null) { var glslName = match[2]; var jsName = tdl.shader.glslNameToJs_(glslName); var loc = -1; if (match[1] == "uniform") { this[jsName + "Loc"] = this.getUniform(glslName); } else if (match[1] == "attribute") { this[jsName + "Loc"] = this.getAttribute(glslName); } if (loc >= 0) { this[jsName + "Loc"] = loc; } } } /** * Binds the shader's program. */ tdl.shader.Shader.prototype.bind = function() { this.gl.useProgram(this.program); } /** * Helper for loading a shader. * @private */ tdl.shader.Shader.prototype.loadShader = function(type, shaderSrc) { var shader = this.gl.createShader(type); if (shader == null) { return null; } // Load the shader source this.gl.shaderSource(shader, shaderSrc); // Compile the shader this.gl.compileShader(shader); // Check the compile status if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { var infoLog = this.gl.getShaderInfoLog(shader); tdl.error("Error compiling shader:\n" + infoLog); this.gl.deleteShader(shader); return null; } return shader; } /** * Helper for looking up an attribute's location. * @private */ tdl.shader.Shader.prototype.getAttribute = function(name) { return this.gl.getAttribLocation(this.program, name); }; /** * Helper for looking up an attribute's location. * @private */ tdl.shader.Shader.prototype.getUniform = function(name) { return this.gl.getUniformLocation(this.program, name); }
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to deal with WebGL * buffers. */ tdl.provide('tdl.buffers'); /** * A module for buffers. * @namespace */ tdl.buffers = tdl.buffers || {}; tdl.buffers.Buffer = function(array, opt_target) { var target = opt_target || gl.ARRAY_BUFFER; var buf = gl.createBuffer(); this.target = target; this.buf = buf; this.set(array); this.numComponents_ = array.numComponents; this.numElements_ = array.numElements; this.totalComponents_ = this.numComponents_ * this.numElements_; if (array.buffer instanceof Float32Array) { this.type_ = gl.FLOAT; this.normalize_ = false; } else if (array.buffer instanceof Uint8Array) { this.type_ = gl.UNSIGNED_BYTE; this.normalize_ = true; } else if (array.buffer instanceof Int8Array) { this.type_ = gl.BYTE; this.normalize_ = true; } else if (array.buffer instanceof Uint16Array) { this.type_ = gl.UNSIGNED_SHORT; this.normalize_ = true; } else if (array.buffer instanceof Int16Array) { this.type_ = gl.SHORT; this.normalize_ = true; } else { throw("unhandled type:" + (typeof array.buffer)); } }; tdl.buffers.Buffer.prototype.set = function(array, opt_usage) { gl.bindBuffer(this.target, this.buf); gl.bufferData(this.target, array.buffer, opt_usage || gl.STATIC_DRAW); } tdl.buffers.Buffer.prototype.setRange = function(array, offset) { gl.bindBuffer(this.target, this.buf); gl.bufferSubData(this.target, offset, array); } tdl.buffers.Buffer.prototype.type = function() { return this.type_; }; tdl.buffers.Buffer.prototype.numComponents = function() { return this.numComponents_; }; tdl.buffers.Buffer.prototype.numElements = function() { return this.numElements_; }; tdl.buffers.Buffer.prototype.totalComponents = function() { return this.totalComponents_; }; tdl.buffers.Buffer.prototype.buffer = function() { return this.buf; }; tdl.buffers.Buffer.prototype.stride = function() { return 0; }; tdl.buffers.Buffer.prototype.normalize = function() { return this.normalize_; } tdl.buffers.Buffer.prototype.offset = function() { return 0; };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to deal with logging. */ tdl.provide('tdl.log'); tdl.require('tdl.string'); /** * A module for log. * @namespace */ tdl.log = tdl.log || {}; /** * Wrapped logging function. * @param {*} msg The message to log. */ tdl.log = function() { var str = tdl.string.argsToString(arguments); if (window.console && window.console.log) { window.console.log(str); } else if (window.dump) { window.dump(str + "\n"); } }; /** * Wrapped logging function. * @param {*} msg The message to log. */ tdl.error = function() { var str = tdl.string.argsToString(arguments); if (window.console) { if (window.console.error) { window.console.error(str); } else if (window.console.log) { window.console.log(str); } else if (window.dump) { window.dump(str + "\n"); } } }; /** * Dumps an object to the console. * * @param {!Object} obj Object to dump. * @param {string} opt_prefix string to prefix each value with. */ tdl.dumpObj = function(obj, opt_prefix) { tdl.log(tdl.string.objToString(obj, opt_prefix)); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains objects to manage textures. */ tdl.provide('tdl.textures'); tdl.require('tdl.webgl'); /** * A module for textures. * @namespace */ tdl.textures = tdl.textures || {}; /** * Loads a texture * @param {{!tdl.math.Vector4|string|!Array.<string>|!img|!canvas}} Passing a * color makes a solid 1pixel 2d texture, passing a URL * makes a 2d texture with that url, passing an array of * urls makes a cubemap, passing an img or canvas makes a 2d texture with * that image. * @param {boolean} opt_flipY Flip the texture in Y? * @param {function} opt_callback Function to execute when texture is loaded. */ tdl.textures.loadTexture = function(arg, opt_flipY, opt_callback) { if (opt_callback) { alert('callback!'); } var id; if (typeof arg == 'string') { td = arg; } else if (arg.length == 4 && typeof arg[0] == 'number') { id = arg.toString(); } else if ((arg.length == 1 || arg.length == 6) && typeof arg[0] == 'string') { id = arg.toString(); } else if (arg.tagName == 'CANVAS') { id = undefined; } else if (arg.tagName == 'IMG') { id = arg.src; } else if (arg.width) { id = undefined; } else { throw "bad args"; } var texture; tdl.textures.init_(gl); if (id !== undefined) { texture = gl.tdl.textures.db[id]; } if (texture) { return texture; } if (typeof arg == 'string') { texture = new tdl.textures.Texture2D(arg, opt_flipY, opt_callback); } else if (arg.length == 4 && typeof arg[0] == 'number') { texture = new tdl.textures.SolidTexture(arg); } else if ((arg.length == 1 || arg.length == 6) && typeof arg[0] == 'string') { texture = new tdl.textures.CubeMap(arg); } else if (arg.tagName == 'CANVAS' || arg.tagName == 'IMG') { texture = new tdl.textures.Texture2D(arg, opt_flipY); } else if (arg.width) { texture = new tdl.textures.ColorTexture2D(arg); } else { throw "bad args"; } gl.tdl.textures.db[arg.toString()] = texture; return texture; }; tdl.textures.addLoadingImage_ = function(img) { tdl.textures.init_(gl); gl.tdl.textures.loadingImages.push(img); }; tdl.textures.removeLoadingImage_ = function(img) { gl.tdl.textures.loadingImages.splice(gl.tdl.textures.loadingImages.indexOf(img), 1); }; tdl.textures.init_ = function(gl) { if (!gl.tdl.textures) { gl.tdl.textures = { }; gl.tdl.textures.loadingImages = []; tdl.webgl.registerContextLostHandler( gl.canvas, tdl.textures.handleContextLost_, true); } if (!gl.tdl.textures.maxTextureSize) { gl.tdl.textures.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); gl.tdl.textures.maxCubeMapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE); } if (!gl.tdl.textures.db) { gl.tdl.textures.db = { }; } }; tdl.textures.handleContextLost_ = function() { if (gl.tdl && gl.tdl.textures) { delete gl.tdl.textures.db; var imgs = gl.tdl.textures.loadingImages; for (var ii = 0; ii < imgs.length; ++ii) { imgs[ii].onload = undefined; } gl.tdl.textures.loadingImages = []; } }; tdl.textures.Texture = function(target) { this.target = target; this.texture = gl.createTexture(); this.params = { }; }; tdl.textures.Texture.prototype.setParameter = function(pname, value) { this.params[pname] = value; gl.bindTexture(this.target, this.texture); gl.texParameteri(this.target, pname, value); }; tdl.textures.Texture.prototype.recoverFromLostContext = function() { this.texture = gl.createTexture(); gl.bindTexture(this.target, this.texture); for (var pname in this.params) { gl.texParameteri(this.target, pname, this.params[pname]); } }; /** * A solid color texture. * @constructor * @param {!tdl.math.vector4} color. */ tdl.textures.SolidTexture = function(color) { tdl.textures.Texture.call(this, gl.TEXTURE_2D); this.color = color.slice(0, 4); this.uploadTexture(); }; tdl.base.inherit(tdl.textures.SolidTexture, tdl.textures.Texture); tdl.textures.SolidTexture.prototype.uploadTexture = function() { gl.bindTexture(gl.TEXTURE_2D, this.texture); var pixel = new Uint8Array(this.color); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel); }; tdl.textures.SolidTexture.prototype.recoverFromLostContext = function() { tdl.textures.Texture.recoverFromLostContext.call(this); this.uploadTexture(); }; tdl.textures.SolidTexture.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, this.texture); }; /** * A depth texture. * @constructor * @param {number} width * @param {number} height */ tdl.textures.DepthTexture = function(width, height) { if (!gl.tdl.depthTexture) { throw("depth textures not supported"); } tdl.textures.Texture.call(this, gl.TEXTURE_2D); this.width = width; this.height = height; this.uploadTexture(); }; tdl.base.inherit(tdl.textures.DepthTexture, tdl.textures.Texture); tdl.textures.DepthTexture.prototype.uploadTexture = function() { gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texImage2D( gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, this.width, this.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); this.setParameter(gl.TEXTURE_MIN_FILTER, gl.NEAREST); this.setParameter(gl.TEXTURE_MAG_FILTER, gl.NEAREST); this.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); this.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); }; tdl.textures.DepthTexture.prototype.recoverFromLostContext = function() { tdl.textures.Texture.recoverFromLostContext.call(this); this.uploadTexture(); }; tdl.textures.DepthTexture.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, this.texture); }; /** * A color from an array of values texture. * @constructor * @param {!{width: number, height: number: pixels: * !Array.<number>} data. */ tdl.textures.ColorTexture = function(data, opt_format, opt_type) { tdl.textures.Texture.call(this, gl.TEXTURE_2D); this.format = opt_format || gl.RGBA; this.type = opt_type || gl.UNSIGNED_BYTE; if (data.pixels instanceof Array) { data.pixels = new Uint8Array(data.pixels); } this.data = data; this.uploadTexture(); }; tdl.base.inherit(tdl.textures.ColorTexture, tdl.textures.Texture); tdl.textures.ColorTexture.prototype.uploadTexture = function() { gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D( gl.TEXTURE_2D, 0, this.format, this.data.width, this.data.height, 0, this.format, this.type, this.data.pixels); }; tdl.textures.ColorTexture.prototype.recoverFromLostContext = function() { tdl.textures.Texture.recoverFromLostContext.call(this); this.uploadTexture(); }; tdl.textures.ColorTexture.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, this.texture); }; /** * @constructor * @param {{string|!Element}} url URL of image to load into texture. * @param {function} opt_callback Function to execute when texture is loaded. */ tdl.textures.Texture2D = function(url, opt_flipY, opt_callback) { if (opt_callback) { alert('callback'); } tdl.textures.Texture.call(this, gl.TEXTURE_2D); this.flipY = opt_flipY || false; var that = this; var img; // Handle dataURLs? if (typeof url !== 'string') { img = url; this.loaded = true; if (opt_callback) { opt_callback(); } } else { img = document.createElement('img'); tdl.textures.addLoadingImage_(img); img.onload = function() { tdl.textures.removeLoadingImage_(img); //tdl.log("loaded image: ", url); that.updateTexture(); if (opt_callback) { opt_callback(); } }; img.onerror = function() { tdl.log("could not load image: ", url); }; } this.img = img; this.uploadTexture(); if (!this.loaded) { img.src = url; } }; tdl.base.inherit(tdl.textures.Texture2D, tdl.textures.Texture); tdl.textures.isPowerOf2 = function(value) { return (value & (value - 1)) == 0; }; tdl.textures.Texture2D.prototype.uploadTexture = function() { gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); if (this.loaded) { gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, this.flipY); this.setTexture(this.img); } else { var pixel = new Uint8Array([255, 255, 255, 255]); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel); } }; tdl.textures.Texture2D.prototype.setTexture = function(element) { // TODO(gman): use texSubImage2D if the size is the same. gl.bindTexture(gl.TEXTURE_2D, this.texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, element); if (tdl.textures.isPowerOf2(element.width) && tdl.textures.isPowerOf2(element.height)) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); gl.generateMipmap(gl.TEXTURE_2D); } else { this.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); this.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); this.setParameter(gl.TEXTURE_MIN_FILTER, gl.LINEAR); } }; tdl.textures.Texture2D.prototype.updateTexture = function() { this.loaded = true; this.uploadTexture(); }; tdl.textures.Texture2D.prototype.recoverFromLostContext = function() { tdl.textures.Texture.recoverFromLostContext.call(this); this.uploadTexture(); }; tdl.textures.Texture2D.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, this.texture); }; /** * Create a texture to be managed externally. * @constructor * @param {string} type GL enum for texture type. */ tdl.textures.ExternalTexture = function(type) { tdl.textures.Texture.call(this, type); this.type = type; }; tdl.base.inherit(tdl.textures.ExternalTexture, tdl.textures.Texture); tdl.textures.ExternalTexture.prototype.recoverFromLostContext = function() { }; tdl.textures.ExternalTexture.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(this.type, this.texture); } /** * Create a 2D texture to be managed externally. * @constructor */ tdl.textures.ExternalTexture2D = function() { tdl.textures.ExternalTexture.call(this, gl.TEXTURE_2D); }; tdl.base.inherit(tdl.textures.ExternalTexture2D, tdl.textures.ExternalTexture); /** * Create and load a CubeMap. * @constructor * @param {!Array.<string>} urls The urls of the 6 faces, which * must be in the order positive_x, negative_x positive_y, * negative_y, positive_z, negative_z OR an array with a single url * where the images are arranged as a cross in this order. * * +--+--+--+--+ * | |PY| | | * +--+--+--+--+ * |NX|PZ|PX|NZ| * +--+--+--+--+ * | |NY| | | * +--+--+--+--+ */ tdl.textures.CubeMap = function(urls) { tdl.textures.init_(gl); tdl.textures.Texture.call(this, gl.TEXTURE_CUBE_MAP); // TODO(gman): make this global. if (!tdl.textures.CubeMap.faceTargets) { tdl.textures.CubeMap.faceTargets = [ gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]; tdl.textures.CubeMap.offsets = [ [2, 1], [0, 1], [1, 0], [1, 2], [1, 1], [3, 1]]; } var faceTargets = tdl.textures.CubeMap.faceTargets; gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.texture); this.setParameter(gl.TEXTURE_MAG_FILTER, gl.LINEAR); this.setParameter(gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); this.setParameter(gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); this.faces = []; if (!urls.length) { this.numUrls = 0; this.size = urls; } else { this.numUrls = urls.length; var that = this; for (var ff = 0; ff < urls.length; ++ff) { var face = { }; this.faces[ff] = face; var img = document.createElement('img'); tdl.textures.addLoadingImage_(img); face.img = img; img.onload = function(faceIndex) { return function() { tdl.textures.removeLoadingImage_(img); tdl.log("loaded image: ", urls[faceIndex]); that.updateTexture(faceIndex); } } (ff); img.onerror = function(url) { return function() { tdl.log("could not load image: ", url); } }(urls[ff]); img.src = urls[ff]; } } this.uploadTextures(); }; tdl.base.inherit(tdl.textures.CubeMap, tdl.textures.Texture); /** * Check if all faces are loaded. * @return {boolean} true if all faces are loaded. */ tdl.textures.CubeMap.prototype.loaded = function() { for (var ff = 0; ff < this.faces.length; ++ff) { if (!this.faces[ff].loaded) { return false; } } return true; }; tdl.textures.clampToMaxSize = function(element, maxSize) { if (element.width <= maxSize && element.height <= maxSize) { return element; } var maxDimension = Math.max(element.width, element.height); var newWidth = Math.floor(element.width * maxSize / maxDimension); var newHeight = Math.floor(element.height * maxSize / maxDimension); var canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; var ctx = canvas.getContext("2d"); ctx.drawImage( element, 0, 0, element.width, element.height, 0, 0, newWidth, newHeight); return canvas; }; /** * Uploads the images to the texture. */ tdl.textures.CubeMap.prototype.uploadTextures = function() { var allFacesLoaded = this.loaded(); var faceTargets = tdl.textures.CubeMap.faceTargets; for (var faceIndex = 0; faceIndex < 6; ++faceIndex) { var uploaded = false; var target = faceTargets[faceIndex]; if (this.faces.length) { var face = this.faces[Math.min(this.faces.length - 1, faceIndex)]; gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.texture); if (allFacesLoaded) { gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); if (this.faces.length == 6) { gl.texImage2D( target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tdl.textures.clampToMaxSize( face.img, gl.tdl.textures.maxCubeMapSize)); } else { var canvas = document.createElement('canvas'); var width = face.img.width / 4; var height = face.img.height / 3; canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); var sx = tdl.textures.CubeMap.offsets[faceIndex][0] * width; var sy = tdl.textures.CubeMap.offsets[faceIndex][1] * height; ctx.drawImage(face.img, sx, sy, width, height, 0, 0, width, height); gl.texImage2D( target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tdl.textures.clampToMaxSize( canvas, gl.tdl.textures.maxCubeMapSize)); } uploaded = true; } } if (!uploaded) { var pixel = new Uint8Array([100,100,255,255]); gl.texImage2D(target, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixel); } } var genMips = false; if (this.faces.length) { var faceImg = this.faces[0].img; if (this.faces.length == 6) { genMips = tdl.textures.isPowerOf2(faceImg.width) && tdl.textures.isPowerOf2(faceImg.height); } else { genMips = tdl.textures.isPowerOf2(faceImg.width / 4) && tdl.textures.isPowerOf2(faceImg.height / 3); } } if (genMips) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); this.setParameter(gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); } else { this.setParameter(gl.TEXTURE_MIN_FILTER, gl.LINEAR); } }; /** * Recover from lost context. */ tdl.textures.CubeMap.prototype.recoverFromLostContext = function() { tdl.textures.Texture.recoverFromLostContext.call(this); this.uploadTextures(); }; /** * Update a just downloaded loaded texture. * @param {number} faceIndex index of face. */ tdl.textures.CubeMap.prototype.updateTexture = function(faceIndex) { // mark the face as loaded var face = this.faces[faceIndex]; face.loaded = true; // If all 6 faces are loaded then upload to GPU. var loaded = this.loaded(); if (loaded) { this.uploadTextures(); } }; /** * Binds the CubeMap to a texture unit * @param {number} unit The texture unit. */ tdl.textures.CubeMap.prototype.bindToUnit = function(unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.texture); };
JavaScript
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview This file contains various functions for taking a screenshot */ tdl.provide('tdl.screenshot'); tdl.require('tdl.io'); tdl.require('tdl.log'); /** * takes a screenshot of a canvas. Sends it to the server to be saved. */ tdl.screenshot.takeScreenshot = function(canvas) { tdl.io.sendJSON( this.url, {cmd: 'screenshot', dataURL: canvas.toDataURL()}, function() {}); };
JavaScript
/* Copyright (C) 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var a=null; PR.registerLangHandler(PR.createSimpleLexer([["opn",/^[([{]+/,a,"([{"],["clo",/^[)\]}]+/,a,")]}"],["com",/^;[^\n\r]*/,a,";"],["pln",/^[\t\n\r \xa0]+/,a,"\t\n\r \xa0"],["str",/^"(?:[^"\\]|\\[\S\s])*(?:"|$)/,a,'"']],[["kwd",/^(?:def|if|do|let|quote|var|fn|loop|recur|throw|try|monitor-enter|monitor-exit|defmacro|defn|defn-|macroexpand|macroexpand-1|for|doseq|dosync|dotimes|and|or|when|not|assert|doto|proxy|defstruct|first|rest|cons|defprotocol|deftype|defrecord|reify|defmulti|defmethod|meta|with-meta|ns|in-ns|create-ns|import|intern|refer|alias|namespace|resolve|ref|deref|refset|new|set!|memfn|to-array|into-array|aset|gen-class|reduce|map|filter|find|nil?|empty?|hash-map|hash-set|vec|vector|seq|flatten|reverse|assoc|dissoc|list|list?|disj|get|union|difference|intersection|extend|extend-type|extend-protocol|prn)\b/,a], ["typ",/^:[\dA-Za-z-]+/]]),["clj"]);
JavaScript
(function(window) { var ORIGIN_ = location.protocol + '//' + location.host; function SlideController() { this.popup = null; this.isPopup = window.opener; if (this.setupDone()) { window.addEventListener('message', this.onMessage_.bind(this), false); // Close popups if we reload the main window. window.addEventListener('beforeunload', function(e) { if (this.popup) { this.popup.close(); } }.bind(this), false); } } SlideController.PRESENTER_MODE_PARAM = 'presentme'; SlideController.prototype.setupDone = function() { var params = location.search.substring(1).split('&').map(function(el) { return el.split('='); }); var presentMe = null; for (var i = 0, param; param = params[i]; ++i) { if (param[0].toLowerCase() == SlideController.PRESENTER_MODE_PARAM) { presentMe = param[1] == 'true'; break; } } if (presentMe !== null) { localStorage.ENABLE_PRESENTOR_MODE = presentMe; // TODO: use window.history.pushState to update URL instead of the redirect. if (window.history.replaceState) { window.history.replaceState({}, '', location.pathname); } else { location.replace(location.pathname); return false; } } var enablePresenterMode = localStorage.getItem('ENABLE_PRESENTOR_MODE'); if (enablePresenterMode && JSON.parse(enablePresenterMode)) { // Only open popup from main deck. Don't want recursive popup opening! if (!this.isPopup) { var opts = 'menubar=no,location=yes,resizable=yes,scrollbars=no,status=no'; this.popup = window.open(location.href, 'mywindow', opts); // Loading in the popup? Trigger the hotkey for turning presenter mode on. this.popup.addEventListener('load', function(e) { var evt = this.popup.document.createEvent('Event'); evt.initEvent('keydown', true, true); evt.keyCode = 'P'.charCodeAt(0); this.popup.document.dispatchEvent(evt); // this.popup.document.body.classList.add('with-notes'); // document.body.classList.add('popup'); }.bind(this), false); } } return true; } SlideController.prototype.onMessage_ = function(e) { var data = e.data; // Restrict messages to being from this origin. Allow local developmet // from file:// though. // TODO: It would be dope if FF implemented location.origin! if (e.origin != ORIGIN_ && ORIGIN_.indexOf('file://') != 0) { alert('Someone tried to postMessage from an unknown origin'); return; } // if (e.source.location.hostname != 'localhost') { // alert('Someone tried to postMessage from an unknown origin'); // return; // } if ('keyCode' in data) { var evt = document.createEvent('Event'); evt.initEvent('keydown', true, true); evt.keyCode = data.keyCode; document.dispatchEvent(evt); } }; SlideController.prototype.sendMsg = function(msg) { // // Send message to popup window. // if (this.popup) { // this.popup.postMessage(msg, ORIGIN_); // } // Send message to main window. if (this.isPopup) { // TODO: It would be dope if FF implemented location.origin. window.opener.postMessage(msg, '*'); } }; window.SlideController = SlideController; })(window);
JavaScript
/* * Hammer.JS * version 0.4 * author: Eight Media * https://github.com/EightMedia/hammer.js */ function Hammer(element, options, undefined) { var self = this; var defaults = { // prevent the default event or not... might be buggy when false prevent_default : false, css_hacks : true, drag : true, drag_vertical : true, drag_horizontal : true, // minimum distance before the drag event starts drag_min_distance : 20, // pixels // pinch zoom and rotation transform : true, scale_treshold : 0.1, rotation_treshold : 15, // degrees tap : true, tap_double : true, tap_max_interval : 300, tap_double_distance: 20, hold : true, hold_timeout : 500 }; options = mergeObject(defaults, options); // some css hacks (function() { if(!options.css_hacks) { return false; } var vendors = ['webkit','moz','ms','o','']; var css_props = { "userSelect": "none", "touchCallout": "none", "userDrag": "none", "tapHighlightColor": "rgba(0,0,0,0)" }; var prop = ''; for(var i = 0; i < vendors.length; i++) { for(var p in css_props) { prop = p; if(vendors[i]) { prop = vendors[i] + prop.substring(0, 1).toUpperCase() + prop.substring(1); } element.style[ prop ] = css_props[p]; } } })(); // holds the distance that has been moved var _distance = 0; // holds the exact angle that has been moved var _angle = 0; // holds the diraction that has been moved var _direction = 0; // holds position movement for sliding var _pos = { }; // how many fingers are on the screen var _fingers = 0; var _first = false; var _gesture = null; var _prev_gesture = null; var _touch_start_time = null; var _prev_tap_pos = {x: 0, y: 0}; var _prev_tap_end_time = null; var _hold_timer = null; var _offset = {}; // keep track of the mouse status var _mousedown = false; var _event_start; var _event_move; var _event_end; /** * angle to direction define * @param float angle * @return string direction */ this.getDirectionFromAngle = function( angle ) { var directions = { down: angle >= 45 && angle < 135, //90 left: angle >= 135 || angle <= -135, //180 up: angle < -45 && angle > -135, //270 right: angle >= -45 && angle <= 45 //0 }; var direction, key; for(key in directions){ if(directions[key]){ direction = key; break; } } return direction; }; /** * count the number of fingers in the event * when no fingers are detected, one finger is returned (mouse pointer) * @param event * @return int fingers */ function countFingers( event ) { // there is a bug on android (until v4?) that touches is always 1, // so no multitouch is supported, e.g. no, zoom and rotation... return event.touches ? event.touches.length : 1; } /** * get the x and y positions from the event object * @param event * @return array [{ x: int, y: int }] */ function getXYfromEvent( event ) { event = event || window.event; // no touches, use the event pageX and pageY if(!event.touches) { var doc = document, body = doc.body; return [{ x: event.pageX || event.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && doc.clientLeft || 0 ), y: event.pageY || event.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && doc.clientTop || 0 ) }]; } // multitouch, return array with positions else { var pos = [], src; for(var t=0, len=event.touches.length; t<len; t++) { src = event.touches[t]; pos.push({ x: src.pageX, y: src.pageY }); } return pos; } } /** * calculate the angle between two points * @param object pos1 { x: int, y: int } * @param object pos2 { x: int, y: int } */ function getAngle( pos1, pos2 ) { return Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x) * 180 / Math.PI; } /** * trigger an event/callback by name with params * @param string name * @param array params */ function triggerEvent( eventName, params ) { // return touches object params.touches = getXYfromEvent(params.originalEvent); params.type = eventName; // trigger callback if(isFunction(self["on"+ eventName])) { self["on"+ eventName].call(self, params); } } /** * cancel event * @param object event * @return void */ function cancelEvent(event){ event = event || window.event; if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue = false; event.cancelBubble = true; } } /** * reset the internal vars to the start values */ function reset() { _pos = {}; _first = false; _fingers = 0; _distance = 0; _angle = 0; _gesture = null; } var gestures = { // hold gesture // fired on touchstart hold : function(event) { // only when one finger is on the screen if(options.hold) { _gesture = 'hold'; clearTimeout(_hold_timer); _hold_timer = setTimeout(function() { if(_gesture == 'hold') { triggerEvent("hold", { originalEvent : event, position : _pos.start }); } }, options.hold_timeout); } }, // drag gesture // fired on mousemove drag : function(event) { // get the distance we moved var _distance_x = _pos.move[0].x - _pos.start[0].x; var _distance_y = _pos.move[0].y - _pos.start[0].y; _distance = Math.sqrt(_distance_x * _distance_x + _distance_y * _distance_y); // drag // minimal movement required if(options.drag && (_distance > options.drag_min_distance) || _gesture == 'drag') { // calculate the angle _angle = getAngle(_pos.start[0], _pos.move[0]); _direction = self.getDirectionFromAngle(_angle); // check the movement and stop if we go in the wrong direction var is_vertical = (_direction == 'up' || _direction == 'down'); if(((is_vertical && !options.drag_vertical) || (!is_vertical && !options.drag_horizontal)) && (_distance > options.drag_min_distance)) { return; } _gesture = 'drag'; var position = { x: _pos.move[0].x - _offset.left, y: _pos.move[0].y - _offset.top }; var event_obj = { originalEvent : event, position : position, direction : _direction, distance : _distance, distanceX : _distance_x, distanceY : _distance_y, angle : _angle }; // on the first time trigger the start event if(_first) { triggerEvent("dragstart", event_obj); _first = false; } // normal slide event triggerEvent("drag", event_obj); cancelEvent(event); } }, // transform gesture // fired on touchmove transform : function(event) { if(options.transform) { var scale = event.scale || 1; var rotation = event.rotation || 0; if(countFingers(event) != 2) { return false; } if(_gesture != 'drag' && (_gesture == 'transform' || Math.abs(1-scale) > options.scale_treshold || Math.abs(rotation) > options.rotation_treshold)) { _gesture = 'transform'; _pos.center = { x: ((_pos.move[0].x + _pos.move[1].x) / 2) - _offset.left, y: ((_pos.move[0].y + _pos.move[1].y) / 2) - _offset.top }; var event_obj = { originalEvent : event, position : _pos.center, scale : scale, rotation : rotation }; // on the first time trigger the start event if(_first) { triggerEvent("transformstart", event_obj); _first = false; } triggerEvent("transform", event_obj); cancelEvent(event); return true; } } return false; }, // tap and double tap gesture // fired on touchend tap : function(event) { // compare the kind of gesture by time var now = new Date().getTime(); var touch_time = now - _touch_start_time; // dont fire when hold is fired if(options.hold && !(options.hold && options.hold_timeout > touch_time)) { return; } // when previous event was tap and the tap was max_interval ms ago var is_double_tap = (function(){ if (_prev_tap_pos && options.tap_double && _prev_gesture == 'tap' && (_touch_start_time - _prev_tap_end_time) < options.tap_max_interval) { var x_distance = Math.abs(_prev_tap_pos[0].x - _pos.start[0].x); var y_distance = Math.abs(_prev_tap_pos[0].y - _pos.start[0].y); return (_prev_tap_pos && _pos.start && Math.max(x_distance, y_distance) < options.tap_double_distance); } return false; })(); if(is_double_tap) { _gesture = 'double_tap'; _prev_tap_end_time = null; triggerEvent("doubletap", { originalEvent : event, position : _pos.start }); cancelEvent(event); } // single tap is single touch else { _gesture = 'tap'; _prev_tap_end_time = now; _prev_tap_pos = _pos.start; if(options.tap) { triggerEvent("tap", { originalEvent : event, position : _pos.start }); cancelEvent(event); } } } }; function handleEvents(event) { switch(event.type) { case 'mousedown': case 'touchstart': _pos.start = getXYfromEvent(event); _touch_start_time = new Date().getTime(); _fingers = countFingers(event); _first = true; _event_start = event; // borrowed from jquery offset https://github.com/jquery/jquery/blob/master/src/offset.js var box = element.getBoundingClientRect(); var clientTop = element.clientTop || document.body.clientTop || 0; var clientLeft = element.clientLeft || document.body.clientLeft || 0; var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop; var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft; _offset = { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; _mousedown = true; // hold gesture gestures.hold(event); if(options.prevent_default) { cancelEvent(event); } break; case 'mousemove': case 'touchmove': if(!_mousedown) { return false; } _event_move = event; _pos.move = getXYfromEvent(event); if(!gestures.transform(event)) { gestures.drag(event); } break; case 'mouseup': case 'mouseout': case 'touchcancel': case 'touchend': if(!_mousedown || (_gesture != 'transform' && event.touches && event.touches.length > 0)) { return false; } _mousedown = false; _event_end = event; // drag gesture // dragstart is triggered, so dragend is possible if(_gesture == 'drag') { triggerEvent("dragend", { originalEvent : event, direction : _direction, distance : _distance, angle : _angle }); } // transform // transformstart is triggered, so transformed is possible else if(_gesture == 'transform') { triggerEvent("transformend", { originalEvent : event, position : _pos.center, scale : event.scale, rotation : event.rotation }); } else { gestures.tap(_event_start); } _prev_gesture = _gesture; // reset vars reset(); break; } } // bind events for touch devices // except for windows phone 7.5, it doesnt support touch events..! if('ontouchstart' in window) { element.addEventListener("touchstart", handleEvents, false); element.addEventListener("touchmove", handleEvents, false); element.addEventListener("touchend", handleEvents, false); element.addEventListener("touchcancel", handleEvents, false); } // for non-touch else { if(element.addEventListener){ // prevent old IE errors element.addEventListener("mouseout", function(event) { if(!isInsideHammer(element, event.relatedTarget)) { handleEvents(event); } }, false); element.addEventListener("mouseup", handleEvents, false); element.addEventListener("mousedown", handleEvents, false); element.addEventListener("mousemove", handleEvents, false); // events for older IE }else if(document.attachEvent){ element.attachEvent("onmouseout", function(event) { if(!isInsideHammer(element, event.relatedTarget)) { handleEvents(event); } }, false); element.attachEvent("onmouseup", handleEvents); element.attachEvent("onmousedown", handleEvents); element.attachEvent("onmousemove", handleEvents); } } /** * find if element is (inside) given parent element * @param object element * @param object parent * @return bool inside */ function isInsideHammer(parent, child) { // get related target for IE if(!child && window.event && window.event.toElement){ child = window.event.toElement; } if(parent === child){ return true; } // loop over parentNodes of child until we find hammer element if(child){ var node = child.parentNode; while(node !== null){ if(node === parent){ return true; }; node = node.parentNode; } } return false; } /** * merge 2 objects into a new object * @param object obj1 * @param object obj2 * @return object merged object */ function mergeObject(obj1, obj2) { var output = {}; if(!obj2) { return obj1; } for (var prop in obj1) { if (prop in obj2) { output[prop] = obj2[prop]; } else { output[prop] = obj1[prop]; } } return output; } function isFunction( obj ){ return Object.prototype.toString.call( obj ) == "[object Function]"; } }
JavaScript
/** * @authors TODO * @fileoverview TODO */ document.cancelFullScreen = document.webkitCancelFullScreen || document.mozCancelFullScreen; /** * @constructor */ function SlideDeck(el) { this.curSlide_ = 0; this.prevSlide_ = 0; this.config_ = null; this.container = el || document.querySelector('slides'); this.slides = []; this.controller = null; this.getCurrentSlideFromHash_(); // Call this explicitly. Modernizr.load won't be done until after DOM load. this.onDomLoaded_.bind(this)(); } /** * @const * @private */ SlideDeck.prototype.SLIDE_CLASSES_ = [ 'far-past', 'past', 'current', 'next', 'far-next']; /** * @const * @private */ SlideDeck.prototype.CSS_DIR_ = 'theme/css/'; /** * @private */ SlideDeck.prototype.getCurrentSlideFromHash_ = function() { var slideNo = parseInt(document.location.hash.substr(1)); if (slideNo) { this.curSlide_ = slideNo - 1; } else { this.curSlide_ = 0; } }; /** * @param {number} slideNo */ SlideDeck.prototype.loadSlide = function(slideNo) { if (slideNo) { this.curSlide_ = slideNo - 1; this.updateSlides_(); } }; /** * @private */ SlideDeck.prototype.onDomLoaded_ = function(e) { document.body.classList.add('loaded'); // Add loaded class for templates to use. this.slides = this.container.querySelectorAll('slide:not([hidden]):not(.backdrop)'); // If we're on a smartphone, apply special sauce. if (Modernizr.mq('only screen and (max-device-width: 480px)')) { // var style = document.createElement('link'); // style.rel = 'stylesheet'; // style.type = 'text/css'; // style.href = this.CSS_DIR_ + 'phone.css'; // document.querySelector('head').appendChild(style); // No need for widescreen layout on a phone. this.container.classList.remove('layout-widescreen'); } this.loadConfig_(SLIDE_CONFIG); this.addEventListeners_(); this.updateSlides_(); // Add slide numbers and total slide count metadata to each slide. var that = this; for (var i = 0, slide; slide = this.slides[i]; ++i) { slide.dataset.slideNum = i + 1; slide.dataset.totalSlides = this.slides.length; slide.addEventListener('click', function(e) { if (document.body.classList.contains('overview')) { that.loadSlide(this.dataset.slideNum); e.preventDefault(); window.setTimeout(function() { that.toggleOverview(); }, 500); } }, false); } // Note: this needs to come after addEventListeners_(), which adds a // 'keydown' listener that this controller relies on. // Also, no need to set this up if we're on mobile. if (!Modernizr.touch) { this.controller = new SlideController(this); if (this.controller.isPopup) { document.body.classList.add('popup'); } } }; /** * @private */ SlideDeck.prototype.addEventListeners_ = function() { document.addEventListener('keydown', this.onBodyKeyDown_.bind(this), false); window.addEventListener('popstate', this.onPopState_.bind(this), false); // var transEndEventNames = { // 'WebkitTransition': 'webkitTransitionEnd', // 'MozTransition': 'transitionend', // 'OTransition': 'oTransitionEnd', // 'msTransition': 'MSTransitionEnd', // 'transition': 'transitionend' // }; // // // Find the correct transitionEnd vendor prefix. // window.transEndEventName = transEndEventNames[ // Modernizr.prefixed('transition')]; // // // When slides are done transitioning, kickoff loading iframes. // // Note: we're only looking at a single transition (on the slide). This // // doesn't include autobuilds the slides may have. Also, if the slide // // transitions on multiple properties (e.g. not just 'all'), this doesn't // // handle that case. // this.container.addEventListener(transEndEventName, function(e) { // this.enableSlideFrames_(this.curSlide_); // }.bind(this), false); // document.addEventListener('slideenter', function(e) { // var slide = e.target; // window.setTimeout(function() { // this.enableSlideFrames_(e.slideNumber); // this.enableSlideFrames_(e.slideNumber + 1); // }.bind(this), 300); // }.bind(this), false); }; /** * @private * @param {Event} e The pop event. */ SlideDeck.prototype.onPopState_ = function(e) { if (e.state != null) { this.curSlide_ = e.state; this.updateSlides_(true); } }; /** * @param {Event} e */ SlideDeck.prototype.onBodyKeyDown_ = function(e) { if (/^(input|textarea)$/i.test(e.target.nodeName) || e.target.isContentEditable) { return; } // Forward keydowns to the main slides if we're the popup. if (this.controller && this.controller.isPopup) { this.controller.sendMsg({keyCode: e.keyCode}); } switch (e.keyCode) { case 13: // Enter if (document.body.classList.contains('overview')) { this.toggleOverview(); } break; case 39: // right arrow case 32: // space case 34: // PgDn this.nextSlide(); e.preventDefault(); break; case 37: // left arrow case 8: // Backspace case 33: // PgUp this.prevSlide(); e.preventDefault(); break; case 40: // down arrow this.nextSlide(); e.preventDefault(); break; case 38: // up arrow this.prevSlide(); e.preventDefault(); break; case 72: // H: Toggle code highlighting document.body.classList.toggle('highlight-code'); break; case 79: // O: Toggle overview this.toggleOverview(); break; case 80: // P if (this.controller && this.controller.isPopup) { document.body.classList.toggle('with-notes'); } else if (this.controller && !this.controller.popup) { document.body.classList.toggle('with-notes'); } break; case 82: // R // TODO: implement refresh on main slides when popup is refreshed. break; case 27: // ESC: Hide notes and highlighting document.body.classList.remove('with-notes'); document.body.classList.remove('highlight-code'); if (document.body.classList.contains('overview')) { this.toggleOverview(); } break; case 70: // F: Toggle fullscreen // Only respect 'f' on body. Don't want to capture keys from an <input>. // Also, ignore browser's fullscreen shortcut (cmd+shift+f) so we don't // get trapped in fullscreen! if (e.target == document.body && !(e.shiftKey && e.metaKey)) { if (document.mozFullScreen !== undefined && !document.mozFullScreen) { document.body.mozRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else if (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen) { document.body.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else { document.cancelFullScreen(); } } break; case 87: // W: Toggle widescreen // Only respect 'w' on body. Don't want to capture keys from an <input>. if (e.target == document.body && !(e.shiftKey && e.metaKey)) { this.container.classList.toggle('layout-widescreen'); } break; } }; /** * */ SlideDeck.prototype.focusOverview_ = function() { var overview = document.body.classList.contains('overview'); for (var i = 0, slide; slide = this.slides[i]; i++) { slide.style[Modernizr.prefixed('transform')] = overview ? 'translateZ(-2500px) translate(' + (( i - this.curSlide_ ) * 105) + '%, 0%)' : ''; } }; /** */ SlideDeck.prototype.toggleOverview = function() { document.body.classList.toggle('overview'); this.focusOverview_(); }; /** * @private */ SlideDeck.prototype.loadConfig_ = function(config) { if (!config) { return; } this.config_ = config; var settings = this.config_.settings; this.loadTheme_(settings.theme || []); if (settings.favIcon) { this.addFavIcon_(settings.favIcon); } // Prettyprint. Default to on. if (!!!('usePrettify' in settings) || settings.usePrettify) { prettyPrint(); } if (settings.analytics) { this.loadAnalytics_(); } if (settings.fonts) { this.addFonts_(settings.fonts); } // Builds. Default to on. if (!!!('useBuilds' in settings) || settings.useBuilds) { this.makeBuildLists_(); } if (settings.title) { document.title = settings.title.replace(/<br\/?>/, ' ') + ' - Google IO 2012'; document.querySelector('[data-config-title]').innerHTML = settings.title; } if (settings.subtitle) { document.querySelector('[data-config-subtitle]').innerHTML = settings.subtitle; } if (this.config_.presenters) { var presenters = this.config_.presenters; var html = []; if (presenters.length == 1) { var p = presenters[0] html = [p.name, p.company].join('<br>'); var gplus = p.gplus ? '<span>g+</span><a href="' + p.gplus + '">' + p.gplus.replace('http://', '') + '</a>' : ''; var twitter = p.twitter ? '<span>twitter</span>' + '<a href="http://twitter.com/' + p.twitter + '">' + p.twitter + '</a>' : ''; var www = p.www ? '<span>www</span><a href="' + p.www + '">' + p.www.replace('http://', '') + '</a>' : ''; var html2 = [gplus, twitter, www].join('<br>'); document.querySelector('[data-config-contact]').innerHTML = html2; } else { for (var i = 0, p; p = presenters[i]; ++i) { html.push(p.name + ' - ' + p.company); } html = html.join('<br>'); } document.querySelector('[data-config-presenter]').innerHTML = html; } /* Left/Right tap areas. Default to including. */ if (!!!('enableSlideAreas' in settings) || settings.enableSlideAreas) { var el = document.createElement('div'); el.classList.add('slide-area'); el.id = 'prev-slide-area'; el.addEventListener('click', this.prevSlide.bind(this), false); this.container.appendChild(el); var el = document.createElement('div'); el.classList.add('slide-area'); el.id = 'next-slide-area'; el.addEventListener('click', this.nextSlide.bind(this), false); this.container.appendChild(el); } if (Modernizr.touch && (!!!('enableTouch' in settings) || settings.enableTouch)) { var self = this; // Note: this prevents mobile zoom in/out but prevents iOS from doing // it's crazy scroll over effect and disaligning the slides. window.addEventListener('touchstart', function(e) { e.preventDefault(); }, false); var hammer = new Hammer(this.container); hammer.ondragend = function(e) { if (e.direction == 'right' || e.direction == 'down') { self.prevSlide(); } else if (e.direction == 'left' || e.direction == 'up') { self.nextSlide(); } }; } }; /** * @private * @param {Array.<string>} fonts */ SlideDeck.prototype.addFonts_ = function(fonts) { var el = document.createElement('link'); el.rel = 'stylesheet'; el.href = 'http://fonts.googleapis.com/css?family=' + fonts.join('|') + '&v2'; document.querySelector('head').appendChild(el); }; /** * @private */ SlideDeck.prototype.buildNextItem_ = function() { var slide = this.slides[this.curSlide_]; var toBuild = slide.querySelector('.to-build'); var built = slide.querySelector('.build-current'); if (built) { built.classList.remove('build-current'); if (built.classList.contains('fade')) { built.classList.add('build-fade'); } } if (!toBuild) { var items = slide.querySelectorAll('.build-fade'); for (var j = 0, item; item = items[j]; j++) { item.classList.remove('build-fade'); } return false; } toBuild.classList.remove('to-build'); toBuild.classList.add('build-current'); return true; }; /** * @param {boolean=} opt_dontPush */ SlideDeck.prototype.prevSlide = function(opt_dontPush) { if (this.curSlide_ > 0) { var bodyClassList = document.body.classList; bodyClassList.remove('highlight-code'); // Toggle off speaker notes if they're showing when we move backwards on the // main slides. If we're the speaker notes popup, leave them up. if (this.controller && !this.controller.isPopup) { bodyClassList.remove('with-notes'); } else if (!this.controller) { bodyClassList.remove('with-notes'); } this.prevSlide_ = this.curSlide_--; this.updateSlides_(opt_dontPush); } }; /** * @param {boolean=} opt_dontPush */ SlideDeck.prototype.nextSlide = function(opt_dontPush) { if (!document.body.classList.contains('overview') && this.buildNextItem_()) { return; } if (this.curSlide_ < this.slides.length - 1) { var bodyClassList = document.body.classList; bodyClassList.remove('highlight-code'); // Toggle off speaker notes if they're showing when we advanced on the main // slides. If we're the speaker notes popup, leave them up. if (this.controller && !this.controller.isPopup) { bodyClassList.remove('with-notes'); } else if (!this.controller) { bodyClassList.remove('with-notes'); } this.prevSlide_ = this.curSlide_++; this.updateSlides_(opt_dontPush); } }; /* Slide events */ /** * Triggered when a slide enter/leave event should be dispatched. * * @param {string} type The type of event to trigger * (e.g. 'slideenter', 'slideleave'). * @param {number} slideNo The index of the slide that is being left. */ SlideDeck.prototype.triggerSlideEvent = function(type, slideNo) { var el = this.getSlideEl_(slideNo); if (!el) { return; } // Call onslideenter/onslideleave if the attribute is defined on this slide. var func = el.getAttribute(type); if (func) { new Function(func).call(el); // TODO: Don't use new Function() :( } // Dispatch event to listeners setup using addEventListener. var evt = document.createEvent('Event'); evt.initEvent(type, true, true); evt.slideNumber = slideNo + 1; // Make it readable evt.slide = el; el.dispatchEvent(evt); }; /** * @private */ SlideDeck.prototype.updateSlides_ = function(opt_dontPush) { var dontPush = opt_dontPush || false; var curSlide = this.curSlide_; for (var i = 0; i < this.slides.length; ++i) { switch (i) { case curSlide - 2: this.updateSlideClass_(i, 'far-past'); break; case curSlide - 1: this.updateSlideClass_(i, 'past'); break; case curSlide: this.updateSlideClass_(i, 'current'); break; case curSlide + 1: this.updateSlideClass_(i, 'next'); break; case curSlide + 2: this.updateSlideClass_(i, 'far-next'); break; default: this.updateSlideClass_(i); break; } }; this.triggerSlideEvent('slideleave', this.prevSlide_); this.triggerSlideEvent('slideenter', curSlide); // window.setTimeout(this.disableSlideFrames_.bind(this, curSlide - 2), 301); // // this.enableSlideFrames_(curSlide - 1); // Previous slide. // this.enableSlideFrames_(curSlide + 1); // Current slide. // this.enableSlideFrames_(curSlide + 2); // Next slide. // Enable current slide's iframes (needed for page loat at current slide). this.enableSlideFrames_(curSlide + 1); // No way to tell when all slide transitions + auto builds are done. // Give ourselves a good buffer to preload the next slide's iframes. window.setTimeout(this.enableSlideFrames_.bind(this, curSlide + 2), 1000); this.updateHash_(dontPush); if (document.body.classList.contains('overview')) { this.focusOverview_(); return; } }; /** * @private * @param {number} slideNo */ SlideDeck.prototype.enableSlideFrames_ = function(slideNo) { var el = this.slides[slideNo - 1]; if (!el) { return; } var frames = el.querySelectorAll('iframe'); for (var i = 0, frame; frame = frames[i]; i++) { this.enableFrame_(frame); } }; /** * @private * @param {number} slideNo */ SlideDeck.prototype.enableFrame_ = function(frame) { var src = frame.dataset.src; if (src && frame.src != src) { frame.src = src; } }; /** * @private * @param {number} slideNo */ SlideDeck.prototype.disableSlideFrames_ = function(slideNo) { var el = this.slides[slideNo - 1]; if (!el) { return; } var frames = el.querySelectorAll('iframe'); for (var i = 0, frame; frame = frames[i]; i++) { this.disableFrame_(frame); } }; /** * @private * @param {Node} frame */ SlideDeck.prototype.disableFrame_ = function(frame) { frame.src = 'about:blank'; }; /** * @private * @param {number} slideNo */ SlideDeck.prototype.getSlideEl_ = function(no) { if ((no < 0) || (no >= this.slides.length)) { return null; } else { return this.slides[no]; } }; /** * @private * @param {number} slideNo * @param {string} className */ SlideDeck.prototype.updateSlideClass_ = function(slideNo, className) { var el = this.getSlideEl_(slideNo); if (!el) { return; } if (className) { el.classList.add(className); } for (var i = 0, slideClass; slideClass = this.SLIDE_CLASSES_[i]; ++i) { if (className != slideClass) { el.classList.remove(slideClass); } } }; /** * @private */ SlideDeck.prototype.makeBuildLists_ = function () { for (var i = this.curSlide_, slide; slide = this.slides[i]; ++i) { var items = slide.querySelectorAll('.build > *'); for (var j = 0, item; item = items[j]; ++j) { if (item.classList) { item.classList.add('to-build'); if (item.parentNode.classList.contains('fade')) { item.classList.add('fade'); } } } } }; /** * @private * @param {boolean} dontPush */ SlideDeck.prototype.updateHash_ = function(dontPush) { if (!dontPush) { var slideNo = this.curSlide_ + 1; var hash = '#' + slideNo; if (window.history.pushState) { window.history.pushState(this.curSlide_, 'Slide ' + slideNo, hash); } else { window.location.replace(hash); } // Record GA hit on this slide. window['_gaq'] && window['_gaq'].push(['_trackPageview', document.location.href]); } }; /** * @private * @param {string} favIcon */ SlideDeck.prototype.addFavIcon_ = function(favIcon) { var el = document.createElement('link'); el.rel = 'icon'; el.type = 'image/png'; el.href = favIcon; document.querySelector('head').appendChild(el); }; /** * @private * @param {string} theme */ SlideDeck.prototype.loadTheme_ = function(theme) { var styles = []; if (theme.constructor.name === 'String') { styles.push(theme); } else { styles = theme; } for (var i = 0, style; themeUrl = styles[i]; i++) { var style = document.createElement('link'); style.rel = 'stylesheet'; style.type = 'text/css'; if (themeUrl.indexOf('http') == -1) { style.href = this.CSS_DIR_ + themeUrl + '.css'; } else { style.href = themeUrl; } document.querySelector('head').appendChild(style); } }; /** * @private */ SlideDeck.prototype.loadAnalytics_ = function() { var _gaq = window['_gaq'] || []; _gaq.push(['_setAccount', this.config_.settings.analytics]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); }; // Polyfill missing APIs (if we need to), then create the slide deck. // iOS < 5 needs classList, dataset, and window.matchMedia. Modernizr contains // the last one. (function() { Modernizr.load({ test: !!document.body.classList && !!document.body.dataset, nope: ['js/polyfills/classList.min.js', 'js/polyfills/dataset.min.js'], complete: function() { window.slidedeck = new SlideDeck(); } }); })();
JavaScript
require(['order!../slide_config', 'order!modernizr.custom.45394', 'order!prettify/prettify', 'order!hammer', 'order!slide-controller', 'order!slide-deck'], function(someModule) { });
JavaScript
var SLIDE_CONFIG = { // Slide settings settings: { title: 'Building Web Applications that use Google APIs and the JavaScript Client for Google APIs', subtitle: '', useBuilds: true, // Default: true. False will turn off slide animation builds. usePrettify: true, // Default: true enableSlideAreas: true, // Default: true. False turns off the click areas on either slide of the slides. enableTouch: true, // Default: true. If touch support should enabled. Note: the device must support touch. //analytics: 'UA-XXXXXXXX-1', favIcon: 'http://bleedinghtml5.appspot.com/images/chrome-logo-tiny2.png', fonts: [ 'Open Sans:regular,semibold,italic,italicsemibold', 'Inconsolata' ], //theme: ['mytheme'], // Add your own custom themes or styles in /theme/css. Leave off the .css extension. }, // Author information presenters: [{ name: 'Brendan O\'Brien', company: 'Software Engineer, Google+', gplus: 'https://plus.google.com/116812371442532868406', twitter: '@ICodeJS', www: '' }] };
JavaScript
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Provides functions to perform the OAuth 2.0 authentication. * @author silvano.luciani@gmail.com (Silvano Luciani) */ /** * Enter a client ID for a web application from the Google Developer Console. * In your Developer Console project, add a JavaScript origin that corresponds * to the domain where you will be running the script. * @type {string} */ // This client ID won't work with your project! CLIENT_ID = '837050751313'; /** * Enter the API key from the Google Developer Console - to handle any * unauthenticated requests in the code. * @type {string} */ // This key won't work with your project! API_KEY = 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM'; /** * To enter one or more authentication scopes, refer to the documentation * for the API. * @type {string} */ SCOPE = 'https://www.googleapis.com/auth/adsense.readonly'; /** * Set the api key and starts the authentication flow calling checkAuth. * Called from the example page after the Google APIs Javascript client has been * loaded. */ function handleClientLoad() { gapi.client.setApiKey(API_KEY); window.setTimeout(checkAuth, 1); } /** * Checks the authorization and calls handleAuthResult once the process * is completed. */ function checkAuth() { gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPE, immediate: true}, handleAuthResult); } /** * Performs the API request if we have an access token, otherwise shows the * authentication button to allow the user to start the flow. * makeApiCall is implemented in each specific code example to query the API and * visualize the data. * @param {object} authResult An OAuth 2.0 token and any associated data. */ function handleAuthResult(authResult) { var authorizeButton = document.getElementById('authorize-button'); if (authResult) { authorizeButton.style.visibility = 'hidden'; makeApiCall(); } else { authorizeButton.style.visibility = ''; authorizeButton.onclick = handleAuthClick; } } /** * Handles authentication requests from the authentication button. * @param {object} event The event that triggered the function. */ function handleAuthClick(event) { gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPE, immediate: false}, handleAuthResult); }
JavaScript
/* * jsTree 1.0-rc3 * http://jstree.com/ * * Copyright (c) 2010 Ivan Bozhanov (vakata.com) * * Licensed same as jquery - under the terms of either the MIT License or the GPL Version 2 License * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * $Date: 2011-02-09 01:17:14 +0200 (ср, 09 февр 2011) $ * $Revision: 236 $ */ /*jslint browser: true, onevar: true, undef: true, bitwise: true, strict: true */ /*global window : false, clearInterval: false, clearTimeout: false, document: false, setInterval: false, setTimeout: false, jQuery: false, navigator: false, XSLTProcessor: false, DOMParser: false, XMLSerializer: false*/ "use strict"; // top wrapper to prevent multiple inclusion (is this OK?) (function () { if(jQuery && jQuery.jstree) { return; } var is_ie6 = false, is_ie7 = false, is_ff2 = false; /* * jsTree core */ (function ($) { // Common functions not related to jsTree // decided to move them to a `vakata` "namespace" $.vakata = {}; // CSS related functions $.vakata.css = { get_css : function(rule_name, delete_flag, sheet) { rule_name = rule_name.toLowerCase(); var css_rules = sheet.cssRules || sheet.rules, j = 0; do { if(css_rules.length && j > css_rules.length + 5) { return false; } if(css_rules[j].selectorText && css_rules[j].selectorText.toLowerCase() == rule_name) { if(delete_flag === true) { if(sheet.removeRule) { sheet.removeRule(j); } if(sheet.deleteRule) { sheet.deleteRule(j); } return true; } else { return css_rules[j]; } } } while (css_rules[++j]); return false; }, add_css : function(rule_name, sheet) { if($.jstree.css.get_css(rule_name, false, sheet)) { return false; } if(sheet.insertRule) { sheet.insertRule(rule_name + ' { }', 0); } else { sheet.addRule(rule_name, null, 0); } return $.vakata.css.get_css(rule_name); }, remove_css : function(rule_name, sheet) { return $.vakata.css.get_css(rule_name, true, sheet); }, add_sheet : function(opts) { var tmp = false, is_new = true; if(opts.str) { if(opts.title) { tmp = $("style[id='" + opts.title + "-stylesheet']")[0]; } if(tmp) { is_new = false; } else { tmp = document.createElement("style"); tmp.setAttribute('type',"text/css"); if(opts.title) { tmp.setAttribute("id", opts.title + "-stylesheet"); } } if(tmp.styleSheet) { if(is_new) { document.getElementsByTagName("head")[0].appendChild(tmp); tmp.styleSheet.cssText = opts.str; } else { tmp.styleSheet.cssText = tmp.styleSheet.cssText + " " + opts.str; } } else { tmp.appendChild(document.createTextNode(opts.str)); document.getElementsByTagName("head")[0].appendChild(tmp); } return tmp.sheet || tmp.styleSheet; } if(opts.url) { if(document.createStyleSheet) { try { tmp = document.createStyleSheet(opts.url); } catch (e) { } } else { tmp = document.createElement('link'); tmp.rel = 'stylesheet'; tmp.type = 'text/css'; tmp.media = "all"; tmp.href = opts.url; document.getElementsByTagName("head")[0].appendChild(tmp); return tmp.styleSheet; } } } }; // private variables var instances = [], // instance array (used by $.jstree.reference/create/focused) focused_instance = -1, // the index in the instance array of the currently focused instance plugins = {}, // list of included plugins prepared_move = {}; // for the move_node function // jQuery plugin wrapper (thanks to jquery UI widget function) $.fn.jstree = function (settings) { var isMethodCall = (typeof settings == 'string'), // is this a method call like $().jstree("open_node") args = Array.prototype.slice.call(arguments, 1), returnValue = this; // if a method call execute the method on all selected instances if(isMethodCall) { if(settings.substring(0, 1) == '_') { return returnValue; } this.each(function() { var instance = instances[$.data(this, "jstree_instance_id")], methodValue = (instance && $.isFunction(instance[settings])) ? instance[settings].apply(instance, args) : instance; if(typeof methodValue !== "undefined" && (settings.indexOf("is_") === 0 || (methodValue !== true && methodValue !== false))) { returnValue = methodValue; return false; } }); } else { this.each(function() { // extend settings and allow for multiple hashes and $.data var instance_id = $.data(this, "jstree_instance_id"), a = [], b = settings ? $.extend({}, true, settings) : {}, c = $(this), s = false, t = []; a = a.concat(args); if(c.data("jstree")) { a.push(c.data("jstree")); } b = a.length ? $.extend.apply(null, [true, b].concat(a)) : b; // if an instance already exists, destroy it first if(typeof instance_id !== "undefined" && instances[instance_id]) { instances[instance_id].destroy(); } // push a new empty object to the instances array instance_id = parseInt(instances.push({}),10) - 1; // store the jstree instance id to the container element $.data(this, "jstree_instance_id", instance_id); // clean up all plugins b.plugins = $.isArray(b.plugins) ? b.plugins : $.jstree.defaults.plugins.slice(); b.plugins.unshift("core"); // only unique plugins b.plugins = b.plugins.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(","); // extend defaults with passed data s = $.extend(true, {}, $.jstree.defaults, b); s.plugins = b.plugins; $.each(plugins, function (i, val) { if($.inArray(i, s.plugins) === -1) { s[i] = null; delete s[i]; } else { t.push(i); } }); s.plugins = t; // push the new object to the instances array (at the same time set the default classes to the container) and init instances[instance_id] = new $.jstree._instance(instance_id, $(this).addClass("jstree jstree-" + instance_id), s); // init all activated plugins for this instance $.each(instances[instance_id]._get_settings().plugins, function (i, val) { instances[instance_id].data[val] = {}; }); $.each(instances[instance_id]._get_settings().plugins, function (i, val) { if(plugins[val]) { plugins[val].__init.apply(instances[instance_id]); } }); // initialize the instance setTimeout(function() { if(instances[instance_id]) { instances[instance_id].init(); } }, 0); }); } // return the jquery selection (or if it was a method call that returned a value - the returned value) return returnValue; }; // object to store exposed functions and objects $.jstree = { defaults : { plugins : [] }, _focused : function () { return instances[focused_instance] || null; }, _reference : function (needle) { // get by instance id if(instances[needle]) { return instances[needle]; } // get by DOM (if still no luck - return null var o = $(needle); if(!o.length && typeof needle === "string") { o = $("#" + needle); } if(!o.length) { return null; } return instances[o.closest(".jstree").data("jstree_instance_id")] || null; }, _instance : function (index, container, settings) { // for plugins to store data in this.data = { core : {} }; this.get_settings = function () { return $.extend(true, {}, settings); }; this._get_settings = function () { return settings; }; this.get_index = function () { return index; }; this.get_container = function () { return container; }; this.get_container_ul = function () { return container.children("ul:eq(0)"); }; this._set_settings = function (s) { settings = $.extend(true, {}, settings, s); }; }, _fn : { }, plugin : function (pname, pdata) { pdata = $.extend({}, { __init : $.noop, __destroy : $.noop, _fn : {}, defaults : false }, pdata); plugins[pname] = pdata; $.jstree.defaults[pname] = pdata.defaults; $.each(pdata._fn, function (i, val) { val.plugin = pname; val.old = $.jstree._fn[i]; $.jstree._fn[i] = function () { var rslt, func = val, args = Array.prototype.slice.call(arguments), evnt = new $.Event("before.jstree"), rlbk = false; if(this.data.core.locked === true && i !== "unlock" && i !== "is_locked") { return; } // Check if function belongs to the included plugins of this instance do { if(func && func.plugin && $.inArray(func.plugin, this._get_settings().plugins) !== -1) { break; } func = func.old; } while(func); if(!func) { return; } // context and function to trigger events, then finally call the function if(i.indexOf("_") === 0) { rslt = func.apply(this, args); } else { rslt = this.get_container().triggerHandler(evnt, { "func" : i, "inst" : this, "args" : args, "plugin" : func.plugin }); if(rslt === false) { return; } if(typeof rslt !== "undefined") { args = rslt; } rslt = func.apply( $.extend({}, this, { __callback : function (data) { this.get_container().triggerHandler( i + '.jstree', { "inst" : this, "args" : args, "rslt" : data, "rlbk" : rlbk }); }, __rollback : function () { rlbk = this.get_rollback(); return rlbk; }, __call_old : function (replace_arguments) { return func.old.apply(this, (replace_arguments ? Array.prototype.slice.call(arguments, 1) : args ) ); } }), args); } // return the result return rslt; }; $.jstree._fn[i].old = val.old; $.jstree._fn[i].plugin = pname; }); }, rollback : function (rb) { if(rb) { if(!$.isArray(rb)) { rb = [ rb ]; } $.each(rb, function (i, val) { instances[val.i].set_rollback(val.h, val.d); }); } } }; // set the prototype for all instances $.jstree._fn = $.jstree._instance.prototype = {}; // load the css when DOM is ready $(function() { // code is copied from jQuery ($.browser is deprecated + there is a bug in IE) var u = navigator.userAgent.toLowerCase(), v = (u.match( /.+?(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1], css_string = '' + '.jstree ul, .jstree li { display:block; margin:0 0 0 0; padding:0 0 0 0; list-style-type:none; } ' + '.jstree li { display:block; min-height:18px; line-height:18px; white-space:nowrap; margin-left:18px; min-width:18px; } ' + '.jstree-rtl li { margin-left:0; margin-right:18px; } ' + '.jstree > ul > li { margin-left:0px; } ' + '.jstree-rtl > ul > li { margin-right:0px; } ' + '.jstree ins { display:inline-block; text-decoration:none; width:18px; height:18px; margin:0 0 0 0; padding:0; } ' + '.jstree a { display:inline-block; line-height:16px; height:16px; color:black; white-space:nowrap; text-decoration:none; padding:1px 2px; margin:0; } ' + '.jstree a:focus { outline: none; } ' + '.jstree a > ins { height:16px; width:16px; } ' + '.jstree a > .jstree-icon { margin-right:3px; } ' + '.jstree-rtl a > .jstree-icon { margin-left:3px; margin-right:0; } ' + 'li.jstree-open > ul { display:block; } ' + 'li.jstree-closed > ul { display:none; } '; // Correct IE 6 (does not support the > CSS selector) if(/msie/.test(u) && parseInt(v, 10) == 6) { is_ie6 = true; // fix image flicker and lack of caching try { document.execCommand("BackgroundImageCache", false, true); } catch (err) { } css_string += '' + '.jstree li { height:18px; margin-left:0; margin-right:0; } ' + '.jstree li li { margin-left:18px; } ' + '.jstree-rtl li li { margin-left:0px; margin-right:18px; } ' + 'li.jstree-open ul { display:block; } ' + 'li.jstree-closed ul { display:none !important; } ' + '.jstree li a { display:inline; border-width:0 !important; padding:0px 2px !important; } ' + '.jstree li a ins { height:16px; width:16px; margin-right:3px; } ' + '.jstree-rtl li a ins { margin-right:0px; margin-left:3px; } '; } // Correct IE 7 (shifts anchor nodes onhover) if(/msie/.test(u) && parseInt(v, 10) == 7) { is_ie7 = true; css_string += '.jstree li a { border-width:0 !important; padding:0px 2px !important; } '; } // correct ff2 lack of display:inline-block if(!/compatible/.test(u) && /mozilla/.test(u) && parseFloat(v, 10) < 1.9) { is_ff2 = true; css_string += '' + '.jstree ins { display:-moz-inline-box; } ' + '.jstree li { line-height:12px; } ' + // WHY?? '.jstree a { display:-moz-inline-box; } ' + '.jstree .jstree-no-icons .jstree-checkbox { display:-moz-inline-stack !important; } '; /* this shouldn't be here as it is theme specific */ } // the default stylesheet $.vakata.css.add_sheet({ str : css_string, title : "jstree" }); }); // core functions (open, close, create, update, delete) $.jstree.plugin("core", { __init : function () { this.data.core.locked = false; this.data.core.to_open = this.get_settings().core.initially_open; this.data.core.to_load = this.get_settings().core.initially_load; }, defaults : { html_titles : false, animation : 500, initially_open : [], initially_load : [], open_parents : true, notify_plugins : true, rtl : false, load_open : false, strings : { loading : "Loading ...", new_node : "New node", multiple_selection : "Multiple selection" } }, _fn : { init : function () { this.set_focus(); if(this._get_settings().core.rtl) { this.get_container().addClass("jstree-rtl").css("direction", "rtl"); } this.get_container().html("<ul><li class='jstree-last jstree-leaf'><ins>&#160;</ins><a class='jstree-loading' href='#'><ins class='jstree-icon'>&#160;</ins>" + this._get_string("loading") + "</a></li></ul>"); this.data.core.li_height = this.get_container_ul().find("li.jstree-closed, li.jstree-leaf").eq(0).height() || 18; this.get_container() .delegate("li > ins", "click.jstree", $.proxy(function (event) { var trgt = $(event.target); // if(trgt.is("ins") && event.pageY - trgt.offset().top < this.data.core.li_height) { this.toggle_node(trgt); } this.toggle_node(trgt); }, this)) .bind("mousedown.jstree", $.proxy(function () { this.set_focus(); // This used to be setTimeout(set_focus,0) - why? }, this)) .bind("dblclick.jstree", function (event) { var sel; if(document.selection && document.selection.empty) { document.selection.empty(); } else { if(window.getSelection) { sel = window.getSelection(); try { sel.removeAllRanges(); sel.collapse(); } catch (err) { } } } }); if(this._get_settings().core.notify_plugins) { this.get_container() .bind("load_node.jstree", $.proxy(function (e, data) { var o = this._get_node(data.rslt.obj), t = this; if(o === -1) { o = this.get_container_ul(); } if(!o.length) { return; } o.find("li").each(function () { var th = $(this); if(th.data("jstree")) { $.each(th.data("jstree"), function (plugin, values) { if(t.data[plugin] && $.isFunction(t["_" + plugin + "_notify"])) { t["_" + plugin + "_notify"].call(t, th, values); } }); } }); }, this)); } if(this._get_settings().core.load_open) { this.get_container() .bind("load_node.jstree", $.proxy(function (e, data) { var o = this._get_node(data.rslt.obj), t = this; if(o === -1) { o = this.get_container_ul(); } if(!o.length) { return; } o.find("li.jstree-open:not(:has(ul))").each(function () { t.load_node(this, $.noop, $.noop); }); }, this)); } this.__callback(); this.load_node(-1, function () { this.loaded(); this.reload_nodes(); }); }, destroy : function () { var i, n = this.get_index(), s = this._get_settings(), _this = this; $.each(s.plugins, function (i, val) { try { plugins[val].__destroy.apply(_this); } catch(err) { } }); this.__callback(); // set focus to another instance if this one is focused if(this.is_focused()) { for(i in instances) { if(instances.hasOwnProperty(i) && i != n) { instances[i].set_focus(); break; } } } // if no other instance found if(n === focused_instance) { focused_instance = -1; } // remove all traces of jstree in the DOM (only the ones set using jstree*) and cleans all events this.get_container() .unbind(".jstree") .undelegate(".jstree") .removeData("jstree_instance_id") .find("[class^='jstree']") .andSelf() .attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); }); $(document) .unbind(".jstree-" + n) .undelegate(".jstree-" + n); // remove the actual data instances[n] = null; delete instances[n]; }, _core_notify : function (n, data) { if(data.opened) { this.open_node(n, false, true); } }, lock : function () { this.data.core.locked = true; this.get_container().children("ul").addClass("jstree-locked").css("opacity","0.7"); this.__callback({}); }, unlock : function () { this.data.core.locked = false; this.get_container().children("ul").removeClass("jstree-locked").css("opacity","1"); this.__callback({}); }, is_locked : function () { return this.data.core.locked; }, save_opened : function () { var _this = this; this.data.core.to_open = []; this.get_container_ul().find("li.jstree-open").each(function () { if(this.id) { _this.data.core.to_open.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); } }); this.__callback(_this.data.core.to_open); }, save_loaded : function () { }, reload_nodes : function (is_callback) { var _this = this, done = true, current = [], remaining = []; if(!is_callback) { this.data.core.reopen = false; this.data.core.refreshing = true; this.data.core.to_open = $.map($.makeArray(this.data.core.to_open), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); }); this.data.core.to_load = $.map($.makeArray(this.data.core.to_load), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); }); if(this.data.core.to_open.length) { this.data.core.to_load = this.data.core.to_load.concat(this.data.core.to_open); } } if(this.data.core.to_load.length) { $.each(this.data.core.to_load, function (i, val) { if(val == "#") { return true; } if($(val).length) { current.push(val); } else { remaining.push(val); } }); if(current.length) { this.data.core.to_load = remaining; $.each(current, function (i, val) { if(!_this._is_loaded(val)) { _this.load_node(val, function () { _this.reload_nodes(true); }, function () { _this.reload_nodes(true); }); done = false; } }); } } if(this.data.core.to_open.length) { $.each(this.data.core.to_open, function (i, val) { _this.open_node(val, false, true); }); } if(done) { // TODO: find a more elegant approach to syncronizing returning requests if(this.data.core.reopen) { clearTimeout(this.data.core.reopen); } this.data.core.reopen = setTimeout(function () { _this.__callback({}, _this); }, 50); this.data.core.refreshing = false; this.reopen(); } }, reopen : function () { var _this = this; if(this.data.core.to_open.length) { $.each(this.data.core.to_open, function (i, val) { _this.open_node(val, false, true); }); } this.__callback({}); }, refresh : function (obj) { var _this = this; this.save_opened(); if(!obj) { obj = -1; } obj = this._get_node(obj); if(!obj) { obj = -1; } if(obj !== -1) { obj.children("UL").remove(); } else { this.get_container_ul().empty(); } this.load_node(obj, function () { _this.__callback({ "obj" : obj}); _this.reload_nodes(); }); }, // Dummy function to fire after the first load (so that there is a jstree.loaded event) loaded : function () { this.__callback(); }, // deal with focus set_focus : function () { if(this.is_focused()) { return; } var f = $.jstree._focused(); if(f) { f.unset_focus(); } this.get_container().addClass("jstree-focused"); focused_instance = this.get_index(); this.__callback(); }, is_focused : function () { return focused_instance == this.get_index(); }, unset_focus : function () { if(this.is_focused()) { this.get_container().removeClass("jstree-focused"); focused_instance = -1; } this.__callback(); }, // traverse _get_node : function (obj) { var $obj = $(obj, this.get_container()); if($obj.is(".jstree") || obj == -1) { return -1; } $obj = $obj.closest("li", this.get_container()); return $obj.length ? $obj : false; }, _get_next : function (obj, strict) { obj = this._get_node(obj); if(obj === -1) { return this.get_container().find("> ul > li:first-child"); } if(!obj.length) { return false; } if(strict) { return (obj.nextAll("li").size() > 0) ? obj.nextAll("li:eq(0)") : false; } if(obj.hasClass("jstree-open")) { return obj.find("li:eq(0)"); } else if(obj.nextAll("li").size() > 0) { return obj.nextAll("li:eq(0)"); } else { return obj.parentsUntil(".jstree","li").next("li").eq(0); } }, _get_prev : function (obj, strict) { obj = this._get_node(obj); if(obj === -1) { return this.get_container().find("> ul > li:last-child"); } if(!obj.length) { return false; } if(strict) { return (obj.prevAll("li").length > 0) ? obj.prevAll("li:eq(0)") : false; } if(obj.prev("li").length) { obj = obj.prev("li").eq(0); while(obj.hasClass("jstree-open")) { obj = obj.children("ul:eq(0)").children("li:last"); } return obj; } else { var o = obj.parentsUntil(".jstree","li:eq(0)"); return o.length ? o : false; } }, _get_parent : function (obj) { obj = this._get_node(obj); if(obj == -1 || !obj.length) { return false; } var o = obj.parentsUntil(".jstree", "li:eq(0)"); return o.length ? o : -1; }, _get_children : function (obj) { obj = this._get_node(obj); if(obj === -1) { return this.get_container().children("ul:eq(0)").children("li"); } if(!obj.length) { return false; } return obj.children("ul:eq(0)").children("li"); }, get_path : function (obj, id_mode) { var p = [], _this = this; obj = this._get_node(obj); if(obj === -1 || !obj || !obj.length) { return false; } obj.parentsUntil(".jstree", "li").each(function () { p.push( id_mode ? this.id : _this.get_text(this) ); }); p.reverse(); p.push( id_mode ? obj.attr("id") : this.get_text(obj) ); return p; }, // string functions _get_string : function (key) { return this._get_settings().core.strings[key] || key; }, is_open : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-open"); }, is_closed : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-closed"); }, is_leaf : function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-leaf"); }, correct_state : function (obj) { obj = this._get_node(obj); if(!obj || obj === -1) { return false; } obj.removeClass("jstree-closed jstree-open").addClass("jstree-leaf").children("ul").remove(); this.__callback({ "obj" : obj }); }, // open/close open_node : function (obj, callback, skip_animation) { obj = this._get_node(obj); if(!obj.length) { return false; } if(!obj.hasClass("jstree-closed")) { if(callback) { callback.call(); } return false; } var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation, t = this; if(!this._is_loaded(obj)) { obj.children("a").addClass("jstree-loading"); this.load_node(obj, function () { t.open_node(obj, callback, skip_animation); }, callback); } else { if(this._get_settings().core.open_parents) { obj.parentsUntil(".jstree",".jstree-closed").each(function () { t.open_node(this, false, true); }); } if(s) { obj.children("ul").css("display","none"); } obj.removeClass("jstree-closed").addClass("jstree-open").children("a").removeClass("jstree-loading"); if(s) { obj.children("ul").stop(true, true).slideDown(s, function () { this.style.display = ""; t.after_open(obj); }); } else { t.after_open(obj); } this.__callback({ "obj" : obj }); if(callback) { callback.call(); } } }, after_open : function (obj) { this.__callback({ "obj" : obj }); }, close_node : function (obj, skip_animation) { obj = this._get_node(obj); var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation, t = this; if(!obj.length || !obj.hasClass("jstree-open")) { return false; } if(s) { obj.children("ul").attr("style","display:block !important"); } obj.removeClass("jstree-open").addClass("jstree-closed"); if(s) { obj.children("ul").stop(true, true).slideUp(s, function () { this.style.display = ""; t.after_close(obj); }); } else { t.after_close(obj); } this.__callback({ "obj" : obj }); }, after_close : function (obj) { this.__callback({ "obj" : obj }); }, toggle_node : function (obj) { obj = this._get_node(obj); if(obj.hasClass("jstree-closed")) { return this.open_node(obj); } if(obj.hasClass("jstree-open")) { return this.close_node(obj); } }, open_all : function (obj, do_animation, original_obj) { obj = obj ? this._get_node(obj) : -1; if(!obj || obj === -1) { obj = this.get_container_ul(); } if(original_obj) { obj = obj.find("li.jstree-closed"); } else { original_obj = obj; if(obj.is(".jstree-closed")) { obj = obj.find("li.jstree-closed").andSelf(); } else { obj = obj.find("li.jstree-closed"); } } var _this = this; obj.each(function () { var __this = this; if(!_this._is_loaded(this)) { _this.open_node(this, function() { _this.open_all(__this, do_animation, original_obj); }, !do_animation); } else { _this.open_node(this, false, !do_animation); } }); // so that callback is fired AFTER all nodes are open if(original_obj.find('li.jstree-closed').length === 0) { this.__callback({ "obj" : original_obj }); } }, close_all : function (obj, do_animation) { var _this = this; obj = obj ? this._get_node(obj) : this.get_container(); if(!obj || obj === -1) { obj = this.get_container_ul(); } obj.find("li.jstree-open").andSelf().each(function () { _this.close_node(this, !do_animation); }); this.__callback({ "obj" : obj }); }, clean_node : function (obj) { obj = obj && obj != -1 ? $(obj) : this.get_container_ul(); obj = obj.is("li") ? obj.find("li").andSelf() : obj.find("li"); obj.removeClass("jstree-last") .filter("li:last-child").addClass("jstree-last").end() .filter(":has(li)") .not(".jstree-open").removeClass("jstree-leaf").addClass("jstree-closed"); obj.not(".jstree-open, .jstree-closed").addClass("jstree-leaf").children("ul").remove(); this.__callback({ "obj" : obj }); }, // rollback get_rollback : function () { this.__callback(); return { i : this.get_index(), h : this.get_container().children("ul").clone(true), d : this.data }; }, set_rollback : function (html, data) { this.get_container().empty().append(html); this.data = data; this.__callback(); }, // Dummy functions to be overwritten by any datastore plugin included load_node : function (obj, s_call, e_call) { this.__callback({ "obj" : obj }); }, _is_loaded : function (obj) { return true; }, // Basic operations: create create_node : function (obj, position, js, callback, is_loaded) { obj = this._get_node(obj); position = typeof position === "undefined" ? "last" : position; var d = $("<li />"), s = this._get_settings().core, tmp; if(obj !== -1 && !obj.length) { return false; } if(!is_loaded && !this._is_loaded(obj)) { this.load_node(obj, function () { this.create_node(obj, position, js, callback, true); }); return false; } this.__rollback(); if(typeof js === "string") { js = { "data" : js }; } if(!js) { js = {}; } if(js.attr) { d.attr(js.attr); } if(js.metadata) { d.data(js.metadata); } if(js.state) { d.addClass("jstree-" + js.state); } if(!js.data) { js.data = this._get_string("new_node"); } if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); } $.each(js.data, function (i, m) { tmp = $("<a />"); if($.isFunction(m)) { m = m.call(this, js); } if(typeof m == "string") { tmp.attr('href','#')[ s.html_titles ? "html" : "text" ](m); } else { if(!m.attr) { m.attr = {}; } if(!m.attr.href) { m.attr.href = '#'; } tmp.attr(m.attr)[ s.html_titles ? "html" : "text" ](m.title); if(m.language) { tmp.addClass(m.language); } } tmp.prepend("<ins class='jstree-icon'>&#160;</ins>"); if(!m.icon && js.icon) { m.icon = js.icon; } if(m.icon) { if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); } else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); } } d.append(tmp); }); d.prepend("<ins class='jstree-icon'>&#160;</ins>"); if(obj === -1) { obj = this.get_container(); if(position === "before") { position = "first"; } if(position === "after") { position = "last"; } } switch(position) { case "before": obj.before(d); tmp = this._get_parent(obj); break; case "after" : obj.after(d); tmp = this._get_parent(obj); break; case "inside": case "first" : if(!obj.children("ul").length) { obj.append("<ul />"); } obj.children("ul").prepend(d); tmp = obj; break; case "last": if(!obj.children("ul").length) { obj.append("<ul />"); } obj.children("ul").append(d); tmp = obj; break; default: if(!obj.children("ul").length) { obj.append("<ul />"); } if(!position) { position = 0; } tmp = obj.children("ul").children("li").eq(position); if(tmp.length) { tmp.before(d); } else { obj.children("ul").append(d); } tmp = obj; break; } if(tmp === -1 || tmp.get(0) === this.get_container().get(0)) { tmp = -1; } this.clean_node(tmp); this.__callback({ "obj" : d, "parent" : tmp }); if(callback) { callback.call(this, d); } return d; }, // Basic operations: rename (deal with text) get_text : function (obj) { obj = this._get_node(obj); if(!obj.length) { return false; } var s = this._get_settings().core.html_titles; obj = obj.children("a:eq(0)"); if(s) { obj = obj.clone(); obj.children("INS").remove(); return obj.html(); } else { obj = obj.contents().filter(function() { return this.nodeType == 3; })[0]; return obj.nodeValue; } }, set_text : function (obj, val) { obj = this._get_node(obj); if(!obj.length) { return false; } obj = obj.children("a:eq(0)"); if(this._get_settings().core.html_titles) { var tmp = obj.children("INS").clone(); obj.html(val).prepend(tmp); this.__callback({ "obj" : obj, "name" : val }); return true; } else { obj = obj.contents().filter(function() { return this.nodeType == 3; })[0]; this.__callback({ "obj" : obj, "name" : val }); return (obj.nodeValue = val); } }, rename_node : function (obj, val) { obj = this._get_node(obj); this.__rollback(); if(obj && obj.length && this.set_text.apply(this, Array.prototype.slice.call(arguments))) { this.__callback({ "obj" : obj, "name" : val }); } }, // Basic operations: deleting nodes delete_node : function (obj) { obj = this._get_node(obj); if(!obj.length) { return false; } this.__rollback(); var p = this._get_parent(obj), prev = $([]), t = this; obj.each(function () { prev = prev.add(t._get_prev(this)); }); obj = obj.detach(); if(p !== -1 && p.find("> ul > li").length === 0) { p.removeClass("jstree-open jstree-closed").addClass("jstree-leaf"); } this.clean_node(p); this.__callback({ "obj" : obj, "prev" : prev, "parent" : p }); return obj; }, prepare_move : function (o, r, pos, cb, is_cb) { var p = {}; p.ot = $.jstree._reference(o) || this; p.o = p.ot._get_node(o); p.r = r === - 1 ? -1 : this._get_node(r); p.p = (typeof pos === "undefined" || pos === false) ? "last" : pos; // TODO: move to a setting if(!is_cb && prepared_move.o && prepared_move.o[0] === p.o[0] && prepared_move.r[0] === p.r[0] && prepared_move.p === p.p) { this.__callback(prepared_move); if(cb) { cb.call(this, prepared_move); } return; } p.ot = $.jstree._reference(p.o) || this; p.rt = $.jstree._reference(p.r) || this; // r === -1 ? p.ot : $.jstree._reference(p.r) || this if(p.r === -1 || !p.r) { p.cr = -1; switch(p.p) { case "first": case "before": case "inside": p.cp = 0; break; case "after": case "last": p.cp = p.rt.get_container().find(" > ul > li").length; break; default: p.cp = p.p; break; } } else { if(!/^(before|after)$/.test(p.p) && !this._is_loaded(p.r)) { return this.load_node(p.r, function () { this.prepare_move(o, r, pos, cb, true); }); } switch(p.p) { case "before": p.cp = p.r.index(); p.cr = p.rt._get_parent(p.r); break; case "after": p.cp = p.r.index() + 1; p.cr = p.rt._get_parent(p.r); break; case "inside": case "first": p.cp = 0; p.cr = p.r; break; case "last": p.cp = p.r.find(" > ul > li").length; p.cr = p.r; break; default: p.cp = p.p; p.cr = p.r; break; } } p.np = p.cr == -1 ? p.rt.get_container() : p.cr; p.op = p.ot._get_parent(p.o); p.cop = p.o.index(); if(p.op === -1) { p.op = p.ot ? p.ot.get_container() : this.get_container(); } if(!/^(before|after)$/.test(p.p) && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp++; } //if(p.p === "before" && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp--; } p.or = p.np.find(" > ul > li:nth-child(" + (p.cp + 1) + ")"); prepared_move = p; this.__callback(prepared_move); if(cb) { cb.call(this, prepared_move); } }, check_move : function () { var obj = prepared_move, ret = true, r = obj.r === -1 ? this.get_container() : obj.r; if(!obj || !obj.o || obj.or[0] === obj.o[0]) { return false; } if(obj.op && obj.np && obj.op[0] === obj.np[0] && obj.cp - 1 === obj.o.index()) { return false; } obj.o.each(function () { if(r.parentsUntil(".jstree", "li").andSelf().index(this) !== -1) { ret = false; return false; } }); return ret; }, move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) { if(!is_prepared) { return this.prepare_move(obj, ref, position, function (p) { this.move_node(p, false, false, is_copy, true, skip_check); }); } if(is_copy) { prepared_move.cy = true; } if(!skip_check && !this.check_move()) { return false; } this.__rollback(); var o = false; if(is_copy) { o = obj.o.clone(true); o.find("*[id]").andSelf().each(function () { if(this.id) { this.id = "copy_" + this.id; } }); } else { o = obj.o; } if(obj.or.length) { obj.or.before(o); } else { if(!obj.np.children("ul").length) { $("<ul />").appendTo(obj.np); } obj.np.children("ul:eq(0)").append(o); } try { obj.ot.clean_node(obj.op); obj.rt.clean_node(obj.np); if(!obj.op.find("> ul > li").length) { obj.op.removeClass("jstree-open jstree-closed").addClass("jstree-leaf").children("ul").remove(); } } catch (e) { } if(is_copy) { prepared_move.cy = true; prepared_move.oc = o; } this.__callback(prepared_move); return prepared_move; }, _get_move : function () { return prepared_move; } } }); })(jQuery); //*/ /* * jsTree ui plugin * This plugins handles selecting/deselecting/hovering/dehovering nodes */ (function ($) { var scrollbar_width, e1, e2; $(function() { if (/msie/.test(navigator.userAgent.toLowerCase())) { e1 = $('<textarea cols="10" rows="2"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body'); e2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body'); scrollbar_width = e1.width() - e2.width(); e1.add(e2).remove(); } else { e1 = $('<div />').css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: 0 }) .prependTo('body').append('<div />').find('div').css({ width: '100%', height: 200 }); scrollbar_width = 100 - e1.width(); e1.parent().remove(); } }); $.jstree.plugin("ui", { __init : function () { this.data.ui.selected = $(); this.data.ui.last_selected = false; this.data.ui.hovered = null; this.data.ui.to_select = this.get_settings().ui.initially_select; this.get_container() .delegate("a", "click.jstree", $.proxy(function (event) { event.preventDefault(); event.currentTarget.blur(); if(!$(event.currentTarget).hasClass("jstree-loading")) { this.select_node(event.currentTarget, true, event); } }, this)) .delegate("a", "mouseenter.jstree", $.proxy(function (event) { if(!$(event.currentTarget).hasClass("jstree-loading")) { this.hover_node(event.target); } }, this)) .delegate("a", "mouseleave.jstree", $.proxy(function (event) { if(!$(event.currentTarget).hasClass("jstree-loading")) { this.dehover_node(event.target); } }, this)) .bind("reopen.jstree", $.proxy(function () { this.reselect(); }, this)) .bind("get_rollback.jstree", $.proxy(function () { this.dehover_node(); this.save_selected(); }, this)) .bind("set_rollback.jstree", $.proxy(function () { this.reselect(); }, this)) .bind("close_node.jstree", $.proxy(function (event, data) { var s = this._get_settings().ui, obj = this._get_node(data.rslt.obj), clk = (obj && obj.length) ? obj.children("ul").find("a.jstree-clicked") : $(), _this = this; if(s.selected_parent_close === false || !clk.length) { return; } clk.each(function () { _this.deselect_node(this); if(s.selected_parent_close === "select_parent") { _this.select_node(obj); } }); }, this)) .bind("delete_node.jstree", $.proxy(function (event, data) { var s = this._get_settings().ui.select_prev_on_delete, obj = this._get_node(data.rslt.obj), clk = (obj && obj.length) ? obj.find("a.jstree-clicked") : [], _this = this; clk.each(function () { _this.deselect_node(this); }); if(s && clk.length) { data.rslt.prev.each(function () { if(this.parentNode) { _this.select_node(this); return false; /* if return false is removed all prev nodes will be selected */} }); } }, this)) .bind("move_node.jstree", $.proxy(function (event, data) { if(data.rslt.cy) { data.rslt.oc.find("a.jstree-clicked").removeClass("jstree-clicked"); } }, this)); }, defaults : { select_limit : -1, // 0, 1, 2 ... or -1 for unlimited select_multiple_modifier : "ctrl", // on, or ctrl, shift, alt select_range_modifier : "shift", selected_parent_close : "select_parent", // false, "deselect", "select_parent" selected_parent_open : true, select_prev_on_delete : true, disable_selecting_children : false, initially_select : [] }, _fn : { _get_node : function (obj, allow_multiple) { if(typeof obj === "undefined" || obj === null) { return allow_multiple ? this.data.ui.selected : this.data.ui.last_selected; } var $obj = $(obj, this.get_container()); if($obj.is(".jstree") || obj == -1) { return -1; } $obj = $obj.closest("li", this.get_container()); return $obj.length ? $obj : false; }, _ui_notify : function (n, data) { if(data.selected) { this.select_node(n, false); } }, save_selected : function () { var _this = this; this.data.ui.to_select = []; this.data.ui.selected.each(function () { if(this.id) { _this.data.ui.to_select.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); } }); this.__callback(this.data.ui.to_select); }, reselect : function () { var _this = this, s = this.data.ui.to_select; s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); }); // this.deselect_all(); WHY deselect, breaks plugin state notifier? $.each(s, function (i, val) { if(val && val !== "#") { _this.select_node(val); } }); this.data.ui.selected = this.data.ui.selected.filter(function () { return this.parentNode; }); this.__callback(); }, refresh : function (obj) { this.save_selected(); return this.__call_old(); }, hover_node : function (obj) { obj = this._get_node(obj); if(!obj.length) { return false; } //if(this.data.ui.hovered && obj.get(0) === this.data.ui.hovered.get(0)) { return; } if(!obj.hasClass("jstree-hovered")) { this.dehover_node(); } this.data.ui.hovered = obj.children("a").addClass("jstree-hovered").parent(); this._fix_scroll(obj); this.__callback({ "obj" : obj }); }, dehover_node : function () { var obj = this.data.ui.hovered, p; if(!obj || !obj.length) { return false; } p = obj.children("a").removeClass("jstree-hovered").parent(); if(this.data.ui.hovered[0] === p[0]) { this.data.ui.hovered = null; } this.__callback({ "obj" : obj }); }, select_node : function (obj, check, e) { obj = this._get_node(obj); if(obj == -1 || !obj || !obj.length) { return false; } var s = this._get_settings().ui, is_multiple = (s.select_multiple_modifier == "on" || (s.select_multiple_modifier !== false && e && e[s.select_multiple_modifier + "Key"])), is_range = (s.select_range_modifier !== false && e && e[s.select_range_modifier + "Key"] && this.data.ui.last_selected && this.data.ui.last_selected[0] !== obj[0] && this.data.ui.last_selected.parent()[0] === obj.parent()[0]), is_selected = this.is_selected(obj), proceed = true, t = this; if(check) { if(s.disable_selecting_children && is_multiple && ( (obj.parentsUntil(".jstree","li").children("a.jstree-clicked").length) || (obj.children("ul").find("a.jstree-clicked:eq(0)").length) ) ) { return false; } proceed = false; switch(!0) { case (is_range): this.data.ui.last_selected.addClass("jstree-last-selected"); obj = obj[ obj.index() < this.data.ui.last_selected.index() ? "nextUntil" : "prevUntil" ](".jstree-last-selected").andSelf(); if(s.select_limit == -1 || obj.length < s.select_limit) { this.data.ui.last_selected.removeClass("jstree-last-selected"); this.data.ui.selected.each(function () { if(this !== t.data.ui.last_selected[0]) { t.deselect_node(this); } }); is_selected = false; proceed = true; } else { proceed = false; } break; case (is_selected && !is_multiple): this.deselect_all(); is_selected = false; proceed = true; break; case (!is_selected && !is_multiple): if(s.select_limit == -1 || s.select_limit > 0) { this.deselect_all(); proceed = true; } break; case (is_selected && is_multiple): this.deselect_node(obj); break; case (!is_selected && is_multiple): if(s.select_limit == -1 || this.data.ui.selected.length + 1 <= s.select_limit) { proceed = true; } break; } } if(proceed && !is_selected) { if(!is_range) { this.data.ui.last_selected = obj; } obj.children("a").addClass("jstree-clicked"); if(s.selected_parent_open) { obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); }); } this.data.ui.selected = this.data.ui.selected.add(obj); this._fix_scroll(obj.eq(0)); this.__callback({ "obj" : obj, "e" : e }); } }, _fix_scroll : function (obj) { var c = this.get_container()[0], t; if(c.scrollHeight > c.offsetHeight) { obj = this._get_node(obj); if(!obj || obj === -1 || !obj.length || !obj.is(":visible")) { return; } t = obj.offset().top - this.get_container().offset().top; if(t < 0) { c.scrollTop = c.scrollTop + t - 1; } if(t + this.data.core.li_height + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0) > c.offsetHeight) { c.scrollTop = c.scrollTop + (t - c.offsetHeight + this.data.core.li_height + 1 + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0)); } } }, deselect_node : function (obj) { obj = this._get_node(obj); if(!obj.length) { return false; } if(this.is_selected(obj)) { obj.children("a").removeClass("jstree-clicked"); this.data.ui.selected = this.data.ui.selected.not(obj); if(this.data.ui.last_selected.get(0) === obj.get(0)) { this.data.ui.last_selected = this.data.ui.selected.eq(0); } this.__callback({ "obj" : obj }); } }, toggle_select : function (obj) { obj = this._get_node(obj); if(!obj.length) { return false; } if(this.is_selected(obj)) { this.deselect_node(obj); } else { this.select_node(obj); } }, is_selected : function (obj) { return this.data.ui.selected.index(this._get_node(obj)) >= 0; }, get_selected : function (context) { return context ? $(context).find("a.jstree-clicked").parent() : this.data.ui.selected; }, deselect_all : function (context) { var ret = context ? $(context).find("a.jstree-clicked").parent() : this.get_container().find("a.jstree-clicked").parent(); ret.children("a.jstree-clicked").removeClass("jstree-clicked"); this.data.ui.selected = $([]); this.data.ui.last_selected = false; this.__callback({ "obj" : ret }); } } }); // include the selection plugin by default $.jstree.defaults.plugins.push("ui"); })(jQuery); //*/ /* * jsTree CRRM plugin * Handles creating/renaming/removing/moving nodes by user interaction. */ (function ($) { $.jstree.plugin("crrm", { __init : function () { this.get_container() .bind("move_node.jstree", $.proxy(function (e, data) { if(this._get_settings().crrm.move.open_onmove) { var t = this; data.rslt.np.parentsUntil(".jstree").andSelf().filter(".jstree-closed").each(function () { t.open_node(this, false, true); }); } }, this)); }, defaults : { input_width_limit : 200, move : { always_copy : false, // false, true or "multitree" open_onmove : true, default_position : "last", check_move : function (m) { return true; } } }, _fn : { _show_input : function (obj, callback) { obj = this._get_node(obj); var rtl = this._get_settings().core.rtl, w = this._get_settings().crrm.input_width_limit, w1 = obj.children("ins").width(), w2 = obj.find("> a:visible > ins").width() * obj.find("> a:visible > ins").length, t = this.get_text(obj), h1 = $("<div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"), h2 = obj.css("position","relative").append( $("<input />", { "value" : t, "class" : "jstree-rename-input", // "size" : t.length, "css" : { "padding" : "0", "border" : "1px solid silver", "position" : "absolute", "left" : (rtl ? "auto" : (w1 + w2 + 4) + "px"), "right" : (rtl ? (w1 + w2 + 4) + "px" : "auto"), "top" : "0px", "height" : (this.data.core.li_height - 2) + "px", "lineHeight" : (this.data.core.li_height - 2) + "px", "width" : "150px" // will be set a bit further down }, "blur" : $.proxy(function () { var i = obj.children(".jstree-rename-input"), v = i.val(); if(v === "") { v = t; } h1.remove(); i.remove(); // rollback purposes this.set_text(obj,t); // rollback purposes this.rename_node(obj, v); callback.call(this, obj, v, t); obj.css("position",""); }, this), "keyup" : function (event) { var key = event.keyCode || event.which; if(key == 27) { this.value = t; this.blur(); return; } else if(key == 13) { this.blur(); return; } else { h2.width(Math.min(h1.text("pW" + this.value).width(),w)); } }, "keypress" : function(event) { var key = event.keyCode || event.which; if(key == 13) { return false; } } }) ).children(".jstree-rename-input"); this.set_text(obj, ""); h1.css({ fontFamily : h2.css('fontFamily') || '', fontSize : h2.css('fontSize') || '', fontWeight : h2.css('fontWeight') || '', fontStyle : h2.css('fontStyle') || '', fontStretch : h2.css('fontStretch') || '', fontVariant : h2.css('fontVariant') || '', letterSpacing : h2.css('letterSpacing') || '', wordSpacing : h2.css('wordSpacing') || '' }); h2.width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select(); }, rename : function (obj) { obj = this._get_node(obj); this.__rollback(); var f = this.__callback; this._show_input(obj, function (obj, new_name, old_name) { f.call(this, { "obj" : obj, "new_name" : new_name, "old_name" : old_name }); }); }, create : function (obj, position, js, callback, skip_rename) { var t, _this = this; obj = this._get_node(obj); if(!obj) { obj = -1; } this.__rollback(); t = this.create_node(obj, position, js, function (t) { var p = this._get_parent(t), pos = $(t).index(); if(callback) { callback.call(this, t); } if(p.length && p.hasClass("jstree-closed")) { this.open_node(p, false, true); } if(!skip_rename) { this._show_input(t, function (obj, new_name, old_name) { _this.__callback({ "obj" : obj, "name" : new_name, "parent" : p, "position" : pos }); }); } else { _this.__callback({ "obj" : t, "name" : this.get_text(t), "parent" : p, "position" : pos }); } }); return t; }, remove : function (obj) { obj = this._get_node(obj, true); var p = this._get_parent(obj), prev = this._get_prev(obj); this.__rollback(); obj = this.delete_node(obj); if(obj !== false) { this.__callback({ "obj" : obj, "prev" : prev, "parent" : p }); } }, check_move : function () { if(!this.__call_old()) { return false; } var s = this._get_settings().crrm.move; if(!s.check_move.call(this, this._get_move())) { return false; } return true; }, move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) { var s = this._get_settings().crrm.move; if(!is_prepared) { if(typeof position === "undefined") { position = s.default_position; } if(position === "inside" && !s.default_position.match(/^(before|after)$/)) { position = s.default_position; } return this.__call_old(true, obj, ref, position, is_copy, false, skip_check); } // if the move is already prepared if(s.always_copy === true || (s.always_copy === "multitree" && obj.rt.get_index() !== obj.ot.get_index() )) { is_copy = true; } this.__call_old(true, obj, ref, position, is_copy, true, skip_check); }, cut : function (obj) { obj = this._get_node(obj, true); if(!obj || !obj.length) { return false; } this.data.crrm.cp_nodes = false; this.data.crrm.ct_nodes = obj; this.__callback({ "obj" : obj }); }, copy : function (obj) { obj = this._get_node(obj, true); if(!obj || !obj.length) { return false; } this.data.crrm.ct_nodes = false; this.data.crrm.cp_nodes = obj; this.__callback({ "obj" : obj }); }, paste : function (obj) { obj = this._get_node(obj); if(!obj || !obj.length) { return false; } var nodes = this.data.crrm.ct_nodes ? this.data.crrm.ct_nodes : this.data.crrm.cp_nodes; if(!this.data.crrm.ct_nodes && !this.data.crrm.cp_nodes) { return false; } if(this.data.crrm.ct_nodes) { this.move_node(this.data.crrm.ct_nodes, obj); this.data.crrm.ct_nodes = false; } if(this.data.crrm.cp_nodes) { this.move_node(this.data.crrm.cp_nodes, obj, false, true); } this.__callback({ "obj" : obj, "nodes" : nodes }); } } }); // include the crr plugin by default // $.jstree.defaults.plugins.push("crrm"); })(jQuery); //*/ /* * jsTree themes plugin * Handles loading and setting themes, as well as detecting path to themes, etc. */ (function ($) { var themes_loaded = []; // this variable stores the path to the themes folder - if left as false - it will be autodetected $.jstree._themes = false; $.jstree.plugin("themes", { __init : function () { this.get_container() .bind("init.jstree", $.proxy(function () { var s = this._get_settings().themes; this.data.themes.dots = s.dots; this.data.themes.icons = s.icons; this.set_theme(s.theme, s.url); }, this)) .bind("loaded.jstree", $.proxy(function () { // bound here too, as simple HTML tree's won't honor dots & icons otherwise if(!this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } if(!this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } }, this)); }, defaults : { theme : "default", url : false, dots : true, icons : true }, _fn : { set_theme : function (theme_name, theme_url) { if(!theme_name) { return false; } if(!theme_url) { theme_url = $.jstree._themes + theme_name + '/style.css'; } if($.inArray(theme_url, themes_loaded) == -1) { $.vakata.css.add_sheet({ "url" : theme_url }); themes_loaded.push(theme_url); } if(this.data.themes.theme != theme_name) { this.get_container().removeClass('jstree-' + this.data.themes.theme); this.data.themes.theme = theme_name; } this.get_container().addClass('jstree-' + theme_name); if(!this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } if(!this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } this.__callback(); }, get_theme : function () { return this.data.themes.theme; }, show_dots : function () { this.data.themes.dots = true; this.get_container().children("ul").removeClass("jstree-no-dots"); }, hide_dots : function () { this.data.themes.dots = false; this.get_container().children("ul").addClass("jstree-no-dots"); }, toggle_dots : function () { if(this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } }, show_icons : function () { this.data.themes.icons = true; this.get_container().children("ul").removeClass("jstree-no-icons"); }, hide_icons : function () { this.data.themes.icons = false; this.get_container().children("ul").addClass("jstree-no-icons"); }, toggle_icons: function () { if(this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } } } }); // autodetect themes path $(function () { if($.jstree._themes === false) { $("script").each(function () { if(this.src.toString().match(/jquery\.jstree[^\/]*?\.js(\?.*)?$/)) { $.jstree._themes = this.src.toString().replace(/jquery\.jstree[^\/]*?\.js(\?.*)?$/, "") + 'themes/'; return false; } }); } if($.jstree._themes === false) { $.jstree._themes = "themes/"; } }); // include the themes plugin by default $.jstree.defaults.plugins.push("themes"); })(jQuery); //*/ /* * jsTree hotkeys plugin * Enables keyboard navigation for all tree instances * Depends on the jstree ui & jquery hotkeys plugins */ (function ($) { var bound = []; function exec(i, event) { var f = $.jstree._focused(), tmp; if(f && f.data && f.data.hotkeys && f.data.hotkeys.enabled) { tmp = f._get_settings().hotkeys[i]; if(tmp) { return tmp.call(f, event); } } } $.jstree.plugin("hotkeys", { __init : function () { if(typeof $.hotkeys === "undefined") { throw "jsTree hotkeys: jQuery hotkeys plugin not included."; } if(!this.data.ui) { throw "jsTree hotkeys: jsTree UI plugin not included."; } $.each(this._get_settings().hotkeys, function (i, v) { if(v !== false && $.inArray(i, bound) == -1) { $(document).bind("keydown", i, function (event) { return exec(i, event); }); bound.push(i); } }); this.get_container() .bind("lock.jstree", $.proxy(function () { if(this.data.hotkeys.enabled) { this.data.hotkeys.enabled = false; this.data.hotkeys.revert = true; } }, this)) .bind("unlock.jstree", $.proxy(function () { if(this.data.hotkeys.revert) { this.data.hotkeys.enabled = true; } }, this)); this.enable_hotkeys(); }, defaults : { "up" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_prev(o)); return false; }, "ctrl+up" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_prev(o)); return false; }, "shift+up" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_prev(o)); return false; }, "down" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_next(o)); return false; }, "ctrl+down" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_next(o)); return false; }, "shift+down" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected || -1; this.hover_node(this._get_next(o)); return false; }, "left" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o) { if(o.hasClass("jstree-open")) { this.close_node(o); } else { this.hover_node(this._get_prev(o)); } } return false; }, "ctrl+left" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o) { if(o.hasClass("jstree-open")) { this.close_node(o); } else { this.hover_node(this._get_prev(o)); } } return false; }, "shift+left" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o) { if(o.hasClass("jstree-open")) { this.close_node(o); } else { this.hover_node(this._get_prev(o)); } } return false; }, "right" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o && o.length) { if(o.hasClass("jstree-closed")) { this.open_node(o); } else { this.hover_node(this._get_next(o)); } } return false; }, "ctrl+right" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o && o.length) { if(o.hasClass("jstree-closed")) { this.open_node(o); } else { this.hover_node(this._get_next(o)); } } return false; }, "shift+right" : function () { var o = this.data.ui.hovered || this.data.ui.last_selected; if(o && o.length) { if(o.hasClass("jstree-closed")) { this.open_node(o); } else { this.hover_node(this._get_next(o)); } } return false; }, "space" : function () { if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").click(); } return false; }, "ctrl+space" : function (event) { event.type = "click"; if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } return false; }, "shift+space" : function (event) { event.type = "click"; if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } return false; }, "f2" : function () { this.rename(this.data.ui.hovered || this.data.ui.last_selected); }, "del" : function () { this.remove(this.data.ui.hovered || this._get_node(null)); } }, _fn : { enable_hotkeys : function () { this.data.hotkeys.enabled = true; }, disable_hotkeys : function () { this.data.hotkeys.enabled = false; } } }); })(jQuery); //*/ /* * jsTree JSON plugin * The JSON data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions. */ (function ($) { $.jstree.plugin("json_data", { __init : function() { var s = this._get_settings().json_data; if(s.progressive_unload) { this.get_container().bind("after_close.jstree", function (e, data) { data.rslt.obj.children("ul").remove(); }); } }, defaults : { // `data` can be a function: // * accepts two arguments - node being loaded and a callback to pass the result to // * will be executed in the current tree's scope & ajax won't be supported data : false, ajax : false, correct_state : true, progressive_render : false, progressive_unload : false }, _fn : { load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_json(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); }, _is_loaded : function (obj) { var s = this._get_settings().json_data; obj = this._get_node(obj); return obj == -1 || !obj || (!s.ajax && !s.progressive_render && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").length > 0; }, refresh : function (obj) { obj = this._get_node(obj); var s = this._get_settings().json_data; if(obj && obj !== -1 && s.progressive_unload && ($.isFunction(s.data) || !!s.ajax)) { obj.removeData("jstree_children"); } return this.__call_old(); }, load_node_json : function (obj, s_call, e_call) { var s = this.get_settings().json_data, d, error_func = function () {}, success_func = function () {}; obj = this._get_node(obj); if(obj && obj !== -1 && (s.progressive_render || s.progressive_unload) && !obj.is(".jstree-open, .jstree-leaf") && obj.children("ul").children("li").length === 0 && obj.data("jstree_children")) { d = this._parse_json(obj.data("jstree_children"), obj); if(d) { obj.append(d); if(!s.progressive_unload) { obj.removeData("jstree_children"); } } this.clean_node(obj); if(s_call) { s_call.call(this); } return; } if(obj && obj !== -1) { if(obj.data("jstree_is_loading")) { return; } else { obj.data("jstree_is_loading",true); } } switch(!0) { case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied."; // function option added here for easier model integration (also supporting async - see callback) case ($.isFunction(s.data)): s.data.call(this, obj, $.proxy(function (d) { d = this._parse_json(d, obj); if(!d) { if(obj === -1 || !obj) { if(s.correct_state) { this.get_container().children("ul").empty(); } } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); } } if(e_call) { e_call.call(this); } } else { if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); } else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); } this.clean_node(obj); if(s_call) { s_call.call(this); } } }, this)); break; case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)): if(!obj || obj == -1) { d = this._parse_json(s.data, obj); if(d) { this.get_container().children("ul").empty().append(d.children()); this.clean_node(); } else { if(s.correct_state) { this.get_container().children("ul").empty(); } } } if(s_call) { s_call.call(this); } break; case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1): error_func = function (x, t, e) { var ef = this.get_settings().json_data.ajax.error; if(ef) { ef.call(this, x, t, e); } if(obj != -1 && obj.length) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(t === "success" && s.correct_state) { this.correct_state(obj); } } else { if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); } } if(e_call) { e_call.call(this); } }; success_func = function (d, t, x) { var sf = this.get_settings().json_data.ajax.success; if(sf) { d = sf.call(this,d,t,x) || d; } if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "") || (!$.isArray(d) && !$.isPlainObject(d))) { return error_func.call(this, x, t, ""); } d = this._parse_json(d, obj); if(d) { if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); } else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); } this.clean_node(obj); if(s_call) { s_call.call(this); } } else { if(obj === -1 || !obj) { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); if(s_call) { s_call.call(this); } } } } }; s.ajax.context = this; s.ajax.error = error_func; s.ajax.success = success_func; if(!s.ajax.dataType) { s.ajax.dataType = "json"; } if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); } if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); } $.ajax(s.ajax); break; } }, _parse_json : function (js, obj, is_callback) { var d = false, p = this._get_settings(), s = p.json_data, t = p.core.html_titles, tmp, i, j, ul1, ul2; if(!js) { return d; } if(s.progressive_unload && obj && obj !== -1) { obj.data("jstree_children", d); } if($.isArray(js)) { d = $(); if(!js.length) { return false; } for(i = 0, j = js.length; i < j; i++) { tmp = this._parse_json(js[i], obj, true); if(tmp.length) { d = d.add(tmp); } } } else { if(typeof js == "string") { js = { data : js }; } if(!js.data && js.data !== "") { return d; } d = $("<li />"); if(js.attr) { d.attr(js.attr); } if(js.metadata) { d.data(js.metadata); } if(js.state) { d.addClass("jstree-" + js.state); } if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); } $.each(js.data, function (i, m) { tmp = $("<a />"); if($.isFunction(m)) { m = m.call(this, js); } if(typeof m == "string") { tmp.attr('href','#')[ t ? "html" : "text" ](m); } else { if(!m.attr) { m.attr = {}; } if(!m.attr.href) { m.attr.href = '#'; } tmp.attr(m.attr)[ t ? "html" : "text" ](m.title); if(m.language) { tmp.addClass(m.language); } } tmp.prepend("<ins class='jstree-icon'>&#160;</ins>"); if(!m.icon && js.icon) { m.icon = js.icon; } if(m.icon) { if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); } else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); } } d.append(tmp); }); d.prepend("<ins class='jstree-icon'>&#160;</ins>"); if(js.children) { if(s.progressive_render && js.state !== "open") { d.addClass("jstree-closed").data("jstree_children", js.children); } else { if(s.progressive_unload) { d.data("jstree_children", js.children); } if($.isArray(js.children) && js.children.length) { tmp = this._parse_json(js.children, obj, true); if(tmp.length) { ul2 = $("<ul />"); ul2.append(tmp); d.append(ul2); } } } } } if(!is_callback) { ul1 = $("<ul />"); ul1.append(d); d = ul1; } return d; }, get_json : function (obj, li_attr, a_attr, is_callback) { var result = [], s = this._get_settings(), _this = this, tmp1, tmp2, li, a, t, lang; obj = this._get_node(obj); if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); } li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ]; if(!is_callback && this.data.types) { li_attr.push(s.types.type_attr); } a_attr = $.isArray(a_attr) ? a_attr : [ ]; obj.each(function () { li = $(this); tmp1 = { data : [] }; if(li_attr.length) { tmp1.attr = { }; } $.each(li_attr, function (i, v) { tmp2 = li.attr(v); if(tmp2 && tmp2.length && tmp2.replace(/jstree[^ ]*/ig,'').length) { tmp1.attr[v] = (" " + tmp2).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,""); } }); if(li.hasClass("jstree-open")) { tmp1.state = "open"; } if(li.hasClass("jstree-closed")) { tmp1.state = "closed"; } if(li.data()) { tmp1.metadata = li.data(); } a = li.children("a"); a.each(function () { t = $(this); if( a_attr.length || $.inArray("languages", s.plugins) !== -1 || t.children("ins").get(0).style.backgroundImage.length || (t.children("ins").get(0).className && t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').length) ) { lang = false; if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) { $.each(s.languages, function (l, lv) { if(t.hasClass(lv)) { lang = lv; return false; } }); } tmp2 = { attr : { }, title : _this.get_text(t, lang) }; $.each(a_attr, function (k, z) { tmp2.attr[z] = (" " + (t.attr(z) || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,""); }); if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) { $.each(s.languages, function (k, z) { if(t.hasClass(z)) { tmp2.language = z; return true; } }); } if(t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) { tmp2.icon = t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,""); } if(t.children("ins").get(0).style.backgroundImage.length) { tmp2.icon = t.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")",""); } } else { tmp2 = _this.get_text(t); } if(a.length > 1) { tmp1.data.push(tmp2); } else { tmp1.data = tmp2; } }); li = li.find("> ul > li"); if(li.length) { tmp1.children = _this.get_json(li, li_attr, a_attr, true); } result.push(tmp1); }); return result; } } }); })(jQuery); //*/ /* * jsTree languages plugin * Adds support for multiple language versions in one tree * This basically allows for many titles coexisting in one node, but only one of them being visible at any given time * This is useful for maintaining the same structure in many languages (hence the name of the plugin) */ (function ($) { $.jstree.plugin("languages", { __init : function () { this._load_css(); }, defaults : [], _fn : { set_lang : function (i) { var langs = this._get_settings().languages, st = false, selector = ".jstree-" + this.get_index() + ' a'; if(!$.isArray(langs) || langs.length === 0) { return false; } if($.inArray(i,langs) == -1) { if(!!langs[i]) { i = langs[i]; } else { return false; } } if(i == this.data.languages.current_language) { return true; } st = $.vakata.css.get_css(selector + "." + this.data.languages.current_language, false, this.data.languages.language_css); if(st !== false) { st.style.display = "none"; } st = $.vakata.css.get_css(selector + "." + i, false, this.data.languages.language_css); if(st !== false) { st.style.display = ""; } this.data.languages.current_language = i; this.__callback(i); return true; }, get_lang : function () { return this.data.languages.current_language; }, _get_string : function (key, lang) { var langs = this._get_settings().languages, s = this._get_settings().core.strings; if($.isArray(langs) && langs.length) { lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language; } if(s[lang] && s[lang][key]) { return s[lang][key]; } if(s[key]) { return s[key]; } return key; }, get_text : function (obj, lang) { obj = this._get_node(obj) || this.data.ui.last_selected; if(!obj.size()) { return false; } var langs = this._get_settings().languages, s = this._get_settings().core.html_titles; if($.isArray(langs) && langs.length) { lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language; obj = obj.children("a." + lang); } else { obj = obj.children("a:eq(0)"); } if(s) { obj = obj.clone(); obj.children("INS").remove(); return obj.html(); } else { obj = obj.contents().filter(function() { return this.nodeType == 3; })[0]; return obj.nodeValue; } }, set_text : function (obj, val, lang) { obj = this._get_node(obj) || this.data.ui.last_selected; if(!obj.size()) { return false; } var langs = this._get_settings().languages, s = this._get_settings().core.html_titles, tmp; if($.isArray(langs) && langs.length) { lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language; obj = obj.children("a." + lang); } else { obj = obj.children("a:eq(0)"); } if(s) { tmp = obj.children("INS").clone(); obj.html(val).prepend(tmp); this.__callback({ "obj" : obj, "name" : val, "lang" : lang }); return true; } else { obj = obj.contents().filter(function() { return this.nodeType == 3; })[0]; this.__callback({ "obj" : obj, "name" : val, "lang" : lang }); return (obj.nodeValue = val); } }, _load_css : function () { var langs = this._get_settings().languages, str = "/* languages css */", selector = ".jstree-" + this.get_index() + ' a', ln; if($.isArray(langs) && langs.length) { this.data.languages.current_language = langs[0]; for(ln = 0; ln < langs.length; ln++) { str += selector + "." + langs[ln] + " {"; if(langs[ln] != this.data.languages.current_language) { str += " display:none; "; } str += " } "; } this.data.languages.language_css = $.vakata.css.add_sheet({ 'str' : str, 'title' : "jstree-languages" }); } }, create_node : function (obj, position, js, callback) { var t = this.__call_old(true, obj, position, js, function (t) { var langs = this._get_settings().languages, a = t.children("a"), ln; if($.isArray(langs) && langs.length) { for(ln = 0; ln < langs.length; ln++) { if(!a.is("." + langs[ln])) { t.append(a.eq(0).clone().removeClass(langs.join(" ")).addClass(langs[ln])); } } a.not("." + langs.join(", .")).remove(); } if(callback) { callback.call(this, t); } }); return t; } } }); })(jQuery); //*/ /* * jsTree cookies plugin * Stores the currently opened/selected nodes in a cookie and then restores them * Depends on the jquery.cookie plugin */ (function ($) { $.jstree.plugin("cookies", { __init : function () { if(typeof $.cookie === "undefined") { throw "jsTree cookie: jQuery cookie plugin not included."; } var s = this._get_settings().cookies, tmp; if(!!s.save_loaded) { tmp = $.cookie(s.save_loaded); if(tmp && tmp.length) { this.data.core.to_load = tmp.split(","); } } if(!!s.save_opened) { tmp = $.cookie(s.save_opened); if(tmp && tmp.length) { this.data.core.to_open = tmp.split(","); } } if(!!s.save_selected) { tmp = $.cookie(s.save_selected); if(tmp && tmp.length && this.data.ui) { this.data.ui.to_select = tmp.split(","); } } this.get_container() .one( ( this.data.ui ? "reselect" : "reopen" ) + ".jstree", $.proxy(function () { this.get_container() .bind("open_node.jstree close_node.jstree select_node.jstree deselect_node.jstree", $.proxy(function (e) { if(this._get_settings().cookies.auto_save) { this.save_cookie((e.handleObj.namespace + e.handleObj.type).replace("jstree","")); } }, this)); }, this)); }, defaults : { save_loaded : "jstree_load", save_opened : "jstree_open", save_selected : "jstree_select", auto_save : true, cookie_options : {} }, _fn : { save_cookie : function (c) { if(this.data.core.refreshing) { return; } var s = this._get_settings().cookies; if(!c) { // if called manually and not by event if(s.save_loaded) { this.save_loaded(); $.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options); } if(s.save_opened) { this.save_opened(); $.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options); } if(s.save_selected && this.data.ui) { this.save_selected(); $.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options); } return; } switch(c) { case "open_node": case "close_node": if(!!s.save_opened) { this.save_opened(); $.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options); } if(!!s.save_loaded) { this.save_loaded(); $.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options); } break; case "select_node": case "deselect_node": if(!!s.save_selected && this.data.ui) { this.save_selected(); $.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options); } break; } } } }); // include cookies by default // $.jstree.defaults.plugins.push("cookies"); })(jQuery); //*/ /* * jsTree sort plugin * Sorts items alphabetically (or using any other function) */ (function ($) { $.jstree.plugin("sort", { __init : function () { this.get_container() .bind("load_node.jstree", $.proxy(function (e, data) { var obj = this._get_node(data.rslt.obj); obj = obj === -1 ? this.get_container().children("ul") : obj.children("ul"); this.sort(obj); }, this)) .bind("rename_node.jstree create_node.jstree create.jstree", $.proxy(function (e, data) { this.sort(data.rslt.obj.parent()); }, this)) .bind("move_node.jstree", $.proxy(function (e, data) { var m = data.rslt.np == -1 ? this.get_container() : data.rslt.np; this.sort(m.children("ul")); }, this)); }, defaults : function (a, b) { return this.get_text(a) > this.get_text(b) ? 1 : -1; }, _fn : { sort : function (obj) { var s = this._get_settings().sort, t = this; obj.append($.makeArray(obj.children("li")).sort($.proxy(s, t))); obj.find("> li > ul").each(function() { t.sort($(this)); }); this.clean_node(obj); } } }); })(jQuery); //*/ /* * jsTree DND plugin * Drag and drop plugin for moving/copying nodes */ (function ($) { var o = false, r = false, m = false, ml = false, sli = false, sti = false, dir1 = false, dir2 = false, last_pos = false; $.vakata.dnd = { is_down : false, is_drag : false, helper : false, scroll_spd : 10, init_x : 0, init_y : 0, threshold : 5, helper_left : 5, helper_top : 10, user_data : {}, drag_start : function (e, data, html) { if($.vakata.dnd.is_drag) { $.vakata.drag_stop({}); } try { e.currentTarget.unselectable = "on"; e.currentTarget.onselectstart = function() { return false; }; if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; } } catch(err) { } $.vakata.dnd.init_x = e.pageX; $.vakata.dnd.init_y = e.pageY; $.vakata.dnd.user_data = data; $.vakata.dnd.is_down = true; $.vakata.dnd.helper = $("<div id='vakata-dragged' />").html(html); //.fadeTo(10,0.25); $(document).bind("mousemove", $.vakata.dnd.drag); $(document).bind("mouseup", $.vakata.dnd.drag_stop); return false; }, drag : function (e) { if(!$.vakata.dnd.is_down) { return; } if(!$.vakata.dnd.is_drag) { if(Math.abs(e.pageX - $.vakata.dnd.init_x) > 5 || Math.abs(e.pageY - $.vakata.dnd.init_y) > 5) { $.vakata.dnd.helper.appendTo("body"); $.vakata.dnd.is_drag = true; $(document).triggerHandler("drag_start.vakata", { "event" : e, "data" : $.vakata.dnd.user_data }); } else { return; } } // maybe use a scrolling parent element instead of document? if(e.type === "mousemove") { // thought of adding scroll in order to move the helper, but mouse poisition is n/a var d = $(document), t = d.scrollTop(), l = d.scrollLeft(); if(e.pageY - t < 20) { if(sti && dir1 === "down") { clearInterval(sti); sti = false; } if(!sti) { dir1 = "up"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() - $.vakata.dnd.scroll_spd); }, 150); } } else { if(sti && dir1 === "up") { clearInterval(sti); sti = false; } } if($(window).height() - (e.pageY - t) < 20) { if(sti && dir1 === "up") { clearInterval(sti); sti = false; } if(!sti) { dir1 = "down"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() + $.vakata.dnd.scroll_spd); }, 150); } } else { if(sti && dir1 === "down") { clearInterval(sti); sti = false; } } if(e.pageX - l < 20) { if(sli && dir2 === "right") { clearInterval(sli); sli = false; } if(!sli) { dir2 = "left"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() - $.vakata.dnd.scroll_spd); }, 150); } } else { if(sli && dir2 === "left") { clearInterval(sli); sli = false; } } if($(window).width() - (e.pageX - l) < 20) { if(sli && dir2 === "left") { clearInterval(sli); sli = false; } if(!sli) { dir2 = "right"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() + $.vakata.dnd.scroll_spd); }, 150); } } else { if(sli && dir2 === "right") { clearInterval(sli); sli = false; } } } $.vakata.dnd.helper.css({ left : (e.pageX + $.vakata.dnd.helper_left) + "px", top : (e.pageY + $.vakata.dnd.helper_top) + "px" }); $(document).triggerHandler("drag.vakata", { "event" : e, "data" : $.vakata.dnd.user_data }); }, drag_stop : function (e) { if(sli) { clearInterval(sli); } if(sti) { clearInterval(sti); } $(document).unbind("mousemove", $.vakata.dnd.drag); $(document).unbind("mouseup", $.vakata.dnd.drag_stop); $(document).triggerHandler("drag_stop.vakata", { "event" : e, "data" : $.vakata.dnd.user_data }); $.vakata.dnd.helper.remove(); $.vakata.dnd.init_x = 0; $.vakata.dnd.init_y = 0; $.vakata.dnd.user_data = {}; $.vakata.dnd.is_down = false; $.vakata.dnd.is_drag = false; } }; $(function() { var css_string = '#vakata-dragged { display:block; margin:0 0 0 0; padding:4px 4px 4px 24px; position:absolute; top:-2000px; line-height:16px; z-index:10000; } '; $.vakata.css.add_sheet({ str : css_string, title : "vakata" }); }); $.jstree.plugin("dnd", { __init : function () { this.data.dnd = { active : false, after : false, inside : false, before : false, off : false, prepared : false, w : 0, to1 : false, to2 : false, cof : false, cw : false, ch : false, i1 : false, i2 : false, mto : false }; this.get_container() .bind("mouseenter.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { if(this.data.themes) { m.attr("class", "jstree-" + this.data.themes.theme); if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); } $.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); } //if($(e.currentTarget).find("> ul > li").length === 0) { if(e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree var tr = $.jstree._reference(e.target), dc; if(tr.data.dnd.foreign) { dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true }); if(dc === true || dc.inside === true || dc.before === true || dc.after === true) { $.vakata.dnd.helper.children("ins").attr("class","jstree-ok"); } } else { tr.prepare_move(o, tr.get_container(), "last"); if(tr.check_move()) { $.vakata.dnd.helper.children("ins").attr("class","jstree-ok"); } } } } }, this)) .bind("mouseup.jstree", $.proxy(function (e) { //if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && $(e.currentTarget).find("> ul > li").length === 0) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree var tr = $.jstree._reference(e.currentTarget), dc; if(tr.data.dnd.foreign) { dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true }); if(dc === true || dc.inside === true || dc.before === true || dc.after === true) { tr._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : tr.get_container(), is_root : true }); } } else { tr.move_node(o, tr.get_container(), "last", e[tr._get_settings().dnd.copy_modifier + "Key"]); } } }, this)) .bind("mouseleave.jstree", $.proxy(function (e) { if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") { return false; } if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); } if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); } if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); } if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); } if($.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); } } }, this)) .bind("mousemove.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { var cnt = this.get_container()[0]; // Horizontal scroll if(e.pageX + 24 > this.data.dnd.cof.left + this.data.dnd.cw) { if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); } this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft += $.vakata.dnd.scroll_spd; }, cnt), 100); } else if(e.pageX - 24 < this.data.dnd.cof.left) { if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); } this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft -= $.vakata.dnd.scroll_spd; }, cnt), 100); } else { if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); } } // Vertical scroll if(e.pageY + 24 > this.data.dnd.cof.top + this.data.dnd.ch) { if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); } this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop += $.vakata.dnd.scroll_spd; }, cnt), 100); } else if(e.pageY - 24 < this.data.dnd.cof.top) { if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); } this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop -= $.vakata.dnd.scroll_spd; }, cnt), 100); } else { if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); } } } }, this)) .bind("scroll.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && m && ml) { m.hide(); ml.hide(); } }, this)) .delegate("a", "mousedown.jstree", $.proxy(function (e) { if(e.which === 1) { this.start_drag(e.currentTarget, e); return false; } }, this)) .delegate("a", "mouseenter.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { this.dnd_enter(e.currentTarget); } }, this)) .delegate("a", "mousemove.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { if(!r || !r.length || r.children("a")[0] !== e.currentTarget) { this.dnd_enter(e.currentTarget); } if(typeof this.data.dnd.off.top === "undefined") { this.data.dnd.off = $(e.target).offset(); } this.data.dnd.w = (e.pageY - (this.data.dnd.off.top || 0)) % this.data.core.li_height; if(this.data.dnd.w < 0) { this.data.dnd.w += this.data.core.li_height; } this.dnd_show(); } }, this)) .delegate("a", "mouseleave.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") { return false; } if(m) { m.hide(); } if(ml) { ml.hide(); } /* var ec = $(e.currentTarget).closest("li"), er = $(e.relatedTarget).closest("li"); if(er[0] !== ec.prev()[0] && er[0] !== ec.next()[0]) { if(m) { m.hide(); } if(ml) { ml.hide(); } } */ this.data.dnd.mto = setTimeout( (function (t) { return function () { t.dnd_leave(e); }; })(this), 0); } }, this)) .delegate("a", "mouseup.jstree", $.proxy(function (e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) { this.dnd_finish(e); } }, this)); $(document) .bind("drag_stop.vakata", $.proxy(function () { if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); } if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); } if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); } if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); } this.data.dnd.after = false; this.data.dnd.before = false; this.data.dnd.inside = false; this.data.dnd.off = false; this.data.dnd.prepared = false; this.data.dnd.w = false; this.data.dnd.to1 = false; this.data.dnd.to2 = false; this.data.dnd.i1 = false; this.data.dnd.i2 = false; this.data.dnd.active = false; this.data.dnd.foreign = false; if(m) { m.css({ "top" : "-2000px" }); } if(ml) { ml.css({ "top" : "-2000px" }); } }, this)) .bind("drag_start.vakata", $.proxy(function (e, data) { if(data.data.jstree) { var et = $(data.event.target); if(et.closest(".jstree").hasClass("jstree-" + this.get_index())) { this.dnd_enter(et); } } }, this)); /* .bind("keydown.jstree-" + this.get_index() + " keyup.jstree-" + this.get_index(), $.proxy(function(e) { if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && !this.data.dnd.foreign) { var h = $.vakata.dnd.helper.children("ins"); if(e[this._get_settings().dnd.copy_modifier + "Key"] && h.hasClass("jstree-ok")) { h.parent().html(h.parent().html().replace(/ \(Copy\)$/, "") + " (Copy)"); } else { h.parent().html(h.parent().html().replace(/ \(Copy\)$/, "")); } } }, this)); */ var s = this._get_settings().dnd; if(s.drag_target) { $(document) .delegate(s.drag_target, "mousedown.jstree-" + this.get_index(), $.proxy(function (e) { o = e.target; $.vakata.dnd.drag_start(e, { jstree : true, obj : e.target }, "<ins class='jstree-icon'></ins>" + $(e.target).text() ); if(this.data.themes) { if(m) { m.attr("class", "jstree-" + this.data.themes.theme); } if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); } $.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); } $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); var cnt = this.get_container(); this.data.dnd.cof = cnt.offset(); this.data.dnd.cw = parseInt(cnt.width(),10); this.data.dnd.ch = parseInt(cnt.height(),10); this.data.dnd.foreign = true; e.preventDefault(); }, this)); } if(s.drop_target) { $(document) .delegate(s.drop_target, "mouseenter.jstree-" + this.get_index(), $.proxy(function (e) { if(this.data.dnd.active && this._get_settings().dnd.drop_check.call(this, { "o" : o, "r" : $(e.target), "e" : e })) { $.vakata.dnd.helper.children("ins").attr("class","jstree-ok"); } }, this)) .delegate(s.drop_target, "mouseleave.jstree-" + this.get_index(), $.proxy(function (e) { if(this.data.dnd.active) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); } }, this)) .delegate(s.drop_target, "mouseup.jstree-" + this.get_index(), $.proxy(function (e) { if(this.data.dnd.active && $.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) { this._get_settings().dnd.drop_finish.call(this, { "o" : o, "r" : $(e.target), "e" : e }); } }, this)); } }, defaults : { copy_modifier : "ctrl", check_timeout : 100, open_timeout : 500, drop_target : ".jstree-drop", drop_check : function (data) { return true; }, drop_finish : $.noop, drag_target : ".jstree-draggable", drag_finish : $.noop, drag_check : function (data) { return { after : false, before : false, inside : true }; } }, _fn : { dnd_prepare : function () { if(!r || !r.length) { return; } this.data.dnd.off = r.offset(); if(this._get_settings().core.rtl) { this.data.dnd.off.right = this.data.dnd.off.left + r.width(); } if(this.data.dnd.foreign) { var a = this._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : r }); this.data.dnd.after = a.after; this.data.dnd.before = a.before; this.data.dnd.inside = a.inside; this.data.dnd.prepared = true; return this.dnd_show(); } this.prepare_move(o, r, "before"); this.data.dnd.before = this.check_move(); this.prepare_move(o, r, "after"); this.data.dnd.after = this.check_move(); if(this._is_loaded(r)) { this.prepare_move(o, r, "inside"); this.data.dnd.inside = this.check_move(); } else { this.data.dnd.inside = false; } this.data.dnd.prepared = true; return this.dnd_show(); }, dnd_show : function () { if(!this.data.dnd.prepared) { return; } var o = ["before","inside","after"], r = false, rtl = this._get_settings().core.rtl, pos; if(this.data.dnd.w < this.data.core.li_height/3) { o = ["before","inside","after"]; } else if(this.data.dnd.w <= this.data.core.li_height*2/3) { o = this.data.dnd.w < this.data.core.li_height/2 ? ["inside","before","after"] : ["inside","after","before"]; } else { o = ["after","inside","before"]; } $.each(o, $.proxy(function (i, val) { if(this.data.dnd[val]) { $.vakata.dnd.helper.children("ins").attr("class","jstree-ok"); r = val; return false; } }, this)); if(r === false) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); } pos = rtl ? (this.data.dnd.off.right - 18) : (this.data.dnd.off.left + 10); switch(r) { case "before": m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top - 6) + "px" }).show(); if(ml) { ml.css({ "left" : (pos + 8) + "px", "top" : (this.data.dnd.off.top - 1) + "px" }).show(); } break; case "after": m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 6) + "px" }).show(); if(ml) { ml.css({ "left" : (pos + 8) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 1) + "px" }).show(); } break; case "inside": m.css({ "left" : pos + ( rtl ? -4 : 4) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height/2 - 5) + "px" }).show(); if(ml) { ml.hide(); } break; default: m.hide(); if(ml) { ml.hide(); } break; } last_pos = r; return r; }, dnd_open : function () { this.data.dnd.to2 = false; this.open_node(r, $.proxy(this.dnd_prepare,this), true); }, dnd_finish : function (e) { if(this.data.dnd.foreign) { if(this.data.dnd.after || this.data.dnd.before || this.data.dnd.inside) { this._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : r, "p" : last_pos }); } } else { this.dnd_prepare(); this.move_node(o, r, last_pos, e[this._get_settings().dnd.copy_modifier + "Key"]); } o = false; r = false; m.hide(); if(ml) { ml.hide(); } }, dnd_enter : function (obj) { if(this.data.dnd.mto) { clearTimeout(this.data.dnd.mto); this.data.dnd.mto = false; } var s = this._get_settings().dnd; this.data.dnd.prepared = false; r = this._get_node(obj); if(s.check_timeout) { // do the calculations after a minimal timeout (users tend to drag quickly to the desired location) if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); } this.data.dnd.to1 = setTimeout($.proxy(this.dnd_prepare, this), s.check_timeout); } else { this.dnd_prepare(); } if(s.open_timeout) { if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); } if(r && r.length && r.hasClass("jstree-closed")) { // if the node is closed - open it, then recalculate this.data.dnd.to2 = setTimeout($.proxy(this.dnd_open, this), s.open_timeout); } } else { if(r && r.length && r.hasClass("jstree-closed")) { this.dnd_open(); } } }, dnd_leave : function (e) { this.data.dnd.after = false; this.data.dnd.before = false; this.data.dnd.inside = false; $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); m.hide(); if(ml) { ml.hide(); } if(r && r[0] === e.target.parentNode) { if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); this.data.dnd.to1 = false; } if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); this.data.dnd.to2 = false; } } }, start_drag : function (obj, e) { o = this._get_node(obj); if(this.data.ui && this.is_selected(o)) { o = this._get_node(null, true); } var dt = o.length > 1 ? this._get_string("multiple_selection") : this.get_text(o), cnt = this.get_container(); if(!this._get_settings().core.html_titles) { dt = dt.replace(/</ig,"&lt;").replace(/>/ig,"&gt;"); } $.vakata.dnd.drag_start(e, { jstree : true, obj : o }, "<ins class='jstree-icon'></ins>" + dt ); if(this.data.themes) { if(m) { m.attr("class", "jstree-" + this.data.themes.theme); } if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); } $.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); } this.data.dnd.cof = cnt.offset(); this.data.dnd.cw = parseInt(cnt.width(),10); this.data.dnd.ch = parseInt(cnt.height(),10); this.data.dnd.active = true; } } }); $(function() { var css_string = '' + '#vakata-dragged ins { display:block; text-decoration:none; width:16px; height:16px; margin:0 0 0 0; padding:0; position:absolute; top:4px; left:4px; ' + ' -moz-border-radius:4px; border-radius:4px; -webkit-border-radius:4px; ' + '} ' + '#vakata-dragged .jstree-ok { background:green; } ' + '#vakata-dragged .jstree-invalid { background:red; } ' + '#jstree-marker { padding:0; margin:0; font-size:12px; overflow:hidden; height:12px; width:8px; position:absolute; top:-30px; z-index:10001; background-repeat:no-repeat; display:none; background-color:transparent; text-shadow:1px 1px 1px white; color:black; line-height:10px; } ' + '#jstree-marker-line { padding:0; margin:0; line-height:0%; font-size:1px; overflow:hidden; height:1px; width:100px; position:absolute; top:-30px; z-index:10000; background-repeat:no-repeat; display:none; background-color:#456c43; ' + ' cursor:pointer; border:1px solid #eeeeee; border-left:0; -moz-box-shadow: 0px 0px 2px #666; -webkit-box-shadow: 0px 0px 2px #666; box-shadow: 0px 0px 2px #666; ' + ' -moz-border-radius:1px; border-radius:1px; -webkit-border-radius:1px; ' + '}' + ''; $.vakata.css.add_sheet({ str : css_string, title : "jstree" }); m = $("<div />").attr({ id : "jstree-marker" }).hide().html("&raquo;") .bind("mouseleave mouseenter", function (e) { m.hide(); ml.hide(); e.preventDefault(); e.stopImmediatePropagation(); return false; }) .appendTo("body"); ml = $("<div />").attr({ id : "jstree-marker-line" }).hide() .bind("mouseup", function (e) { if(r && r.length) { r.children("a").trigger(e); e.preventDefault(); e.stopImmediatePropagation(); return false; } }) .bind("mouseleave", function (e) { var rt = $(e.relatedTarget); if(rt.is(".jstree") || rt.closest(".jstree").length === 0) { if(r && r.length) { r.children("a").trigger(e); m.hide(); ml.hide(); e.preventDefault(); e.stopImmediatePropagation(); return false; } } }) .appendTo("body"); $(document).bind("drag_start.vakata", function (e, data) { if(data.data.jstree) { m.show(); if(ml) { ml.show(); } } }); $(document).bind("drag_stop.vakata", function (e, data) { if(data.data.jstree) { m.hide(); if(ml) { ml.hide(); } } }); }); })(jQuery); //*/ /* * jsTree checkbox plugin * Inserts checkboxes in front of every node * Depends on the ui plugin * DOES NOT WORK NICELY WITH MULTITREE DRAG'N'DROP */ (function ($) { $.jstree.plugin("checkbox", { __init : function () { this.data.checkbox.noui = this._get_settings().checkbox.override_ui; if(this.data.ui && this.data.checkbox.noui) { this.select_node = this.deselect_node = this.deselect_all = $.noop; this.get_selected = this.get_checked; } this.get_container() .bind("open_node.jstree create_node.jstree clean_node.jstree refresh.jstree", $.proxy(function (e, data) { this._prepare_checkboxes(data.rslt.obj); }, this)) .bind("loaded.jstree", $.proxy(function (e) { this._prepare_checkboxes(); }, this)) .delegate( (this.data.ui && this.data.checkbox.noui ? "a" : "ins.jstree-checkbox") , "click.jstree", $.proxy(function (e) { e.preventDefault(); if(this._get_node(e.target).hasClass("jstree-checked")) { this.uncheck_node(e.target); } else { this.check_node(e.target); } if(this.data.ui && this.data.checkbox.noui) { this.save_selected(); if(this.data.cookies) { this.save_cookie("select_node"); } } else { e.stopImmediatePropagation(); return false; } }, this)); }, defaults : { override_ui : false, two_state : false, real_checkboxes : false, checked_parent_open : true, real_checkboxes_names : function (n) { return [ ("check_" + (n[0].id || Math.ceil(Math.random() * 10000))) , 1]; } }, __destroy : function () { this.get_container() .find("input.jstree-real-checkbox").removeClass("jstree-real-checkbox").end() .find("ins.jstree-checkbox").remove(); }, _fn : { _checkbox_notify : function (n, data) { if(data.checked) { this.check_node(n, false); } }, _prepare_checkboxes : function (obj) { obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj); if(obj === false) { return; } // added for removing root nodes var c, _this = this, t, ts = this._get_settings().checkbox.two_state, rc = this._get_settings().checkbox.real_checkboxes, rcn = this._get_settings().checkbox.real_checkboxes_names; obj.each(function () { t = $(this); c = t.is("li") && (t.hasClass("jstree-checked") || (rc && t.children(":checked").length)) ? "jstree-checked" : "jstree-unchecked"; t.find("li").andSelf().each(function () { var $t = $(this), nm; $t.children("a" + (_this.data.languages ? "" : ":eq(0)") ).not(":has(.jstree-checkbox)").prepend("<ins class='jstree-checkbox'>&#160;</ins>").parent().not(".jstree-checked, .jstree-unchecked").addClass( ts ? "jstree-unchecked" : c ); if(rc) { if(!$t.children(":checkbox").length) { nm = rcn.call(_this, $t); $t.prepend("<input type='checkbox' class='jstree-real-checkbox' id='" + nm[0] + "' name='" + nm[0] + "' value='" + nm[1] + "' />"); } else { $t.children(":checkbox").addClass("jstree-real-checkbox"); } } if(!ts) { if(c === "jstree-checked" || $t.hasClass("jstree-checked") || $t.children(':checked').length) { $t.find("li").andSelf().addClass("jstree-checked").children(":checkbox").prop("checked", true); } } else { if($t.hasClass("jstree-checked") || $t.children(':checked').length) { $t.addClass("jstree-checked").children(":checkbox").prop("checked", true); } } }); }); if(!ts) { obj.find(".jstree-checked").parent().parent().each(function () { _this._repair_state(this); }); } }, change_state : function (obj, state) { obj = this._get_node(obj); var coll = false, rc = this._get_settings().checkbox.real_checkboxes; if(!obj || obj === -1) { return false; } state = (state === false || state === true) ? state : obj.hasClass("jstree-checked"); if(this._get_settings().checkbox.two_state) { if(state) { obj.removeClass("jstree-checked").addClass("jstree-unchecked"); if(rc) { obj.children(":checkbox").prop("checked", false); } } else { obj.removeClass("jstree-unchecked").addClass("jstree-checked"); if(rc) { obj.children(":checkbox").prop("checked", true); } } } else { if(state) { coll = obj.find("li").andSelf(); if(!coll.filter(".jstree-checked, .jstree-undetermined").length) { return false; } coll.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked"); if(rc) { coll.children(":checkbox").prop("checked", false); } } else { coll = obj.find("li").andSelf(); if(!coll.filter(".jstree-unchecked, .jstree-undetermined").length) { return false; } coll.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked"); if(rc) { coll.children(":checkbox").prop("checked", true); } if(this.data.ui) { this.data.ui.last_selected = obj; } this.data.checkbox.last_selected = obj; } obj.parentsUntil(".jstree", "li").each(function () { var $this = $(this); if(state) { if($this.children("ul").children("li.jstree-checked, li.jstree-undetermined").length) { $this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined"); if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); } return false; } else { $this.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked"); if(rc) { $this.children(":checkbox").prop("checked", false); } } } else { if($this.children("ul").children("li.jstree-unchecked, li.jstree-undetermined").length) { $this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined"); if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); } return false; } else { $this.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked"); if(rc) { $this.children(":checkbox").prop("checked", true); } } } }); } if(this.data.ui && this.data.checkbox.noui) { this.data.ui.selected = this.get_checked(); } this.__callback(obj); return true; }, check_node : function (obj) { if(this.change_state(obj, false)) { obj = this._get_node(obj); if(this._get_settings().checkbox.checked_parent_open) { var t = this; obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); }); } this.__callback({ "obj" : obj }); } }, uncheck_node : function (obj) { if(this.change_state(obj, true)) { this.__callback({ "obj" : this._get_node(obj) }); } }, check_all : function () { var _this = this, coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li"); coll.each(function () { _this.change_state(this, false); }); this.__callback(); }, uncheck_all : function () { var _this = this, coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li"); coll.each(function () { _this.change_state(this, true); }); this.__callback(); }, is_checked : function(obj) { obj = this._get_node(obj); return obj.length ? obj.is(".jstree-checked") : false; }, get_checked : function (obj, get_all) { obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj); return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-checked") : obj.find("> ul > .jstree-checked, .jstree-undetermined > ul > .jstree-checked"); }, get_unchecked : function (obj, get_all) { obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj); return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-unchecked") : obj.find("> ul > .jstree-unchecked, .jstree-undetermined > ul > .jstree-unchecked"); }, show_checkboxes : function () { this.get_container().children("ul").removeClass("jstree-no-checkboxes"); }, hide_checkboxes : function () { this.get_container().children("ul").addClass("jstree-no-checkboxes"); }, _repair_state : function (obj) { obj = this._get_node(obj); if(!obj.length) { return; } if(this._get_settings().checkbox.two_state) { obj.find('li').andSelf().not('.jstree-checked').removeClass('jstree-undetermined').addClass('jstree-unchecked').children(':checkbox').prop('checked', true); return; } var rc = this._get_settings().checkbox.real_checkboxes, a = obj.find("> ul > .jstree-checked").length, b = obj.find("> ul > .jstree-undetermined").length, c = obj.find("> ul > li").length; if(c === 0) { if(obj.hasClass("jstree-undetermined")) { this.change_state(obj, false); } } else if(a === 0 && b === 0) { this.change_state(obj, true); } else if(a === c) { this.change_state(obj, false); } else { obj.parentsUntil(".jstree","li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined"); if(rc) { obj.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); } } }, reselect : function () { if(this.data.ui && this.data.checkbox.noui) { var _this = this, s = this.data.ui.to_select; s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); }); this.deselect_all(); $.each(s, function (i, val) { _this.check_node(val); }); this.__callback(); } else { this.__call_old(); } }, save_loaded : function () { var _this = this; this.data.core.to_load = []; this.get_container_ul().find("li.jstree-closed.jstree-undetermined").each(function () { if(this.id) { _this.data.core.to_load.push("#" + this.id); } }); } } }); $(function() { var css_string = '.jstree .jstree-real-checkbox { display:none; } '; $.vakata.css.add_sheet({ str : css_string, title : "jstree" }); }); })(jQuery); //*/ /* * jsTree XML plugin * The XML data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions. */ (function ($) { $.vakata.xslt = function (xml, xsl, callback) { var rs = "", xm, xs, processor, support; // TODO: IE9 no XSLTProcessor, no document.recalc if(document.recalc) { xm = document.createElement('xml'); xs = document.createElement('xml'); xm.innerHTML = xml; xs.innerHTML = xsl; $("body").append(xm).append(xs); setTimeout( (function (xm, xs, callback) { return function () { callback.call(null, xm.transformNode(xs.XMLDocument)); setTimeout( (function (xm, xs) { return function () { $(xm).remove(); $(xs).remove(); }; })(xm, xs), 200); }; })(xm, xs, callback), 100); return true; } if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor === "undefined") { xml = new DOMParser().parseFromString(xml, "text/xml"); xsl = new DOMParser().parseFromString(xsl, "text/xml"); // alert(xml.transformNode()); // callback.call(null, new XMLSerializer().serializeToString(rs)); } if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor !== "undefined") { processor = new XSLTProcessor(); support = $.isFunction(processor.transformDocument) ? (typeof window.XMLSerializer !== "undefined") : true; if(!support) { return false; } xml = new DOMParser().parseFromString(xml, "text/xml"); xsl = new DOMParser().parseFromString(xsl, "text/xml"); if($.isFunction(processor.transformDocument)) { rs = document.implementation.createDocument("", "", null); processor.transformDocument(xml, xsl, rs, null); callback.call(null, new XMLSerializer().serializeToString(rs)); return true; } else { processor.importStylesheet(xsl); rs = processor.transformToFragment(xml, document); callback.call(null, $("<div />").append(rs).html()); return true; } } return false; }; var xsl = { 'nest' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + '<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/html" />' + '<xsl:template match="/">' + ' <xsl:call-template name="nodes">' + ' <xsl:with-param name="node" select="/root" />' + ' </xsl:call-template>' + '</xsl:template>' + '<xsl:template name="nodes">' + ' <xsl:param name="node" />' + ' <ul>' + ' <xsl:for-each select="$node/item">' + ' <xsl:variable name="children" select="count(./item) &gt; 0" />' + ' <li>' + ' <xsl:attribute name="class">' + ' <xsl:if test="position() = last()">jstree-last </xsl:if>' + ' <xsl:choose>' + ' <xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + ' <xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + ' <xsl:otherwise>jstree-leaf </xsl:otherwise>' + ' </xsl:choose>' + ' <xsl:value-of select="@class" />' + ' </xsl:attribute>' + ' <xsl:for-each select="@*">' + ' <xsl:if test="name() != \'class\' and name() != \'state\' and name() != \'hasChildren\'">' + ' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + ' </xsl:if>' + ' </xsl:for-each>' + ' <ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + ' <xsl:for-each select="content/name">' + ' <a>' + ' <xsl:attribute name="href">' + ' <xsl:choose>' + ' <xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + ' <xsl:otherwise>#</xsl:otherwise>' + ' </xsl:choose>' + ' </xsl:attribute>' + ' <xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + ' <xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + ' <xsl:for-each select="@*">' + ' <xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + ' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + ' </xsl:if>' + ' </xsl:for-each>' + ' <ins>' + ' <xsl:attribute name="class">jstree-icon ' + ' <xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + ' </xsl:attribute>' + ' <xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + ' <xsl:text>&#xa0;</xsl:text>' + ' </ins>' + ' <xsl:copy-of select="./child::node()" />' + ' </a>' + ' </xsl:for-each>' + ' <xsl:if test="$children or @hasChildren"><xsl:call-template name="nodes"><xsl:with-param name="node" select="current()" /></xsl:call-template></xsl:if>' + ' </li>' + ' </xsl:for-each>' + ' </ul>' + '</xsl:template>' + '</xsl:stylesheet>', 'flat' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + '<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/xml" />' + '<xsl:template match="/">' + ' <ul>' + ' <xsl:for-each select="//item[not(@parent_id) or @parent_id=0 or not(@parent_id = //item/@id)]">' + /* the last `or` may be removed */ ' <xsl:call-template name="nodes">' + ' <xsl:with-param name="node" select="." />' + ' <xsl:with-param name="is_last" select="number(position() = last())" />' + ' </xsl:call-template>' + ' </xsl:for-each>' + ' </ul>' + '</xsl:template>' + '<xsl:template name="nodes">' + ' <xsl:param name="node" />' + ' <xsl:param name="is_last" />' + ' <xsl:variable name="children" select="count(//item[@parent_id=$node/attribute::id]) &gt; 0" />' + ' <li>' + ' <xsl:attribute name="class">' + ' <xsl:if test="$is_last = true()">jstree-last </xsl:if>' + ' <xsl:choose>' + ' <xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + ' <xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + ' <xsl:otherwise>jstree-leaf </xsl:otherwise>' + ' </xsl:choose>' + ' <xsl:value-of select="@class" />' + ' </xsl:attribute>' + ' <xsl:for-each select="@*">' + ' <xsl:if test="name() != \'parent_id\' and name() != \'hasChildren\' and name() != \'class\' and name() != \'state\'">' + ' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + ' </xsl:if>' + ' </xsl:for-each>' + ' <ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + ' <xsl:for-each select="content/name">' + ' <a>' + ' <xsl:attribute name="href">' + ' <xsl:choose>' + ' <xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + ' <xsl:otherwise>#</xsl:otherwise>' + ' </xsl:choose>' + ' </xsl:attribute>' + ' <xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + ' <xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + ' <xsl:for-each select="@*">' + ' <xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + ' <xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + ' </xsl:if>' + ' </xsl:for-each>' + ' <ins>' + ' <xsl:attribute name="class">jstree-icon ' + ' <xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + ' </xsl:attribute>' + ' <xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + ' <xsl:text>&#xa0;</xsl:text>' + ' </ins>' + ' <xsl:copy-of select="./child::node()" />' + ' </a>' + ' </xsl:for-each>' + ' <xsl:if test="$children">' + ' <ul>' + ' <xsl:for-each select="//item[@parent_id=$node/attribute::id]">' + ' <xsl:call-template name="nodes">' + ' <xsl:with-param name="node" select="." />' + ' <xsl:with-param name="is_last" select="number(position() = last())" />' + ' </xsl:call-template>' + ' </xsl:for-each>' + ' </ul>' + ' </xsl:if>' + ' </li>' + '</xsl:template>' + '</xsl:stylesheet>' }, escape_xml = function(string) { return string .toString() .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }; $.jstree.plugin("xml_data", { defaults : { data : false, ajax : false, xsl : "flat", clean_node : false, correct_state : true, get_skip_empty : false, get_include_preamble : true }, _fn : { load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_xml(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); }, _is_loaded : function (obj) { var s = this._get_settings().xml_data; obj = this._get_node(obj); return obj == -1 || !obj || (!s.ajax && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0; }, load_node_xml : function (obj, s_call, e_call) { var s = this.get_settings().xml_data, error_func = function () {}, success_func = function () {}; obj = this._get_node(obj); if(obj && obj !== -1) { if(obj.data("jstree_is_loading")) { return; } else { obj.data("jstree_is_loading",true); } } switch(!0) { case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied."; case ($.isFunction(s.data)): s.data.call(this, obj, $.proxy(function (d) { this.parse_xml(d, $.proxy(function (d) { if(d) { d = d.replace(/ ?xmlns="[^"]*"/ig, ""); if(d.length > 10) { d = $(d); if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); } if(s.clean_node) { this.clean_node(obj); } if(s_call) { s_call.call(this); } } else { if(obj && obj !== -1) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); if(s_call) { s_call.call(this); } } } else { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } } } }, this)); }, this)); break; case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)): if(!obj || obj == -1) { this.parse_xml(s.data, $.proxy(function (d) { if(d) { d = d.replace(/ ?xmlns="[^"]*"/ig, ""); if(d.length > 10) { d = $(d); this.get_container().children("ul").empty().append(d.children()); if(s.clean_node) { this.clean_node(obj); } if(s_call) { s_call.call(this); } } } else { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } }, this)); } break; case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1): error_func = function (x, t, e) { var ef = this.get_settings().xml_data.ajax.error; if(ef) { ef.call(this, x, t, e); } if(obj !== -1 && obj.length) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(t === "success" && s.correct_state) { this.correct_state(obj); } } else { if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); } } if(e_call) { e_call.call(this); } }; success_func = function (d, t, x) { d = x.responseText; var sf = this.get_settings().xml_data.ajax.success; if(sf) { d = sf.call(this,d,t,x) || d; } if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) { return error_func.call(this, x, t, ""); } this.parse_xml(d, $.proxy(function (d) { if(d) { d = d.replace(/ ?xmlns="[^"]*"/ig, ""); if(d.length > 10) { d = $(d); if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); } if(s.clean_node) { this.clean_node(obj); } if(s_call) { s_call.call(this); } } else { if(obj && obj !== -1) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); if(s_call) { s_call.call(this); } } } else { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } } } }, this)); }; s.ajax.context = this; s.ajax.error = error_func; s.ajax.success = success_func; if(!s.ajax.dataType) { s.ajax.dataType = "xml"; } if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); } if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); } $.ajax(s.ajax); break; } }, parse_xml : function (xml, callback) { var s = this._get_settings().xml_data; $.vakata.xslt(xml, xsl[s.xsl], callback); }, get_xml : function (tp, obj, li_attr, a_attr, is_callback) { var result = "", s = this._get_settings(), _this = this, tmp1, tmp2, li, a, lang; if(!tp) { tp = "flat"; } if(!is_callback) { is_callback = 0; } obj = this._get_node(obj); if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); } li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ]; if(!is_callback && this.data.types && $.inArray(s.types.type_attr, li_attr) === -1) { li_attr.push(s.types.type_attr); } a_attr = $.isArray(a_attr) ? a_attr : [ ]; if(!is_callback) { if(s.xml_data.get_include_preamble) { result += '<' + '?xml version="1.0" encoding="UTF-8"?' + '>'; } result += "<root>"; } obj.each(function () { result += "<item"; li = $(this); $.each(li_attr, function (i, v) { var t = li.attr(v); if(!s.xml_data.get_skip_empty || typeof t !== "undefined") { result += " " + v + "=\"" + escape_xml((" " + (t || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\""; } }); if(li.hasClass("jstree-open")) { result += " state=\"open\""; } if(li.hasClass("jstree-closed")) { result += " state=\"closed\""; } if(tp === "flat") { result += " parent_id=\"" + escape_xml(is_callback) + "\""; } result += ">"; result += "<content>"; a = li.children("a"); a.each(function () { tmp1 = $(this); lang = false; result += "<name"; if($.inArray("languages", s.plugins) !== -1) { $.each(s.languages, function (k, z) { if(tmp1.hasClass(z)) { result += " lang=\"" + escape_xml(z) + "\""; lang = z; return false; } }); } if(a_attr.length) { $.each(a_attr, function (k, z) { var t = tmp1.attr(z); if(!s.xml_data.get_skip_empty || typeof t !== "undefined") { result += " " + z + "=\"" + escape_xml((" " + t || "").replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\""; } }); } if(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) { result += ' icon="' + escape_xml(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + '"'; } if(tmp1.children("ins").get(0).style.backgroundImage.length) { result += ' icon="' + escape_xml(tmp1.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","").replace(/'/ig,"").replace(/"/ig,"")) + '"'; } result += ">"; result += "<![CDATA[" + _this.get_text(tmp1, lang) + "]]>"; result += "</name>"; }); result += "</content>"; tmp2 = li[0].id || true; li = li.find("> ul > li"); if(li.length) { tmp2 = _this.get_xml(tp, li, li_attr, a_attr, tmp2); } else { tmp2 = ""; } if(tp == "nest") { result += tmp2; } result += "</item>"; if(tp == "flat") { result += tmp2; } }); if(!is_callback) { result += "</root>"; } return result; } } }); })(jQuery); //*/ /* * jsTree search plugin * Enables both sync and async search on the tree * DOES NOT WORK WITH JSON PROGRESSIVE RENDER */ (function ($) { $.expr[':'].jstree_contains = function(a,i,m){ return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0; }; $.expr[':'].jstree_title_contains = function(a,i,m) { return (a.getAttribute("title") || "").toLowerCase().indexOf(m[3].toLowerCase())>=0; }; $.jstree.plugin("search", { __init : function () { this.data.search.str = ""; this.data.search.result = $(); if(this._get_settings().search.show_only_matches) { this.get_container() .bind("search.jstree", function (e, data) { $(this).children("ul").find("li").hide().removeClass("jstree-last"); data.rslt.nodes.parentsUntil(".jstree").andSelf().show() .filter("ul").each(function () { $(this).children("li:visible").eq(-1).addClass("jstree-last"); }); }) .bind("clear_search.jstree", function () { $(this).children("ul").find("li").css("display","").end().end().jstree("clean_node", -1); }); } }, defaults : { ajax : false, search_method : "jstree_contains", // for case insensitive - jstree_contains show_only_matches : false }, _fn : { search : function (str, skip_async) { if($.trim(str) === "") { this.clear_search(); return; } var s = this.get_settings().search, t = this, error_func = function () { }, success_func = function () { }; this.data.search.str = str; if(!skip_async && s.ajax !== false && this.get_container_ul().find("li.jstree-closed:not(:has(ul)):eq(0)").length > 0) { this.search.supress_callback = true; error_func = function () { }; success_func = function (d, t, x) { var sf = this.get_settings().search.ajax.success; if(sf) { d = sf.call(this,d,t,x) || d; } this.data.search.to_open = d; this._search_open(); }; s.ajax.context = this; s.ajax.error = error_func; s.ajax.success = success_func; if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, str); } if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, str); } if(!s.ajax.data) { s.ajax.data = { "search_string" : str }; } if(!s.ajax.dataType || /^json/.exec(s.ajax.dataType)) { s.ajax.dataType = "json"; } $.ajax(s.ajax); return; } if(this.data.search.result.length) { this.clear_search(); } this.data.search.result = this.get_container().find("a" + (this.data.languages ? "." + this.get_lang() : "" ) + ":" + (s.search_method) + "(" + this.data.search.str + ")"); this.data.search.result.addClass("jstree-search").parent().parents(".jstree-closed").each(function () { t.open_node(this, false, true); }); this.__callback({ nodes : this.data.search.result, str : str }); }, clear_search : function (str) { this.data.search.result.removeClass("jstree-search"); this.__callback(this.data.search.result); this.data.search.result = $(); }, _search_open : function (is_callback) { var _this = this, done = true, current = [], remaining = []; if(this.data.search.to_open.length) { $.each(this.data.search.to_open, function (i, val) { if(val == "#") { return true; } if($(val).length && $(val).is(".jstree-closed")) { current.push(val); } else { remaining.push(val); } }); if(current.length) { this.data.search.to_open = remaining; $.each(current, function (i, val) { _this.open_node(val, function () { _this._search_open(true); }); }); done = false; } } if(done) { this.search(this.data.search.str, true); } } } }); })(jQuery); //*/ /* * jsTree contextmenu plugin */ (function ($) { $.vakata.context = { hide_on_mouseleave : false, cnt : $("<div id='vakata-contextmenu' />"), vis : false, tgt : false, par : false, func : false, data : false, rtl : false, show : function (s, t, x, y, d, p, rtl) { $.vakata.context.rtl = !!rtl; var html = $.vakata.context.parse(s), h, w; if(!html) { return; } $.vakata.context.vis = true; $.vakata.context.tgt = t; $.vakata.context.par = p || t || null; $.vakata.context.data = d || null; $.vakata.context.cnt .html(html) .css({ "visibility" : "hidden", "display" : "block", "left" : 0, "top" : 0 }); if($.vakata.context.hide_on_mouseleave) { $.vakata.context.cnt .one("mouseleave", function(e) { $.vakata.context.hide(); }); } h = $.vakata.context.cnt.height(); w = $.vakata.context.cnt.width(); if(x + w > $(document).width()) { x = $(document).width() - (w + 5); $.vakata.context.cnt.find("li > ul").addClass("right"); } if(y + h > $(document).height()) { y = y - (h + t[0].offsetHeight); $.vakata.context.cnt.find("li > ul").addClass("bottom"); } $.vakata.context.cnt .css({ "left" : x, "top" : y }) .find("li:has(ul)") .bind("mouseenter", function (e) { var w = $(document).width(), h = $(document).height(), ul = $(this).children("ul").show(); if(w !== $(document).width()) { ul.toggleClass("right"); } if(h !== $(document).height()) { ul.toggleClass("bottom"); } }) .bind("mouseleave", function (e) { $(this).children("ul").hide(); }) .end() .css({ "visibility" : "visible" }) .show(); $(document).triggerHandler("context_show.vakata"); }, hide : function () { $.vakata.context.vis = false; $.vakata.context.cnt.attr("class","").css({ "visibility" : "hidden" }); $(document).triggerHandler("context_hide.vakata"); }, parse : function (s, is_callback) { if(!s) { return false; } var str = "", tmp = false, was_sep = true; if(!is_callback) { $.vakata.context.func = {}; } str += "<ul>"; $.each(s, function (i, val) { if(!val) { return true; } $.vakata.context.func[i] = val.action; if(!was_sep && val.separator_before) { str += "<li class='vakata-separator vakata-separator-before'></li>"; } was_sep = false; str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins "; if(val.icon && val.icon.indexOf("/") === -1) { str += " class='" + val.icon + "' "; } if(val.icon && val.icon.indexOf("/") !== -1) { str += " style='background:url(" + val.icon + ") center center no-repeat;' "; } str += ">&#160;</ins><a href='#' rel='" + i + "'>"; if(val.submenu) { str += "<span style='float:" + ($.vakata.context.rtl ? "left" : "right") + ";'>&raquo;</span>"; } str += val.label + "</a>"; if(val.submenu) { tmp = $.vakata.context.parse(val.submenu, true); if(tmp) { str += tmp; } } str += "</li>"; if(val.separator_after) { str += "<li class='vakata-separator vakata-separator-after'></li>"; was_sep = true; } }); str = str.replace(/<li class\='vakata-separator vakata-separator-after'\><\/li\>$/,""); str += "</ul>"; $(document).triggerHandler("context_parse.vakata"); return str.length > 10 ? str : false; }, exec : function (i) { if($.isFunction($.vakata.context.func[i])) { // if is string - eval and call it! $.vakata.context.func[i].call($.vakata.context.data, $.vakata.context.par); return true; } else { return false; } } }; $(function () { var css_string = '' + '#vakata-contextmenu { display:block; visibility:hidden; left:0; top:-200px; position:absolute; margin:0; padding:0; min-width:180px; background:#ebebeb; border:1px solid silver; z-index:10000; *width:180px; } ' + '#vakata-contextmenu ul { min-width:180px; *width:180px; } ' + '#vakata-contextmenu ul, #vakata-contextmenu li { margin:0; padding:0; list-style-type:none; display:block; } ' + '#vakata-contextmenu li { line-height:20px; min-height:20px; position:relative; padding:0px; } ' + '#vakata-contextmenu li a { padding:1px 6px; line-height:17px; display:block; text-decoration:none; margin:1px 1px 0 1px; } ' + '#vakata-contextmenu li ins { float:left; width:16px; height:16px; text-decoration:none; margin-right:2px; } ' + '#vakata-contextmenu li a:hover, #vakata-contextmenu li.vakata-hover > a { background:gray; color:white; } ' + '#vakata-contextmenu li ul { display:none; position:absolute; top:-2px; left:100%; background:#ebebeb; border:1px solid gray; } ' + '#vakata-contextmenu .right { right:100%; left:auto; } ' + '#vakata-contextmenu .bottom { bottom:-1px; top:auto; } ' + '#vakata-contextmenu li.vakata-separator { min-height:0; height:1px; line-height:1px; font-size:1px; overflow:hidden; margin:0 2px; background:silver; /* border-top:1px solid #fefefe; */ padding:0; } '; $.vakata.css.add_sheet({ str : css_string, title : "vakata" }); $.vakata.context.cnt .delegate("a","click", function (e) { e.preventDefault(); }) .delegate("a","mouseup", function (e) { if(!$(this).parent().hasClass("jstree-contextmenu-disabled") && $.vakata.context.exec($(this).attr("rel"))) { $.vakata.context.hide(); } else { $(this).blur(); } }) .delegate("a","mouseover", function () { $.vakata.context.cnt.find(".vakata-hover").removeClass("vakata-hover"); }) .appendTo("body"); $(document).bind("mousedown", function (e) { if($.vakata.context.vis && !$.contains($.vakata.context.cnt[0], e.target)) { $.vakata.context.hide(); } }); if(typeof $.hotkeys !== "undefined") { $(document) .bind("keydown", "up", function (e) { if($.vakata.context.vis) { var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").prevAll("li:not(.vakata-separator)").first(); if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").last(); } o.addClass("vakata-hover"); e.stopImmediatePropagation(); e.preventDefault(); } }) .bind("keydown", "down", function (e) { if($.vakata.context.vis) { var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").nextAll("li:not(.vakata-separator)").first(); if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").first(); } o.addClass("vakata-hover"); e.stopImmediatePropagation(); e.preventDefault(); } }) .bind("keydown", "right", function (e) { if($.vakata.context.vis) { $.vakata.context.cnt.find(".vakata-hover").children("ul").show().children("li:not(.vakata-separator)").removeClass("vakata-hover").first().addClass("vakata-hover"); e.stopImmediatePropagation(); e.preventDefault(); } }) .bind("keydown", "left", function (e) { if($.vakata.context.vis) { $.vakata.context.cnt.find(".vakata-hover").children("ul").hide().children(".vakata-separator").removeClass("vakata-hover"); e.stopImmediatePropagation(); e.preventDefault(); } }) .bind("keydown", "esc", function (e) { $.vakata.context.hide(); e.preventDefault(); }) .bind("keydown", "space", function (e) { $.vakata.context.cnt.find(".vakata-hover").last().children("a").click(); e.preventDefault(); }); } }); $.jstree.plugin("contextmenu", { __init : function () { this.get_container() .delegate("a", "contextmenu.jstree", $.proxy(function (e) { e.preventDefault(); if(!$(e.currentTarget).hasClass("jstree-loading")) { this.show_contextmenu(e.currentTarget, e.pageX, e.pageY); } }, this)) .delegate("a", "click.jstree", $.proxy(function (e) { if(this.data.contextmenu) { $.vakata.context.hide(); } }, this)) .bind("destroy.jstree", $.proxy(function () { // TODO: move this to descruct method if(this.data.contextmenu) { $.vakata.context.hide(); } }, this)); $(document).bind("context_hide.vakata", $.proxy(function () { this.data.contextmenu = false; }, this)); }, defaults : { select_node : false, // requires UI plugin show_at_node : true, items : { // Could be a function that should return an object like this one "create" : { "separator_before" : false, "separator_after" : true, "label" : "Create", "action" : function (obj) { this.create(obj); } }, "rename" : { "separator_before" : false, "separator_after" : false, "label" : "Rename", "action" : function (obj) { this.rename(obj); } }, "remove" : { "separator_before" : false, "icon" : false, "separator_after" : false, "label" : "Delete", "action" : function (obj) { if(this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } } }, "ccp" : { "separator_before" : true, "icon" : false, "separator_after" : false, "label" : "Edit", "action" : false, "submenu" : { "cut" : { "separator_before" : false, "separator_after" : false, "label" : "Cut", "action" : function (obj) { this.cut(obj); } }, "copy" : { "separator_before" : false, "icon" : false, "separator_after" : false, "label" : "Copy", "action" : function (obj) { this.copy(obj); } }, "paste" : { "separator_before" : false, "icon" : false, "separator_after" : false, "label" : "Paste", "action" : function (obj) { this.paste(obj); } } } } } }, _fn : { show_contextmenu : function (obj, x, y) { obj = this._get_node(obj); var s = this.get_settings().contextmenu, a = obj.children("a:visible:eq(0)"), o = false, i = false; if(s.select_node && this.data.ui && !this.is_selected(obj)) { this.deselect_all(); this.select_node(obj, true); } if(s.show_at_node || typeof x === "undefined" || typeof y === "undefined") { o = a.offset(); x = o.left; y = o.top + this.data.core.li_height; } i = obj.data("jstree") && obj.data("jstree").contextmenu ? obj.data("jstree").contextmenu : s.items; if($.isFunction(i)) { i = i.call(this, obj); } this.data.contextmenu = true; $.vakata.context.show(i, a, x, y, this, obj, this._get_settings().core.rtl); if(this.data.themes) { $.vakata.context.cnt.attr("class", "jstree-" + this.data.themes.theme + "-context"); } } } }); })(jQuery); //*/ /* * jsTree types plugin * Adds support types of nodes * You can set an attribute on each li node, that represents its type. * According to the type setting the node may get custom icon/validation rules */ (function ($) { $.jstree.plugin("types", { __init : function () { var s = this._get_settings().types; this.data.types.attach_to = []; this.get_container() .bind("init.jstree", $.proxy(function () { var types = s.types, attr = s.type_attr, icons_css = "", _this = this; $.each(types, function (i, tp) { $.each(tp, function (k, v) { if(!/^(max_depth|max_children|icon|valid_children)$/.test(k)) { _this.data.types.attach_to.push(k); } }); if(!tp.icon) { return true; } if( tp.icon.image || tp.icon.position) { if(i == "default") { icons_css += '.jstree-' + _this.get_index() + ' a > .jstree-icon { '; } else { icons_css += '.jstree-' + _this.get_index() + ' li[' + attr + '="' + i + '"] > a > .jstree-icon { '; } if(tp.icon.image) { icons_css += ' background-image:url(' + tp.icon.image + '); '; } if(tp.icon.position){ icons_css += ' background-position:' + tp.icon.position + '; '; } else { icons_css += ' background-position:0 0; '; } icons_css += '} '; } }); if(icons_css !== "") { $.vakata.css.add_sheet({ 'str' : icons_css, title : "jstree-types" }); } }, this)) .bind("before.jstree", $.proxy(function (e, data) { var s, t, o = this._get_settings().types.use_data ? this._get_node(data.args[0]) : false, d = o && o !== -1 && o.length ? o.data("jstree") : false; if(d && d.types && d.types[data.func] === false) { e.stopImmediatePropagation(); return false; } if($.inArray(data.func, this.data.types.attach_to) !== -1) { if(!data.args[0] || (!data.args[0].tagName && !data.args[0].jquery)) { return; } s = this._get_settings().types.types; t = this._get_type(data.args[0]); if( ( (s[t] && typeof s[t][data.func] !== "undefined") || (s["default"] && typeof s["default"][data.func] !== "undefined") ) && this._check(data.func, data.args[0]) === false ) { e.stopImmediatePropagation(); return false; } } }, this)); if(is_ie6) { this.get_container() .bind("load_node.jstree set_type.jstree", $.proxy(function (e, data) { var r = data && data.rslt && data.rslt.obj && data.rslt.obj !== -1 ? this._get_node(data.rslt.obj).parent() : this.get_container_ul(), c = false, s = this._get_settings().types; $.each(s.types, function (i, tp) { if(tp.icon && (tp.icon.image || tp.icon.position)) { c = i === "default" ? r.find("li > a > .jstree-icon") : r.find("li[" + s.type_attr + "='" + i + "'] > a > .jstree-icon"); if(tp.icon.image) { c.css("backgroundImage","url(" + tp.icon.image + ")"); } c.css("backgroundPosition", tp.icon.position || "0 0"); } }); }, this)); } }, defaults : { // defines maximum number of root nodes (-1 means unlimited, -2 means disable max_children checking) max_children : -1, // defines the maximum depth of the tree (-1 means unlimited, -2 means disable max_depth checking) max_depth : -1, // defines valid node types for the root nodes valid_children : "all", // whether to use $.data use_data : false, // where is the type stores (the rel attribute of the LI element) type_attr : "rel", // a list of types types : { // the default type "default" : { "max_children" : -1, "max_depth" : -1, "valid_children": "all" // Bound functions - you can bind any other function here (using boolean or function) //"select_node" : true } } }, _fn : { _types_notify : function (n, data) { if(data.type && this._get_settings().types.use_data) { this.set_type(data.type, n); } }, _get_type : function (obj) { obj = this._get_node(obj); return (!obj || !obj.length) ? false : obj.attr(this._get_settings().types.type_attr) || "default"; }, set_type : function (str, obj) { obj = this._get_node(obj); var ret = (!obj.length || !str) ? false : obj.attr(this._get_settings().types.type_attr, str); if(ret) { this.__callback({ obj : obj, type : str}); } return ret; }, _check : function (rule, obj, opts) { obj = this._get_node(obj); var v = false, t = this._get_type(obj), d = 0, _this = this, s = this._get_settings().types, data = false; if(obj === -1) { if(!!s[rule]) { v = s[rule]; } else { return; } } else { if(t === false) { return; } data = s.use_data ? obj.data("jstree") : false; if(data && data.types && typeof data.types[rule] !== "undefined") { v = data.types[rule]; } else if(!!s.types[t] && typeof s.types[t][rule] !== "undefined") { v = s.types[t][rule]; } else if(!!s.types["default"] && typeof s.types["default"][rule] !== "undefined") { v = s.types["default"][rule]; } } if($.isFunction(v)) { v = v.call(this, obj); } if(rule === "max_depth" && obj !== -1 && opts !== false && s.max_depth !== -2 && v !== 0) { // also include the node itself - otherwise if root node it is not checked obj.children("a:eq(0)").parentsUntil(".jstree","li").each(function (i) { // check if current depth already exceeds global tree depth if(s.max_depth !== -1 && s.max_depth - (i + 1) <= 0) { v = 0; return false; } d = (i === 0) ? v : _this._check(rule, this, false); // check if current node max depth is already matched or exceeded if(d !== -1 && d - (i + 1) <= 0) { v = 0; return false; } // otherwise - set the max depth to the current value minus current depth if(d >= 0 && (d - (i + 1) < v || v < 0) ) { v = d - (i + 1); } // if the global tree depth exists and it minus the nodes calculated so far is less than `v` or `v` is unlimited if(s.max_depth >= 0 && (s.max_depth - (i + 1) < v || v < 0) ) { v = s.max_depth - (i + 1); } }); } return v; }, check_move : function () { if(!this.__call_old()) { return false; } var m = this._get_move(), s = m.rt._get_settings().types, mc = m.rt._check("max_children", m.cr), md = m.rt._check("max_depth", m.cr), vc = m.rt._check("valid_children", m.cr), ch = 0, d = 1, t; if(vc === "none") { return false; } if($.isArray(vc) && m.ot && m.ot._get_type) { m.o.each(function () { if($.inArray(m.ot._get_type(this), vc) === -1) { d = false; return false; } }); if(d === false) { return false; } } if(s.max_children !== -2 && mc !== -1) { ch = m.cr === -1 ? this.get_container().find("> ul > li").not(m.o).length : m.cr.find("> ul > li").not(m.o).length; if(ch + m.o.length > mc) { return false; } } if(s.max_depth !== -2 && md !== -1) { d = 0; if(md === 0) { return false; } if(typeof m.o.d === "undefined") { // TODO: deal with progressive rendering and async when checking max_depth (how to know the depth of the moved node) t = m.o; while(t.length > 0) { t = t.find("> ul > li"); d ++; } m.o.d = d; } if(md - m.o.d < 0) { return false; } } return true; }, create_node : function (obj, position, js, callback, is_loaded, skip_check) { if(!skip_check && (is_loaded || this._is_loaded(obj))) { var p = (typeof position == "string" && position.match(/^before|after$/i) && obj !== -1) ? this._get_parent(obj) : this._get_node(obj), s = this._get_settings().types, mc = this._check("max_children", p), md = this._check("max_depth", p), vc = this._check("valid_children", p), ch; if(typeof js === "string") { js = { data : js }; } if(!js) { js = {}; } if(vc === "none") { return false; } if($.isArray(vc)) { if(!js.attr || !js.attr[s.type_attr]) { if(!js.attr) { js.attr = {}; } js.attr[s.type_attr] = vc[0]; } else { if($.inArray(js.attr[s.type_attr], vc) === -1) { return false; } } } if(s.max_children !== -2 && mc !== -1) { ch = p === -1 ? this.get_container().find("> ul > li").length : p.find("> ul > li").length; if(ch + 1 > mc) { return false; } } if(s.max_depth !== -2 && md !== -1 && (md - 1) < 0) { return false; } } return this.__call_old(true, obj, position, js, callback, is_loaded, skip_check); } } }); })(jQuery); //*/ /* * jsTree HTML plugin * The HTML data store. Datastores are build by replacing the `load_node` and `_is_loaded` functions. */ (function ($) { $.jstree.plugin("html_data", { __init : function () { // this used to use html() and clean the whitespace, but this way any attached data was lost this.data.html_data.original_container_html = this.get_container().find(" > ul > li").clone(true); // remove white space from LI node - otherwise nodes appear a bit to the right this.data.html_data.original_container_html.find("li").andSelf().contents().filter(function() { return this.nodeType == 3; }).remove(); }, defaults : { data : false, ajax : false, correct_state : true }, _fn : { load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_html(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); }, _is_loaded : function (obj) { obj = this._get_node(obj); return obj == -1 || !obj || (!this._get_settings().html_data.ajax && !$.isFunction(this._get_settings().html_data.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0; }, load_node_html : function (obj, s_call, e_call) { var d, s = this.get_settings().html_data, error_func = function () {}, success_func = function () {}; obj = this._get_node(obj); if(obj && obj !== -1) { if(obj.data("jstree_is_loading")) { return; } else { obj.data("jstree_is_loading",true); } } switch(!0) { case ($.isFunction(s.data)): s.data.call(this, obj, $.proxy(function (d) { if(d && d !== "" && d.toString && d.toString().replace(/^[\s\n]+$/,"") !== "") { d = $(d); if(!d.is("ul")) { d = $("<ul />").append(d); } if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); } this.clean_node(obj); if(s_call) { s_call.call(this); } } else { if(obj && obj !== -1) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); if(s_call) { s_call.call(this); } } } else { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } } }, this)); break; case (!s.data && !s.ajax): if(!obj || obj == -1) { this.get_container() .children("ul").empty() .append(this.data.html_data.original_container_html) .find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end() .filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); this.clean_node(); } if(s_call) { s_call.call(this); } break; case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)): if(!obj || obj == -1) { d = $(s.data); if(!d.is("ul")) { d = $("<ul />").append(d); } this.get_container() .children("ul").empty().append(d.children()) .find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end() .filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); this.clean_node(); } if(s_call) { s_call.call(this); } break; case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1): obj = this._get_node(obj); error_func = function (x, t, e) { var ef = this.get_settings().html_data.ajax.error; if(ef) { ef.call(this, x, t, e); } if(obj != -1 && obj.length) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(t === "success" && s.correct_state) { this.correct_state(obj); } } else { if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); } } if(e_call) { e_call.call(this); } }; success_func = function (d, t, x) { var sf = this.get_settings().html_data.ajax.success; if(sf) { d = sf.call(this,d,t,x) || d; } if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) { return error_func.call(this, x, t, ""); } if(d) { d = $(d); if(!d.is("ul")) { d = $("<ul />").append(d); } if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); } else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); } this.clean_node(obj); if(s_call) { s_call.call(this); } } else { if(obj && obj !== -1) { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); if(s.correct_state) { this.correct_state(obj); if(s_call) { s_call.call(this); } } } else { if(s.correct_state) { this.get_container().children("ul").empty(); if(s_call) { s_call.call(this); } } } } }; s.ajax.context = this; s.ajax.error = error_func; s.ajax.success = success_func; if(!s.ajax.dataType) { s.ajax.dataType = "html"; } if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); } if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); } $.ajax(s.ajax); break; } } } }); // include the HTML data plugin by default $.jstree.defaults.plugins.push("html_data"); })(jQuery); //*/ /* * jsTree themeroller plugin * Adds support for jQuery UI themes. Include this at the end of your plugins list, also make sure "themes" is not included. */ (function ($) { $.jstree.plugin("themeroller", { __init : function () { var s = this._get_settings().themeroller; this.get_container() .addClass("ui-widget-content") .addClass("jstree-themeroller") .delegate("a","mouseenter.jstree", function (e) { if(!$(e.currentTarget).hasClass("jstree-loading")) { $(this).addClass(s.item_h); } }) .delegate("a","mouseleave.jstree", function () { $(this).removeClass(s.item_h); }) .bind("init.jstree", $.proxy(function (e, data) { data.inst.get_container().find("> ul > li > .jstree-loading > ins").addClass("ui-icon-refresh"); this._themeroller(data.inst.get_container().find("> ul > li")); }, this)) .bind("open_node.jstree create_node.jstree", $.proxy(function (e, data) { this._themeroller(data.rslt.obj); }, this)) .bind("loaded.jstree refresh.jstree", $.proxy(function (e) { this._themeroller(); }, this)) .bind("close_node.jstree", $.proxy(function (e, data) { this._themeroller(data.rslt.obj); }, this)) .bind("delete_node.jstree", $.proxy(function (e, data) { this._themeroller(data.rslt.parent); }, this)) .bind("correct_state.jstree", $.proxy(function (e, data) { data.rslt.obj .children("ins.jstree-icon").removeClass(s.opened + " " + s.closed + " ui-icon").end() .find("> a > ins.ui-icon") .filter(function() { return this.className.toString() .replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"") .indexOf("ui-icon-") === -1; }).removeClass(s.item_open + " " + s.item_clsd).addClass(s.item_leaf || "jstree-no-icon"); }, this)) .bind("select_node.jstree", $.proxy(function (e, data) { data.rslt.obj.children("a").addClass(s.item_a); }, this)) .bind("deselect_node.jstree deselect_all.jstree", $.proxy(function (e, data) { this.get_container() .find("a." + s.item_a).removeClass(s.item_a).end() .find("a.jstree-clicked").addClass(s.item_a); }, this)) .bind("dehover_node.jstree", $.proxy(function (e, data) { data.rslt.obj.children("a").removeClass(s.item_h); }, this)) .bind("hover_node.jstree", $.proxy(function (e, data) { this.get_container() .find("a." + s.item_h).not(data.rslt.obj).removeClass(s.item_h); data.rslt.obj.children("a").addClass(s.item_h); }, this)) .bind("move_node.jstree", $.proxy(function (e, data) { this._themeroller(data.rslt.o); this._themeroller(data.rslt.op); }, this)); }, __destroy : function () { var s = this._get_settings().themeroller, c = [ "ui-icon" ]; $.each(s, function (i, v) { v = v.split(" "); if(v.length) { c = c.concat(v); } }); this.get_container() .removeClass("ui-widget-content") .find("." + c.join(", .")).removeClass(c.join(" ")); }, _fn : { _themeroller : function (obj) { var s = this._get_settings().themeroller; obj = !obj || obj == -1 ? this.get_container_ul() : this._get_node(obj).parent(); obj .find("li.jstree-closed") .children("ins.jstree-icon").removeClass(s.opened).addClass("ui-icon " + s.closed).end() .children("a").addClass(s.item) .children("ins.jstree-icon").addClass("ui-icon") .filter(function() { return this.className.toString() .replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"") .indexOf("ui-icon-") === -1; }).removeClass(s.item_leaf + " " + s.item_open).addClass(s.item_clsd || "jstree-no-icon") .end() .end() .end() .end() .find("li.jstree-open") .children("ins.jstree-icon").removeClass(s.closed).addClass("ui-icon " + s.opened).end() .children("a").addClass(s.item) .children("ins.jstree-icon").addClass("ui-icon") .filter(function() { return this.className.toString() .replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"") .indexOf("ui-icon-") === -1; }).removeClass(s.item_leaf + " " + s.item_clsd).addClass(s.item_open || "jstree-no-icon") .end() .end() .end() .end() .find("li.jstree-leaf") .children("ins.jstree-icon").removeClass(s.closed + " ui-icon " + s.opened).end() .children("a").addClass(s.item) .children("ins.jstree-icon").addClass("ui-icon") .filter(function() { return this.className.toString() .replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"") .indexOf("ui-icon-") === -1; }).removeClass(s.item_clsd + " " + s.item_open).addClass(s.item_leaf || "jstree-no-icon"); } }, defaults : { "opened" : "ui-icon-triangle-1-se", "closed" : "ui-icon-triangle-1-e", "item" : "ui-state-default", "item_h" : "ui-state-hover", "item_a" : "ui-state-active", "item_open" : "ui-icon-folder-open", "item_clsd" : "ui-icon-folder-collapsed", "item_leaf" : "ui-icon-document" } }); $(function() { var css_string = '' + '.jstree-themeroller .ui-icon { overflow:visible; } ' + '.jstree-themeroller a { padding:0 2px; } ' + '.jstree-themeroller .jstree-no-icon { display:none; }'; $.vakata.css.add_sheet({ str : css_string, title : "jstree" }); }); })(jQuery); //*/ /* * jsTree unique plugin * Forces different names amongst siblings (still a bit experimental) * NOTE: does not check language versions (it will not be possible to have nodes with the same title, even in different languages) */ (function ($) { $.jstree.plugin("unique", { __init : function () { this.get_container() .bind("before.jstree", $.proxy(function (e, data) { var nms = [], res = true, p, t; if(data.func == "move_node") { // obj, ref, position, is_copy, is_prepared, skip_check if(data.args[4] === true) { if(data.args[0].o && data.args[0].o.length) { data.args[0].o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); }); res = this._check_unique(nms, data.args[0].np.find("> ul > li").not(data.args[0].o), "move_node"); } } } if(data.func == "create_node") { // obj, position, js, callback, is_loaded if(data.args[4] || this._is_loaded(data.args[0])) { p = this._get_node(data.args[0]); if(data.args[1] && (data.args[1] === "before" || data.args[1] === "after")) { p = this._get_parent(data.args[0]); if(!p || p === -1) { p = this.get_container(); } } if(typeof data.args[2] === "string") { nms.push(data.args[2]); } else if(!data.args[2] || !data.args[2].data) { nms.push(this._get_string("new_node")); } else { nms.push(data.args[2].data); } res = this._check_unique(nms, p.find("> ul > li"), "create_node"); } } if(data.func == "rename_node") { // obj, val nms.push(data.args[1]); t = this._get_node(data.args[0]); p = this._get_parent(t); if(!p || p === -1) { p = this.get_container(); } res = this._check_unique(nms, p.find("> ul > li").not(t), "rename_node"); } if(!res) { e.stopPropagation(); return false; } }, this)); }, defaults : { error_callback : $.noop }, _fn : { _check_unique : function (nms, p, func) { var cnms = []; p.children("a").each(function () { cnms.push($(this).text().replace(/^\s+/g,"")); }); if(!cnms.length || !nms.length) { return true; } cnms = cnms.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(","); if((cnms.length + nms.length) != cnms.concat(nms).sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",").length) { this._get_settings().unique.error_callback.call(null, nms, p, func); return false; } return true; }, check_move : function () { if(!this.__call_old()) { return false; } var p = this._get_move(), nms = []; if(p.o && p.o.length) { p.o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); }); return this._check_unique(nms, p.np.find("> ul > li").not(p.o), "check_move"); } return true; } } }); })(jQuery); //*/ /* * jsTree wholerow plugin * Makes select and hover work on the entire width of the node * MAY BE HEAVY IN LARGE DOM */ (function ($) { $.jstree.plugin("wholerow", { __init : function () { if(!this.data.ui) { throw "jsTree wholerow: jsTree UI plugin not included."; } this.data.wholerow.html = false; this.data.wholerow.to = false; this.get_container() .bind("init.jstree", $.proxy(function (e, data) { this._get_settings().core.animation = 0; }, this)) .bind("open_node.jstree create_node.jstree clean_node.jstree loaded.jstree", $.proxy(function (e, data) { this._prepare_wholerow_span( data && data.rslt && data.rslt.obj ? data.rslt.obj : -1 ); }, this)) .bind("search.jstree clear_search.jstree reopen.jstree after_open.jstree after_close.jstree create_node.jstree delete_node.jstree clean_node.jstree", $.proxy(function (e, data) { if(this.data.to) { clearTimeout(this.data.to); } this.data.to = setTimeout( (function (t, o) { return function() { t._prepare_wholerow_ul(o); }; })(this, data && data.rslt && data.rslt.obj ? data.rslt.obj : -1), 0); }, this)) .bind("deselect_all.jstree", $.proxy(function (e, data) { this.get_container().find(" > .jstree-wholerow .jstree-clicked").removeClass("jstree-clicked " + (this.data.themeroller ? this._get_settings().themeroller.item_a : "" )); }, this)) .bind("select_node.jstree deselect_node.jstree ", $.proxy(function (e, data) { data.rslt.obj.each(function () { var ref = data.inst.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt((($(this).offset().top - data.inst.get_container().offset().top + data.inst.get_container()[0].scrollTop) / data.inst.data.core.li_height),10)) + ")"); // ref.children("a")[e.type === "select_node" ? "addClass" : "removeClass"]("jstree-clicked"); ref.children("a").attr("class",data.rslt.obj.children("a").attr("class")); }); }, this)) .bind("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) { this.get_container().find(" > .jstree-wholerow .jstree-hovered").removeClass("jstree-hovered " + (this.data.themeroller ? this._get_settings().themeroller.item_h : "" )); if(e.type === "hover_node") { var ref = this.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt(((data.rslt.obj.offset().top - this.get_container().offset().top + this.get_container()[0].scrollTop) / this.data.core.li_height),10)) + ")"); // ref.children("a").addClass("jstree-hovered"); ref.children("a").attr("class",data.rslt.obj.children(".jstree-hovered").attr("class")); } }, this)) .delegate(".jstree-wholerow-span, ins.jstree-icon, li", "click.jstree", function (e) { var n = $(e.currentTarget); if(e.target.tagName === "A" || (e.target.tagName === "INS" && n.closest("li").is(".jstree-open, .jstree-closed"))) { return; } n.closest("li").children("a:visible:eq(0)").click(); e.stopImmediatePropagation(); }) .delegate("li", "mouseover.jstree", $.proxy(function (e) { e.stopImmediatePropagation(); if($(e.currentTarget).children(".jstree-hovered, .jstree-clicked").length) { return false; } this.hover_node(e.currentTarget); return false; }, this)) .delegate("li", "mouseleave.jstree", $.proxy(function (e) { if($(e.currentTarget).children("a").hasClass("jstree-hovered").length) { return; } this.dehover_node(e.currentTarget); }, this)); if(is_ie7 || is_ie6) { $.vakata.css.add_sheet({ str : ".jstree-" + this.get_index() + " { position:relative; } ", title : "jstree" }); } }, defaults : { }, __destroy : function () { this.get_container().children(".jstree-wholerow").remove(); this.get_container().find(".jstree-wholerow-span").remove(); }, _fn : { _prepare_wholerow_span : function (obj) { obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj); if(obj === false) { return; } // added for removing root nodes obj.each(function () { $(this).find("li").andSelf().each(function () { var $t = $(this); if($t.children(".jstree-wholerow-span").length) { return true; } $t.prepend("<span class='jstree-wholerow-span' style='width:" + ($t.parentsUntil(".jstree","li").length * 18) + "px;'>&#160;</span>"); }); }); }, _prepare_wholerow_ul : function () { var o = this.get_container().children("ul").eq(0), h = o.html(); o.addClass("jstree-wholerow-real"); if(this.data.wholerow.last_html !== h) { this.data.wholerow.last_html = h; this.get_container().children(".jstree-wholerow").remove(); this.get_container().append( o.clone().removeClass("jstree-wholerow-real") .wrapAll("<div class='jstree-wholerow' />").parent() .width(o.parent()[0].scrollWidth) .css("top", (o.height() + ( is_ie7 ? 5 : 0)) * -1 ) .find("li[id]").each(function () { this.removeAttribute("id"); }).end() ); } } } }); $(function() { var css_string = '' + '.jstree .jstree-wholerow-real { position:relative; z-index:1; } ' + '.jstree .jstree-wholerow-real li { cursor:pointer; } ' + '.jstree .jstree-wholerow-real a { border-left-color:transparent !important; border-right-color:transparent !important; } ' + '.jstree .jstree-wholerow { position:relative; z-index:0; height:0; } ' + '.jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { width:100%; } ' + '.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li, .jstree .jstree-wholerow a { margin:0 !important; padding:0 !important; } ' + '.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { background:transparent !important; }' + '.jstree .jstree-wholerow ins, .jstree .jstree-wholerow span, .jstree .jstree-wholerow input { display:none !important; }' + '.jstree .jstree-wholerow a, .jstree .jstree-wholerow a:hover { text-indent:-9999px; !important; width:100%; padding:0 !important; border-right-width:0px !important; border-left-width:0px !important; } ' + '.jstree .jstree-wholerow-span { position:absolute; left:0; margin:0px; padding:0; height:18px; border-width:0; padding:0; z-index:0; }'; if(is_ff2) { css_string += '' + '.jstree .jstree-wholerow a { display:block; height:18px; margin:0; padding:0; border:0; } ' + '.jstree .jstree-wholerow-real a { border-color:transparent !important; } '; } if(is_ie7 || is_ie6) { css_string += '' + '.jstree .jstree-wholerow, .jstree .jstree-wholerow li, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow a { margin:0; padding:0; line-height:18px; } ' + '.jstree .jstree-wholerow a { display:block; height:18px; line-height:18px; overflow:hidden; } '; } $.vakata.css.add_sheet({ str : css_string, title : "jstree" }); }); })(jQuery); //*/ /* * jsTree model plugin * This plugin gets jstree to use a class model to retrieve data, creating great dynamism */ (function ($) { var nodeInterface = ["getChildren","getChildrenCount","getAttr","getName","getProps"], validateInterface = function(obj, inter) { var valid = true; obj = obj || {}; inter = [].concat(inter); $.each(inter, function (i, v) { if(!$.isFunction(obj[v])) { valid = false; return false; } }); return valid; }; $.jstree.plugin("model", { __init : function () { if(!this.data.json_data) { throw "jsTree model: jsTree json_data plugin not included."; } this._get_settings().json_data.data = function (n, b) { var obj = (n == -1) ? this._get_settings().model.object : n.data("jstree_model"); if(!validateInterface(obj, nodeInterface)) { return b.call(null, false); } if(this._get_settings().model.async) { obj.getChildren($.proxy(function (data) { this.model_done(data, b); }, this)); } else { this.model_done(obj.getChildren(), b); } }; }, defaults : { object : false, id_prefix : false, async : false }, _fn : { model_done : function (data, callback) { var ret = [], s = this._get_settings(), _this = this; if(!$.isArray(data)) { data = [data]; } $.each(data, function (i, nd) { var r = nd.getProps() || {}; r.attr = nd.getAttr() || {}; if(nd.getChildrenCount()) { r.state = "closed"; } r.data = nd.getName(); if(!$.isArray(r.data)) { r.data = [r.data]; } if(_this.data.types && $.isFunction(nd.getType)) { r.attr[s.types.type_attr] = nd.getType(); } if(r.attr.id && s.model.id_prefix) { r.attr.id = s.model.id_prefix + r.attr.id; } if(!r.metadata) { r.metadata = { }; } r.metadata.jstree_model = nd; ret.push(r); }); callback.call(null, ret); } } }); })(jQuery); //*/ })();
JavaScript
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Utility functions for the examples set. * @author silvano.luciani@gmail.com (Silvano Luciani) */ /** * Formats the date object to 'yyyy-mm-dd'. * @param {object} date a Date object. * @return {string} The formatted string. */ function formatDate(date) { var dateArr = [String(date.getFullYear())]; dateArr.push(getTwoDigitString(date.getMonth() + 1)); dateArr.push(getTwoDigitString(date.getDate())); return dateArr.join('-'); } /** * Converts a numeric value to a two digit string. * @param {number} int a numeric value. * @return {string} The two digit string. */ function getTwoDigitString(int) { return int < 10 ? '0' + String(int) : String(int); }
JavaScript
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Provides functions to perform the OAuth 2.0 authentication. * @author silvano.luciani@gmail.com (Silvano Luciani) */ /** * Enter a client ID for a web application from the Google Developer Console. * In your Developer Console project, add a JavaScript origin that corresponds * to the domain where you will be running the script. * @type {string} */ // This client ID won't work with your project! CLIENT_ID = '837050751313'; /** * Enter the API key from the Google Developer Console - to handle any * unauthenticated requests in the code. * @type {string} */ // This key won't work with your project! API_KEY = 'AIzaSyAdjHPT5Pb7Nu56WJ_nlrMGOAgUAtKjiPM'; /** * To enter one or more authentication scopes, refer to the documentation * for the API. * @type {string} */ SCOPE = 'https://www.googleapis.com/auth/adsense.readonly'; /** * Set the api key and starts the authentication flow calling checkAuth. * Called from the example page after the Google APIs Javascript client has been * loaded. */ function handleClientLoad() { gapi.client.setApiKey(API_KEY); window.setTimeout(checkAuth, 1); } /** * Checks the authorization and calls handleAuthResult once the process * is completed. */ function checkAuth() { gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPE, immediate: true}, handleAuthResult); } /** * Performs the API request if we have an access token, otherwise shows the * authentication button to allow the user to start the flow. * makeApiCall is implemented in each specific code example to query the API and * visualize the data. * @param {object} authResult An OAuth 2.0 token and any associated data. */ function handleAuthResult(authResult) { var authorizeButton = document.getElementById('authorize-button'); if (authResult) { authorizeButton.style.visibility = 'hidden'; makeApiCall(); } else { authorizeButton.style.visibility = ''; authorizeButton.onclick = handleAuthClick; } } /** * Handles authentication requests from the authentication button. * @param {object} event The event that triggered the function. */ function handleAuthClick(event) { gapi.auth.authorize({client_id: CLIENT_ID, scope: SCOPE, immediate: false}, handleAuthResult); }
JavaScript
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Utility functions for the examples set. * @author silvano.luciani@gmail.com (Silvano Luciani) */ /** * Formats the date object to 'yyyy-mm-dd'. * @param {object} date a Date object. * @return {string} The formatted string. */ function formatDate(date) { var dateArr = [String(date.getFullYear())]; dateArr.push(getTwoDigitString(date.getMonth())); dateArr.push(getTwoDigitString(date.getDate())); return dateArr.join('-'); } /** * Converts a numeric value to a two digit string. * @param {number} int a numeric value. * @return {string} The two digit string. */ function getTwoDigitString(int) { return int < 10 ? '0' + String(int) : String(int); }
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Reference example for the Core Reporting API. This example * demonstrates how to access the important information from version 3 of * the Google Analytics Core Reporting API. * @author api.nickm@gmail.com (Nick Mihailovski) */ // Simple place to store all the results before printing to the user. var output = []; // Initialize the UI Dates. document.getElementById('start-date').value = lastNDays(14); document.getElementById('end-date').value = lastNDays(0); /** * Executes a Core Reporting API query to retrieve the top 25 organic search * terms. Once complete, handleCoreReportingResults is executed. Note: A user * must have gone through the Google APIs authorization routine and the Google * Anaytics client library must be loaded before this function is called. */ function makeApiCall() { gapi.client.analytics.data.ga.get({ 'ids': document.getElementById('table-id').value, 'start-date': document.getElementById('start-date').value, 'end-date': document.getElementById('end-date').value, 'metrics': 'ga:visits', 'dimensions': 'ga:source,ga:keyword', 'sort': '-ga:visits,ga:source', 'filters': 'ga:medium==organic', 'max-results': 25 }).execute(handleCoreReportingResults); } /** * Handles the response from the CVore Reporting API. If sucessful, the * results object from the API is passed to various printing functions. * If there was an error, a message with the error is printed to the user. * @param {Object} results The object returned from the API. */ function handleCoreReportingResults(results) { if (!results.code) { outputToPage('Query Success'); printReportInfo(results); printPaginationInfo(results); printProfileInfo(results); printQuery(results); printColumnHeaders(results); printTotalsForAllResults(results); printRows(results); outputToPage(output.join('')); } else { outputToPage('There was an error: ' + results.message); } } /** * Prints general information about this report. * @param {Object} results The object returned from the API. */ function printReportInfo(results) { output.push( '<h3>Report Information</h3>', '<p>', 'Contains Sampled Data = ', results.containsSampledData, '<br>', 'Kind = ', results.kind, '<br>', 'ID = ', results.id, '<br>', 'Self Link = ', results.selfLink, '<br>', '</p>'); } /** * Prints common pagination details. * @param {Object} results The object returned from the API. */ function printPaginationInfo(results) { output.push( '<h3>Pagination Information</h3>', '<p>', 'Items Per Page = ', results.itemsPerPage, '<br>', 'Total Results = ', results.totalResults, '<br>', 'Previous Link = ', results.previousLink ? results.previousLink : '', '<br>', 'Next Link = ', results.nextLink ? results.nextLink : '', '<br>', '</p>'); } /** * Prints information about this profile. * @param {Object} results The object returned from the API. */ function printProfileInfo(results) { var info = results.profileInfo; output.push( '<h3>Profile Information</h3>', '<p>', 'Account Id = ', info.accountId, '<br>', 'Web Property Id = ', info.webPropertyId, '<br>', 'Profile Id = ', info.profileId, '<br>', 'Table Id = ', info.tableId, '<br>', 'Profile Name = ', info.profileName, '<br>', '</p>'); } /** * Prints the query in the results. This query object represents the original * query issued to the API. Each key in the object is the query parameter * name and the value is the query parameter value. * @param {Object} results The object returned from the API. */ function printQuery(results) { output.push('<h3>Query Parameters</h3><p>'); for (var key in results.query) { output.push(key, ' = ', results.query[key], '<br>'); } output.push('</p>'); } /** * Prints the information for each column. The main data from the API is * returned as rows of data. The column headers describe the names and * types of each column in the rows. * @param {Object} results The object returned from the API. */ function printColumnHeaders(results) { output.push('<h3>Column Headers</h3>'); for (var i = 0, header; header = results.columnHeaders[i]; ++i) { output.push( '<p>', 'Name = ', header.name, '<br>', 'Column Type = ', header.columnType, '<br>', 'Data Type = ', header.dataType, '<br>', '</p>'); } } /** * Prints the total metric value for all pages the query matched. * @param {Object} results The object returned from the API. */ function printTotalsForAllResults(results) { output.push( '<h3>Total Metrics For All Results</h3>', '<p>This query returned ', results.rows.length, ' rows. ', 'But the query matched ', results.totalResults, ' total results. ', 'Here are the metric totals for the matched total results.</p>'); var totals = results.totalsForAllResults; for (metricName in totals) { output.push( '<p>', 'Metric Name = ', metricName, '<br>', 'Metric Total = ', totals[metricName], '<br>', '</p>'); } } /** * Prints all the column headers and rows of data as an HTML table. * @param {Object} results The object returned from the API. */ function printRows(results) { output.push('<h3>All Rows Of Data</h3>'); if (results.rows && results.rows.length) { var table = ['<table>']; // Put headers in table. table.push('<tr>'); for (var i = 0, header; header = results.columnHeaders[i]; ++i) { table.push('<th>', header.name, '</th>'); } table.push('</tr>'); // Put cells in table. for (var i = 0, row; row = results.rows[i]; ++i) { table.push('<tr><td>', row.join('</td><td>'), '</td></tr>'); } table.push('</table>'); output.push(table.join('')); } else { output.push('<p>No rows found.</p>'); } } /** * Utility method to update the output section of the HTML page. Used * to output messages to the user. This overwrites any existing content * in the output area. * @param {String} output The HTML string to output. */ function outputToPage(output) { document.getElementById('output').innerHTML = output; } /** * Utility method to update the output section of the HTML page. Used * to output messages to the user. This appends content to any existing * content in the output area. * @param {String} output The HTML string to output. */ function updatePage(output) { document.getElementById('output').innerHTML += '<br>' + output; } /** * Utility method to return the lastNdays from today in the format yyyy-MM-dd. * @param {Number} n The number of days in the past from tpday that we should * return a date. Value of 0 returns today. */ function lastNDays(n) { var today = new Date(); var before = new Date(); before.setDate(today.getDate() - n); var year = before.getFullYear(); var month = before.getMonth() + 1; if (month < 10) { month = '0' + month; } var day = before.getDate(); if (day < 10) { day = '0' + day; } return [year, month, day].join('-'); }
JavaScript