text
stringlengths 7
3.69M
|
|---|
import React from "react";
import { completeReservation, deleteTable } from "../../utils/api";
export default function Table({table, loadDashboard}) {
async function finishReservation(event) {
const abortController = new AbortController()
if (window.confirm('Is this table ready to seat new guests? This cannot be undone.')) {
await completeReservation(event.target.id, abortController.signal)
loadDashboard()
}
}
async function destroyTable(event) {
const abortController = new AbortController()
await deleteTable(event.target.id, abortController)
loadDashboard()
}
return (
<div className='my-5 border border-dark p-3'>
<button id={table.table_id} className='float-right bg-danger text-white' onClick={destroyTable}>X</button>
<h4 className='text-center content-header'>Table {table.table_id}</h4>
<p className='mx-2'>Name: {table.table_name}</p>
<p className='mx-2'>Capacity: {table.capacity}</p>
{table.reservation_id && <p className='mx-2'>Reservation ID: {table.reservation_id}</p>}
<p className='mx-2' data-table-id-status={table.table_id}>Status: {table.reservation_id ? 'Occupied' : 'Free'}</p>
{table.reservation_id &&
<div className='d-flex justify-content-center'>
<button id={table.table_id} className='w-fit-content m-3' onClick={finishReservation}>Finish Reservation</button>
</div>
}
</div>
)
}
|
function _Initialize() {
$NC.setGlobalVar({
policyVal: {
LO420: "",
LO440: "",
LO450: ""
},
CARRIER_CD: "",
SCAN_CD: "",
BARCD_DATA_DIV: "-",
NEWORDER_CHK: "",
ORDERCAN_CHK: "",
ORDERHOLD_CHK: "",
SUM_ENTRY_QTY: 0,
SUM_CONFIRM_QTY: 0,
SUM_INSPECT_QTY: 0,
ORDER_DIV: "",
ZONE_CD: "",
CANCEL_YN: "N",
INSPECT_YN: "N",
INSPECT_CHK: false,
BOX_TYPE: null,
SCANCOMPLETE: true
});
$NC.G_JWINDOW.set({
minWidth: 1050,
minHeight: 560
});
var a = $NC.G_JWINDOW.get("onFocus");
$NC.G_JWINDOW.set("onFocus", function() {
a.call(this, $NC.G_JWINDOW);
setFocusScan();
});
grdMasterInitialize();
grdSubInitialize();
$NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD);
$NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM);
$NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD);
$NC.setInitDatePicker("#dtpQOutbound_Date");
$("#divProgressbar").progressbar();
$("#btnQBu_Cd").click(showUserBuPopup);
$("#btnQCarrier_Cd").click(showCarrierPopup);
$("#btnDeliveryChange").click(onBtnDeliveryChange);
$("#btnBoxSave").click(onBtnBoxSave);
$("#btnBoxComplete").click(onBtnBoxComplete);
$("#btnBoxManage").click(onBtnBoxManage);
$("#btnBWScanConfirm").click(onBtnBWScanConfirm);
$("#btnInit").click(onBtnInit);
$("#edtScan").css("ime-mode", "disabled");
$("#divMasterView,#divGridBox,#divBottomView").mousedown(function(b) {
b.stopImmediatePropagation();
b.preventDefault();
setTimeout(function() {
setFocusScan();
}, 100);
});
$("#divMasterInfoExpender").mouseenter(function(c) {
var b = $("#tblMasterInfoView").data("resizeVal");
if (b == $NC.G_OFFSET.masterInfoMaxLine) {
return;
}
$("#tblMasterInfoView").find("tr").show();
}).mouseleave(function(c) {
var b = $("#tblMasterInfoView").data("resizeVal");
if (b == $NC.G_OFFSET.masterInfoMaxLine) {
return;
}
$("#tblMasterInfoView").find("tr:gt(" + (b - 1) + ")").hide();
}).hide();
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CSUSERCENTER",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_CENTER_CD: "%"
})
}, {
selector: "#cboQCenter_Cd",
codeField: "CENTER_CD",
nameField: "CENTER_NM",
onComplete: function() {
$NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD);
setPolicyValInfo();
}
});
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CMCODE",
P_QUERY_PARAMS: $NC.getParams({
P_CODE_GRP: "DELIVERY_TYPE",
P_CODE_CD: "%",
P_SUB_CD1: "",
P_SUB_CD2: ""
})
}, {
selector: "#cboQDelivery_Type",
codeField: "CODE_CD",
nameField: "CODE_NM",
fullNameField: "CODE_CD_F"
});
$NC.G_VAR.buttons._inquiry = "0";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
$NC.G_JWINDOW.maximise(function() {
setFocusScan();
});
}
function _OnLoaded() {
}
function _SetResizeOffset() {
$NC.G_OFFSET.masterInfoMinLine = 2;
$NC.G_OFFSET.masterInfoMaxLine = 4;
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $("#divBottomView").outerHeight(true)
+ $NC.G_LAYOUT.nonClientHeight - 1;
$NC.G_OFFSET.subConditionHeight = $("#divSubConditionView").outerHeight();
}
function _OnResize(f) {
var g = f.width() - $NC.G_LAYOUT.border1;
var c = f.height() - $NC.G_OFFSET.nonClientHeight;
var e = Math.max($NC.getTruncVal(g * 0.35), 500);
var d = g - e - $NC.G_LAYOUT.margin1 - $NC.G_LAYOUT.border1;
$NC.resizeContainer("#divCenterView", g, c);
$NC.resizeContainer("#divDetailView", d, c);
$NC.resizeContainer("#divMasterView", e, c);
var a = Math.max(Math.min($NC.getTruncVal((c - 500) / 20) * 10, 100), 0);
var b = $("#edtBox_No");
if (a != b.data("resizeVal")) {
b.css({
height: 70 + a,
"font-size": 20 + a
}).data("resizeVal", a);
}
a = $NC.G_OFFSET.masterInfoMaxLine;
if (c < 600) {
a = Math.min(Math.max($NC.G_OFFSET.masterInfoMaxLine - Math.ceil((600 - c) / 35), $NC.G_OFFSET.masterInfoMinLine),
$NC.G_OFFSET.masterInfoMaxLine);
}
b = $("#tblMasterInfoView");
if (a != b.data("resizeVal")) {
b.find("tr:gt(1)").show();
b.find("tr:gt(" + (a) + ")").hide();
b.data("resizeVal", a);
$("#divMasterInfoExpender").hide();
}
$NC.resizeGrid("#grdMaster", d, c - ($NC.G_LAYOUT.header + $NC.G_LAYOUT.border1 + $NC.G_OFFSET.subConditionHeight));
}
function _OnInputKeyDown(d, b) {
var f = b.prop("id").substr(3).toUpperCase();
switch (f) {
case "SCAN":
if (d.keyCode == 9) {
d.stopImmediatePropagation();
return;
}
var a = "";
var c = 0;
if (d.keyCode == 192) {
a = $NC.getValue(b);
c = a.length;
if (isNaN(Number(a) || c.length == 0)) {
d.stopImmediatePropagation();
showMessage("검수수량을 정확히 입력하십시오.");
return;
}
onScanFnNumAdd(a);
onChkFWScanConfirm();
d.stopImmediatePropagation();
return;
}
if (d.keyCode == 109) {
a = $NC.getValue(b);
if (isNaN(Number(a)) || c.length == 0) {
d.stopImmediatePropagation();
showMessage("검수수량을 정확히 입력하십시오.");
return;
}
onScanFnNumSubtract(a);
d.stopImmediatePropagation();
return;
}
if (d.keyCode == 111) {
a = $NC.getValue(b);
if (isNaN(Number(a))) {
d.stopImmediatePropagation();
showMessage("검수수량을 정확히 입력하십시오.");
return;
}
onScanFnNumDivide(a);
onChkFWScanConfirm();
d.stopImmediatePropagation();
return;
}
break;
}
}
function _OnInputKeyUp(d, b) {
var f = b.prop("id").substr(3).toUpperCase();
switch (f) {
case "SCAN":
var a = "";
var c = 0;
if (d.keyCode == 13) {
a = $NC.getValue(b);
c = a.length;
if (c == 0) {
d.stopImmediatePropagation();
return;
}
a = a.toUpperCase();
if (a.substr(0, 2) == "OP" && (a.match(/-/g).length == 4 || a.match(/-/g).length == 3)) {
onScanhas(a);
d.stopImmediatePropagation();
return;
}
if (a.length == 12 || a.length == 6) {
onScanWB_NoYn(a);
d.stopImmediatePropagation();
return;
}
if (a.length < 4) {
a = $NC.getValue(b);
if (isNaN(Number(a))) {
d.stopImmediatePropagation();
showMessage("검수수량을 정확히 입력하십시오.");
return;
}
onScanFnNumDivide(a);
onChkFWScanConfirm();
d.stopImmediatePropagation();
return;
}
onScanItem(a);
onChkFWScanConfirm();
d.stopImmediatePropagation();
}
break;
}
}
function _OnConditionChange(c, a, f) {
var g = a.prop("id").substr(4).toUpperCase();
switch (g) {
case "CENTER_CD":
setPolicyValInfo();
break;
case "BU_CD":
var d;
var b = [ ];
if (!$NC.isNull(f)) {
d = {
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: f
};
b = $NP.getUserBuInfo({
queryParams: d
});
}
if (b.length <= 1) {
onUserBuPopup(b[0]);
} else {
$NP.showUserBuPopup({
queryParams: d,
queryData: b
}, onUserBuPopup, onUserBuPopup);
}
return;
case "CARRIER_CD":
var d;
var b = [ ];
if (!$NC.isNull(f)) {
d = {
P_CARRIER_CD: f,
P_VIEW_DIV: "1"
};
b = $NP.getCarrierInfo({
queryParams: d
});
}
if (b.length <= 1) {
onCarrierPopup(b[0]);
} else {
$NP.showCarrierPopup({
queryParams: d,
queryData: b
}, onCarrierPopup, onCarrierPopup);
}
return;
case "OUTBOUND_DATE":
$NC.setValueDatePicker(a, f, "출고일자를 정확히 입력하십시오.");
break;
}
onChangingCondition();
}
function onChangingCondition() {
$NC.clearGridData(G_GRDMASTER);
$NC.G_VAR.SUM_ENTRY_QTY = 0;
$NC.G_VAR.SUM_CONFIRM_QTY = 0;
$NC.G_VAR.SUM_INSPECT_QTY = 0;
$NC.G_VAR.INSPECT_YN = "N";
$NC.G_VAR.NEWORDER_CHK = "N";
$NC.G_VAR.ORDERCAN_CHK = "N";
$NC.G_VAR.ORDERHOLD_CHK = "N";
$NC.G_VAR.SCANCOMPLETE = true;
$NC.G_VAR.INSPECT_CHK = false;
$NC.G_VAR.BOX_TYPE = "";
$NC.G_VAR.SCAN_CD = "";
$NC.G_VAR.ZONE_CD = "";
$NC.setEnable("#cboQCenter_Cd");
$NC.setEnable("#edtQBu_Cd");
$NC.setEnable("#btnQBu_Cd");
$NC.setEnable("#dtpQOutbound_Date");
$NC.setValue("#edtQOutbound_No");
$NC.setValue("#edtQPacking_Batch");
setOrderInfoValue();
setItemInfoValue();
$NC.setValue("#edtBox_No");
$NC.setValue("#divProgressVal", "0 / 0 [ 0 %]");
$("#divProgressbar").progressbar("value", 0);
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", true);
setEnableButton("#btnDeliveryChange", false);
setFocusScan();
}
function _Inquiry() {
$NC.setInitGridVar(G_GRDMASTER);
var c = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(c)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var b = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(b)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var a = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(a)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
var d = $NC.getValue("#edtQPacking_Batch");
if ($NC.isNull(d)) {
showMessage("묶음차수를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
G_GRDMASTER.queryParams = $NC.getParams({
P_CENTER_CD: c,
P_BU_CD: b,
P_OUTBOUND_DATE: a,
P_OUTBOUND_NO: d,
P_ZONE_CD: $NC.G_VAR.ZONE_CD
});
G_GRDMASTER.queryId = "LOM7010E.RS_MASTER";
$NC.serviceCall("/LOM7010E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster, onError);
}
function _New() {
}
function _Save(n) {
if (G_GRDMASTER.data.getLength() == 0) {
setFocusScan();
return;
}
var l = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(l)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var k = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(k)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var c = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(c)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
var a = $NC.getValue("#edtQOutbound_No");
if ($NC.isNull(a)) {
showMessage("출고번호를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var m = $NC.getValue("#edtQPacking_Batch");
if ($NC.isNull(m)) {
showMessage("묶음차수를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var h = $NC.getValue("#edtBox_No");
if ($NC.isNull(h)) {
showMessage("박스번호를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var g = $NC.getValue("#cboBox_Type");
var p = [ ];
var f;
var e;
for (var j = 0, o = G_GRDMASTER.data.getLength(); j < o; j++) {
e = G_GRDMASTER.data.getItem(j);
if (e.CRUD == "U") {
f = {
P_CENTER_CD: e.CENTER_CD,
P_BU_CD: e.BU_CD,
P_OUTBOUND_DATE: e.OUTBOUND_DATE,
P_OUTBOUND_NO: e.OUTBOUND_NO,
P_BOX_NO: h,
P_BRAND_CD: e.BRAND_CD,
P_ITEM_CD: e.ITEM_CD,
P_ITEM_STATE: e.ITEM_STATE,
P_ITEM_LOT: e.ITEM_LOT,
P_CONFIRM_QTY: e.INSPECT_QTY
};
p.push(f);
}
}
var d = "N";
var b;
switch (n) {
case "onBoxComplete":
if (p.length === 0 && $NC.G_VAR.SUM_INSPECT_QTY == 0) {
showMessage("검수 후 박스완료 처리하십시오.");
return;
}
d = "Y";
b = onBoxComplete;
break;
case "onBoxSave":
if (p.length === 0) {
showMessage("검수 후 박스저장 처리하십시오.");
return;
}
b = onBoxSave;
break;
case "onShowBoxManage":
if (p.length === 0) {
onShowBoxManage();
return;
}
b = onShowBoxManage;
break;
default:
return;
}
$NC.serviceCallAndWait("/LOM7010E/save.do", {
P_DS_MASTER: $NC.getParams({
P_CENTER_CD: l,
P_BU_CD: k,
P_OUTBOUND_DATE: c,
P_OUTBOUND_NO: a,
P_PACKING_BATCH: m,
P_CARRIER_CD: $NC.G_VAR.CARRIER_CD,
P_BOX_NO: h,
P_BOX_TYPE: $NC.G_VAR.BOX_TYPE,
P_USER_ID: $NC.G_USERINFO.USER_ID
}),
P_DS_DETAIL: $NC.toJson(p),
P_COMPLETE_YN: d,
P_CARRIER_CD: $NC.G_VAR.CARRIER_CD
}, b, onError);
}
function _Delete() {
}
function _Cancel() {
var a = $NC.getGridLastKeyVal(G_GRDMASTER, {
selectKey: new Array("BRAND_CD", "OUTBOUND_DATE", "ITEM_CD")
});
_Inquiry();
G_GRDMASTER.lastKeyVal = a;
}
function _Print(a, b) {
}
function grdMasterOnGetColumns() {
var a = [ ];
$NC.setGridColumn(a, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "상품명",
minWidth: 230
});
$NC.setGridColumn(a, {
id: "ENTRY_QTY",
field: "ENTRY_QTY",
name: "등록수량",
minWidth: 85,
cssClass: "align-right"
});
$NC.setGridColumn(a, {
id: "CONFIRM_QTY",
field: "CONFIRM_QTY",
name: "기검수수량",
minWidth: 85,
cssClass: "align-right"
});
$NC.setGridColumn(a, {
id: "INSPECT_QTY",
field: "INSPECT_QTY",
name: "현검수수량",
minWidth: 85,
cssClass: "align-right"
});
$NC.setGridColumn(a, {
id: "REMAIN_QTY",
field: "REMAIN_QTY",
name: "미검수수량",
minWidth: 85,
cssClass: "align-right"
});
$NC.setGridColumn(a, {
id: "QTY_IN_BOX",
field: "QTY_IN_BOX",
name: "입수",
minWidth: 60,
cssClass: "align-right"
});
$NC.setGridColumn(a, {
id: "ITEM_BAR_CD",
field: "ITEM_BAR_CD",
name: "상품바코드",
minWidth: 100
});
$NC.setGridColumn(a, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "상품코드",
minWidth: 100
});
$NC.setGridColumn(a, {
id: "BRAND_NM",
field: "BRAND_NM",
name: "브랜드명",
minWidth: 90
});
return $NC.setGridColumnDefaultFormatter(a);
}
function grdMasterInitialize() {
var a = {
frozenColumn: 3,
rowHeight: 32,
specialRow: {
compareFn: function(b, c) {
if (c.INSPECT_YN === "Y") {
return "specialrow3";
}
if (c.REMAIN_QTY == 0) {
return "specialrow4";
}
}
}
};
$NC.setInitGridObject("#grdMaster", {
columns: grdMasterOnGetColumns(),
queryId: "LOM7010E.RS_MASTER",
sortCol: "ITEM_CD",
gridOptions: a
});
G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll);
}
function grdMasterOnAfterScroll(b, a) {
var c = a.rows[0];
if (G_GRDMASTER.lastRow != null) {
if (c == G_GRDMASTER.lastRow) {
b.stopImmediatePropagation();
return;
}
}
setItemInfoValue(G_GRDMASTER.data.getItem(c));
$NC.setGridDisplayRows("#grdMaster", c + 1);
setFocusScan();
}
function onBtnBoxSave(a) {
if ($(a.target).hasClass("disabled")) {
return;
}
_Save("onBoxSave");
}
function onBtnBoxComplete(a) {
if (a != undefined && $(a.target).hasClass("disabled")) {
return;
}
if ($NC.isNull($NC.G_VAR.CARRIER_CD)) {
showMessage("운송사 선택 후 박스완료 처리하십시오.");
return;
}
if ($NC.isNull($NC.G_USERINFO.PRINT_WB_NO) || $NC.isNull($NC.G_USERINFO.PRINT_LO_BILL)
|| $NC.isNull($NC.G_USERINFO.PRINT_CARD)) {
alert("설정하신 프린터가 없습니다.\n\n자동출력프린터를 먼저 등록하십시오.");
return;
}
$NC.G_VAR.BOX_TYPE = "01";
_Save("onBoxComplete");
}
function onBtnBoxManage(a) {
if ($(a.target).hasClass("disabled")) {
return;
}
_Save("onShowBoxManage");
}
function onBtnFWScanConfirm(g) {
if (g != undefined && $(g.target).hasClass("disabled")) {
return;
}
if (G_GRDMASTER.data.getLength() == 0) {
setFocusScan();
return;
}
if ($NC.G_VAR.SUM_INSPECT_QTY > 0 && $NC.G_VAR.SCANCOMPLETE) {
showMessage("박스완료하지 않은 검수내역이 존재합니다.\n\n박스완료 후 검수완료 처리하십시오.");
return;
}
var d = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(d)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var b = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(b)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var a = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(a)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
var f = $NC.getValue("#edtQOutbound_No");
if ($NC.isNull(f)) {
showMessage("출고번호를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var h = $NC.getValue("#edtQPacking_Batch");
if ($NC.isNull(h)) {
showMessage("묶음차수를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var c = "";
if ($NC.G_VAR.SUM_ENTRY_QTY > $NC.G_VAR.SUM_CONFIRM_QTY + $NC.G_VAR.SUM_INSPECT_QTY) {
c = "미검수 상품이 존재합니다.\n\n검수완료 처리하시겠습니까?";
}
if (c == "" || c == undefined) {
$NC.serviceCall("/LOM7010E/callFWScanConfirm.do", {
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: d,
P_BU_CD: b,
P_OUTBOUND_DATE: a,
P_PACKING_BATCH: h,
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onFWScanConfirm, onError);
} else {
showMessage({
message: c,
onYesFn: function() {
$NC.serviceCall("/LOM7010E/callFWScanConfirm.do", {
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: d,
P_BU_CD: b,
P_OUTBOUND_DATE: a,
P_PACKING_BATCH: h,
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onFWScanConfirm, onError);
},
onNoFn: function() {
setFocusScan();
}
});
}
}
function onBtnDeliveryChange(c) {
if ($(c.target).hasClass("disabled")) {
return;
}
if (G_GRDMASTER.data.getLength() == 0) {
setFocusScan();
return;
}
var b = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
var a = $NC.getValue("#cboQDelivery_Type");
if (b.DELIVERY_TYPE == a) {
alert("동일한 배송유형으로 변경 처리하실 수 없습니다");
setFocusScan();
return;
}
showMessage({
message: "배송유형변경 처리하시겠습니까?",
onYesFn: function() {
$NC.serviceCall("/LOM7010E/callSP.do", {
P_QUERY_ID: "LO_FW_DIRECTIONS_INVNO_PROC2",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: b.CENTER_CD,
P_BU_CD: b.BU_CD,
P_OUTBOUND_DATE: b.OUTBOUND_DATE,
P_OUTBOUND_NO: b.OUTBOUND_NO,
P_WB_NO: b.WB_NO,
P_DIRECTION_INVNO: a,
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onDeliveryChangeSucess, onError);
setFocusScan();
},
onNoFn: function() {
setFocusScan();
}
});
}
function onBtnBWScanConfirm(f) {
if ($(f.target).hasClass("disabled")) {
return;
}
if (G_GRDMASTER.data.getLength() == 0) {
setFocusScan();
return;
}
var c = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(c)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var b = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(b)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var a = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(a)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
var d = $NC.getValue("#edtQOutbound_No");
if ($NC.isNull(d)) {
showMessage("출고번호를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
var g = $NC.getValue("#edtQPacking_Batch");
if ($NC.isNull(g)) {
showMessage("묶음차수를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
showMessage({
message: "검수취소 처리하시겠습니까?",
onYesFn: function() {
$NC.serviceCall("/LOM7010E/callBWScanConfirm.do", {
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: c,
P_BU_CD: b,
P_OUTBOUND_DATE: a,
P_OUTBOUND_NO: d,
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onBWScanConfirm, onError);
setFocusScan();
},
onNoFn: function() {
setFocusScan();
}
});
}
function onBtnInit(b) {
if ($(b.target).hasClass("disabled")) {
return;
}
var a = function() {
onChangingCondition();
$NC.setEnable("#cboQCenter_Cd");
$NC.setEnable("#edtQBu_Cd");
$NC.setEnable("#btnQBu_Cd");
$NC.setEnable("#dtpQOutbound_Date");
setFocusScan();
};
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.G_VAR.INSPECT_YN == "Y") {
a.call(this);
} else {
showMessage({
message: "현재 검수 작업 중 입니다.\n\n초기화 하시겠습니까?",
onYesFn: function() {
a.call(this);
},
onNoFn: function() {
setFocusScan();
}
});
}
return;
}
setFocusScan();
}
function onGetMaster(a) {
$NC.setInitGridData(G_GRDMASTER, a);
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.isNull(G_GRDMASTER.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridSelectRow(G_GRDMASTER, {
selectKey: ["BRAND_CD", "OUTBOUND_DATE", "ITEM_CD"],
selectVal: G_GRDMASTER.lastKeyVal
});
}
$NC.setEnable("#cboQCenter_Cd", false);
$NC.setEnable("#edtQBu_Cd", false);
$NC.setEnable("#btnQBu_Cd", false);
$NC.setEnable("#dtpQOutbound_Date", false);
} else {
$NC.setGridDisplayRows("#grdMaster", 0, 0);
onChangingCondition();
showMessage("존재하지 않는 출고전표입니다. 확인 후 작업하십시오.");
return;
}
var b = G_GRDMASTER.data.getItem(0);
setOrderInfoValue(b);
onCalcSummary();
$NC.G_VAR.INSPECT_YN = b.INSPECT_YN;
$NC.G_VAR.NEWORDER_CHK = b.ORDER_CHK;
$NC.G_VAR.ORDERCAN_CHK = b.ORDER_CAN;
$NC.G_VAR.ORDERHOLD_CHK = b.ORDER_HOLD;
if ($NC.G_VAR.ORDERCAN_CHK == "Y") {
if (b.ORDER_DIV == "2") {
alert("합포장 주문에 주문취소 건이 포함되어있습니다.\n\n 피킹지시서와 상품을 함께 사무실로 인계바랍니다.");
} else {
alert("주문취소 건입니다.\n\n 피킹지시서와 상품을 함께 사무실로 인계바랍니다.");
}
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setValue("#edtBox_No", "주문취소");
$("#edtBox_No").addClass("inspected");
setUpdateOrderCan(b.CENTER_CD, b.BU_CD, b.OUTBOUND_DATE, b.OUTBOUND_NO);
return;
} else {
if ($NC.G_VAR.ORDERHOLD_CHK == "Y") {
alert("주문보류 처리된 전표입니다.\n\n [주문보류관리] 화면에서 해당전표를 확인해 주시기 바랍니다.");
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setValue("#edtBox_No", "주문보류");
$("#edtBox_No").addClass("inspected");
return;
} else {
if ($NC.G_VAR.INSPECT_YN == "Y") {
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", true);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", true);
$NC.setValue("#edtBox_No", "검수완료");
$("#edtBox_No").addClass("inspected");
return;
} else {
if ($NC.G_VAR.NEWORDER_CHK == "Y") {
alert("합포장대상 전표입니다.\n\n 동일한 수령자의 다른 주문전표를 확인해 주시기 바랍니다.");
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setValue("#edtBox_No", "합포장대상 ");
$("#edtBox_No").addClass("inspected");
return;
} else {
$NC.setValue("#edtBox_No", b.BOX_NO);
$("#edtBox_No").removeClass("inspected");
}
}
}
}
setEnableButton("#btnBoxSave", b.BOXING_YN == "N");
setEnableButton("#btnBoxComplete", true);
setEnableButton("#btnBoxManage", true);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
setFocusScan();
}
function onGetMasterByWb_No(a) {
$NC.setInitGridData(G_GRDMASTER, a);
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.isNull(G_GRDMASTER.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridSelectRow(G_GRDMASTER, {
selectKey: ["BRAND_CD", "OUTBOUND_DATE", "ITEM_CD"],
selectVal: G_GRDMASTER.lastKeyVal
});
}
var f = G_GRDMASTER.data.getItem(0);
var b = f.CENTER_CD;
var e = f.BU_CD;
var d = f.OUTBOUND_DATE;
var c = f.OUTBOUND_NO;
if (b != $NC.getValue("#cboQCenter_Cd")) {
showMessage("작업중인 물류센터의 전표가 아닙니다.\n\n확인 후 작업하십시오.");
return;
}
$NC.setValue("#edtQBu_Cd", e);
$NC.setValue("#dtpQOutbound_Date", d);
$NC.setValue("#edtQOutbound_No", c);
$NC.setValue("#edtQPacking_Batch", c);
$NC.setEnable("#cboQCenter_Cd", false);
$NC.setEnable("#edtQBu_Cd", false);
$NC.setEnable("#btnQBu_Cd", false);
$NC.setEnable("#dtpQOutbound_Date", false);
} else {
$NC.setGridDisplayRows("#grdMaster", 0, 0);
onChangingCondition();
showMessage("현재 스캔검수를 진행한 내역이 없습니다. 확인 후 작업하십시오.");
return;
}
var f = G_GRDMASTER.data.getItem(0);
setOrderInfoValue(f);
onCalcSummary();
$NC.G_VAR.INSPECT_YN = f.INSPECT_YN;
$NC.G_VAR.NEWORDER_CHK = f.ORDER_CHK;
$NC.G_VAR.ORDERCAN_CHK = f.ORDER_CAN;
$NC.G_VAR.ORDERHOLD_CHK = f.ORDER_HOLD;
if ($NC.G_VAR.ORDERCAN_CHK == "Y") {
if (f.ORDER_DIV == "2") {
alert("합포장 주문에 주문취소 건이 포함되어있습니다.\n\n 피킹지시서와 상품을 함께 사무실로 인계바랍니다.");
} else {
alert("주문취소 건입니다.\n\n 피킹지시서와 상품을 함께 사무실로 인계바랍니다.");
}
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setValue("#edtBox_No", "주문취소");
$("#edtBox_No").addClass("inspected");
setUpdateOrderCan(f.CENTER_CD, f.BU_CD, f.OUTBOUND_DATE, f.OUTBOUND_NO);
return;
} else {
if ($NC.G_VAR.INSPECT_YN == "Y") {
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", true);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", true);
$NC.setValue("#edtBox_No", "검수완료");
$("#edtBox_No").addClass("inspected");
return;
} else {
if ($NC.G_VAR.NEWORDER_CHK == "Y") {
alert("합포장대상 전표입니다.\n\n 동일한 수령자의 다른 주문전표를 확인해 주시기 바랍니다.");
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnFWScanConfirm", true);
$NC.setValue("#edtBox_No", "합포장대상 ");
$("#edtBox_No").addClass("inspected");
return;
} else {
if ($NC.G_VAR.ORDERHOLD_CHK == "Y") {
alert("주문보류 처리된 전표입니다.\n\n [주문보류관리] 화면에서 해당전표를 확인해 주시기 바랍니다.");
setEnableButton("#btnBoxSave", false);
setEnableButton("#btnBoxComplete", false);
setEnableButton("#btnBoxManage", false);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
$NC.setValue("#edtBox_No", "주문보류");
$("#edtBox_No").addClass("inspected");
return;
} else {
$NC.setValue("#edtBox_No", f.BOX_NO);
$("#edtBox_No").removeClass("inspected");
}
}
}
}
setEnableButton("#btnBoxSave", f.BOXING_YN == "N");
setEnableButton("#btnBoxComplete", true);
setEnableButton("#btnBoxManage", true);
setEnableButton("#btnFWScanConfirm", false);
setEnableButton("#btnBWScanConfirm", false);
setEnableButton("#btnDeliveryChange", false);
setFocusScan();
}
function doPrint1() {
var a = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
var b = [ ];
b.push($NC.getValue("#edtBox_No"));
if ($NC.G_VAR.CARRIER_CD == "0020") {
var reportDoc = "lo/LABEL_LOM08";
var queryId = "WR.RS_LABEL_LOM03";
var queryParams = {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_OUTBOUND_DATE: a.OUTBOUND_DATE,
P_OUTBOUND_NO: a.OUTBOUND_NO,
P_PRINT_YN: ""
};
// 출력 호출
$NC.G_MAIN.showPrintPreview({
reportDoc: reportDoc,
queryId: queryId,
queryParams: queryParams,
iFrameNo: 1,
checkedValue: b.toString(),
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO,
internalQueryYn: "N"
});
/*$NC.G_MAIN.silentPrint({
printParams: [{
reportDoc: "lo/LABEL_LOM08",
queryId: "WR.RS_LABEL_LOM03",
queryParams: {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_OUTBOUND_DATE: a.OUTBOUND_DATE,
P_OUTBOUND_NO: a.OUTBOUND_NO,
P_PRINT_YN: ""
},
iFrameNo: 1,
checkedValue: b.toString(),
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO,
internalQueryYn: "N"
}],
onAfterPrint: function() {
setFocusScan();
}
});*/
} else {
var reportDoc = "lo/LABEL_LOM08";
var queryId = "WR.RS_LABEL_LOM02";
var queryParams = {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_OUTBOUND_DATE: a.OUTBOUND_DATE,
P_OUTBOUND_NO: a.OUTBOUND_NO,
P_PRINT_YN: ""
};
// 출력 호출
$NC.G_MAIN.showPrintPreview({
reportDoc: reportDoc,
queryId: queryId,
queryParams: queryParams,
iFrameNo: 1,
checkedValue: b.toString(),
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO,
internalQueryYn: "N"
});
/*$NC.G_MAIN.silentPrint({
printParams: [{
reportDoc: "lo/LABEL_LOM08",
queryId: "WR.RS_LABEL_LOM02",
queryParams: {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_OUTBOUND_DATE: a.OUTBOUND_DATE,
P_OUTBOUND_NO: a.OUTBOUND_NO,
P_PRINT_YN: ""
},
iFrameNo: 1,
checkedValue: b.toString(),
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO,
internalQueryYn: "N"
}],
onAfterPrint: function() {
setFocusScan();
}
});*/
}
}
function onShowBoxManage(a) {
if (!$NC.isNull(a)) {
var d = $NC.toArray(a);
if (d.O_MSG !== "OK") {
showMessage(d.O_MSG);
return;
}
}
var e = $NC.getValue("#cboQCenter_Cd");
var c = $NC.getValue("#edtQBu_Cd");
var b = $NC.getValue("#dtpQOutbound_Date");
var f = $NC.getValue("#edtQOutbound_No");
var g = $NC.getValue("#edtQPacking_Batch");
$NC.G_MAIN.showProgramSubPopup({
PROGRAM_ID: "LOM7011P",
PROGRAM_NM: "박스통합",
url: "lo/LOM7011P.html",
width: 870,
height: 450,
userData: {
P_CENTER_CD: e,
P_BU_CD: c,
P_OUTBOUND_DATE: b,
P_OUTBOUND_NO: f,
P_PACKING_BATCH: g,
P_CARRIER_CD: $NC.G_VAR.CARRIER_CD,
P_POLICY_LO450: $NC.G_VAR.policyVal.LO450,
P_INSPECT_YN: $NC.G_VAR.INSPECT_YN === "Y" ? false : true,
P_CARD_MSG_YN: $NC.isNull($NC.getValue("#edtCard_Msg")) === true ? false : true
},
onCancel: function() {
if ($NC.G_VAR.INSPECT_YN == "Y") {
return;
}
var h = $NC.getGridLastKeyVal(G_GRDMASTER, {
selectKey: new Array("BRAND_CD", "OUTBOUND_DATE", "ITEM_CD")
});
_Inquiry();
G_GRDMASTER.lastKeyVal = h;
}
});
}
function onBoxSave(a) {
_Cancel();
}
function onBoxComplete(a) {
if ($NC.G_VAR.INSPECT_CHK) {
onBtnFWScanConfirm();
} else {
doPrint1();
_Cancel();
}
}
function onFWScanConfirm(a) {
var b = $NC.toArray(a);
if (!$NC.isNull(b)) {
if (b.O_MSG !== "OK") {
showMessage(b.O_MSG);
return;
}
}
doPrint1();
_Inquiry();
}
function onBWScanConfirm(a) {
var b = $NC.toArray(a);
if (!$NC.isNull(b)) {
if (b.O_MSG !== "OK") {
showMessage(b.O_MSG);
return;
}
}
_Inquiry();
}
function onDeliveryChangeSucess(a) {
var b = $NC.toArray(a);
if (!$NC.isNull(b)) {
if (b.O_MSG !== "OK") {
showMessage(b.O_MSG);
return;
}
}
_Inquiry();
}
function onChkFWScanConfirm() {
if (!onValidateScan(true)) {
return;
}
if ($NC.G_VAR.SUM_ENTRY_QTY === $NC.G_VAR.SUM_CONFIRM_QTY + $NC.G_VAR.SUM_INSPECT_QTY) {
$NC.G_VAR.SCANCOMPLETE = false;
$NC.G_VAR.INSPECT_CHK = true;
if (!$NC.isNull($NC.G_USERINFO.PRINT_WB_NO) && !$NC.isNull($NC.G_USERINFO.PRINT_LO_BILL)
&& !$NC.isNull($NC.G_USERINFO.PRINT_CARD)) {
onBtnBoxComplete();
} else {
alert("설정하신 프린터가 없습니다.\n\n자동출력프린터를 먼저 등록하십시오.");
return;
}
return;
}
$NC.G_VAR.SCANCOMPLETE = true;
$NC.G_VAR.INSPECT_CHK = false;
setFocusScan();
}
function showUserBuPopup() {
$NP.showUserBuPopup({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: "%"
}, onUserBuPopup, function() {
setFocusScan();
});
}
function onUserBuPopup(a) {
if (!$NC.isNull(a)) {
$NC.setValue("#edtQBu_Cd", a.BU_CD);
$NC.setValue("#edtQBu_Nm", a.BU_NM);
$NC.setValue("#edtQCust_Cd", a.CUST_CD);
setFocusScan();
} else {
$NC.setValue("#edtQBu_Cd");
$NC.setValue("#edtQBu_Nm");
$NC.setValue("#edtQCust_Cd");
$NC.setFocus("#edtQBu_Cd", true);
}
onChangingCondition();
setPolicyValInfo();
}
function showCarrierPopup() {
var a = $NC.getValue("#edtQCarrier_Cd");
$NP.showCarrierPopup({
queryParams: {
P_CARRIER_CD: a,
P_VIEW_DIV: "1"
}
}, onCarrierPopup, function() {
$NC.setFocus("#edtQCarrier_Cd", true);
});
}
function onCarrierPopup(a) {
if (!$NC.isNull(a)) {
$NC.setValue("#edtQCarrier_Cd", a.CARRIER_CD);
$NC.setValue("#edtQCarrier_Nm", a.CARRIER_NM);
} else {
$NC.setValue("#edtQCarrier_Cd");
$NC.setValue("#edtQCarrier_Nm");
$NC.setFocus("#edtQCarrier_Cd", true);
}
}
function setPolicyValInfo() {
$NC.G_VAR.policyVal.LO420 = "";
$NC.G_VAR.policyVal.LO440 = "";
$NC.G_VAR.policyVal.LO450 = "";
var c = $NC.getValue("#cboQCenter_Cd");
var b = $NC.getValue("#edtQBu_Cd");
for ( var a in $NC.G_VAR.policyVal) {
$NC.serviceCallAndWait("/LOM7010E/callSP.do", {
P_QUERY_ID: "WF.GET_POLICY_VAL",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: c,
P_BU_CD: b,
P_POLICY_CD: a
})
}, onGetPolicyVal, onError);
}
}
function onGetPolicyVal(a) {
var b = $NC.toArray(a.data);
if (!$NC.isNull(b)) {
if (b.O_MSG === "OK") {
$NC.G_VAR.policyVal[b.P_POLICY_CD] = b.O_POLICY_VAL;
}
var c = [ ];
if (b.P_POLICY_CD == "LO440") {
$NC.G_VAR.CARRIER_CD = b.O_POLICY_VAL;
c = $NP.getCarrierInfo({
queryParams: {
P_CARRIER_CD: $NC.G_VAR.CARRIER_CD,
P_VIEW_DIV: "1"
}
});
onCarrierPopup(c[0]);
}
}
}
function onScanhas(a) {
var b = function() {
onChangingCondition();
var c = a.substr(2).split($NC.G_VAR.BARCD_DATA_DIV);
var d = a;
$NC.G_VAR.SCAN_CD = a;
// $NC.serviceCall("/LOM9070E/callWbProc.do", {
// P_QUERY_ID: "LO_HAS_SCAN_CHK",
// P_QUERY_PARAMS: $NC.getParams({
// P_CENTER_CD: $NC.getValue("#cboQCenter_Cd"),
// P_HAS_DATE: $NC.G_USERINFO.LOGIN_DATE,
// P_WB_NO: d,
// P_USER_ID: $NC.G_USERINFO.USER_ID
// })
// }, onExecSP, onSaveError);
onScanOrder($NC.G_VAR.SCAN_CD);
};
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.G_VAR.INSPECT_YN == "N") {
showMessage({
message: "현재 검수 작업 중 입니다.\n\n데이터를 다시 가져오시겠습니까?",
onYesFn: function() {
b.call(this);
},
onNoFn: function() {
setFocusScan();
}
});
} else {
b.call(this);
}
return;
}
b.call(this);
}
function onScanOrder(a) {
var b = function() {
onChangingCondition();
var e = a.substr(2).split($NC.G_VAR.BARCD_DATA_DIV);
var c = e[0];
var g = e[1];
var f = $NC.getDate(e[2]);
var d = e[3];
if (!$NC.isNull(e[4])) {
$NC.G_VAR.ZONE_CD = e[4];
} else {
$NC.G_VAR.ZONE_CD = "";
}
$NC.setValue("#cboQCenter_Cd", c);
$NC.setValue("#edtQBu_Cd", g);
$NC.setValue("#dtpQOutbound_Date", f);
$NC.setValue("#edtQPacking_Batch", d);
_Inquiry();
};
b.call(this);
}
function onScanWB_NoYn(a) {
var d = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(d)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var c = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(c)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var b = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(b)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
$NC.serviceCallAndWait("/LOM7010E/callSP.do", {
P_QUERY_ID: "LOM7010E.GET_WB_NO_YN",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: d,
P_BU_CD: c,
P_OUTBOUND_DATE: b,
P_WB_NO: a
})
}, onGetScanWB_NoYn);
}
function onGetScanWB_NoYn(a) {
var b = $NC.toArray(a);
if ($NC.isNull(b)) {
return;
}
if (b.O_MSG !== "OK") {
showMessage(b.O_MSG);
return;
}
if (b.O_WB_NO_YN == "Y") {
onScanOrderByWB_No(b.P_WB_NO);
return;
} else {
if (G_GRDMASTER.data.getLength() > 0) {
onScanItem(b.P_WB_NO);
onChkFWScanConfirm();
return;
}
}
setFocusScan();
}
function onScanOrderByWB_No(a) {
var b = function() {
onChangingCondition();
var e = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(e)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var d = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(d)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var c = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(c)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
G_GRDMASTER.queryParams = $NC.getParams({
P_CENTER_CD: e,
P_BU_CD: d,
P_OUTBOUND_DATE: c,
P_WB_NO: a
});
G_GRDMASTER.queryId = "LOM7010E.RS_MASTER1";
$NC.serviceCall("/LOM7010E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMasterByWb_No, onError);
};
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.G_VAR.INSPECT_YN == "N") {
showMessage({
message: "현재 검수 작업 중 입니다.\n\n데이터를 다시 가져오시겠습니까?",
onYesFn: function() {
b.call(this);
},
onNoFn: function() {
setFocusScan();
}
});
} else {
b.call(this);
}
return;
}
b.call(this);
}
function onScanItem(a) {
if (!onValidateScan(false)) {
return;
}
if (onScanItemCounting(a)) {
return;
}
var d = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(d)) {
showMessage({
message: "물류센터를 선택하십시오.",
focusSelector: "#cboQCenter_Cd"
});
return;
}
var c = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(c)) {
showMessage({
message: "사업구분 코드를 입력하십시오.",
focusSelector: "#edtQBu_Cd"
});
return;
}
var b = $NC.getValue("#dtpQOutbound_Date");
if ($NC.isNull(b)) {
showMessage({
message: "출고일자를 입력하십시오.",
focusSelector: "#dtpQOutbound_Date"
});
return;
}
var e = $NC.getValue("#edtQOutbound_No");
if ($NC.isNull(e)) {
showMessage("출고번호를 확인할 수 없습니다.\n\n전표를 다시 스캔하십시오.");
return;
}
$NC.serviceCallAndWait("/LOM7010E/callSP.do", {
P_QUERY_ID: "LOM7010E.GET_ITEM_INFO",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: d,
P_BU_CD: c,
P_OUTBOUND_DATE: b,
P_OUTBOUND_NO: e,
P_ITEM_BAR_CD: a
})
}, onGetItemInfo, onError);
}
function onScanBoxType(a) {
if (!onValidateScan(false)) {
return;
}
var b = a;
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CMCODE",
P_QUERY_PARAMS: $NC.getParams({
P_CODE_GRP: "",
P_CODE_CD: "%",
P_SUB_CD1: b,
P_SUB_CD2: ""
})
}, {
selector: "#cboBox_Type",
codeField: "CODE_CD",
nameField: "CODE_NM",
fullNameField: "CODE_CD_F",
onComplete: function() {
var c = $NC.getValue("#cboBox_Type");
if (c == "") {
alert("존재하지 않는 BOX코드 입니다.");
return;
}
}
});
}
function onScanFnButton(a) {
}
function onScanFnNumAdd(a) {
if (!onValidateScan(true)) {
return;
}
var f = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
if (!f) {
showMessage("상품이 선택되지 않았습니다.\n\n상품 선택 또는 스캔 후 입력하십시오.");
return;
}
var e = Number(f.ENTRY_QTY);
var b = Number(f.CONFIRM_QTY);
var c = Number(f.INSPECT_QTY);
var d = Number(a);
if (isNaN(d) || d == 0) {
showMessage("수량을 정확히 입력하십시오.");
return;
}
if (e < c + b + d) {
showMessage("등록수량을 초과해서 검수할 수 없습니다.\n\n수량을 다시 입력하십시오.");
return;
}
f.INSPECT_QTY = c + d;
f.REMAIN_QTY = e - b - c - d;
$NC.setValue("#edtInspect_Qty", f.INSPECT_QTY);
if (f.CRUD === "R") {
f.CRUD = "U";
}
G_GRDMASTER.data.updateItem(f.id, f);
G_GRDMASTER.lastRowModified = true;
setEnableButton("#btnBoxSave", true);
setProgressBar(d);
setFocusScan();
}
function onScanFnNumSubtract(a) {
if (!onValidateScan(true)) {
return;
}
var f = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
if (!f) {
showMessage("상품이 선택되지 않았습니다.\n\n상품 선택 또는 스캔 후 입력하십시오.");
return;
}
var e = Number(f.ENTRY_QTY);
var b = Number(f.CONFIRM_QTY);
var c = Number(f.INSPECT_QTY);
var d = Number(a);
if (isNaN(d) || d == 0) {
showMessage("수량을 정확히 입력하십시오.");
return;
}
if (c < d) {
showMessage("현검수수량이 0보다 작을 수 없습니다\n\n수량을 다시 입력하십시오.");
return;
}
f.INSPECT_QTY = c - d;
f.REMAIN_QTY = e - b - c + d;
$NC.setValue("#edtInspect_Qty", f.INSPECT_QTY);
if (f.CRUD === "R") {
f.CRUD = "U";
}
G_GRDMASTER.data.updateItem(f.id, f);
G_GRDMASTER.lastRowModified = true;
setEnableButton("#btnBoxSave", true);
setProgressBar(d * -1);
setFocusScan();
}
function onScanFnNumDivide(a) {
if (!onValidateScan(true)) {
return;
}
var g = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
if (!g) {
showMessage("상품이 선택되지 않았습니다.\n\n상품 선택 또는 스캔 후 입력하십시오.");
return;
}
var f = Number(g.ENTRY_QTY);
var b = Number(g.CONFIRM_QTY);
var d = Number(g.INSPECT_QTY);
var h = d;
var e = 0;
var c = a.length;
if (c == 0) {
e = f - b - d;
} else {
d = 0;
e = Number(a);
}
if (isNaN(e)) {
showMessage("수량을 정확히 입력하십시오.");
return;
}
if (f < d + b + e) {
showMessage("등록수량을 초과해서 검수할 수 없습니다.\n\n수량을 다시 입력하십시오.");
return;
}
g.INSPECT_QTY = d + e;
g.REMAIN_QTY = f - b - d - e;
$NC.setValue("#edtInspect_Qty", g.INSPECT_QTY);
if (g.CRUD === "R") {
g.CRUD = "U";
}
G_GRDMASTER.data.updateItem(g.id, g);
G_GRDMASTER.lastRowModified = true;
setEnableButton("#btnBoxSave", true);
setProgressBar(g.INSPECT_QTY - h);
setFocusScan();
}
function onValidateScan(a) {
if (G_GRDMASTER.data.getLength() == 0) {
showMessage("현재 검수 중이 아닙니다.\n\n전표를 먼저 스캔하십시오.");
return false;
}
if ($NC.G_VAR.INSPECT_YN == "Y") {
showMessage("검수완료 처리된 전표입니다. 수정할 수 없습니다.");
return false;
}
if ($NC.G_VAR.NEWORDER_CHK == "Y") {
showMessage("합포장 대상 전표입니다. 수정할 수 없습니다.");
return false;
}
if ($NC.G_VAR.ORDERCAN_CHK == "Y") {
showMessage("주문취소 처리된 전표입니다. 수정할 수 없습니다.");
return false;
}
if ($NC.G_VAR.ORDERHOLD_CHK == "Y") {
showMessage("주문보류 처리된 전표입니다. 수정할 수 없습니다.");
return false;
}
if (a) {
if ($NC.G_VAR.policyVal.LO420 !== "Y") {
showMessage("정책 설정에 의해 검수수량을 직접 입력할 수 없습니다.\n\n스캔을 통해 검수 처리하삽시오.");
return false;
}
}
return true;
}
function onCalcSummary() {
if (G_GRDMASTER.data.getLength() == 0) {
$NC.G_VAR.SUM_ENTRY_QTY = 0;
$NC.G_VAR.SUM_CONFIRM_QTY = 0;
$NC.G_VAR.SUM_INSPECT_QTY = 0;
$NC.setValue("#divProgressVal", "0 / 0 [ 0 %]");
$("#divProgressbar").progressbar("value", 0);
} else {
var b = $NC.getGridSumVal(G_GRDMASTER, {
sumKey: ["ENTRY_QTY", "CONFIRM_QTY", "INSPECT_QTY"]
});
$NC.G_VAR.SUM_ENTRY_QTY = b.ENTRY_QTY;
$NC.G_VAR.SUM_INSPECT_QTY = b.INSPECT_QTY;
$NC.G_VAR.SUM_CONFIRM_QTY = b.CONFIRM_QTY;
var a = b.CONFIRM_QTY + b.INSPECT_QTY;
var c = $NC.getRoundVal((a / b.ENTRY_QTY) * 100);
$NC.setValue("#divProgressVal", a + " / " + b.ENTRY_QTY + " [ " + c + "%]");
$("#divProgressbar").progressbar("value", c);
}
}
function onGetItemInfo(a) {
var b = $NC.toArray(a);
if ($NC.isNull(b)) {
return;
}
if (b.O_MSG !== "OK") {
showMessage(b.O_MSG);
return;
}
onScanItemCounting(b.P_ITEM_BARCD, b.O_COLUMN_NM, b.O_ITEM_CD);
}
function onScanItemCounting(j, a, b) {
var h = -1;
var c;
if (!$NC.isNull(a)) {
h = $NC.getGridSearchRow(G_GRDMASTER, {
searchKey: a,
searchVal: j
});
} else {
for (var d = 0, g = G_GRDMASTER.data.getLength(); d < g; d++) {
c = G_GRDMASTER.data.getItem(d);
if (c.REMAIN_QTY > "0") {
if (c.ITEM_CD === j || c.ITEM_BAR_CD === j || c.BOX_BAR_CD === j || c.CASE_BAR_CD === j) {
h = d;
break;
}
}
}
}
if (h == -1) {
showMessage("검수가 완료되었거나 전표에 존재하지 않는 상품입니다. \n\n다른 상품을 스캔하십시오.");
return false;
}
$NC.setGridSelectRow(G_GRDMASTER, h);
c = G_GRDMASTER.data.getItem(G_GRDMASTER.lastRow);
if (!$NC.isNull(a)) {
c[a] = j;
}
var e = 1;
var f = Number(c.ENTRY_QTY);
var l = Number(c.CONFIRM_QTY);
var k = Number(c.INSPECT_QTY);
if (f < k + l + e) {
showMessage("검수가 완료된 상품입니다. 다른 상품을 스캔하십시오.");
return true;
}
c.INSPECT_QTY = k + e;
c.REMAIN_QTY = f - l - k - e;
$NC.setValue("#edtInspect_Qty", c.INSPECT_QTY);
if (c.CRUD === "R") {
c.CRUD = "U";
}
G_GRDMASTER.data.updateItem(c.id, c);
G_GRDMASTER.lastRowModified = true;
setEnableButton("#btnBoxSave", true);
setProgressBar(e);
setFocusScan();
return true;
}
function setFocusScan() {
$NC.setFocus("#edtScan");
$NC.setValue("#edtScan");
}
function setEnableButton(a, c) {
var b = $NC.getView(a);
if (b.length == 0) {
return;
}
if ($NC.isNull(c)) {
c = true;
}
if (c) {
b.removeClass("disabled");
} else {
b.addClass("disabled");
}
}
function setUpdateOrderCan(c, a, b, d) {
$NC.serviceCallAndWait("/LOM7010E/callSP.do", {
P_QUERY_ID: "LOM7010E.SET_ERLOSTATUS_INFO",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: c,
P_BU_CD: a,
P_OUTBOUND_DATE: b,
P_OUTBOUND_NO: d
})
}, onGetUpdateOrderCan, onError);
}
function onGetUpdateOrderCan(a) {
var b = $NC.toArray(a.data);
if (!$NC.isNull(b)) {
if (b.O_MSG === "OK") {
}
}
}
function setItemInfoValue(a) {
if ($NC.isNull(a)) {
a = {};
}
$NC.setValue("#edtItem_Cd", a.ITEM_CD);
$NC.setValue("#edtItem_Nm", a.ITEM_NM);
$NC.setValue("#edtItem_Spec", a.ITEM_SPEC);
$NC.setValue("#edtQty_In_Box", a.QTY_IN_BOX);
$NC.setValue("#edtEntry_Qty", a.ENTRY_QTY);
$NC.setValue("#edtConfirm_Qty", a.CONFIRM_QTY);
$NC.setValue("#edtInspect_Qty", a.INSPECT_QTY);
$NC.setValue("#edtOutbound_No", a.OUTBOUND_NO);
$NC.setValue("#edtQOutbound_No", a.OUTBOUND_NO);
$NC.setValue("#edtBu_No", a.BU_NO);
if (a.DELIVERY_TYPE == "1") {
$NC.G_VAR.CARRIER_CD = "0020";
} else {
$NC.G_VAR.CARRIER_CD = "0010";
}
}
function setOrderInfoValue(a) {
if ($NC.isNull(a)) {
a = {};
}
$NC.setValue("#edtOrderer_Nm", a.ORDERER_NM);
$NC.setValue("#chkGift_Wrap_Yn", a.GIFT_WRAP_YN);
$NC.setValue("#edtCard_From", a.BU_KEY);
$NC.setValue("#edtCard_To", a.CARD_TO);
$NC.setValue("#edtCard_Msg", a.CARD_MSG);
$NC.setValue("#edtOrderer_Msg", a.ORDERER_MSG);
$NC.setValue("#edtPacking_Batch", a.PACKING_BATCH);
$NC.setValue("#edtDelivery_Type", a.DELIVERY_TYPE_D);
$NC.setValue("#edtShip_Type", a.SHIP_TYPE_D);
$NC.setValue("#edtQPacking_Batch", a.PACKING_BATCH);
$NC.setValue("#edtRemark1", a.REMARK1);
if (a.SHIP_TYPE !== "1" && !$NC.isNull(a.SHIP_TYPE) && a.INSPECT_YN == "N") {
alert("[" + a.SHIP_TYPE_D + "] 상품입니다.\n\n 포장 후 사무실로 전달바랍니다.");
setFocusScan();
}
}
function setProgressBar(b) {
if ($NC.isNull(b)) {
b = 0;
}
$NC.G_VAR.SUM_INSPECT_QTY = $NC.G_VAR.SUM_INSPECT_QTY + Number(b);
var a = $NC.G_VAR.SUM_CONFIRM_QTY + $NC.G_VAR.SUM_INSPECT_QTY;
var c = $NC.getRoundVal((a / $NC.G_VAR.SUM_ENTRY_QTY) * 100);
$NC.setValue("#divProgressVal", a + " / " + $NC.G_VAR.SUM_ENTRY_QTY + " [ " + c + "%]");
$("#divProgressbar").progressbar("value", c);
}
function showMessage(b, a) {
if ($NC.isNull(b)) {
return;
}
if ($NC.isNull(a)) {
a = false;
}
if (typeof b == "string") {
$NC.G_MAIN.showMessage({
message: b,
buttons: {
"확인": function() {
$NC.G_MAIN.setFocusActiveWindow();
setFocusScan();
}
},
hideFocus: a
});
return;
}
if ($NC.isNull(b.buttons) && !$NC.isNull(b.focusSelector)) {
$NC.G_MAIN.showMessage({
message: b,
buttons: {
"확인": function() {
$NC.G_MAIN.setFocusActiveWindow();
$NC.setFocus(b.focusSelector);
}
},
hideFocus: a
});
return;
}
var c = {};
if (b.onYesFn) {
c["예"] = function() {
$NC.G_MAIN.setFocusActiveWindow();
b.onYesFn.call(this);
};
}
if (b.onNoFn) {
c["아니오"] = function() {
$NC.G_MAIN.setFocusActiveWindow();
b.onNoFn.call(this);
};
}
$NC.G_MAIN.showMessage({
message: b.message,
buttons: c,
hideFocus: a
});
}
function onError(a) {
var b = $NC.getErrorMessage(a);
switch (b.RESULT_CD) {
case $NC.G_CONSTS.RESULT_CD_ERROR:
$NC.G_MAIN.showMessage({
message: b.RESULT_MSG,
buttons: {
"확인": function() {
$NC.G_MAIN.setFocusActiveWindow();
setFocusScan();
}
},
hideFocus: true
});
break;
case $NC.G_CONSTS.RESULT_CD_ACCESSDENIED:
alert(b.RESULT_MSG);
$NC.G_MAIN.showLoginPopup(1);
break;
case $NC.G_CONSTS.RESULT_CD_ERROR_HTML:
$NC.G_MAIN.showMessage({
title: "오류",
message: b.RESULT_MSG,
width: 700,
height: 450,
buttons: {
"확인": function() {
$NC.G_MAIN.setFocusActiveWindow();
setFocusScan();
}
},
hideFocus: true
});
break;
default:
$NC.G_MAIN.setFocusActiveWindow();
setFocusScan();
}
_Inquiry();
}
function grdSubOnGetColumns() {
var a = [ ];
$NC.setGridColumn(a, {
id: "HAS_NO",
field: "HAS_NO",
name: "HAS처리번호",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(a, {
id: "LINE_NO",
field: "LINE_NO",
name: "HAS처리순번",
minWidth: 40,
cssClass: "align-center"
});
$NC.setGridColumn(a, {
id: "OUTBOUND_DATE",
field: "OUTBOUND_DATE",
name: "출고일자",
minWidth: 140
});
$NC.setGridColumn(a, {
id: "ORDERER_NM",
field: "ORDERER_NM",
name: "주문자명",
minWidth: 80
});
$NC.setGridColumn(a, {
id: "SHIPPER_NM",
field: "SHIPPER_NM",
name: "수령자명",
minWidth: 80
});
$NC.setGridColumn(a, {
id: "SHIPPER_TEL",
field: "SHIPPER_TEL",
name: "전화번호",
minWidth: 150
});
$NC.setGridColumn(a, {
id: "SHIPPER_HP",
field: "SHIPPER_HP",
name: "휴대폰번호",
minWidth: 150
});
$NC.setGridColumn(a, {
id: "SHIPPER_ZIP_CD",
field: "SHIPPER_ZIP_CD",
name: "수령자우편호",
minWidth: 110,
cssClass: "align-center"
});
$NC.setGridColumn(a, {
id: "SHIPPER_ADDR_BASIC",
field: "SHIPPER_ADDR_BASIC",
name: "수령자주소",
minWidth: 160
});
$NC.setGridColumn(a, {
id: "SHIPPER_ADDR_DETAIL",
field: "SHIPPER_ADDR_DETAIL",
name: "수령자상세주소",
minWidth: 160
});
$NC.setGridColumn(a, {
id: "ZONE_CD",
field: "ZONE_CD",
name: "존코드",
minWidth: 40,
cssClass: "align-center"
});
$NC.setGridColumn(a, {
id: "LOCATION_CD",
field: "LOCATION_CD",
name: "LOC",
minWidth: 90
});
$NC.setGridColumn(a, {
id: "END_YN",
field: "END_YN",
name: "처리여부",
minWidth: 80,
cssClass: "align-center"
});
return $NC.setGridColumnDefaultFormatter(a);
}
function grdSubInitialize() {
var a = {
frozenColumn: 4,
rowHeight: 32,
specialRow: {
compareKey: "END_YN",
compareVal: "Y",
compareOperator: "==",
cssClass: "specialrow1"
}
};
$NC.setInitGridObject("#grdSub", {
columns: grdSubOnGetColumns(),
queryId: "LOM7010E.RS_SUB",
gridOptions: a
});
G_GRDSUB.view.onSelectedRowsChanged.subscribe(grdSubOnAfterScroll);
}
function grdSubOnAfterScroll(b, a) {
var c = a.rows[0];
if (G_GRDSUB.lastRow != null) {
if (c == G_GRDSUB.lastRow) {
b.stopImmediatePropagation();
return;
}
}
setItemInfoValue(G_GRDSUB.data.getItem(c));
$NC.setGridDisplayRows("#grdSub", c + 1);
}
function onExecSP(b) {
var d = $NC.toArray(b);
var c = d.RESULT_DATA;
var a = c.substr(0, 1);
if (a == 2) {
onScanOrder($NC.G_VAR.SCAN_CD);
onChangingCondition();
return;
} else {
if (a == 3) {
onScanOrder($NC.G_VAR.SCAN_CD);
onChangingCondition();
return;
} else {
if (a == 4) {
onScanOrder($NC.G_VAR.SCAN_CD);
onChangingCondition();
return;
} else {
if (a == "O") {
onScanOrder($NC.G_VAR.SCAN_CD);
return;
} else {
if (a == 1) {
$NC.setValue("#edtBox_No", "합포장대상");
if (!$NC.isNull(a)) {
if (a !== "1" && a !== "2" && a !== "3") {
onChangingCondition();
alert(d.RESULT_DATA);
return;
}
}
_Inquiry1();
}
}
}
}
}
}
function _Inquiry1() {
var b = $NC.getValue("#cboQCenter_Cd");
var a = $NC.G_USERINFO.LOGIN_DATE;
$NC.setInitGridVar(G_GRDMASTER);
$NC.setInitGridVar(G_GRDSUB);
G_GRDSUB.queryParams = $NC.getParams({
P_CENTER_CD: b,
P_HAS_DATE: a,
P_WB_NO: $NC.G_VAR.SCAN_CD,
P_USER_ID: $NC.G_USERINFO.USER_ID
});
$NC.serviceCall("/LOM7010E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub);
}
function onGetSub(a) {
$NC.setInitGridData(G_GRDSUB, a);
if (G_GRDSUB.data.getLength() > 0) {
if ($NC.isNull(G_GRDSUB.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDSUB, 0);
} else {
$NC.setGridSelectRow(G_GRDSUB, {
selectKey: ["ORDERER_NM", "WB_NO"],
selectVal: G_GRDSUB.lastKeyVal
});
}
doPrint2();
} else {
$NC.setGridDisplayRows("#grdSub", 0, 0);
$NC.setValue("#edtBox_No", "");
}
$NC.G_VAR.buttons._inquiry = "0";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
setFocusScan();
}
function doPrint2() {
var a = G_GRDSUB.data.getItem(G_GRDSUB.lastRow);
var reportDoc = "lo/LABEL_LOM12";
var queryId = "WR.RS_LABEL_LOM12";
var queryParams = {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_HAS_DATE: a.HAS_DATE,
P_HAS_NO: a.HAS_NO,
P_LINE_NO: a.LINE_NO
};
// 출력 호출
$NC.G_MAIN.showPrintPreview({
reportDoc: reportDoc,
queryId: queryId,
queryParams: queryParams,
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO
});
/*$NC.G_MAIN.silentPrint({
printParams: [{
reportDoc: "lo/LABEL_LOM12",
queryId: "WR.RS_LABEL_LOM12",
queryParams: {
P_CENTER_CD: a.CENTER_CD,
P_BU_CD: a.BU_CD,
P_HAS_DATE: a.HAS_DATE,
P_HAS_NO: a.HAS_NO,
P_LINE_NO: a.LINE_NO
},
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_WB_NO
}],
onAfterPrint: function() {
setFocusScan();
}
});*/
}
function onSaveError(a) {
$NC.onError(a);
setFocusScan();
}
|
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
<<<<<<< Sampler
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import Ionicons from "react-native-vector-icons/Ionicons";
import SamplerEditionNavigation from "./components/navigation/Navigation";
import AddSampler from "./components/sampler/addSampler";
const Tabs = createBottomTabNavigator();
const App = () => {
return (
<NavigationContainer>
<Tabs.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
switch (route.name) {
case "Sampler":
iconName = focused ? "musical-notes" : "musical-notes-outline";
break;
case "Add sampler":
iconName = focused ? "add-circle" : "add-circle-outline";
break;
default:
iconName = "ban";
break;
}
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{ activeTintColor: "tomato", inactiveTintColor: "gray" }}
>
<Tabs.Screen name="Sampler" component={SamplerEditionNavigation}/>
<Tabs.Screen name="Add sampler">
{(props) => <AddSampler {...props} />}
</Tabs.Screen>
</Tabs.Navigator>
</NavigationContainer>
=======
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
>>>>>>> main
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
<<<<<<< Sampler
export default App;
=======
>>>>>>> main
|
var React = require('react');
var superagent = require('superagent');
var timer;
var loadingText;
function startTimer(callback) {
loadingText = 'Loading';
timer = setInterval(function() {
loadingText += '.';
callback();
}, 200);
}
function stopTimer(callback) {
clearInterval(timer);
callback();
}
var ViewProfileModal = React.createClass({
getInitialState: function() {
return {
loadingText: ''
}
},
componentWillReceiveProps: function(nextProps) {
console.log('cWRP');
if (this.props.visible === false && nextProps.visible === true) {
this.loadUserProfile();
$(this.refs.viewProfileModal.getDOMNode()).modal('show');
} else if (this.props.visible === true && nextProps.visible === false) {
$(this.refs.viewProfileModal.getDOMNode()).modal('hide');
} else if (nextProps.visible === true) {
$(this.refs.viewProfileModal.getDOMNode()).modal('show');
}
},
loadUserProfile: function() {
var component = this;
startTimer(function() { if (loadingText.length < 15) { component.setState({loadingText: loadingText}) } else { loadingText = 'Loading'; }});
superagent
.get(window.Routing.generate('api_me'))
.end(function(err, res) {
stopTimer(function() { component.setState({loadingText: ''})});
if (res.body.me) {
component.props.actions.loadUserProfile(res.body.me);
}
});
},
handleClose: function() {
this.props.actions.hideViewProfileModal();
},
handleSaveAndClose: function() {
this.props.actions.hideViewProfileModal();
},
render: function () {
var userId = this.props.user.id ? this.props.user.id : '';
var email = this.props.user.email ? this.props.user.email : '';
var username = this.props.user.username ? this.props.user.username : '';
var userProfile = this.state.loadingText ? (<p>{this.state.loadingText}</p>) : (<div><p>id: {userId}</p> <p>username: {email}</p><p>email: {username}</p></div>);
return (
<div ref="viewProfileModal" className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button onClick={this.handleClose} type="button" className="close" data-dismall="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 className="modal-title">Your Profile</h4>
</div>
<div className="modal-body">
{userProfile}
</div>
<div className="modal-footer">
<button onClick={this.handleClose} type="button" className="btn btn-default" data-dismiss="modal">Close</button>
<button onClick={this.handleSaveAndClose} type="button" className="btn btn-primary" data-dismiss="modal">Save Profile</button>
</div>
</div>
</div>
</div>
);
}
});
module.exports = {
ViewProfileModal: ViewProfileModal
};
|
$(document ).ready(function() {
var basepath = $("#basepath").val();
$(document).on('submit','#driverForm',function(e){
e.preventDefault();
if(validateDriver())
{
var formDataserialize = $("#driverForm").serialize();
formDataserialize = decodeURI(formDataserialize);
console.log(formDataserialize);
var formData = { formDatas: formDataserialize };
var type = "POST"; //for creating new resource
var urlpath = basepath + 'driver/driver_action';
$("#driversavebtn").css('display', 'none');
$("#loaderbtn").css('display', 'block');
$.ajax({
type: type,
url: urlpath,
data: formData,
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(result) {
if (result.msg_status == 1) {
$("#suceessmodal").modal({
"backdrop": "static",
"keyboard": true,
"show": true
});
var addurl = basepath + "driver/addDriver";
var listurl = basepath + "driver";
$("#responsemsg").text(result.msg_data);
$("#response_add_more").attr("href", addurl);
$("#response_list_view").attr("href", listurl);
}
else {
$("#driver_response_msg").text(result.msg_data);
}
$("#loaderbtn").css('display', 'none');
$("#driversavebtn").css({
"display": "block",
"margin": "0 auto"
});
},
error: function(jqXHR, exception) {
var msg = '';
}
});
}
});
$(document).on('keyup','#driverpassword',function(e){
e.preventDefault();
var mode = $("#mode").val();
var pass = $("#driverpassword").val();
var prevPass = $("#prvpassword").val();
if(prevPass==pass && mode=="EDIT") {
}
else{
if(pass.length>= 4 ){
$("#loader_search").css("display","block");
$("#already_used").css("display","none");
$("#available").css("display","none");
var type = "POST"; //for creating new resource
var urlpath = basepath + 'driver/checkPassword';
// $("#driversavebtn").css('display', 'none');
// $("#loaderbtn").css('display', 'block');
$.ajax({
type: type,
url: urlpath,
data: {pass:pass},
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(result) {
if(result.msg_status==1){
$("#loader_search").css("display","none");
$("#already_used").css("display","block");
$("#available").css("display","none");
$("#driversavebtn").attr('disabled',true);
}
else{
$("#loader_search").css("display","none");
$("#already_used").css("display","none");
$("#available").css("display","block");
$("#driversavebtn").attr('disabled',false);
}
},
error: function(jqXHR, exception) {
var msg = '';
}
});
}
else{
$("#loader_search").css("display","none");
$("#already_used").css("display","none");
$("#available").css("display","none");
$("#driversavebtn").attr('disabled',false);
}
}
});
// Code
$(document).on('keyup','#drivercode',function(e){
e.preventDefault();
var mode = $("#mode").val();
var drivercode = $("#drivercode").val();
var prevdrivrecode = $("#prvdrivercode").val();
if(drivercode==prevdrivrecode && mode=="EDIT") {
}
else{
$("#error_msg").text("").css("display", "none");
var type = "POST";
var urlpath = basepath + 'driver/checkDriverCode';
$.ajax({
type: type,
url: urlpath,
data: {drivercode:drivercode},
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(result) {
if(result.msg_status==1){
$("#error_msg")
.text("Error : This driver code already exist.Please check...")
.addClass("form_error")
.css("display", "block");
$("#driversavebtn").attr('disabled',true);
}
else{
$("#error_msg").text("").css("display", "none");
$("#driversavebtn").attr('disabled',false);
}
},
error: function(jqXHR, exception) {
var msg = '';
}
});
}
});
$(document).on("click", ".driverstatus", function() {
var uid = $(this).data("driverid");
var status = $(this).data("setstatus");
var url = basepath + 'driver/setStatus';
setActiveStatus(uid, status, url);
});
});/* document ready end */
function validateDriver()
{
var drivercode = $("#drivercode").val();
var drivername = $("#drivername").val();
var vehicleType = $("#vehicleType").val();
var driverpassword = $("#driverpassword").val();
var workingproject = $("#workingproject").val();
$("#error_msg").text("").css("dispaly", "none").removeClass("form_error");
if(drivercode=="")
{
$("#drivercode").focus();
$("#error_msg")
.text("Error : Enter Driver Code")
.addClass("form_error")
.css("display", "block");
return false;
}
if(drivername=="")
{
$("#drivername").focus();
$("#error_msg")
.text("Error : Enter Driver Name")
.addClass("form_error")
.css("display", "block");
return false;
}
if(workingproject=="0")
{
$("#workingproject").focus();
$("#error_msg")
.text("Error : Select Project")
.addClass("form_error")
.css("display", "block");
return false;
}
if(vehicleType=="0")
{
$("#vehicleType").focus();
$("#error_msg")
.text("Error : Select Vehicle Type")
.addClass("form_error")
.css("display", "block");
return false;
}
if(driverpassword=="")
{
$("#driverpassword").focus();
$("#error_msg")
.text("Error : Enter Driver Password")
.addClass("form_error")
.css("display", "block");
return false;
}
if(driverpassword.length <4 )
{
$("#driverpassword").focus();
$("#error_msg")
.text("Error : Enter 4 digit pin")
.addClass("form_error")
.css("display", "block");
return false;
}
return true;
}
|
import React from "react";
import { connect } from "react-redux";
import { Switch, Route, Link } from "react-router-dom";
import { getAbbMonthName } from "utilities/dates";
import Milestone from "./scenes/Milestone";
import TopGreyBar from "../../components/TopGreyBar";
import "./style.css";
const MilestoneListItem = props => {
let dueDate = props.status.new_due_date.split("-");
let dueDateStr = `${getAbbMonthName(parseInt(dueDate[1], 10) - 1)} ${
dueDate[2]
}, ${dueDate[0]}`;
return (
<tr>
<td>
<Link
to={`/projects/${props.projectId}/milestones/${props.milestone.id}`}
>
{props.milestone.title}
</Link>
</td>
<td>{props.statusStr}</td>
<td>{props.status ? props.status.percent_complete + "%" : ""}</td>
<td>{dueDateStr}</td>
<td>{props.status ? props.status.new_budget : ""}</td>
</tr>
);
};
const mapStateToProps = (state, ownProps) => {
let projectId = parseInt(ownProps.match.params.projectId, 10);
let project = state.projects.items.find(({ id }) => id === projectId);
let milestones = state.milestones.items.filter(
({ project }) => project === projectId
);
let milestoneStatuses = state.projectMilestoneDevelopmentStepStatuses.items.filter(
s =>
s.milestone && milestones.find(({ id }) => id === s.milestone)
? true
: false
);
let statuses = state.statuses.items;
return {
milestones,
projectId,
milestoneStatuses,
statuses,
project
};
};
const MilestonesList = connect(mapStateToProps)(props => {
return (
<div className="milestones-list">
<h3 className="text-center">Project Milestones</h3>
<TopGreyBar
projectId={props.projectId}
milestones={props.milestones.length}
showMilestones={true}
milestonesActive={true}
history={props.history}
showNewMilestone={true}
/>
<div className="title">
<div className="label">Project Title</div>
<input
type="text"
value={props.project ? props.project.title : ""}
disabled
/>
</div>
<table>
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th>% Complete</th>
<th>Due Date</th>
<th>Budget</th>
</tr>
</thead>
<tbody>
{props.milestones.map(milestone => {
let milestoneStatuses = props.milestoneStatuses
.filter(ms => ms.milestone === milestone.id)
.sort((a, b) => Date.parse(b.date) - Date.parse(a.date));
let currentStatus = milestoneStatuses.length
? milestoneStatuses[0]
: null;
let statusStr = "";
if (currentStatus)
statusStr = props.statuses.find(
({ id }) => id === currentStatus.status
).display_name;
return (
<MilestoneListItem
key={milestone.id}
milestone={milestone}
status={currentStatus}
statusStr={statusStr}
projectId={props.projectId}
/>
);
})}
</tbody>
</table>
</div>
);
});
const NewMilestone = props => <Milestone {...props} milestone={null} />;
const Milestones = props => (
<div className="milestones">
<Switch>
<Route
path={`/projects/:projectId/milestones/new`}
component={NewMilestone}
/>
<Route
path={`/projects/:projectId/milestones/:milestoneId`}
component={Milestone}
/>
<Route
path={`/projects/:projectId/milestones`}
component={MilestonesList}
/>
</Switch>
</div>
);
export default Milestones;
|
var script = document.getElementById("map_load");
var JS__FILE__ = script.getAttribute("src"); // 获得当前js文件路径
var home = JS__FILE__.substr(0, JS__FILE__.lastIndexOf("/") + 1); // 地图API主目录
// 地图类型 baidu google
var MAP_TYPE = 'baidu';
// websocket请求协议 wss ws
var WEBSOCKET_PROTOCOL = 'ws';
(function () {
window.Map_loadScriptTime = (new Date).getTime();
if (MAP_TYPE === 'baidu') { // 百度地图
document.write('<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=kOyXAhTgxQztZLD6uddERiprSBswsNlc"></script>');
document.write('<script type="text/javascript" src="' + home + 'b_markerClusterer_new.js"></script>');
// document.write('<script type="text/javascript" src="' + home + 'b_markerClusterer.js"></script>');
document.write('<script type="text/javascript" src="' + home + 'b_TextIconOverlay.js"></script>');
document.write('<script type="text/javascript" src="https://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>');
} else { // 谷歌地图
document.write('<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGwT3XelPA7xS3wtyOekwZ6RKCJKV_GKM&libraries=drawing"> </script>');
document.write('<script src="' + home + 'g_markerClusterer.js"></script>');
}
})();
|
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import InfiniteCalendar from './src/index'
var badges = {"20160612":2, "20160621":5};
var today = new Date();
var minDate = new Date(2014,0,1);
var nextweek = new Date(2016,5,29);
render(<InfiniteCalendar badges={badges} selectedDate={today} rangeSelection={true} rangeSelectionBehavior="drag" rangeSelectionEndDate={nextweek} minDate={minDate} />,
document.getElementById('root')
)
|
//소스는 웬만하면 퍼가지 마세요.
//콘솔에 입력하여 실행할수 있습니다.
alert('TG_2를 이용해 주셔서 감사합니다... 로딩을 시작합니다.(일부 사이트에선 tg를 사용하실수 없습니다.(play스토어,크롬새탭등))')
console.log('Loading');
const p = (e) =>{console.log(e)};
const 프린트 = (e) =>{console.log(e)};
const 출력 = (e) =>{console.log(e)};
const p_warn = (e) =>{console.warn(e)};
const 출력_경고 = (e) =>{console.warn(e)};
const a = (e) =>{alert(e)};
const 알림창 = (e) =>{alert(e)};
const print = (e) =>{console.log(e)};
const print_warn = (e) =>{console.warn(e)};
const open = (e) =>{window.open(e)};
const 열기 = (e) =>{window.open(e)};
const o = (e) =>{window.open(e)};
const close = () =>{window.close()};
const 닫기 = () =>{window.close()};
const c = () =>{window.close()};
const href = (e) =>{window.location.href=e};
const 사이트이동 = (e) =>{window.location.href=e};
const h = (e) =>{window.location.href=e};
const google = () =>{window.location.href='https://google.com/'};
const naver = () =>{window.location.href='https://naver.com/'};
const daum = () =>{window.location.href='https://daum.net/'};
const bing = () =>{window.location.href='https://bing.com/'};
const youtube = () =>{window.location.href='https://youtube.com/'};
const 입력창 = (e) =>{prompt(e)};
console.log('Loading_finish');
alert('로딩이 완료되었습니다. TG코드는 한번만 입력하면 해당 콘솔에서 이용 가능하며 타 사이트로 이동할땐 다시 설치해야할수 있습니다.')
console.log('✅인증된 TG가 정상 작동중입니다. (공식빌드 1.0)');
|
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
var Quaternion = (function () {
function Quaternion(x, y, z, w) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
if (w === void 0) { w = 1.0; }
this._x = x;
this._y = y;
this._z = z;
this._w = w;
}
;
Object.defineProperty(Quaternion.prototype, "x", {
get: function () {
return this._x;
},
set: function (value) {
this._x = value;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Quaternion.prototype, "y", {
get: function () {
return this._y;
},
set: function (value) {
this._y = value;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Quaternion.prototype, "z", {
get: function () {
return this._z;
},
set: function (value) {
this._z = value;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Quaternion.prototype, "w", {
get: function () {
return this._w;
},
set: function (value) {
this._w = value;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Quaternion.prototype.set = function (x, y, z, w) {
this._x = x;
this._y = y;
this._z = z;
this._w = w;
this._onChangeCallback();
return this;
};
Quaternion.prototype.copy = function (quaternion) {
this._x = quaternion._x;
this._y = quaternion._y;
this._z = quaternion._z;
this._w = quaternion._w;
this._onChangeCallback();
return this;
};
Quaternion.createFromEuler = function (euler, result) {
// http://www.mathworks.com/matlabcentral/fileexchange/
// 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
// content/SpinCalc.m
var c1 = Math.cos(euler.x / 2);
var c2 = Math.cos(euler.y / 2);
var c3 = Math.cos(euler.z / 2);
var s1 = Math.sin(euler.x / 2);
var s2 = Math.sin(euler.y / 2);
var s3 = Math.sin(euler.z / 2);
if (euler.order === 'XYZ') {
result._x = s1 * c2 * c3 + c1 * s2 * s3;
result._y = c1 * s2 * c3 - s1 * c2 * s3;
result._z = c1 * c2 * s3 + s1 * s2 * c3;
result._w = c1 * c2 * c3 - s1 * s2 * s3;
}
else if (euler.order === 'YXZ') {
result._x = s1 * c2 * c3 + c1 * s2 * s3;
result._y = c1 * s2 * c3 - s1 * c2 * s3;
result._z = c1 * c2 * s3 - s1 * s2 * c3;
result._w = c1 * c2 * c3 + s1 * s2 * s3;
}
else if (euler.order === 'ZXY') {
result._x = s1 * c2 * c3 - c1 * s2 * s3;
result._y = c1 * s2 * c3 + s1 * c2 * s3;
result._z = c1 * c2 * s3 + s1 * s2 * c3;
result._w = c1 * c2 * c3 - s1 * s2 * s3;
}
else if (euler.order === 'ZYX') {
result._x = s1 * c2 * c3 - c1 * s2 * s3;
result._y = c1 * s2 * c3 + s1 * c2 * s3;
result._z = c1 * c2 * s3 - s1 * s2 * c3;
result._w = c1 * c2 * c3 + s1 * s2 * s3;
}
else if (euler.order === 'YZX') {
result._x = s1 * c2 * c3 + c1 * s2 * s3;
result._y = c1 * s2 * c3 + s1 * c2 * s3;
result._z = c1 * c2 * s3 - s1 * s2 * c3;
result._w = c1 * c2 * c3 - s1 * s2 * s3;
}
else if (euler.order === 'XZY') {
result._x = s1 * c2 * c3 - c1 * s2 * s3;
result._y = c1 * s2 * c3 - s1 * c2 * s3;
result._z = c1 * c2 * s3 + s1 * s2 * c3;
result._w = c1 * c2 * c3 + s1 * s2 * s3;
}
result._onChangeCallback();
return result;
};
Quaternion.createFromAxisAngle = function (axis, angle, result) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
// assumes axis is normalized
var halfAngle = angle / 2, s = Math.sin(halfAngle);
result._x = axis.x * s;
result._y = axis.y * s;
result._z = axis.z * s;
result._w = Math.cos(halfAngle);
result._onChangeCallback();
return result;
};
Quaternion.createFromRotationMatrix = function (m, result) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33, s;
if (trace > 0) {
s = 0.5 / Math.sqrt(trace + 1.0);
result._w = 0.25 / s;
result._x = (m32 - m23) * s;
result._y = (m13 - m31) * s;
result._z = (m21 - m12) * s;
}
else if (m11 > m22 && m11 > m33) {
s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
result._w = (m32 - m23) / s;
result._x = 0.25 * s;
result._y = (m12 + m21) / s;
result._z = (m13 + m31) / s;
}
else if (m22 > m33) {
s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
result._w = (m13 - m31) / s;
result._x = (m12 + m21) / s;
result._y = 0.25 * s;
result._z = (m23 + m32) / s;
}
else {
s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
result._w = (m21 - m12) / s;
result._x = (m13 + m31) / s;
result._y = (m23 + m32) / s;
result._z = 0.25 * s;
}
result._onChangeCallback();
return result;
};
Quaternion.inverse = function (quaternion, result) {
result.copy(quaternion);
result.conjugate();
result.normalize();
return result;
};
Quaternion.prototype.conjugate = function () {
this._x *= -1;
this._y *= -1;
this._z *= -1;
this._onChangeCallback();
return this;
};
Quaternion.prototype.lengthSquared = function () {
return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
};
Quaternion.prototype.length = function () {
return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
};
Quaternion.prototype.normalize = function () {
var l = this.length();
if (l === 0) {
this._x = 0;
this._y = 0;
this._z = 0;
this._w = 1;
}
else {
l = 1 / l;
this._x = this._x * l;
this._y = this._y * l;
this._z = this._z * l;
this._w = this._w * l;
}
this._onChangeCallback();
};
Quaternion.multiply = function (a, b, result) {
// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
result._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
result._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
result._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
result._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
result._onChangeCallback();
return result;
};
Quaternion.prototype.multiply = function (q) {
return Quaternion.multiply(this, q, this);
};
Quaternion.prototype.equals = function (quaternion) {
return (quaternion._x === this._x) && (quaternion._y === this._y) && (quaternion._z === this._z) && (quaternion._w === this._w);
};
Quaternion.prototype.onChange = function (callback) {
this._onChangeCallback = callback;
return this;
};
Quaternion.prototype._onChangeCallback = function () {
};
Quaternion.prototype.suppressChangeCallback = function (func) {
var temp = this._onChangeCallback;
this._onChangeCallback = function () { };
func();
this._onChangeCallback = temp;
};
Quaternion.prototype.clone = function () {
return new Quaternion(this._x, this._y, this._z, this._w);
};
Quaternion.prototype.toJS = function () {
return [this._x, this._y, this._z, this._w];
};
Quaternion.slerp = function (qa, qb, t, result) {
var x = qa._x, y = qa._y, z = qa._z, w = qa._w;
var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
if (cosHalfTheta < 0) {
result._w = -qb._w;
result._x = -qb._x;
result._y = -qb._y;
result._z = -qb._z;
cosHalfTheta = -cosHalfTheta;
}
else {
result.copy(qb);
}
if (cosHalfTheta >= 1.0) {
result._w = qa.w;
result._x = qa.x;
result._y = qa.y;
result._z = qa.z;
return;
}
var halfTheta = Math.acos(cosHalfTheta);
var sinHalfTheta = Math.sqrt(1.0 - cosHalfTheta * cosHalfTheta);
if (Math.abs(sinHalfTheta) < 0.001) {
result._w = 0.5 * (w + result._w);
result._x = 0.5 * (x + result._x);
result._y = 0.5 * (y + result._y);
result._z = 0.5 * (z + result._z);
return;
}
var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta;
var ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
result._w = (w * ratioA + result._w * ratioB);
result._x = (x * ratioA + result._x * ratioB);
result._y = (y * ratioA + result._y * ratioB);
result._z = (z * ratioA + result._z * ratioB);
result._onChangeCallback();
};
return Quaternion;
})();
Zia.Quaternion = Quaternion;
})(Zia || (Zia = {}));
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
var Vector3 = (function () {
function Vector3(x, y, z) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
this._x = x;
this._y = y;
this._z = z;
}
;
Object.defineProperty(Vector3.prototype, "x", {
get: function () {
return this._x;
},
set: function (v) {
this._x = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector3.prototype, "y", {
get: function () {
return this._y;
},
set: function (v) {
this._y = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector3.prototype, "z", {
get: function () {
return this._z;
},
set: function (v) {
this._z = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Vector3.prototype.set = function (x, y, z) {
this._x = x;
this._y = y;
this._z = z;
this._onChangeCallback();
return this;
};
Vector3.prototype.applyEuler = function (euler) {
Zia.Quaternion.createFromEuler(euler, Vector3._quaternionTemp);
this.applyQuaternion(Vector3._quaternionTemp);
return this;
};
Vector3.prototype.applyAxisAngle = function (axis, angle) {
Zia.Quaternion.createFromAxisAngle(axis, angle, Vector3._quaternionTemp);
this.applyQuaternion(Vector3._quaternionTemp);
return this;
};
Vector3.prototype.applyMatrix3 = function (m) {
var x = this._x;
var y = this._y;
var z = this._z;
var e = m.elements;
this._x = e[0] * x + e[3] * y + e[6] * z;
this._y = e[1] * x + e[4] * y + e[7] * z;
this._z = e[2] * x + e[5] * y + e[8] * z;
this._onChangeCallback();
return this;
};
Vector3.prototype.applyMatrix4 = function (m) {
// input: Zia.Matrix4 affine matrix
var x = this._x, y = this._y, z = this._z;
var e = m.elements;
this._x = e[0] * x + e[4] * y + e[8] * z + e[12];
this._y = e[1] * x + e[5] * y + e[9] * z + e[13];
this._z = e[2] * x + e[6] * y + e[10] * z + e[14];
this._onChangeCallback();
return this;
};
Vector3.prototype.applyProjection = function (m) {
// input: Zia.Matrix4 projection matrix
var x = this._x, y = this._y, z = this._z;
var e = m.elements;
var d = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
this._x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * d;
this._y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * d;
this._z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * d;
this._onChangeCallback();
return this;
};
Vector3.prototype.applyQuaternion = function (q) {
var x = this._x;
var y = this._y;
var z = this._z;
var qx = q.x;
var qy = q.y;
var qz = q.z;
var qw = q.w;
var ix = qw * x + qy * z - qz * y;
var iy = qw * y + qz * x - qx * z;
var iz = qw * z + qx * y - qy * x;
var iw = -qx * x - qy * y - qz * z;
this._x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
this._y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
this._z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
this._onChangeCallback();
return this;
};
Vector3.prototype.transformDirection = function (m) {
// input: Zia.Matrix4 affine matrix
// vector interpreted as a direction
var x = this._x, y = this._y, z = this._z;
var e = m.elements;
this._x = e[0] * x + e[4] * y + e[8] * z;
this._y = e[1] * x + e[5] * y + e[9] * z;
this._z = e[2] * x + e[6] * y + e[10] * z;
this._onChangeCallback();
this.normalize();
return this;
};
Vector3.prototype.nearEqual = function (right, epsilon) {
return Zia.MathUtil.withinEpsilon(this._x, right._x, epsilon._x) &&
Zia.MathUtil.withinEpsilon(this._y, right._y, epsilon._y) &&
Zia.MathUtil.withinEpsilon(this._z, right._z, epsilon._z);
};
Vector3.prototype.add = function (value) {
return Vector3.add(this, value, this);
};
Vector3.prototype.subtract = function (value) {
return Vector3.subtract(this, value, this);
};
Vector3.prototype.multiply = function (value) {
return Vector3.multiply(this, value, this);
};
Vector3.prototype.multiplyScalar = function (value) {
return Vector3.multiplyScalar(this, value, this);
};
Vector3.prototype.negate = function () {
return Zia.Vector3.negate(this, this);
};
Vector3.prototype.lengthSquared = function () {
return this._x * this._x + this._y * this._y + this._z * this._z;
};
Vector3.prototype.length = function () {
return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z);
};
Vector3.prototype.normalize = function () {
return Zia.Vector3.normalize(this, this);
};
Vector3.prototype.equals = function (v) {
return (v._x === this._x) && (v._y === this._y) && (v._z === this._z);
};
Vector3.prototype.onChange = function (callback) {
this._onChangeCallback = callback;
return this;
};
Vector3.prototype._onChangeCallback = function () { };
Vector3.prototype.suppressChangeCallback = function (func) {
var temp = this._onChangeCallback;
this._onChangeCallback = function () { };
func();
this._onChangeCallback = temp;
};
Vector3.prototype.clone = function (result) {
if (result === void 0) { result = new Vector3(); }
result.set(this._x, this._y, this._z);
return result;
};
Vector3.prototype.toJS = function () {
return [this._x, this._y, this._z];
};
Vector3.prototype.toArray = function () {
return this.toJS();
};
Vector3.add = function (a, b, result) {
result._x = a._x + b._x;
result._y = a._y + b._y;
result._z = a._z + b._z;
result._onChangeCallback();
return result;
};
Vector3.ceil = function (value, result) {
result._x = Math.ceil(value._x);
result._y = Math.ceil(value._y);
result._z = Math.ceil(value._z);
result._onChangeCallback();
return result;
};
Vector3.clamp = function (value, min, max, result) {
if (value._x < min._x) {
result._x = min._x;
}
else if (value._x > max._x) {
result._x = max._x;
}
if (value._y < min._y) {
result._y = min._y;
}
else if (value._y > max._y) {
result._y = max._y;
}
if (value._z < min._z) {
result._z = min._z;
}
else if (value._z > max._z) {
result._z = max._z;
}
result._onChangeCallback();
return result;
};
Vector3.cross = function (a, b, result) {
if (result === void 0) { result = new Vector3(); }
var x = a._x, y = a._y, z = a._z;
result._x = y * b._z - z * b._y;
result._y = z * b._x - x * b._z;
result._z = x * b._y - y * b._x;
result._onChangeCallback();
return result;
};
Vector3.distance = function (value1, value2) {
return Math.sqrt(Vector3.distanceSquared(value1, value2));
};
Vector3.distanceSquared = function (value1, value2) {
var dx = value1._x - value2._x;
var dy = value1._y - value2._y;
var dz = value1._z - value2._z;
return dx * dx + dy * dy + dz * dz;
};
Vector3.divide = function (value1, value2, result) {
result._x = value1._x / value2._x;
result._y = value1._y / value2._y;
result._z = value1._z / value2._z;
result._onChangeCallback();
return result;
};
Vector3.divideScalar = function (v, scalar, result) {
result._x = v._x / scalar;
result._y = v._y / scalar;
result._z = v._z / scalar;
result._onChangeCallback();
return result;
};
Vector3.dot = function (value1, value2) {
return value1._x * value2._x
+ value1._y * value2._y
+ value1._z * value2._z;
};
Vector3.floor = function (value, result) {
result._x = Math.floor(value._x);
result._y = Math.floor(value._y);
result._z = Math.floor(value._z);
result._onChangeCallback();
return result;
};
Vector3.lerp = function (value1, value2, amount, result) {
if (result === void 0) { result = new Vector3(); }
result._x = value1._x + (value2._x - value1._x) * amount;
result._y = value1._y + (value2._y - value1._y) * amount;
result._z = value1._z + (value2._z - value1._z) * amount;
result._onChangeCallback();
return result;
};
Vector3.max = function (value1, value2, result) {
result._x = (value1._x > value2._x) ? value1._x : value2._x;
result._y = (value1._y > value2._y) ? value1._y : value2._y;
result._z = (value1._z > value2._z) ? value1._z : value2._z;
result._onChangeCallback();
return result;
};
Vector3.min = function (value1, value2, result) {
result._x = (value1._x < value2._x) ? value1._x : value2._x;
result._y = (value1._y < value2._y) ? value1._y : value2._y;
result._z = (value1._z < value2._z) ? value1._z : value2._z;
result._onChangeCallback();
return result;
};
Vector3.multiply = function (value1, value2, result) {
result._x = value1._x * value2._x;
result._y = value1._y * value2._y;
result._z = value1._z * value2._z;
result._onChangeCallback();
return result;
};
Vector3.multiplyScalar = function (v, scalar, result) {
result._x = v._x * scalar;
result._y = v._y * scalar;
result._z = v._z * scalar;
result._onChangeCallback();
return result;
};
Vector3.negate = function (value, result) {
return Vector3.multiplyScalar(value, -1, result);
};
Vector3.normalize = function (value, result) {
return Vector3.divideScalar(value, value.length(), result);
};
Vector3.subtract = function (a, b, result) {
result._x = a._x - b._x;
result._y = a._y - b._y;
result._z = a._z - b._z;
result._onChangeCallback();
return result;
};
Vector3._quaternionTemp = new Zia.Quaternion();
Vector3.reflect = (function () {
var v1 = new Vector3();
return function (value, normal, result) {
if (result === void 0) { result = new Vector3(); }
normal.clone(v1);
Vector3.multiplyScalar(v1, 2 * Vector3.dot(value, normal), v1);
return Vector3.subtract(value, v1, result);
};
})();
return Vector3;
})();
Zia.Vector3 = Vector3;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var Color4 = (function () {
function Color4(r, g, b, a) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
Color4.prototype.copy = function (other) {
this.r = other.r;
this.g = other.g;
this.b = other.b;
this.a = other.a;
return this;
};
Color4.prototype.multiplyScalar = function (s) {
this.r *= s;
this.g *= s;
this.b *= s;
return this;
};
Color4.prototype.toJS = function () {
return [this.r, this.g, this.b, this.a];
};
return Color4;
})();
Zia.Color4 = Color4;
})(Zia || (Zia = {}));
/**
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
var Euler = (function () {
function Euler(x, y, z, order) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
if (order === void 0) { order = Euler.DefaultOrder; }
this._x = x;
this._y = y;
this._z = z;
this._order = order;
}
Object.defineProperty(Euler.prototype, "x", {
get: function () {
return this._x;
},
set: function (value) {
this._x = value;
this.onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Euler.prototype, "y", {
get: function () {
return this._y;
},
set: function (value) {
this._y = value;
this.onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Euler.prototype, "z", {
get: function () {
return this._z;
},
set: function (value) {
this._z = value;
this.onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Euler.prototype, "order", {
get: function () {
return this._order;
},
set: function (value) {
this._order = value;
this.onChangeCallback();
},
enumerable: true,
configurable: true
});
Euler.prototype.set = function (x, y, z, order) {
this._x = x;
this._y = y;
this._z = z;
this._order = order || this._order;
this.onChangeCallback();
return this;
};
Euler.prototype.copy = function (euler) {
this._x = euler._x;
this._y = euler._y;
this._z = euler._z;
this._order = euler._order;
this.onChangeCallback();
return this;
};
Euler.prototype.setFromRotationMatrix = function (m, order) {
var clamp = Zia.MathUtil.clamp;
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements;
var m11 = te[0], m12 = te[4], m13 = te[8];
var m21 = te[1], m22 = te[5], m23 = te[9];
var m31 = te[2], m32 = te[6], m33 = te[10];
order = order || this._order;
if (order === 'XYZ') {
this._y = Math.asin(clamp(m13, -1, 1));
if (Math.abs(m13) < 0.99999) {
this._x = Math.atan2(-m23, m33);
this._z = Math.atan2(-m12, m11);
}
else {
this._x = Math.atan2(m32, m22);
this._z = 0;
}
}
else if (order === 'YXZ') {
this._x = Math.asin(-clamp(m23, -1, 1));
if (Math.abs(m23) < 0.99999) {
this._y = Math.atan2(m13, m33);
this._z = Math.atan2(m21, m22);
}
else {
this._y = Math.atan2(-m31, m11);
this._z = 0;
}
}
else if (order === 'ZXY') {
this._x = Math.asin(clamp(m32, -1, 1));
if (Math.abs(m32) < 0.99999) {
this._y = Math.atan2(-m31, m33);
this._z = Math.atan2(-m12, m22);
}
else {
this._y = 0;
this._z = Math.atan2(m21, m11);
}
}
else if (order === 'ZYX') {
this._y = Math.asin(-clamp(m31, -1, 1));
if (Math.abs(m31) < 0.99999) {
this._x = Math.atan2(m32, m33);
this._z = Math.atan2(m21, m11);
}
else {
this._x = 0;
this._z = Math.atan2(-m12, m22);
}
}
else if (order === 'YZX') {
this._z = Math.asin(clamp(m21, -1, 1));
if (Math.abs(m21) < 0.99999) {
this._x = Math.atan2(-m23, m22);
this._y = Math.atan2(-m31, m11);
}
else {
this._x = 0;
this._y = Math.atan2(m13, m33);
}
}
else if (order === 'XZY') {
this._z = Math.asin(-clamp(m12, -1, 1));
if (Math.abs(m12) < 0.99999) {
this._x = Math.atan2(m32, m22);
this._y = Math.atan2(m13, m11);
}
else {
this._x = Math.atan2(-m23, m33);
this._y = 0;
}
}
else {
console.warn('Zia.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
}
this._order = order;
this.onChangeCallback();
return this;
};
Euler.prototype.setFromQuaternion = function (q, order) {
var clamp = Zia.MathUtil.clamp;
// q is assumed to be normalized
// http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
var sqx = q.x * q.x;
var sqy = q.y * q.y;
var sqz = q.z * q.z;
var sqw = q.w * q.w;
order = order || this._order;
if (order === 'XYZ') {
this._x = Math.atan2(2 * (q.x * q.w - q.y * q.z), (sqw - sqx - sqy + sqz));
this._y = Math.asin(clamp(2 * (q.x * q.z + q.y * q.w), -1, 1));
this._z = Math.atan2(2 * (q.z * q.w - q.x * q.y), (sqw + sqx - sqy - sqz));
}
else if (order === 'YXZ') {
this._x = Math.asin(clamp(2 * (q.x * q.w - q.y * q.z), -1, 1));
this._y = Math.atan2(2 * (q.x * q.z + q.y * q.w), (sqw - sqx - sqy + sqz));
this._z = Math.atan2(2 * (q.x * q.y + q.z * q.w), (sqw - sqx + sqy - sqz));
}
else if (order === 'ZXY') {
this._x = Math.asin(clamp(2 * (q.x * q.w + q.y * q.z), -1, 1));
this._y = Math.atan2(2 * (q.y * q.w - q.z * q.x), (sqw - sqx - sqy + sqz));
this._z = Math.atan2(2 * (q.z * q.w - q.x * q.y), (sqw - sqx + sqy - sqz));
}
else if (order === 'ZYX') {
this._x = Math.atan2(2 * (q.x * q.w + q.z * q.y), (sqw - sqx - sqy + sqz));
this._y = Math.asin(clamp(2 * (q.y * q.w - q.x * q.z), -1, 1));
this._z = Math.atan2(2 * (q.x * q.y + q.z * q.w), (sqw + sqx - sqy - sqz));
}
else if (order === 'YZX') {
this._x = Math.atan2(2 * (q.x * q.w - q.z * q.y), (sqw - sqx + sqy - sqz));
this._y = Math.atan2(2 * (q.y * q.w - q.x * q.z), (sqw + sqx - sqy - sqz));
this._z = Math.asin(clamp(2 * (q.x * q.y + q.z * q.w), -1, 1));
}
else if (order === 'XZY') {
this._x = Math.atan2(2 * (q.x * q.w + q.y * q.z), (sqw - sqx + sqy - sqz));
this._y = Math.atan2(2 * (q.x * q.z + q.y * q.w), (sqw + sqx - sqy - sqz));
this._z = Math.asin(clamp(2 * (q.z * q.w - q.x * q.y), -1, 1));
}
else {
console.warn('Zia.Euler: .setFromQuaternion() given unsupported order: ' + order);
}
this._order = order;
return this;
};
Euler.prototype.reorder = function (newOrder) {
// WARNING: this discards revolution information -bhouston
Zia.Quaternion.createFromEuler(this, Euler._reorderTemp);
this.setFromQuaternion(Euler._reorderTemp, newOrder);
};
Euler.prototype.equals = function (euler) {
return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
};
Euler.prototype.onChange = function (callback) {
this.onChangeCallback = callback;
return this;
};
Euler.prototype.onChangeCallback = function () {
};
Euler.prototype.clone = function () {
return new Euler(this._x, this._y, this._z, this._order);
};
Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
Euler.DefaultOrder = 'XYZ';
Euler._reorderTemp = new Zia.Quaternion();
return Euler;
})();
Zia.Euler = Euler;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
Zia.MathUtil = {
TWO_PI: Math.PI * 2,
PI_OVER_TWO: Math.PI / 2,
PI_OVER_FOUR: Math.PI / 4,
withinEpsilon: function (a, b, epsilon) {
var num = a - b;
return ((-epsilon <= num) && (num <= epsilon));
},
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
generateUUID: (function () {
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
return function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++)
uuid[i] = chars[0 | Math.random() * radix];
}
else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
})(),
// Clamp value to range <a, b>
clamp: function (x, a, b) {
return (x < a) ? a : ((x > b) ? b : x);
},
degToRad: function () {
var degreeToRadiansFactor = Math.PI / 180;
return function (degrees) {
return degrees * degreeToRadiansFactor;
};
}(),
};
})(Zia || (Zia = {}));
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
/**
* Represents a 3x3 matrix. The elements are stored in a `Float32Array`
* in column-major order to optimise handoff to WebGL.
*/
var Matrix3 = (function () {
/**
* Constructs a new 3x3 matrix. Parameters are supplied in row-major order
* to aid readability. If called with no parameters, all matrix elements are
* initialised to 0. If called with any parameters, make sure you supply
* all 9 values.
*
* @summary Constructs a new 4x4 matrix.
*
* @param m11 The value for row 0, column 0.
* @param m12 The value for row 0, column 1.
* @param m13 The value for row 0, column 2.
* @param m21 The value for row 1, column 0.
* @param m22 The value for row 1, column 1.
* @param m23 The value for row 1, column 2.
* @param m31 The value for row 2, column 0.
* @param m32 The value for row 2, column 1.
* @param m33 The value for row 2, column 2.
*/
function Matrix3(m11, m12, m13, m21, m22, m23, m31, m32, m33) {
if (m11 === void 0) { m11 = 1.0; }
if (m12 === void 0) { m12 = 0.0; }
if (m13 === void 0) { m13 = 0.0; }
if (m21 === void 0) { m21 = 0.0; }
if (m22 === void 0) { m22 = 1.0; }
if (m23 === void 0) { m23 = 0.0; }
if (m31 === void 0) { m31 = 0.0; }
if (m32 === void 0) { m32 = 0.0; }
if (m33 === void 0) { m33 = 1.0; }
var values = [
m11, m21, m31,
m12, m22, m32,
m13, m23, m33,
];
this.elements = new Float32Array(values);
}
;
Matrix3.prototype.set = function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
var te = this.elements;
te[0] = n11;
te[3] = n12;
te[6] = n13;
te[1] = n21;
te[4] = n22;
te[7] = n23;
te[2] = n31;
te[5] = n32;
te[8] = n33;
return this;
};
Matrix3.createIdentity = function (result) {
result.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
return result;
};
Matrix3.prototype.copy = function (m) {
var me = m.elements;
this.set(me[0], me[3], me[6], me[1], me[4], me[7], me[2], me[5], me[8]);
return this;
};
Matrix3.prototype.multiplyScalar = function (s) {
var te = this.elements;
te[0] *= s;
te[3] *= s;
te[6] *= s;
te[1] *= s;
te[4] *= s;
te[7] *= s;
te[2] *= s;
te[5] *= s;
te[8] *= s;
return this;
};
Matrix3.prototype.determinant = function () {
var te = this.elements;
var a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8];
return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
};
Matrix3.prototype.getInverse = function (matrix, throwOnNonInvertible) {
// input: Zia.Matrix4
// ( based on http://code.google.com/p/webgl-mjs/ )
if (throwOnNonInvertible === void 0) { throwOnNonInvertible = false; }
var me = matrix.elements;
var te = this.elements;
te[0] = me[10] * me[5] - me[6] * me[9];
te[1] = -me[10] * me[1] + me[2] * me[9];
te[2] = me[6] * me[1] - me[2] * me[5];
te[3] = -me[10] * me[4] + me[6] * me[8];
te[4] = me[10] * me[0] - me[2] * me[8];
te[5] = -me[6] * me[0] + me[2] * me[4];
te[6] = me[9] * me[4] - me[5] * me[8];
te[7] = -me[9] * me[0] + me[1] * me[8];
te[8] = me[5] * me[0] - me[1] * me[4];
var det = me[0] * te[0] + me[1] * te[3] + me[2] * te[6];
// no inverse
if (det === 0) {
var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
if (throwOnNonInvertible) {
throw new Error(msg);
}
else {
console.warn(msg);
}
Matrix3.createIdentity(this);
return this;
}
this.multiplyScalar(1.0 / det);
return this;
};
Matrix3.prototype.transpose = function () {
var tmp, m = this.elements;
tmp = m[1];
m[1] = m[3];
m[3] = tmp;
tmp = m[2];
m[2] = m[6];
m[6] = tmp;
tmp = m[5];
m[5] = m[7];
m[7] = tmp;
return this;
};
Matrix3.prototype.getNormalMatrix = function (m) {
// input: Zia.Matrix4
this.getInverse(m).transpose();
return this;
};
Matrix3.prototype.clone = function () {
var te = this.elements;
return new Zia.Matrix3(te[0], te[3], te[6], te[1], te[4], te[7], te[2], te[5], te[8]);
};
return Matrix3;
})();
Zia.Matrix3 = Matrix3;
})(Zia || (Zia = {}));
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
var Matrix4 = (function () {
function Matrix4(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) {
if (m11 === void 0) { m11 = 0.0; }
if (m12 === void 0) { m12 = 0.0; }
if (m13 === void 0) { m13 = 0.0; }
if (m14 === void 0) { m14 = 0.0; }
if (m21 === void 0) { m21 = 0.0; }
if (m22 === void 0) { m22 = 0.0; }
if (m23 === void 0) { m23 = 0.0; }
if (m24 === void 0) { m24 = 0.0; }
if (m31 === void 0) { m31 = 0.0; }
if (m32 === void 0) { m32 = 0.0; }
if (m33 === void 0) { m33 = 0.0; }
if (m34 === void 0) { m34 = 0.0; }
if (m41 === void 0) { m41 = 0.0; }
if (m42 === void 0) { m42 = 0.0; }
if (m43 === void 0) { m43 = 0.0; }
if (m44 === void 0) { m44 = 0.0; }
var values = [
m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44
];
this.elements = new Float32Array(values);
}
Matrix4.compose = function (scale, rotation, translation, result) {
Matrix4.createFromQuaternion(rotation, result);
result.multiply(Matrix4.createScale(scale, Matrix4._composeTemp));
result.setTranslation(translation);
return result;
};
Matrix4.createTranslation = function (translation, result) {
return result.set(1, 0, 0, translation.x, 0, 1, 0, translation.y, 0, 0, 1, translation.z, 0, 0, 0, 1);
};
Matrix4.createRotationX = function (angle, result) {
var c = Math.cos(angle), s = Math.sin(angle);
return result.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
};
Matrix4.createRotationY = function (angle, result) {
var c = Math.cos(angle), s = Math.sin(angle);
return result.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
};
Matrix4.createRotationZ = function (angle, result) {
var c = Math.cos(angle), s = Math.sin(angle);
return result.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
};
Matrix4.createFromAxisAngle = function (axis, angle, result) {
// Based on http://www.gamedev.net/reference/articles/article1199.asp
var c = Math.cos(angle);
var s = Math.sin(angle);
var t = 1 - c;
var x = axis.x, y = axis.y, z = axis.z;
var tx = t * x, ty = t * y;
return result.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
};
Matrix4.createFromQuaternion = function (quaternion, result) {
var te = result.elements;
var x = quaternion.x, y = quaternion.y, z = quaternion.z, w = quaternion.w;
var x2 = x + x, y2 = y + y, z2 = z + z;
var xx = x * x2, xy = x * y2, xz = x * z2;
var yy = y * y2, yz = y * z2, zz = z * z2;
var wx = w * x2, wy = w * y2, wz = w * z2;
te[0] = 1 - (yy + zz);
te[4] = xy - wz;
te[8] = xz + wy;
te[1] = xy + wz;
te[5] = 1 - (xx + zz);
te[9] = yz - wx;
te[2] = xz - wy;
te[6] = yz + wx;
te[10] = 1 - (xx + yy);
te[3] = 0;
te[7] = 0;
te[11] = 0;
te[12] = 0;
te[13] = 0;
te[14] = 0;
te[15] = 1;
return result;
};
Matrix4.createOrthographicOffCenter = function (left, right, bottom, top, near, far, result) {
if (result === void 0) { result = new Matrix4(); }
var te = result.elements;
var w = right - left;
var h = top - bottom;
var p = far - near;
var x = (right + left) / w;
var y = (top + bottom) / h;
var z = (far + near) / p;
te[0] = 2 / w;
te[4] = 0;
te[8] = 0;
te[12] = -x;
te[1] = 0;
te[5] = 2 / h;
te[9] = 0;
te[13] = -y;
te[2] = 0;
te[6] = 0;
te[10] = -2 / p;
te[14] = -z;
te[3] = 0;
te[7] = 0;
te[11] = 0;
te[15] = 1;
return result;
};
Matrix4.createPerspectiveOffCenter = function (left, right, bottom, top, near, far, result) {
if (result === void 0) { result = new Matrix4(); }
var te = result.elements;
var x = 2 * near / (right - left);
var y = 2 * near / (top - bottom);
var a = (right + left) / (right - left);
var b = (top + bottom) / (top - bottom);
var c = -(far + near) / (far - near);
var d = -2 * far * near / (far - near);
te[0] = x;
te[4] = 0;
te[8] = a;
te[12] = 0;
te[1] = 0;
te[5] = y;
te[9] = b;
te[13] = 0;
te[2] = 0;
te[6] = 0;
te[10] = c;
te[14] = d;
te[3] = 0;
te[7] = 0;
te[11] = -1;
te[15] = 0;
return result;
};
Matrix4.createPerspectiveFieldOfView = function (fieldOfView, aspectRatio, near, far, result) {
if (result === void 0) { result = new Matrix4(); }
var ymax = near * Math.tan(fieldOfView * 0.5);
var ymin = -ymax;
var xmin = ymin * aspectRatio;
var xmax = ymax * aspectRatio;
return Matrix4.createPerspectiveOffCenter(xmin, xmax, ymin, ymax, near, far, result);
};
Matrix4.createScale = function (scale, result) {
if (result === void 0) { result = new Matrix4(); }
return result.set(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
};
Matrix4.createUniformScale = function (scale, result) {
if (result === void 0) { result = new Matrix4(); }
return result.set(scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1);
};
Matrix4.createIdentity = function (result) {
if (result === void 0) { result = new Matrix4(); }
return result.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
};
;
Matrix4.multiply = function (left, right, result) {
if (result === void 0) { result = new Matrix4(); }
var ae = left.elements;
var be = right.elements;
var te = result.elements;
var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
return result;
};
Matrix4.multiplyByScalar = function (matrix, scalar, result) {
if (result === void 0) { result = new Matrix4(); }
var te = matrix.elements;
var re = result.elements;
re[0] = te[0] * scalar;
re[1] = te[1] * scalar;
re[2] = te[2] * scalar;
re[3] = te[3] * scalar;
re[4] = te[4] * scalar;
re[5] = te[5] * scalar;
re[6] = te[6] * scalar;
re[7] = te[7] * scalar;
re[8] = te[8] * scalar;
re[9] = te[9] * scalar;
re[10] = te[10] * scalar;
re[11] = te[11] * scalar;
re[12] = te[12] * scalar;
re[13] = te[13] * scalar;
re[14] = te[14] * scalar;
re[15] = te[15] * scalar;
return result;
};
Matrix4.invert = function (matrix, result) {
if (result === void 0) { result = new Matrix4(); }
var te = matrix.elements;
var me = result.elements;
var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
te[0] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
te[4] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
te[8] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
te[12] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
te[1] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
te[5] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
te[9] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
te[13] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
te[2] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
te[6] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
te[10] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
te[14] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
te[3] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
te[7] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
te[11] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
te[15] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
var det = n11 * te[0] + n21 * te[4] + n31 * te[8] + n41 * te[12];
if (det === 0) {
throw new Error("Can't invert matrix, determinant is 0");
}
Matrix4.multiplyByScalar(result, 1 / det, result);
return result;
};
Matrix4.transpose = function (matrix, result) {
if (result === void 0) { result = new Matrix4(); }
var te = matrix.elements;
var re = result.elements;
var tmp;
tmp = te[1];
re[1] = te[4];
re[4] = tmp;
tmp = te[2];
re[2] = te[8];
re[8] = tmp;
tmp = te[6];
re[6] = te[9];
re[9] = tmp;
tmp = te[3];
re[3] = te[12];
re[12] = tmp;
tmp = te[7];
re[7] = te[13];
re[13] = tmp;
tmp = te[11];
re[11] = te[14];
re[14] = tmp;
return result;
};
;
Matrix4.prototype.getTranslation = function (result) {
if (result === void 0) { result = new Zia.Vector3(); }
var te = this.elements;
result.x = te[12];
result.y = te[13];
result.z = te[14];
return result;
};
Matrix4.prototype.setTranslation = function (translation) {
var te = this.elements;
te[12] = translation.x;
te[13] = translation.y;
te[14] = translation.z;
};
Matrix4.prototype.set = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
var te = this.elements;
te[0] = n11;
te[4] = n12;
te[8] = n13;
te[12] = n14;
te[1] = n21;
te[5] = n22;
te[9] = n23;
te[13] = n24;
te[2] = n31;
te[6] = n32;
te[10] = n33;
te[14] = n34;
te[3] = n41;
te[7] = n42;
te[11] = n43;
te[15] = n44;
return this;
};
Matrix4.prototype.makeRotationFromEuler = function (euler) {
var te = this.elements;
var x = euler.x, y = euler.y, z = euler.z;
var a = Math.cos(x), b = Math.sin(x);
var c = Math.cos(y), d = Math.sin(y);
var e = Math.cos(z), f = Math.sin(z);
if (euler.order === 'XYZ') {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[0] = c * e;
te[4] = -c * f;
te[8] = d;
te[1] = af + be * d;
te[5] = ae - bf * d;
te[9] = -b * c;
te[2] = bf - ae * d;
te[6] = be + af * d;
te[10] = a * c;
}
else if (euler.order === 'YXZ') {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[0] = ce + df * b;
te[4] = de * b - cf;
te[8] = a * d;
te[1] = a * f;
te[5] = a * e;
te[9] = -b;
te[2] = cf * b - de;
te[6] = df + ce * b;
te[10] = a * c;
}
else if (euler.order === 'ZXY') {
var ce = c * e, cf = c * f, de = d * e, df = d * f;
te[0] = ce - df * b;
te[4] = -a * f;
te[8] = de + cf * b;
te[1] = cf + de * b;
te[5] = a * e;
te[9] = df - ce * b;
te[2] = -a * d;
te[6] = b;
te[10] = a * c;
}
else if (euler.order === 'ZYX') {
var ae = a * e, af = a * f, be = b * e, bf = b * f;
te[0] = c * e;
te[4] = be * d - af;
te[8] = ae * d + bf;
te[1] = c * f;
te[5] = bf * d + ae;
te[9] = af * d - be;
te[2] = -d;
te[6] = b * c;
te[10] = a * c;
}
else if (euler.order === 'YZX') {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[0] = c * e;
te[4] = bd - ac * f;
te[8] = bc * f + ad;
te[1] = f;
te[5] = a * e;
te[9] = -b * e;
te[2] = -d * e;
te[6] = ad * f + bc;
te[10] = ac - bd * f;
}
else if (euler.order === 'XZY') {
var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
te[0] = c * e;
te[4] = -f;
te[8] = d * e;
te[1] = ac * f + bd;
te[5] = a * e;
te[9] = ad * f - bc;
te[2] = bc * f - ad;
te[6] = b * e;
te[10] = bd * f + ac;
}
te[3] = 0;
te[7] = 0;
te[11] = 0;
te[12] = 0;
te[13] = 0;
te[14] = 0;
te[15] = 1;
return this;
};
Matrix4.prototype.multiply = function (m) {
return Zia.Matrix4.multiply(this, m, this);
};
Matrix4.prototype.determinant = function () {
var te = this.elements;
var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
return (n41 * (+n14 * n23 * n32
- n13 * n24 * n32
- n14 * n22 * n33
+ n12 * n24 * n33
+ n13 * n22 * n34
- n12 * n23 * n34) +
n42 * (+n11 * n23 * n34
- n11 * n24 * n33
+ n14 * n21 * n33
- n13 * n21 * n34
+ n13 * n24 * n31
- n14 * n23 * n31) +
n43 * (+n11 * n24 * n32
- n11 * n22 * n34
- n14 * n21 * n32
+ n12 * n21 * n34
+ n14 * n22 * n31
- n12 * n24 * n31) +
n44 * (-n13 * n22 * n31
- n11 * n23 * n32
+ n11 * n22 * n33
+ n13 * n21 * n32
- n12 * n21 * n33
+ n12 * n23 * n31));
};
Matrix4.prototype.clone = function (result) {
if (result === void 0) { result = new Matrix4(); }
result.elements.set(this.elements);
return result;
};
Matrix4.prototype.decompose = function (scale, rotation, translation) {
var te = this.elements;
var vector = Matrix4._decomposeVectorTemp;
var matrix = Matrix4._decomposeMatrixTemp;
var sx = vector.set(te[0], te[1], te[2]).length();
var sy = vector.set(te[4], te[5], te[6]).length();
var sz = vector.set(te[8], te[9], te[10]).length();
var det = this.determinant();
if (det < 0) {
sx = -sx;
}
translation.x = te[12];
translation.y = te[13];
translation.z = te[14];
matrix.elements.set(this.elements);
var invSX = 1 / sx;
var invSY = 1 / sy;
var invSZ = 1 / sz;
matrix.elements[0] *= invSX;
matrix.elements[1] *= invSX;
matrix.elements[2] *= invSX;
matrix.elements[4] *= invSY;
matrix.elements[5] *= invSY;
matrix.elements[6] *= invSY;
matrix.elements[8] *= invSZ;
matrix.elements[9] *= invSZ;
matrix.elements[10] *= invSZ;
Zia.Quaternion.createFromRotationMatrix(matrix, rotation);
scale.x = sx;
scale.y = sy;
scale.z = sz;
return true;
};
Matrix4._composeTemp = new Matrix4();
Matrix4.createLookAt = (function () {
var x = new Zia.Vector3();
var y = new Zia.Vector3();
var z = new Zia.Vector3();
return function (eye, target, up, result) {
if (result === void 0) { result = new Matrix4(); }
var te = result.elements;
Zia.Vector3.subtract(eye, target, z).normalize();
Zia.Vector3.cross(up, z, x).normalize();
Zia.Vector3.cross(z, x, y);
var translateX = Zia.Vector3.dot(x, eye);
var translateY = Zia.Vector3.dot(y, eye);
var translateZ = Zia.Vector3.dot(z, eye);
te[0] = x.x;
te[4] = x.y;
te[8] = x.z;
te[12] = -translateX;
te[1] = y.x;
te[5] = y.y;
te[9] = y.z;
te[13] = -translateY;
te[2] = z.x;
te[6] = z.y;
te[10] = z.z;
te[14] = -translateZ;
te[3] = 0;
te[7] = 0;
te[11] = 0;
te[15] = 1;
return result;
};
})();
Matrix4._decomposeVectorTemp = new Zia.Vector3();
Matrix4._decomposeMatrixTemp = new Matrix4();
return Matrix4;
})();
Zia.Matrix4 = Matrix4;
})(Zia || (Zia = {}));
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
var Vector2 = (function () {
function Vector2(x, y) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
this._x = x;
this._y = y;
}
Object.defineProperty(Vector2.prototype, "x", {
get: function () {
return this._x;
},
set: function (v) {
this._x = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector2.prototype, "y", {
get: function () {
return this._y;
},
set: function (v) {
this._y = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Vector2.prototype.set = function (x, y) {
this._x = x;
this._y = y;
this._onChangeCallback();
return this;
};
Vector2.prototype.copy = function (v) {
this._x = v._x;
this._y = v._y;
this._onChangeCallback();
return this;
};
Vector2.prototype.add = function (v) {
return Zia.Vector2.add(this, v, this);
};
Vector2.prototype.addVectors = function (a, b) {
this._x = a._x + b._x;
this._y = a._y + b._y;
this._onChangeCallback();
return this;
};
Vector2.prototype.addScalar = function (s) {
this._x += s;
this._y += s;
this._onChangeCallback();
return this;
};
Vector2.prototype.subtract = function (v) {
return Zia.Vector2.subtract(this, v, this);
};
Vector2.prototype.multiply = function (v) {
this._x *= v._x;
this._y *= v._y;
this._onChangeCallback();
return this;
};
Vector2.prototype.multiplyScalar = function (s) {
this._x *= s;
this._y *= s;
this._onChangeCallback();
return this;
};
Vector2.prototype.divide = function (v) {
this._x /= v._x;
this._y /= v._y;
this._onChangeCallback();
return this;
};
Vector2.prototype.divideScalar = function (scalar) {
if (scalar !== 0) {
var invScalar = 1 / scalar;
this._x *= invScalar;
this._y *= invScalar;
}
else {
this._x = 0;
this._y = 0;
}
this._onChangeCallback();
return this;
};
Vector2.prototype.min = function (v) {
if (this._x > v._x) {
this._x = v._x;
}
if (this._y > v._y) {
this._y = v._y;
}
this._onChangeCallback();
return this;
};
Vector2.prototype.max = function (v) {
if (this._x < v._x) {
this._x = v._x;
}
if (this._y < v._y) {
this._y = v._y;
}
this._onChangeCallback();
return this;
};
Vector2.prototype.clamp = function (min, max) {
// This function assumes min < max, if this assumption isn't true it will not operate correctly
if (this._x < min._x) {
this._x = min._x;
}
else if (this._x > max._x) {
this._x = max._x;
}
if (this._y < min._y) {
this._y = min._y;
}
else if (this._y > max._y) {
this._y = max._y;
}
this._onChangeCallback();
return this;
};
Vector2.prototype.clampScalar = function (minVal, maxVal) {
Vector2._clampScalarMinTemp.set(minVal, minVal);
Vector2._clampScalarMaxTemp.set(maxVal, maxVal);
return this.clamp(Vector2._clampScalarMinTemp, Vector2._clampScalarMaxTemp);
};
Vector2.prototype.floor = function () {
this._x = Math.floor(this._x);
this._y = Math.floor(this._y);
this._onChangeCallback();
return this;
};
Vector2.prototype.ceil = function () {
this._x = Math.ceil(this._x);
this._y = Math.ceil(this._y);
this._onChangeCallback();
return this;
};
Vector2.prototype.round = function () {
this._x = Math.round(this._x);
this._y = Math.round(this._y);
this._onChangeCallback();
return this;
};
Vector2.prototype.roundToZero = function () {
this._x = (this._x < 0) ? Math.ceil(this._x) : Math.floor(this._x);
this._y = (this._y < 0) ? Math.ceil(this._y) : Math.floor(this._y);
this._onChangeCallback();
return this;
};
Vector2.prototype.negate = function () {
return this.multiplyScalar(-1);
};
Vector2.prototype.dot = function (v) {
return this._x * v._x + this._y * v._y;
};
Vector2.prototype.lengthSq = function () {
return this._x * this._x + this._y * this._y;
};
Vector2.prototype.length = function () {
return Math.sqrt(this._x * this._x + this._y * this._y);
};
Vector2.prototype.normalize = function () {
return this.divideScalar(this.length());
};
Vector2.prototype.distanceTo = function (v) {
return Math.sqrt(this.distanceToSquared(v));
};
Vector2.prototype.distanceToSquared = function (v) {
var dx = this._x - v._x, dy = this._y - v._y;
return dx * dx + dy * dy;
};
Vector2.prototype.setLength = function (l) {
var oldLength = this.length();
if (oldLength !== 0 && l !== oldLength) {
this.multiplyScalar(l / oldLength);
}
return this;
};
Vector2.prototype.lerp = function (v, alpha) {
this._x += (v._x - this._x) * alpha;
this._y += (v._y - this._y) * alpha;
this._onChangeCallback();
return this;
};
Vector2.prototype.equals = function (v) {
return ((v._x === this._x) && (v._y === this._y));
};
Vector2.prototype.onChange = function (callback) {
this._onChangeCallback = callback;
return this;
};
Vector2.prototype._onChangeCallback = function () {
};
Vector2.prototype.clone = function () {
return new Zia.Vector2(this._x, this._y);
};
Vector2.prototype.toJS = function () {
return [this._x, this._y];
};
Vector2.prototype.toArray = function () {
return this.toJS();
};
Vector2.add = function (value1, value2, result) {
if (result === void 0) { result = new Vector2(); }
result._x = value1._x + value2._x;
result._y = value1._y + value2._y;
result._onChangeCallback();
return result;
};
Vector2.subtract = function (value1, value2, result) {
if (result === void 0) { result = new Vector2(); }
result._x = value1._x - value2._x;
result._y = value1._y - value2._y;
result._onChangeCallback();
return result;
};
;
Vector2._clampScalarMinTemp = new Vector2();
Vector2._clampScalarMaxTemp = new Vector2();
return Vector2;
})();
Zia.Vector2 = Vector2;
})(Zia || (Zia = {}));
/*!
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var Zia;
(function (Zia) {
/**
* Represents a 4-dimensional vector.
*/
var Vector4 = (function () {
/**
* Constructs a new 4-dimensional vector.
*
* @param x The value for the x coordinate.
* @param y The value for the y coordinate.
* @param z The value for the z coordinate.
* @param w The value for the w coordinate.
*/
function Vector4(x, y, z, w) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
if (w === void 0) { w = 1.0; }
this._x = x;
this._y = y;
this._z = z;
this._w = w;
}
;
Object.defineProperty(Vector4.prototype, "x", {
get: function () {
return this._x;
},
set: function (v) {
this._x = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector4.prototype, "y", {
get: function () {
return this._y;
},
set: function (v) {
this._y = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector4.prototype, "z", {
get: function () {
return this._z;
},
set: function (v) {
this._z = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Vector4.prototype, "w", {
get: function () {
return this._w;
},
set: function (v) {
this._w = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Vector4.prototype.set = function (x, y, z, w) {
this._x = x;
this._y = y;
this._z = z;
this._w = w;
this._onChangeCallback();
return this;
};
Vector4.prototype.copy = function (v) {
this._x = v._x;
this._y = v._y;
this._z = v._z;
this._w = (v._w !== undefined) ? v._w : 1;
this._onChangeCallback();
return this;
};
Vector4.prototype.add = function (v) {
this._x += v._x;
this._y += v._y;
this._z += v._z;
this._w += v._w;
this._onChangeCallback();
return this;
};
Vector4.prototype.addScalar = function (s) {
this._x += s;
this._y += s;
this._z += s;
this._w += s;
this._onChangeCallback();
return this;
};
Vector4.prototype.addVectors = function (a, b) {
this._x = a._x + b._x;
this._y = a._y + b._y;
this._z = a._z + b._z;
this._w = a._w + b._w;
this._onChangeCallback();
return this;
};
Vector4.prototype.sub = function (v) {
this._x -= v._x;
this._y -= v._y;
this._z -= v._z;
this._w -= v._w;
this._onChangeCallback();
return this;
};
Vector4.prototype.subVectors = function (a, b) {
this._x = a._x - b._x;
this._y = a._y - b._y;
this._z = a._z - b._z;
this._w = a._w - b._w;
this._onChangeCallback();
return this;
};
Vector4.prototype.multiplyScalar = function (scalar) {
this._x *= scalar;
this._y *= scalar;
this._z *= scalar;
this._w *= scalar;
this._onChangeCallback();
return this;
};
Vector4.prototype.applyMatrix4 = function (m) {
var x = this._x;
var y = this._y;
var z = this._z;
var w = this._w;
var e = m.elements;
this._x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
this._y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
this._z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
this._w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
this._onChangeCallback();
return this;
};
Vector4.prototype.divideScalar = function (scalar) {
if (scalar !== 0) {
var invScalar = 1 / scalar;
this._x *= invScalar;
this._y *= invScalar;
this._z *= invScalar;
this._w *= invScalar;
}
else {
this._x = 0;
this._y = 0;
this._z = 0;
this._w = 1;
}
this._onChangeCallback();
return this;
};
Vector4.prototype.setAxisAngleFromQuaternion = function (q) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
// q is assumed to be normalized
this._w = 2 * Math.acos(q.w);
var s = Math.sqrt(1 - q.w * q.w);
if (s < 0.0001) {
this._x = 1;
this._y = 0;
this._z = 0;
}
else {
this._x = q.x / s;
this._y = q.y / s;
this._z = q.z / s;
}
this._onChangeCallback();
return this;
};
Vector4.prototype.setAxisAngleFromRotationMatrix = function (m) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var angle, x, y, z, epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10];
if ((Math.abs(m12 - m21) < epsilon)
&& (Math.abs(m13 - m31) < epsilon)
&& (Math.abs(m23 - m32) < epsilon)) {
// singularity found
// first check for identity matrix which must have +1 for all terms
// in leading diagonal and zero in other terms
if ((Math.abs(m12 + m21) < epsilon2)
&& (Math.abs(m13 + m31) < epsilon2)
&& (Math.abs(m23 + m32) < epsilon2)
&& (Math.abs(m11 + m22 + m33 - 3) < epsilon2)) {
// this singularity is identity matrix so angle = 0
this.set(1, 0, 0, 0);
return this; // zero angle, arbitrary axis
}
// otherwise this singularity is angle = 180
angle = Math.PI;
var xx = (m11 + 1) / 2;
var yy = (m22 + 1) / 2;
var zz = (m33 + 1) / 2;
var xy = (m12 + m21) / 4;
var xz = (m13 + m31) / 4;
var yz = (m23 + m32) / 4;
if ((xx > yy) && (xx > zz)) {
if (xx < epsilon) {
x = 0;
y = 0.707106781;
z = 0.707106781;
}
else {
x = Math.sqrt(xx);
y = xy / x;
z = xz / x;
}
}
else if (yy > zz) {
if (yy < epsilon) {
x = 0.707106781;
y = 0;
z = 0.707106781;
}
else {
y = Math.sqrt(yy);
x = xy / y;
z = yz / y;
}
}
else {
if (zz < epsilon) {
x = 0.707106781;
y = 0.707106781;
z = 0;
}
else {
z = Math.sqrt(zz);
x = xz / z;
y = yz / z;
}
}
this.set(x, y, z, angle);
return this; // return 180 deg rotation
}
// as we have reached here there are no singularities so we can handle normally
var s = Math.sqrt((m32 - m23) * (m32 - m23)
+ (m13 - m31) * (m13 - m31)
+ (m21 - m12) * (m21 - m12)); // used to normalize
if (Math.abs(s) < 0.001)
s = 1;
// prevent divide by zero, should not happen if matrix is orthogonal and should be
// caught by singularity test above, but I've left it in just in case
this._x = (m32 - m23) / s;
this._y = (m13 - m31) / s;
this._z = (m21 - m12) / s;
this._w = Math.acos((m11 + m22 + m33 - 1) / 2);
this._onChangeCallback();
return this;
};
Vector4.prototype.min = function (v) {
if (this._x > v._x) {
this._x = v._x;
}
if (this._y > v._y) {
this._y = v._y;
}
if (this._z > v._z) {
this._z = v._z;
}
if (this._w > v._w) {
this._w = v._w;
}
this._onChangeCallback();
return this;
};
Vector4.prototype.max = function (v) {
if (this._x < v._x) {
this._x = v._x;
}
if (this._y < v._y) {
this._y = v._y;
}
if (this._z < v._z) {
this._z = v._z;
}
if (this._w < v._w) {
this._w = v._w;
}
this._onChangeCallback();
return this;
};
Vector4.prototype.clamp = function (min, max) {
// This function assumes min < max, if this assumption isn't true it will not operate correctly
if (this._x < min._x) {
this._x = min._x;
}
else if (this._x > max._x) {
this._x = max._x;
}
if (this._y < min._y) {
this._y = min._y;
}
else if (this._y > max._y) {
this._y = max._y;
}
if (this._z < min._z) {
this._z = min._z;
}
else if (this._z > max._z) {
this._z = max._z;
}
if (this._w < min._w) {
this._w = min._w;
}
else if (this._w > max._w) {
this._w = max._w;
}
this._onChangeCallback();
return this;
};
Vector4.prototype.clampScalar = function (minVal, maxVal) {
if (Vector4._min === undefined) {
Vector4._min = new Zia.Vector4();
Vector4._max = new Zia.Vector4();
}
Vector4._min.set(minVal, minVal, minVal, minVal);
Vector4._max.set(maxVal, maxVal, maxVal, maxVal);
return this.clamp(Vector4._min, Vector4._max);
};
;
Vector4.prototype.floor = function () {
this._x = Math.floor(this._x);
this._y = Math.floor(this._y);
this._z = Math.floor(this._z);
this._w = Math.floor(this._w);
this._onChangeCallback();
return this;
};
Vector4.prototype.ceil = function () {
this._x = Math.ceil(this._x);
this._y = Math.ceil(this._y);
this._z = Math.ceil(this._z);
this._w = Math.ceil(this._w);
this._onChangeCallback();
return this;
};
Vector4.prototype.round = function () {
this._x = Math.round(this._x);
this._y = Math.round(this._y);
this._z = Math.round(this._z);
this._w = Math.round(this._w);
this._onChangeCallback();
return this;
};
Vector4.prototype.roundToZero = function () {
this._x = (this._x < 0) ? Math.ceil(this._x) : Math.floor(this._x);
this._y = (this._y < 0) ? Math.ceil(this._y) : Math.floor(this._y);
this._z = (this._z < 0) ? Math.ceil(this._z) : Math.floor(this._z);
this._w = (this._w < 0) ? Math.ceil(this._w) : Math.floor(this._w);
this._onChangeCallback();
return this;
};
Vector4.prototype.negate = function () {
this._x = -this._x;
this._y = -this._y;
this._z = -this._z;
this._w = -this._w;
this._onChangeCallback();
return this;
};
Vector4.prototype.dot = function (v) {
return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
};
Vector4.prototype.lengthSq = function () {
return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
};
Vector4.prototype.length = function () {
return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
};
Vector4.prototype.lengthManhattan = function () {
return Math.abs(this._x) + Math.abs(this._y) + Math.abs(this._z) + Math.abs(this._w);
};
Vector4.prototype.normalize = function () {
return this.divideScalar(this.length());
};
Vector4.prototype.lerp = function (v, alpha) {
this._x += (v._x - this._x) * alpha;
this._y += (v._y - this._y) * alpha;
this._z += (v._z - this._z) * alpha;
this._w += (v._w - this._w) * alpha;
this._onChangeCallback();
return this;
};
Vector4.prototype.equals = function (v) {
return ((v._x === this._x) && (v._y === this._y) && (v._z === this._z) && (v._w === this._w));
};
Vector4.prototype.clone = function () {
return new Zia.Vector4(this._x, this._y, this._z, this._w);
};
Vector4.prototype.onChange = function (callback) {
this._onChangeCallback = callback;
return this;
};
Vector4.prototype._onChangeCallback = function () {
};
Vector4.prototype.suppressChangeCallback = function (func) {
var temp = this._onChangeCallback;
this._onChangeCallback = function () { };
func();
this._onChangeCallback = temp;
};
return Vector4;
})();
Zia.Vector4 = Vector4;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
function mergeVertexData() {
var arrays = [];
for (var _i = 0; _i < arguments.length; _i++) {
arrays[_i - 0] = arguments[_i];
}
var vertexData = [];
if (arrays.length < 1) {
throw "You must pass at least one array in to mergeVertexData";
}
var vertexCount = arrays[0].length;
for (var i = 1; i < arrays.length; i++) {
if (arrays[i].length !== vertexCount) {
throw "All arrays passed in must have the same length";
}
}
for (var i = 0; i < vertexCount; i++) {
for (var j = 0; j < arrays.length; j++) {
Array.prototype.push.apply(vertexData, arrays[j][i].toJS());
}
}
return vertexData;
}
GeometricPrimitive.mergeVertexData = mergeVertexData;
function convertToModel(graphicsDevice, primitive) {
var vertexData = Zia.GeometricPrimitive.mergeVertexData(primitive.positions, primitive.normals, primitive.textureCoordinates);
var vertices = new Float32Array(vertexData);
var vertexBuffer = new Zia.VertexBuffer(graphicsDevice, new Zia.VertexDeclaration([
new Zia.VertexElement("aVertexPosition", 3, 0),
new Zia.VertexElement("aVertexNormal", 3, 3 * 4),
new Zia.VertexElement("aTextureCoord", 2, 6 * 4)
]), vertices);
var indexBuffer = new Zia.IndexBuffer(graphicsDevice, new Uint16Array(primitive.indices));
var program = new Zia.BasicProgram(graphicsDevice);
var model = new Zia.Model([
new Zia.ModelMesh(graphicsDevice, [
new Zia.ModelMeshPart({
indexBuffer: indexBuffer,
startIndex: 0,
indexCount: primitive.indices.length,
vertexBuffer: vertexBuffer
})
])
]);
for (var i = 0; i < model.meshes.length; i++) {
var mesh = model.meshes[i];
for (var j = 0; j < mesh.meshParts.length; j++) {
mesh.meshParts[j].program = program;
}
}
return model;
}
GeometricPrimitive.convertToModel = convertToModel;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
// From http://bocoup.com/weblog/counting-uniforms-in-webgl/
function getProgramInfo(gl, program) {
var result = {
attributes: [],
uniforms: [],
samplers: {}
};
var activeUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
var activeAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
function toSimpleObject(activeInfo, location) {
return {
location: location,
name: activeInfo.name,
size: activeInfo.size,
type: activeInfo.type
};
}
// Loop through active uniforms
for (var i = 0; i < activeUniforms; i++) {
var uniform = gl.getActiveUniform(program, i);
result.uniforms.push(toSimpleObject(uniform, gl.getUniformLocation(program, uniform.name)));
}
// Loop through active attributes
for (var i = 0; i < activeAttributes; i++) {
var attribute = gl.getActiveAttrib(program, i);
result.attributes.push(toSimpleObject(attribute, gl.getAttribLocation(program, attribute.name)));
}
// Loop through samplers
var samplerIndex = 0;
for (var i = 0; i < result.uniforms.length; i++) {
var uniform = result.uniforms[i];
switch (uniform.type) {
case gl.SAMPLER_2D:
case gl.SAMPLER_CUBE:
result.samplers[uniform.name] = samplerIndex++;
break;
}
}
return result;
}
/**
* Wrapper for a single WebGL Program object.
*/
var Program = (function () {
/**
* Constructs a new program.
*
* @param graphicsDevice The graphics device.
* @param vertexShader The vertex shader.
* @param fragmentShader The fragmentShader.
*/
function Program(graphicsDevice, vertexShader, fragmentShader) {
this._graphicsDevice = graphicsDevice;
var gl = this._gl = graphicsDevice.gl;
var program = gl.createProgram();
gl.attachShader(program, vertexShader.shader);
gl.attachShader(program, fragmentShader.shader);
gl.linkProgram(program);
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var error = gl.getProgramInfoLog(program);
gl.deleteProgram(program);
throw new Error('Failed to link program: ' + error);
}
this._program = program;
var programInfo = getProgramInfo(this._gl, this._program);
this._attributes = programInfo.attributes;
this._uniforms = programInfo.uniforms;
this._uniformsByName = {};
for (var i = 0; i < this._uniforms.length; i++) {
var uniform = this._uniforms[i];
this._uniformsByName[uniform.name] = uniform;
}
this._samplerIndices = programInfo.samplers;
}
;
Program.prototype.apply = function () {
this._graphicsDevice._currentProgram = this;
this._gl.useProgram(this._program);
this._onApply();
};
Program.prototype._onApply = function () {
};
Program.prototype.setUniform = function (name, value) {
if (value instanceof Zia.Color4) {
Program._temp.set(value.r, value.g, value.b, value.a);
value = Program._temp;
}
var uniform = this._uniformsByName[name];
if (uniform === undefined) {
return;
}
var gl = this._gl;
switch (uniform.type) {
case gl.FLOAT:
gl.uniform1f(uniform.location, value);
break;
case gl.FLOAT_VEC2:
gl.uniform2f(uniform.location, value._x, value._y);
break;
case gl.FLOAT_VEC3:
gl.uniform3f(uniform.location, value._x, value._y, value._z);
break;
case gl.FLOAT_VEC4:
gl.uniform4f(uniform.location, value.x, value.y, value.z, value.w);
break;
case gl.FLOAT_MAT3:
gl.uniformMatrix3fv(uniform.location, false, value.elements);
break;
case gl.FLOAT_MAT4:
gl.uniformMatrix4fv(uniform.location, false, value.elements);
break;
case gl.SAMPLER_2D:
this._setUniformSampler(gl, uniform, value, gl.TEXTURE_2D);
break;
case gl.SAMPLER_CUBE:
this._setUniformSampler(gl, uniform, value, gl.TEXTURE_CUBE_MAP);
break;
default:
throw "Not implemented for type: " + uniform.type;
}
};
Program.prototype._setUniformSampler = function (gl, uniform, value, textureType) {
var samplerIndex = this._samplerIndices[uniform.name];
gl.activeTexture(gl.TEXTURE0 + samplerIndex);
if (value !== null) {
gl.bindTexture(textureType, value._texture);
gl.uniform1i(uniform.location, samplerIndex);
}
else {
gl.bindTexture(textureType, null);
}
};
Program.prototype.destroy = function () {
var attachedShaders = this._gl.getAttachedShaders(this._program);
for (var i = 0; i < attachedShaders.length; i++) {
this._gl.detachShader(this._program, attachedShaders[i]);
}
this._gl.deleteProgram(this._program);
};
Program._temp = new Zia.Vector4();
return Program;
})();
Zia.Program = Program;
})(Zia || (Zia = {}));
// Based on EffectHelpers from XNA. Original licence follows:
//-----------------------------------------------------------------------------
// EffectHelpers.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
var Zia;
(function (Zia) {
(function (ProgramDirtyFlags) {
ProgramDirtyFlags[ProgramDirtyFlags["ModelViewProj"] = 1] = "ModelViewProj";
ProgramDirtyFlags[ProgramDirtyFlags["Model"] = 2] = "Model";
ProgramDirtyFlags[ProgramDirtyFlags["EyePosition"] = 4] = "EyePosition";
ProgramDirtyFlags[ProgramDirtyFlags["MaterialColor"] = 8] = "MaterialColor";
ProgramDirtyFlags[ProgramDirtyFlags["SpecularColor"] = 16] = "SpecularColor";
ProgramDirtyFlags[ProgramDirtyFlags["SpecularPower"] = 32] = "SpecularPower";
ProgramDirtyFlags[ProgramDirtyFlags["EnvironmentMapAmount"] = 64] = "EnvironmentMapAmount";
ProgramDirtyFlags[ProgramDirtyFlags["EnvironmentMapSpecular"] = 128] = "EnvironmentMapSpecular";
ProgramDirtyFlags[ProgramDirtyFlags["FresnelFactor"] = 256] = "FresnelFactor";
ProgramDirtyFlags[ProgramDirtyFlags["All"] = -1] = "All";
})(Zia.ProgramDirtyFlags || (Zia.ProgramDirtyFlags = {}));
var ProgramDirtyFlags = Zia.ProgramDirtyFlags;
Zia.ProgramUtil = {
enableDefaultLighting: function (light0, light1, light2) {
light0.direction = new Zia.Vector3(-0.5265408, -0.5735765, -0.6275069);
light0.diffuseColor = new Zia.Vector3(1, 0.9607844, 0.8078432);
light0.specularColor = new Zia.Vector3(1, 0.9607844, 0.8078432);
light0.enabled = true;
light1.direction = new Zia.Vector3(0.7198464, 0.3420201, 0.6040227);
light1.diffuseColor = new Zia.Vector3(0.9647059, 0.7607844, 0.4078432);
light1.specularColor = new Zia.Vector3();
light1.enabled = true;
light2.direction = new Zia.Vector3(0.4545195, -0.7660444, 0.4545195);
light2.diffuseColor = new Zia.Vector3(0.3231373, 0.3607844, 0.3937255);
light2.specularColor = new Zia.Vector3(0.3231373, 0.3607844, 0.3937255);
light2.enabled = true;
return new Zia.Vector3(0.05333332, 0.09882354, 0.1819608);
},
setModelViewProj: (function () {
var modelViewProjectionMatrix = new Zia.Matrix4();
return function (program, dirtyFlags, model, view, projection, modelView) {
if ((dirtyFlags & 1) != 0) {
Zia.Matrix4.multiply(view, model, modelView);
Zia.Matrix4.multiply(projection, modelView, modelViewProjectionMatrix);
program.setUniform('uMVPMatrix', modelViewProjectionMatrix);
dirtyFlags &= ~1;
}
return dirtyFlags;
};
})(),
setMaterialColor: function (program, lightingEnabled, alpha, diffuseColor, emissiveColor, ambientLightColor) {
// Desired lighting model:
//
// ((AmbientLightColor + sum(diffuse directional light)) * DiffuseColor) + EmissiveColor
//
// When lighting is disabled, ambient and directional lights are ignored, leaving:
//
// DiffuseColor + EmissiveColor
//
// For the lighting disabled case, we can save one shader instruction by precomputing
// diffuse+emissive on the CPU, after which the shader can use DiffuseColor directly,
// ignoring its emissive parameter.
//
// When lighting is enabled, we can merge the ambient and emissive settings. If we
// set our emissive parameter to emissive+(ambient*diffuse), the shader no longer
// needs to bother adding the ambient contribution, simplifying its computation to:
//
// (sum(diffuse directional light) * DiffuseColor) + EmissiveColor
//
// For further optimization goodness, we merge material alpha with the diffuse
// color parameter, and premultiply all color values by this alpha.
if (lightingEnabled) {
var diffuse = new Zia.Vector4(diffuseColor.x * alpha, diffuseColor.y * alpha, diffuseColor.z * alpha, alpha);
var emissive = new Zia.Vector3((emissiveColor.x + ambientLightColor.x * diffuseColor.x) * alpha, (emissiveColor.y + ambientLightColor.y * diffuseColor.y) * alpha, (emissiveColor.z + ambientLightColor.z * diffuseColor.z) * alpha);
program.setUniform('uDiffuseColor', diffuse);
program.setUniform('uEmissiveColor', emissive);
}
else {
var diffuse = new Zia.Vector4((diffuseColor.x + emissiveColor.x) * alpha, (diffuseColor.y + emissiveColor.y) * alpha, (diffuseColor.z + emissiveColor.z) * alpha, alpha);
program.setUniform('uDiffuseColor', diffuse);
}
},
setLightingMatrices: (function () {
var modelInverseTransposeMatrix = new Zia.Matrix3();
var viewInverseMatrix = new Zia.Matrix4();
var eyePosition = new Zia.Vector3();
return function (program, dirtyFlags, model, view) {
if ((dirtyFlags & 2) != 0) {
program.setUniform('uMMatrix', model);
modelInverseTransposeMatrix.getNormalMatrix(model);
program.setUniform('uMMatrixInverseTranspose', modelInverseTransposeMatrix);
dirtyFlags &= ~2;
}
if ((dirtyFlags & 4) != 0) {
Zia.Matrix4.invert(viewInverseMatrix, view);
viewInverseMatrix.getTranslation(eyePosition);
program.setUniform('uEyePosition', eyePosition);
dirtyFlags &= ~4;
}
return dirtyFlags;
};
})()
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (Comparison) {
Comparison[Comparison["Never"] = 0] = "Never";
Comparison[Comparison["Always"] = 1] = "Always";
Comparison[Comparison["Less"] = 2] = "Less";
Comparison[Comparison["Equal"] = 3] = "Equal";
Comparison[Comparison["LessEqual"] = 4] = "LessEqual";
Comparison[Comparison["Greater"] = 5] = "Greater";
Comparison[Comparison["GreaterEqual"] = 6] = "GreaterEqual";
Comparison[Comparison["NotEqual"] = 7] = "NotEqual";
})(Zia.Comparison || (Zia.Comparison = {}));
var Comparison = Zia.Comparison;
var DepthStencilState = (function () {
function DepthStencilState() {
this.isDepthEnabled = true;
this.depthFunction = Comparison.Less;
}
DepthStencilState.mapComparison = function (comparison, gl) {
switch (comparison) {
case Comparison.Never: return gl.NEVER;
case Comparison.Always: return gl.ALWAYS;
case Comparison.Less: return gl.LESS;
case Comparison.Equal: return gl.EQUAL;
case Comparison.LessEqual: return gl.LEQUAL;
case Comparison.Greater: return gl.GREATER;
case Comparison.GreaterEqual: return gl.GEQUAL;
case Comparison.NotEqual: return gl.NOTEQUAL;
}
};
DepthStencilState.prototype._apply = function (gl) {
if (this.isDepthEnabled) {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(DepthStencilState.mapComparison(this.depthFunction, gl));
}
else {
gl.disable(gl.DEPTH_TEST);
}
};
return DepthStencilState;
})();
Zia.DepthStencilState = DepthStencilState;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (ClearOptions) {
ClearOptions[ClearOptions["DepthBuffer"] = 0] = "DepthBuffer";
ClearOptions[ClearOptions["StencilBuffer"] = 1] = "StencilBuffer";
ClearOptions[ClearOptions["ColorBuffer"] = 2] = "ColorBuffer";
})(Zia.ClearOptions || (Zia.ClearOptions = {}));
var ClearOptions = Zia.ClearOptions;
(function (PrimitiveType) {
PrimitiveType[PrimitiveType["PointList"] = 0] = "PointList";
PrimitiveType[PrimitiveType["LineList"] = 1] = "LineList";
PrimitiveType[PrimitiveType["LineStrip"] = 2] = "LineStrip";
PrimitiveType[PrimitiveType["LineLoop"] = 3] = "LineLoop";
PrimitiveType[PrimitiveType["TriangleList"] = 4] = "TriangleList";
PrimitiveType[PrimitiveType["TriangleStrip"] = 5] = "TriangleStrip";
PrimitiveType[PrimitiveType["TriangleFan"] = 6] = "TriangleFan";
})(Zia.PrimitiveType || (Zia.PrimitiveType = {}));
var PrimitiveType = Zia.PrimitiveType;
var GraphicsDevice = (function () {
function GraphicsDevice(canvas, debug) {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
this._canvas = canvas;
var gl = this.gl = canvas.getContext('webgl', {
antialias: true
});
if (debug) {
gl = this.gl = Zia.DebugUtil.makeDebugContext(gl);
}
var viewport = this._viewport = new Zia.Viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
viewport.onChange(function () {
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
gl.depthRange(viewport.minDepth, viewport.maxDepth);
});
this.rasterizerState = new Zia.RasterizerState();
this.depthStencilState = new Zia.DepthStencilState();
}
Object.defineProperty(GraphicsDevice.prototype, "viewport", {
get: function () {
return this._viewport;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GraphicsDevice.prototype, "rasterizerState", {
get: function () {
return this._rasterizerState;
},
set: function (value) {
this._rasterizerState = value;
this._rasterizerState._apply(this.gl);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GraphicsDevice.prototype, "depthStencilState", {
get: function () {
return this._depthStencilState;
},
set: function (value) {
this._depthStencilState = value;
this._depthStencilState._apply(this.gl);
},
enumerable: true,
configurable: true
});
GraphicsDevice.prototype.clear = function (clearOptions, color, depth, stencil) {
var clearMask = 0;
if (Zia.EnumUtil.hasFlag(clearOptions, Zia.ClearOptions.DepthBuffer)) {
clearMask |= this.gl.DEPTH_BUFFER_BIT;
this.gl.clearDepth(depth);
}
if (Zia.EnumUtil.hasFlag(clearOptions, Zia.ClearOptions.StencilBuffer)) {
clearMask |= this.gl.STENCIL_BUFFER_BIT;
this.gl.clearStencil(stencil);
}
if (Zia.EnumUtil.hasFlag(clearOptions, Zia.ClearOptions.ColorBuffer)) {
clearMask |= this.gl.COLOR_BUFFER_BIT;
this.gl.clearColor(color.r, color.g, color.b, color.a);
}
this.gl.clear(clearMask);
};
GraphicsDevice.prototype.setIndexBuffer = function (indexBuffer) {
this._indexBuffer = indexBuffer;
};
GraphicsDevice.prototype.setVertexBuffers = function (vertexBuffers) {
this._vertexBuffers = vertexBuffers;
};
GraphicsDevice.prototype.setVertexBuffer = function (vertexBuffer) {
this._vertexBuffers = [vertexBuffer];
};
GraphicsDevice.prototype.drawIndexedPrimitives = function (primitiveType, startIndex, indexCount) {
var gl = this.gl;
var enabledAttributeLocations = this._bindVertexAttributes(gl);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer._buffer);
gl.drawElements(this._getMode(primitiveType), indexCount, gl.UNSIGNED_SHORT, startIndex * 4);
for (var i = 0; i < enabledAttributeLocations.length; i++) {
gl.disableVertexAttribArray(enabledAttributeLocations[i]);
}
};
GraphicsDevice.prototype.drawPrimitives = function (primitiveType, startVertex, vertexCount) {
var gl = this.gl;
var enabledAttributeLocations = this._bindVertexAttributes(gl);
gl.drawArrays(this._getMode(primitiveType), startVertex, vertexCount);
for (var i = 0; i < enabledAttributeLocations.length; i++) {
gl.disableVertexAttribArray(enabledAttributeLocations[i]);
}
};
GraphicsDevice.prototype.resize = function () {
var canvas = this._canvas;
var width = canvas.clientWidth;
var height = canvas.clientHeight;
if (canvas.width != width || canvas.height != height) {
canvas.width = width;
canvas.height = height;
this.viewport.set(0, 0, width, height);
return true;
}
return false;
};
GraphicsDevice.prototype.toggleFullScreen = function () {
Zia.HtmlUtil.toggleFullScreen(this._canvas);
};
GraphicsDevice.prototype._bindVertexAttributes = function (gl) {
var enabledAttributeLocations = [];
for (var i = 0; i < this._currentProgram._attributes.length; i++) {
var attribute = this._currentProgram._attributes[i];
var vertexBuffer = this._findVertexBuffer(attribute.name);
if (vertexBuffer) {
enabledAttributeLocations.push(attribute.location);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer._buffer);
gl.vertexAttribPointer(attribute.location, vertexBuffer.element.numComponents, gl.FLOAT, false, vertexBuffer.buffer.vertexDeclaration.stride, vertexBuffer.element.offset);
gl.enableVertexAttribArray(attribute.location);
}
}
return enabledAttributeLocations;
};
GraphicsDevice.prototype._findVertexBuffer = function (attributeName) {
for (var i = 0; i < this._vertexBuffers.length; i++) {
var vertexBuffer = this._vertexBuffers[i];
for (var j = 0; j < vertexBuffer.vertexDeclaration.elements.length; j++) {
var element = vertexBuffer.vertexDeclaration.elements[j];
if (element.attributeName === attributeName) {
return {
buffer: vertexBuffer,
element: element
};
}
}
}
return null;
};
GraphicsDevice.prototype._getMode = function (primitiveType) {
switch (primitiveType) {
case PrimitiveType.PointList: return this.gl.POINTS;
case PrimitiveType.LineList: return this.gl.LINES;
case PrimitiveType.LineStrip: return this.gl.LINE_STRIP;
case PrimitiveType.LineLoop: return this.gl.LINE_LOOP;
case PrimitiveType.TriangleList: return this.gl.TRIANGLES;
case PrimitiveType.TriangleStrip: return this.gl.TRIANGLE_STRIP;
case PrimitiveType.TriangleFan: return this.gl.TRIANGLE_FAN;
}
};
return GraphicsDevice;
})();
Zia.GraphicsDevice = GraphicsDevice;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var IndexBuffer = (function () {
function IndexBuffer(graphicsDevice, data) {
this._gl = graphicsDevice.gl;
this._buffer = this._gl.createBuffer();
if (data !== undefined) {
this.setData(data);
}
}
IndexBuffer.prototype.setData = function (data) {
var gl = this._gl;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW);
};
IndexBuffer.prototype.destroy = function () {
this._gl.deleteBuffer(this._buffer);
};
return IndexBuffer;
})();
Zia.IndexBuffer = IndexBuffer;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var Model = (function () {
function Model(meshes) {
this.meshes = meshes;
}
Model.prototype.draw = function (modelMatrix, viewMatrix, projectionMatrix, programOverride) {
if (programOverride === void 0) { programOverride = null; }
for (var i = 0; i < this.meshes.length; i++) {
var mesh = this.meshes[i];
for (var j = 0; j < mesh.programs.length; j++) {
var program = programOverride || mesh.programs[j];
program.modelMatrix = modelMatrix;
program.viewMatrix = viewMatrix;
program.projectionMatrix = projectionMatrix;
}
mesh.draw(programOverride);
}
};
return Model;
})();
Zia.Model = Model;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var ModelMesh = (function () {
function ModelMesh(graphicsDevice, meshParts) {
this.graphicsDevice = graphicsDevice;
this.meshParts = meshParts;
for (var i = 0; i < meshParts.length; i++) {
meshParts[i]._parent = this;
}
this.programs = [];
}
ModelMesh.prototype.draw = function (programOverride) {
if (programOverride === void 0) { programOverride = null; }
for (var i = 0; i < this.meshParts.length; i++) {
var meshPart = this.meshParts[i];
var program = programOverride || meshPart.program;
if (meshPart.indexCount > 0) {
this.graphicsDevice.setVertexBuffer(meshPart.vertexBuffer);
this.graphicsDevice.setIndexBuffer(meshPart.indexBuffer);
program.apply();
this.graphicsDevice.drawIndexedPrimitives(4 /* TriangleList */, meshPart.startIndex, meshPart.indexCount);
}
}
};
return ModelMesh;
})();
Zia.ModelMesh = ModelMesh;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var ModelMeshPart = (function () {
function ModelMeshPart(options) {
options = Zia.ObjectUtil.reverseMerge(options || {}, {
indexBuffer: null,
startIndex: 0,
indexCount: 0,
vertexBuffer: null
});
this.indexBuffer = options.indexBuffer;
this.startIndex = options.startIndex;
this.indexCount = options.indexCount;
this.vertexBuffer = options.vertexBuffer;
this._program = null;
this._parent = null;
}
Object.defineProperty(ModelMeshPart.prototype, "program", {
get: function () {
return this._program;
},
set: function (value) {
if (value === this._program)
return;
if (this._program) {
var removeProgram = true;
for (var i = 0; i < this._parent.meshParts.length; i++) {
var meshPart = this._parent.meshParts[i];
if (meshPart !== this && meshPart._program === this._program) {
removeProgram = false;
break;
}
}
if (removeProgram) {
var programIndex = this._parent.programs.indexOf(this._program);
if (programIndex >= 0) {
this._parent.programs.splice(programIndex, 1);
}
}
}
this._program = value;
this._parent.programs.push(value);
},
enumerable: true,
configurable: true
});
return ModelMeshPart;
})();
Zia.ModelMeshPart = ModelMeshPart;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (CullMode) {
CullMode[CullMode["Back"] = 0] = "Back";
CullMode[CullMode["Front"] = 1] = "Front";
CullMode[CullMode["FrontAndBack"] = 2] = "FrontAndBack";
CullMode[CullMode["None"] = 3] = "None";
})(Zia.CullMode || (Zia.CullMode = {}));
var CullMode = Zia.CullMode;
var RasterizerState = (function () {
function RasterizerState(options) {
options = Zia.ObjectUtil.reverseMerge(options || {}, {
cullMode: Zia.CullMode.Back,
isFrontClockwise: false,
isPolygonOffsetEnabled: false,
polygonOffsetFactor: 0.0,
polygonOffsetUnits: 0.0
});
this.cullMode = options.cullMode;
this.isFrontClockwise = options.isFrontClockwise;
this.isPolygonOffsetEnabled = options.isPolygonOffsetEnabled;
this.polygonOffsetFactor = options.polygonOffsetFactor;
this.polygonOffsetUnits = options.polygonOffsetUnits;
}
RasterizerState.prototype._apply = function (gl) {
switch (this.cullMode) {
case CullMode.Back:
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
break;
case CullMode.Front:
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.FRONT);
break;
case CullMode.FrontAndBack:
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.FRONT_AND_BACK);
break;
case CullMode.None:
gl.disable(gl.CULL_FACE);
break;
}
gl.frontFace(this.isFrontClockwise ? gl.CW : gl.CCW);
if (this.isPolygonOffsetEnabled) {
gl.enable(gl.POLYGON_OFFSET_FILL);
gl.polygonOffset(this.polygonOffsetFactor, this.polygonOffsetUnits);
}
else {
gl.disable(gl.POLYGON_OFFSET_FILL);
}
};
return RasterizerState;
})();
Zia.RasterizerState = RasterizerState;
})(Zia || (Zia = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Zia;
(function (Zia) {
var Shader = (function () {
function Shader(graphicsDevice, type, source) {
var gl = this._gl = graphicsDevice.gl;
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var error = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error('Failed to compile shader: ' + error);
}
this.shader = shader;
}
;
Shader.prototype.destroy = function () {
this._gl.deleteShader(this.shader);
};
return Shader;
})();
Zia.Shader = Shader;
var FragmentShader = (function (_super) {
__extends(FragmentShader, _super);
function FragmentShader(graphicsDevice, source) {
_super.call(this, graphicsDevice, graphicsDevice.gl.FRAGMENT_SHADER, source);
}
;
return FragmentShader;
})(Shader);
Zia.FragmentShader = FragmentShader;
var VertexShader = (function (_super) {
__extends(VertexShader, _super);
function VertexShader(graphicsDevice, source) {
_super.call(this, graphicsDevice, graphicsDevice.gl.VERTEX_SHADER, source);
}
;
return VertexShader;
})(Shader);
Zia.VertexShader = VertexShader;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var Texture = (function () {
function Texture(graphicsDevice, options, textureType) {
var gl = this._gl = graphicsDevice.gl;
this._texture = this._gl.createTexture();
this._textureType = textureType;
this._options = Zia.ObjectUtil.reverseMerge(options || {}, {
filter: 3 /* MinNearestMagMipLinear */,
wrapS: 0 /* Repeat */,
wrapT: 0 /* Repeat */
});
gl.bindTexture(textureType, this._texture);
gl.texParameteri(textureType, gl.TEXTURE_WRAP_S, Zia.TextureWrapUtil._map(gl, this._options.wrapS));
gl.texParameteri(textureType, gl.TEXTURE_WRAP_T, Zia.TextureWrapUtil._map(gl, this._options.wrapT));
var mappedFilterValues = Zia.TextureFilterUtil._map(gl, this._options.filter);
gl.texParameteri(textureType, gl.TEXTURE_MIN_FILTER, mappedFilterValues[0]);
gl.texParameteri(textureType, gl.TEXTURE_MAG_FILTER, mappedFilterValues[1]);
gl.bindTexture(textureType, null);
}
Texture.prototype._setData = function (setImageDataCallback, flipY) {
var gl = this._gl;
var textureType = this._textureType;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(textureType, this._texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
setImageDataCallback(gl);
gl.bindTexture(textureType, null);
};
Texture.prototype._generateMipmap = function () {
var gl = this._gl;
var textureType = this._textureType;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(textureType, this._texture);
gl.generateMipmap(textureType);
gl.bindTexture(textureType, null);
};
Texture.prototype.destroy = function () {
this._gl.deleteTexture(this._texture);
};
return Texture;
})();
Zia.Texture = Texture;
})(Zia || (Zia = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Zia;
(function (Zia) {
var Texture2D = (function (_super) {
__extends(Texture2D, _super);
function Texture2D(graphicsDevice, options) {
_super.call(this, graphicsDevice, options, graphicsDevice.gl.TEXTURE_2D);
}
Texture2D.prototype.setData = function (data) {
var width = this.width, height = this.height;
this._setData(function (gl) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}, true);
this._generateMipmap();
};
Texture2D.createFromImagePath = function (graphicsDevice, imagePath, options) {
var result = new Zia.Texture2D(graphicsDevice, options);
var gl = graphicsDevice.gl;
// Set temporary 1x1 white texture, until image has loaded
result.width = 1;
result.height = 1;
result.setData(new Uint8Array([255, 255, 255, 255]));
var image = new Image();
image.onload = function () {
result._setData(function () {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
}, true);
result._generateMipmap();
result.width = image.naturalWidth;
result.height = image.naturalHeight;
};
image.src = imagePath;
return result;
};
Texture2D.createFromImageData = function (graphicsDevice, imageData, width, height, options) {
var result = new Zia.Texture2D(graphicsDevice, options);
result.width = width;
result.height = height;
var gl = graphicsDevice.gl;
result.setData(imageData);
return result;
};
Texture2D.createWhiteTexture = function (graphicsDevice) {
var whitePixel = new Uint8Array([255, 255, 255, 255]);
return Texture2D.createFromImageData(graphicsDevice, whitePixel, 1, 1);
};
return Texture2D;
})(Zia.Texture);
Zia.Texture2D = Texture2D;
})(Zia || (Zia = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Zia;
(function (Zia) {
Zia.CubeMapFaceUtil = {
_map: function (gl, face) {
switch (face) {
case 1 /* NegativeX */:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_X;
case 3 /* NegativeY */:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Y;
case 5 /* NegativeZ */:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Z;
case 0 /* PositiveX */:
return gl.TEXTURE_CUBE_MAP_POSITIVE_X;
case 2 /* PositiveY */:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Y;
case 4 /* PositiveZ */:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Z;
default:
throw "Invalid face: " + face;
}
}
};
var TextureCube = (function (_super) {
__extends(TextureCube, _super);
function TextureCube(graphicsDevice, options) {
_super.call(this, graphicsDevice, options, graphicsDevice.gl.TEXTURE_CUBE_MAP);
}
TextureCube.prototype.setData = function (cubeMapFace, data) {
var size = this.size;
this._setData(function (gl) {
gl.texImage2D(Zia.CubeMapFaceUtil._map(gl, cubeMapFace), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}, false);
};
TextureCube.createFromImagePaths = function (graphicsDevice, imagePaths, options) {
if (imagePaths.length !== 6) {
throw "Must pass an array of 6 URLs";
}
var result = new Zia.TextureCube(graphicsDevice, options);
// Set temporary 1x1 white texture, until images have loaded
result.size = 1;
var whitePixel = new Uint8Array([255, 255, 255, 255]);
for (var i = 0; i < 6; i++) {
result.setData(i, whitePixel);
}
var gl = graphicsDevice.gl;
var loaded = 0;
for (var i = 0; i < imagePaths.length; i++) {
var imagePath = imagePaths[i];
(function (localI) {
var image = new Image();
image.onload = function () {
result._setData(function () {
gl.texImage2D(Zia.CubeMapFaceUtil._map(gl, localI), 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
}, false);
if (image.naturalWidth != image.naturalHeight) {
throw "Must use square textures for TextureCube";
}
if (loaded === 0) {
result.size = image.naturalWidth;
}
else if (image.naturalWidth !== result.size) {
throw "All 6 textures must have the same dimensions";
}
loaded++;
if (loaded === 6) {
result._generateMipmap();
}
};
image.src = imagePath;
})(i);
}
return result;
};
return TextureCube;
})(Zia.Texture);
Zia.TextureCube = TextureCube;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (TextureFilter) {
TextureFilter[TextureFilter["MinMagMipNearest"] = 0] = "MinMagMipNearest";
TextureFilter[TextureFilter["MinMagNearestMipLinear"] = 1] = "MinMagNearestMipLinear";
TextureFilter[TextureFilter["MinNearestMagLinearMipNearest"] = 2] = "MinNearestMagLinearMipNearest";
TextureFilter[TextureFilter["MinNearestMagMipLinear"] = 3] = "MinNearestMagMipLinear";
TextureFilter[TextureFilter["MinLinearMagMipNearest"] = 4] = "MinLinearMagMipNearest";
TextureFilter[TextureFilter["MinLinearMagNearestMipLinear"] = 5] = "MinLinearMagNearestMipLinear";
TextureFilter[TextureFilter["MinMagLinearMipNearest"] = 6] = "MinMagLinearMipNearest";
TextureFilter[TextureFilter["MinMagMipLinear"] = 7] = "MinMagMipLinear";
TextureFilter[TextureFilter["MinMagNearest"] = 8] = "MinMagNearest";
TextureFilter[TextureFilter["MinNearestMagLinear"] = 9] = "MinNearestMagLinear";
TextureFilter[TextureFilter["MinLinearMagNearest"] = 10] = "MinLinearMagNearest";
TextureFilter[TextureFilter["MinMagLinear"] = 11] = "MinMagLinear";
})(Zia.TextureFilter || (Zia.TextureFilter = {}));
var TextureFilter = Zia.TextureFilter;
Zia.TextureFilterUtil = {
_map: function (gl, filter) {
switch (filter) {
case TextureFilter.MinMagMipNearest:
return [gl.NEAREST_MIPMAP_NEAREST, gl.NEAREST];
case TextureFilter.MinMagNearestMipLinear:
return [gl.NEAREST_MIPMAP_LINEAR, gl.NEAREST];
case TextureFilter.MinNearestMagLinearMipNearest:
return [gl.NEAREST_MIPMAP_NEAREST, gl.LINEAR];
case TextureFilter.MinNearestMagMipLinear:
return [gl.NEAREST_MIPMAP_LINEAR, gl.LINEAR];
case TextureFilter.MinLinearMagMipNearest:
return [gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST];
case TextureFilter.MinLinearMagNearestMipLinear:
return [gl.LINEAR_MIPMAP_LINEAR, gl.NEAREST];
case TextureFilter.MinMagLinearMipNearest:
return [gl.LINEAR_MIPMAP_NEAREST, gl.LINEAR];
case TextureFilter.MinMagMipLinear:
return [gl.LINEAR_MIPMAP_LINEAR, gl.LINEAR];
case TextureFilter.MinMagNearest:
return [gl.NEAREST, gl.NEAREST];
case TextureFilter.MinNearestMagLinear:
return [gl.NEAREST, gl.LINEAR];
case TextureFilter.MinLinearMagNearest:
return [gl.LINEAR, gl.NEAREST];
case TextureFilter.MinMagLinear:
return [gl.LINEAR, gl.LINEAR];
default:
throw "Invalid value: " + filter;
}
}
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (TextureWrap) {
TextureWrap[TextureWrap["Repeat"] = 0] = "Repeat";
TextureWrap[TextureWrap["ClampToEdge"] = 1] = "ClampToEdge";
TextureWrap[TextureWrap["MirroredRepeat"] = 2] = "MirroredRepeat";
})(Zia.TextureWrap || (Zia.TextureWrap = {}));
var TextureWrap = Zia.TextureWrap;
Zia.TextureWrapUtil = {
_map: function (gl, wrap) {
switch (wrap) {
case TextureWrap.Repeat:
return gl.REPEAT;
case TextureWrap.ClampToEdge:
return gl.CLAMP_TO_EDGE;
case TextureWrap.MirroredRepeat:
return gl.MIRRORED_REPEAT;
default:
throw "Invalid value: " + wrap;
}
}
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var VertexBuffer = (function () {
function VertexBuffer(graphicsDevice, vertexDeclaration, data) {
this._gl = graphicsDevice.gl;
this._buffer = this._gl.createBuffer();
this.vertexDeclaration = vertexDeclaration;
if (data !== undefined) {
this.setData(data);
}
}
VertexBuffer.prototype.setData = function (data) {
var gl = this._gl;
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
};
VertexBuffer.prototype.destroy = function () {
this._gl.deleteBuffer(this._buffer);
};
return VertexBuffer;
})();
Zia.VertexBuffer = VertexBuffer;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var VertexElement = (function () {
function VertexElement(attributeName, numComponents, offset) {
if (offset === void 0) { offset = 0; }
this.attributeName = attributeName;
this.numComponents = numComponents;
this.offset = offset;
}
return VertexElement;
})();
Zia.VertexElement = VertexElement;
var VertexDeclaration = (function () {
function VertexDeclaration(elements) {
this.elements = elements;
this.elements = elements;
this.stride = 4 * elements
.map(function (v) { return v.numComponents; })
.reduce(function (p, c) { return p + c; }, 0);
}
return VertexDeclaration;
})();
Zia.VertexDeclaration = VertexDeclaration;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var Viewport = (function () {
function Viewport(x, y, width, height, minDepth, maxDepth) {
if (minDepth === void 0) { minDepth = 0.0; }
if (maxDepth === void 0) { maxDepth = 1.0; }
this._onChangeCallback = function () { };
this._x = x;
this._y = y;
this._width = width;
this._height = height;
this._minDepth = minDepth;
this._maxDepth = maxDepth;
}
;
Object.defineProperty(Viewport.prototype, "x", {
get: function () {
return this._x;
},
set: function (v) {
this._x = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "y", {
get: function () {
return this._y;
},
set: function (v) {
this._y = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "width", {
get: function () {
return this._width;
},
set: function (v) {
this._width = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "height", {
get: function () {
return this._height;
},
set: function (v) {
this._height = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "minDepth", {
get: function () {
return this._minDepth;
},
set: function (v) {
this._minDepth = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "maxDepth", {
get: function () {
return this._maxDepth;
},
set: function (v) {
this._maxDepth = v;
this._onChangeCallback();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Viewport.prototype, "aspectRatio", {
get: function () {
if (this._height == 0 || this._width == 0)
return 0;
return this._width / this._height;
},
enumerable: true,
configurable: true
});
Viewport.prototype.set = function (x, y, width, height, minDepth, maxDepth) {
this._x = x;
this._y = y;
this._width = width;
this._height = height;
if (minDepth !== undefined) {
this._minDepth = minDepth;
}
if (maxDepth !== undefined) {
this._maxDepth = maxDepth;
}
this._onChangeCallback();
};
Viewport.prototype.onChange = function (callback) {
this._onChangeCallback = callback;
return this;
};
Viewport.prototype.suppressChangeCallback = function (func) {
var temp = this._onChangeCallback;
this._onChangeCallback = function () { };
func();
this._onChangeCallback = temp;
};
return Viewport;
})();
Zia.Viewport = Viewport;
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
var cubeFaceCount = 6;
var faceNormals = [
new Zia.Vector3(0, 0, 1),
new Zia.Vector3(0, 0, -1),
new Zia.Vector3(1, 0, 0),
new Zia.Vector3(-1, 0, 0),
new Zia.Vector3(0, 1, 0),
new Zia.Vector3(0, -1, 0)
];
var textureCoordinates = [
new Zia.Vector2(1, 1),
new Zia.Vector2(1, 0),
new Zia.Vector2(0, 0),
new Zia.Vector2(0, 1)
];
var side1 = new Zia.Vector3();
var side2 = new Zia.Vector3();
function createCube(size) {
if (size === void 0) { size = 1.0; }
var positions = [];
var normals = [];
var texCoords = [];
var indices = [];
size /= 2.0;
for (var i = 0; i < cubeFaceCount; i++) {
var normal = faceNormals[i];
var basis = (i >= 4) ? new Zia.Vector3(0, 0, 1) : new Zia.Vector3(0, 1, 0);
side1.set(normal.x, normal.y, normal.z);
Zia.Vector3.cross(side1, basis, side1);
side2.set(normal.x, normal.y, normal.z);
Zia.Vector3.cross(side2, side1, side2);
var vbase = i * 4;
indices.push(vbase + 0);
indices.push(vbase + 2);
indices.push(vbase + 1);
indices.push(vbase + 0);
indices.push(vbase + 3);
indices.push(vbase + 2);
positions.push(normal.clone(new Zia.Vector3()).subtract(side1).subtract(side2).multiplyScalar(size));
positions.push(normal.clone(new Zia.Vector3()).subtract(side1).add(side2).multiplyScalar(size));
positions.push(normal.clone(new Zia.Vector3()).add(side1).add(side2).multiplyScalar(size));
positions.push(normal.clone(new Zia.Vector3()).add(side1).subtract(side2).multiplyScalar(size));
normals.push(normal);
normals.push(normal);
normals.push(normal);
normals.push(normal);
texCoords.push(textureCoordinates[0]);
texCoords.push(textureCoordinates[1]);
texCoords.push(textureCoordinates[2]);
texCoords.push(textureCoordinates[3]);
}
return {
positions: positions,
normals: normals,
textureCoordinates: texCoords,
indices: indices
};
}
GeometricPrimitive.createCube = createCube;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
function getCircleVector(i, tessellation) {
var angle = i * 2.0 * Math.PI / tessellation;
var dx = Math.sin(angle);
var dz = Math.cos(angle);
return new Zia.Vector3(dx, 0, dz);
}
var createCylinderCapTemp1 = new Zia.Vector3();
function createCylinderCap(positions, normals, texCoords, indices, tessellation, height, radius, isTop) {
for (var i = 0; i < tessellation - 2; i++) {
var i1 = (i + 1) % tessellation;
var i2 = (i + 2) % tessellation;
if (isTop) {
i2 = [i1, i1 = i2][0];
}
var vbase = positions.length;
indices.push(vbase);
indices.push(vbase + i2);
indices.push(vbase + i1);
}
var normal = new Zia.Vector3(0, 1, 0);
var textureScale = new Zia.Vector2(-0.5, -0.5);
if (!isTop) {
normal.negate();
textureScale.x = -textureScale.x;
}
for (var i = 0; i < tessellation; i++) {
var circleVector = getCircleVector(i, tessellation);
var position = circleVector.clone(new Zia.Vector3()).multiplyScalar(radius);
createCylinderCapTemp1.set(normal.x, normal.y, normal.z);
createCylinderCapTemp1.multiplyScalar(height);
position.add(createCylinderCapTemp1);
positions.push(position);
normals.push(normal);
texCoords.push(new Zia.Vector2(circleVector.x * textureScale.x + 0.5, 1.0 - circleVector.z * textureScale.y + 0.5));
}
}
var vector2UnitY = new Zia.Vector2(0, 1);
function createCylinder(height, diameter, tessellation) {
if (height === void 0) { height = 1.0; }
if (diameter === void 0) { diameter = 1.0; }
if (tessellation === void 0) { tessellation = 32; }
if (tessellation < 3) {
throw "tessellation must be >= 3";
}
var positions = [];
var normals = [];
var texCoords = [];
var indices = [];
height /= 2;
var topOffset = new Zia.Vector3(0, 1, 0).multiplyScalar(height);
var radius = diameter / 2;
var stride = tessellation + 1;
for (var i = 0; i <= tessellation; i++) {
var normal = getCircleVector(i, tessellation);
var sideOffset = normal.clone(new Zia.Vector3()).multiplyScalar(radius);
var textureCoordinate = new Zia.Vector2(i / tessellation, 1);
positions.push(sideOffset.clone(new Zia.Vector3()).add(topOffset));
normals.push(normal);
texCoords.push(textureCoordinate);
positions.push(sideOffset.clone(new Zia.Vector3()).subtract(topOffset));
normals.push(normal);
texCoords.push(textureCoordinate.clone().subtract(vector2UnitY));
indices.push(i * 2);
indices.push(i * 2 + 1);
indices.push((i * 2 + 2) % (stride * 2));
indices.push(i * 2 + 1);
indices.push((i * 2 + 3) % (stride * 2));
indices.push((i * 2 + 2) % (stride * 2));
}
createCylinderCap(positions, normals, texCoords, indices, tessellation, height, radius, true);
createCylinderCap(positions, normals, texCoords, indices, tessellation, height, radius, false);
return {
positions: positions,
normals: normals,
textureCoordinates: texCoords,
indices: indices
};
}
GeometricPrimitive.createCylinder = createCylinder;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
/** Creates a plane primitive. */
function createPlane(sizeX, sizeY, tessellation, uvFactor) {
if (sizeX === void 0) { sizeX = 1.0; }
if (sizeY === void 0) { sizeY = 1.0; }
if (tessellation === void 0) { tessellation = 1; }
if (uvFactor === void 0) { uvFactor = new Zia.Vector2(1, 1); }
if (tessellation < 1) {
throw "tessellation must be > 0";
}
var lineWidth = tessellation + 1;
var positions = new Array(lineWidth * lineWidth);
var normals = new Array(lineWidth * lineWidth);
var texCoords = new Array(lineWidth * lineWidth);
var indices = new Array(tessellation * tessellation * 6);
var deltaX = sizeX / tessellation;
var deltaY = sizeY / tessellation;
sizeX /= 2.0;
sizeY /= 2.0;
var normal = new Zia.Vector3(0, 1, 0);
// Create vertices
var vertexCount = 0;
for (var y = 0; y < (tessellation + 1); y++) {
for (var x = 0; x < (tessellation + 1); x++) {
positions[vertexCount] = new Zia.Vector3(-sizeX + deltaX * x, 0, sizeY - deltaY * y);
normals[vertexCount] = normal;
texCoords[vertexCount] = new Zia.Vector2(1.0 - 1.0 * x / tessellation * uvFactor.x, 1.0 - 1.0 * y / tessellation * uvFactor.y);
vertexCount++;
}
}
// Create indices
var indexCount = 0;
for (var y = 0; y < tessellation; y++) {
for (var x = 0; x < tessellation; x++) {
// Six indices (two triangles) per face.
var vbase = lineWidth * y + x;
indices[indexCount++] = (vbase + 1);
indices[indexCount++] = (vbase + 1 + lineWidth);
indices[indexCount++] = (vbase + lineWidth);
indices[indexCount++] = (vbase + 1);
indices[indexCount++] = (vbase + lineWidth);
indices[indexCount++] = (vbase);
}
}
return {
positions: positions,
normals: normals,
textureCoordinates: texCoords,
indices: indices
};
}
GeometricPrimitive.createPlane = createPlane;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
/** Creates a sphere primitive. */
function createSphere(diameter, tessellation) {
if (diameter === void 0) { diameter = 1.0; }
if (tessellation === void 0) { tessellation = 16; }
if (tessellation < 3) {
throw "tessellation must be >= 3";
}
var verticalSegments = tessellation;
var horizontalSegments = tessellation * 2;
var positions = new Array((verticalSegments + 1) * (horizontalSegments + 1));
var normals = new Array((verticalSegments + 1) * (horizontalSegments + 1));
var texCoords = new Array((verticalSegments + 1) * (horizontalSegments + 1));
var indices = new Array((verticalSegments) * (horizontalSegments + 1) * 6);
var radius = diameter / 2;
// Create rings of vertices at progressively higher latitudes.
var vertexCount = 0;
for (var i = 0; i <= verticalSegments; i++) {
var v = 1.0 - i / verticalSegments;
var latitude = ((i * Math.PI / verticalSegments) - Math.PI / 2.0);
var dy = Math.sin(latitude);
var dxz = Math.cos(latitude);
// Create a single ring of vertices at this latitude.
for (var j = 0; j <= horizontalSegments; j++) {
var u = j / horizontalSegments;
var longitude = j * 2.0 * Math.PI / horizontalSegments;
var dx = Math.sin(longitude);
var dz = Math.cos(longitude);
dx *= dxz;
dz *= dxz;
var normal = new Zia.Vector3(dx, dy, dz);
var textureCoordinate = new Zia.Vector2(u, 1 - v);
positions[vertexCount] = normal.clone(new Zia.Vector3()).multiplyScalar(radius);
normals[vertexCount] = normal;
texCoords[vertexCount] = textureCoordinate;
vertexCount++;
}
}
// Fill the index buffer with triangles joining each pair of latitude rings.
var stride = horizontalSegments + 1;
var indexCount = 0;
for (var i = 0; i < verticalSegments; i++) {
for (var j = 0; j <= horizontalSegments; j++) {
var nextI = i + 1;
var nextJ = (j + 1) % stride;
indices[indexCount++] = (i * stride + j);
indices[indexCount++] = (i * stride + nextJ);
indices[indexCount++] = (nextI * stride + j);
indices[indexCount++] = (i * stride + nextJ);
indices[indexCount++] = (nextI * stride + nextJ);
indices[indexCount++] = (nextI * stride + j);
}
}
return {
positions: positions,
normals: normals,
textureCoordinates: texCoords,
indices: indices
};
}
GeometricPrimitive.createSphere = createSphere;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
var TeapotPatch = (function () {
function TeapotPatch(mirrorZ, indices) {
this.mirrorZ = mirrorZ;
this.indices = indices;
}
return TeapotPatch;
})();
var teapotPatches = [
new TeapotPatch(true, [102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
new TeapotPatch(true, [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]),
new TeapotPatch(true, [24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]),
new TeapotPatch(true, [96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3]),
new TeapotPatch(true, [0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117]),
new TeapotPatch(false, [41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]),
new TeapotPatch(false, [53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 28, 65, 66, 67]),
new TeapotPatch(false, [68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83]),
new TeapotPatch(false, [80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95]),
new TeapotPatch(true, [118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37])
];
var teapotControlPoints = [
new Zia.Vector3(0, 0.345, -0.05),
new Zia.Vector3(-0.028, 0.345, -0.05),
new Zia.Vector3(-0.05, 0.345, -0.028),
new Zia.Vector3(-0.05, 0.345, -0),
new Zia.Vector3(0, 0.3028125, -0.334375),
new Zia.Vector3(-0.18725, 0.3028125, -0.334375),
new Zia.Vector3(-0.334375, 0.3028125, -0.18725),
new Zia.Vector3(-0.334375, 0.3028125, -0),
new Zia.Vector3(0, 0.3028125, -0.359375),
new Zia.Vector3(-0.20125, 0.3028125, -0.359375),
new Zia.Vector3(-0.359375, 0.3028125, -0.20125),
new Zia.Vector3(-0.359375, 0.3028125, -0),
new Zia.Vector3(0, 0.27, -0.375),
new Zia.Vector3(-0.21, 0.27, -0.375),
new Zia.Vector3(-0.375, 0.27, -0.21),
new Zia.Vector3(-0.375, 0.27, -0),
new Zia.Vector3(0, 0.13875, -0.4375),
new Zia.Vector3(-0.245, 0.13875, -0.4375),
new Zia.Vector3(-0.4375, 0.13875, -0.245),
new Zia.Vector3(-0.4375, 0.13875, -0),
new Zia.Vector3(0, 0.007499993, -0.5),
new Zia.Vector3(-0.28, 0.007499993, -0.5),
new Zia.Vector3(-0.5, 0.007499993, -0.28),
new Zia.Vector3(-0.5, 0.007499993, -0),
new Zia.Vector3(0, -0.105, -0.5),
new Zia.Vector3(-0.28, -0.105, -0.5),
new Zia.Vector3(-0.5, -0.105, -0.28),
new Zia.Vector3(-0.5, -0.105, -0),
new Zia.Vector3(0, -0.105, 0.5),
new Zia.Vector3(0, -0.2175, -0.5),
new Zia.Vector3(-0.28, -0.2175, -0.5),
new Zia.Vector3(-0.5, -0.2175, -0.28),
new Zia.Vector3(-0.5, -0.2175, -0),
new Zia.Vector3(0, -0.27375, -0.375),
new Zia.Vector3(-0.21, -0.27375, -0.375),
new Zia.Vector3(-0.375, -0.27375, -0.21),
new Zia.Vector3(-0.375, -0.27375, -0),
new Zia.Vector3(0, -0.2925, -0.375),
new Zia.Vector3(-0.21, -0.2925, -0.375),
new Zia.Vector3(-0.375, -0.2925, -0.21),
new Zia.Vector3(-0.375, -0.2925, -0),
new Zia.Vector3(0, 0.17625, 0.4),
new Zia.Vector3(-0.075, 0.17625, 0.4),
new Zia.Vector3(-0.075, 0.2325, 0.375),
new Zia.Vector3(0, 0.2325, 0.375),
new Zia.Vector3(0, 0.17625, 0.575),
new Zia.Vector3(-0.075, 0.17625, 0.575),
new Zia.Vector3(-0.075, 0.2325, 0.625),
new Zia.Vector3(0, 0.2325, 0.625),
new Zia.Vector3(0, 0.17625, 0.675),
new Zia.Vector3(-0.075, 0.17625, 0.675),
new Zia.Vector3(-0.075, 0.2325, 0.75),
new Zia.Vector3(0, 0.2325, 0.75),
new Zia.Vector3(0, 0.12, 0.675),
new Zia.Vector3(-0.075, 0.12, 0.675),
new Zia.Vector3(-0.075, 0.12, 0.75),
new Zia.Vector3(0, 0.12, 0.75),
new Zia.Vector3(0, 0.06375, 0.675),
new Zia.Vector3(-0.075, 0.06375, 0.675),
new Zia.Vector3(-0.075, 0.007499993, 0.75),
new Zia.Vector3(0, 0.007499993, 0.75),
new Zia.Vector3(0, -0.04875001, 0.625),
new Zia.Vector3(-0.075, -0.04875001, 0.625),
new Zia.Vector3(-0.075, -0.09562501, 0.6625),
new Zia.Vector3(0, -0.09562501, 0.6625),
new Zia.Vector3(-0.075, -0.105, 0.5),
new Zia.Vector3(-0.075, -0.18, 0.475),
new Zia.Vector3(0, -0.18, 0.475),
new Zia.Vector3(0, 0.02624997, -0.425),
new Zia.Vector3(-0.165, 0.02624997, -0.425),
new Zia.Vector3(-0.165, -0.18, -0.425),
new Zia.Vector3(0, -0.18, -0.425),
new Zia.Vector3(0, 0.02624997, -0.65),
new Zia.Vector3(-0.165, 0.02624997, -0.65),
new Zia.Vector3(-0.165, -0.12375, -0.775),
new Zia.Vector3(0, -0.12375, -0.775),
new Zia.Vector3(0, 0.195, -0.575),
new Zia.Vector3(-0.0625, 0.195, -0.575),
new Zia.Vector3(-0.0625, 0.17625, -0.6),
new Zia.Vector3(0, 0.17625, -0.6),
new Zia.Vector3(0, 0.27, -0.675),
new Zia.Vector3(-0.0625, 0.27, -0.675),
new Zia.Vector3(-0.0625, 0.27, -0.825),
new Zia.Vector3(0, 0.27, -0.825),
new Zia.Vector3(0, 0.28875, -0.7),
new Zia.Vector3(-0.0625, 0.28875, -0.7),
new Zia.Vector3(-0.0625, 0.2934375, -0.88125),
new Zia.Vector3(0, 0.2934375, -0.88125),
new Zia.Vector3(0, 0.28875, -0.725),
new Zia.Vector3(-0.0375, 0.28875, -0.725),
new Zia.Vector3(-0.0375, 0.298125, -0.8625),
new Zia.Vector3(0, 0.298125, -0.8625),
new Zia.Vector3(0, 0.27, -0.7),
new Zia.Vector3(-0.0375, 0.27, -0.7),
new Zia.Vector3(-0.0375, 0.27, -0.8),
new Zia.Vector3(0, 0.27, -0.8),
new Zia.Vector3(0, 0.4575, -0),
new Zia.Vector3(0, 0.4575, -0.2),
new Zia.Vector3(-0.1125, 0.4575, -0.2),
new Zia.Vector3(-0.2, 0.4575, -0.1125),
new Zia.Vector3(-0.2, 0.4575, -0),
new Zia.Vector3(0, 0.3825, -0),
new Zia.Vector3(0, 0.27, -0.35),
new Zia.Vector3(-0.196, 0.27, -0.35),
new Zia.Vector3(-0.35, 0.27, -0.196),
new Zia.Vector3(-0.35, 0.27, -0),
new Zia.Vector3(0, 0.3075, -0.1),
new Zia.Vector3(-0.056, 0.3075, -0.1),
new Zia.Vector3(-0.1, 0.3075, -0.056),
new Zia.Vector3(-0.1, 0.3075, -0),
new Zia.Vector3(0, 0.3075, -0.325),
new Zia.Vector3(-0.182, 0.3075, -0.325),
new Zia.Vector3(-0.325, 0.3075, -0.182),
new Zia.Vector3(-0.325, 0.3075, -0),
new Zia.Vector3(0, 0.27, -0.325),
new Zia.Vector3(-0.182, 0.27, -0.325),
new Zia.Vector3(-0.325, 0.27, -0.182),
new Zia.Vector3(-0.325, 0.27, -0),
new Zia.Vector3(0, -0.33, -0),
new Zia.Vector3(-0.1995, -0.33, -0.35625),
new Zia.Vector3(0, -0.31125, -0.375),
new Zia.Vector3(0, -0.33, -0.35625),
new Zia.Vector3(-0.35625, -0.33, -0.1995),
new Zia.Vector3(-0.375, -0.31125, -0),
new Zia.Vector3(-0.35625, -0.33, -0),
new Zia.Vector3(-0.21, -0.31125, -0.375),
new Zia.Vector3(-0.375, -0.31125, -0.21)
];
function createPatchIndices(tessellation, isMirrored, baseIndex) {
var stride = tessellation + 1;
var indices = new Array(6);
var result = [];
for (var i = 0; i < tessellation; i++) {
for (var j = 0; j < tessellation; j++) {
indices[0] = baseIndex + i * stride + j;
indices[2] = baseIndex + (i + 1) * stride + j;
indices[1] = baseIndex + (i + 1) * stride + j + 1;
indices[3] = baseIndex + i * stride + j;
indices[5] = baseIndex + (i + 1) * stride + j + 1;
indices[4] = baseIndex + i * stride + j + 1;
if (isMirrored) {
indices.reverse();
}
for (var k = 0; k < indices.length; k++) {
result.push(indices[k]);
}
}
}
return result;
}
var cubicInterpolateTemp1 = new Zia.Vector3();
var cubicInterpolateTemp2 = new Zia.Vector3();
var cubicInterpolateTemp3 = new Zia.Vector3();
var cubicInterpolateTemp4 = new Zia.Vector3();
function cubicInterpolate(p1, p2, p3, p4, t) {
var t2 = t * t;
var onet2 = (1 - t) * (1 - t);
cubicInterpolateTemp1.set(p1.x, p1.y, p1.z).multiplyScalar((1 - t) * onet2);
cubicInterpolateTemp2.set(p2.x, p2.y, p2.z).multiplyScalar(3 * t * onet2);
cubicInterpolateTemp3.set(p3.x, p3.y, p3.z).multiplyScalar(3 * t2 * (1 - t));
cubicInterpolateTemp4.set(p4.x, p4.y, p4.z).multiplyScalar(t * t2);
return cubicInterpolateTemp1.clone(new Zia.Vector3()).
add(cubicInterpolateTemp2).
add(cubicInterpolateTemp3).
add(cubicInterpolateTemp4);
}
var cubicTangentTemp1 = new Zia.Vector3();
var cubicTangentTemp2 = new Zia.Vector3();
var cubicTangentTemp3 = new Zia.Vector3();
var cubicTangentTemp4 = new Zia.Vector3();
function cubicTangent(p1, p2, p3, p4, t) {
var t2 = t * t;
cubicTangentTemp1.set(p1.x, p1.y, p1.z).multiplyScalar(-1 + 2 * t - t2);
cubicTangentTemp2.set(p2.x, p2.y, p2.z).multiplyScalar(1 - 4 * t + 3 * t2);
cubicTangentTemp3.set(p3.x, p3.y, p3.z).multiplyScalar(2 * t - 3 * t2);
cubicTangentTemp4.set(p4.x, p4.y, p4.z).multiplyScalar(t2);
return cubicTangentTemp1.clone(new Zia.Vector3()).
add(cubicTangentTemp2).
add(cubicTangentTemp3).
add(cubicTangentTemp4);
}
function createPatchVertices(patch, tessellation, isMirrored, positions, normals, textureCoordinates) {
for (var i = 0; i <= tessellation; i++) {
var u = i / tessellation;
for (var j = 0; j <= tessellation; j++) {
var v = j / tessellation;
var p1 = cubicInterpolate(patch[0], patch[1], patch[2], patch[3], u);
var p2 = cubicInterpolate(patch[4], patch[5], patch[6], patch[7], u);
var p3 = cubicInterpolate(patch[8], patch[9], patch[10], patch[11], u);
var p4 = cubicInterpolate(patch[12], patch[13], patch[14], patch[15], u);
var position = cubicInterpolate(p1, p2, p3, p4, v);
var q1 = cubicInterpolate(patch[0], patch[4], patch[8], patch[12], v);
var q2 = cubicInterpolate(patch[1], patch[5], patch[9], patch[13], v);
var q3 = cubicInterpolate(patch[2], patch[6], patch[10], patch[14], v);
var q4 = cubicInterpolate(patch[3], patch[7], patch[11], patch[15], v);
var tangent1 = cubicTangent(p1, p2, p3, p4, v);
var tangent2 = cubicTangent(q1, q2, q3, q4, u);
var normal = Zia.Vector3.cross(tangent1, tangent2);
if (!normal.nearEqual(new Zia.Vector3(), new Zia.Vector3(1e-7))) {
normal.normalize();
if (isMirrored) {
normal.negate();
}
}
else {
normal.x = 0.0;
normal.y = position.y < 0.0 ? -1.0 : 1.0;
normal.z = 0.0;
}
var mirroredU = isMirrored ? 1 - u : u;
var textureCoordinate = new Zia.Vector2(mirroredU, 1 - v);
positions.push(position);
normals.push(normal);
textureCoordinates.push(textureCoordinate);
}
}
}
function tessellatePatch(positions, normals, textureCoordinates, indices, patch, tessellation, scale, isMirrored) {
var controlPoints = new Array(16);
for (var i = 0; i < 16; i++) {
controlPoints[i] = teapotControlPoints[patch.indices[i]].clone(new Zia.Vector3()).multiply(scale);
}
var vbase = positions.length;
Array.prototype.push.apply(indices, createPatchIndices(tessellation, isMirrored, vbase));
createPatchVertices(controlPoints, tessellation, isMirrored, positions, normals, textureCoordinates);
}
function createTeapot(size, tessellation) {
if (size === void 0) { size = 1.0; }
if (tessellation === void 0) { tessellation = 8; }
if (tessellation < 1) {
throw "tessellation must be > 0";
}
var positions = [];
var normals = [];
var textureCoordinates = [];
var indices = [];
var scaleVector = new Zia.Vector3(size, size, size);
var scaleNegateX = scaleVector.clone(new Zia.Vector3());
scaleNegateX.x = -scaleNegateX.x;
var scaleNegateZ = scaleVector.clone(new Zia.Vector3());
scaleNegateZ.z = -scaleNegateZ.z;
var scaleNegateXZ = new Zia.Vector3(-size, size, -size);
for (var i = 0; i < teapotPatches.length; i++) {
var patch = teapotPatches[i];
tessellatePatch(positions, normals, textureCoordinates, indices, patch, tessellation, scaleVector, false);
tessellatePatch(positions, normals, textureCoordinates, indices, patch, tessellation, scaleNegateX, true);
if (patch.mirrorZ) {
tessellatePatch(positions, normals, textureCoordinates, indices, patch, tessellation, scaleNegateZ, true);
tessellatePatch(positions, normals, textureCoordinates, indices, patch, tessellation, scaleNegateXZ, false);
}
}
return {
positions: positions,
normals: normals,
textureCoordinates: textureCoordinates,
indices: indices
};
}
GeometricPrimitive.createTeapot = createTeapot;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
// -----------------------------------------------------------------------------
// The following code is a port of SharpDX https://github.com/sharpdx/sharpdx
// -----------------------------------------------------------------------------
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of DirectXTk http://directxtk.codeplex.com
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
var Zia;
(function (Zia) {
var GeometricPrimitive;
(function (GeometricPrimitive) {
/** Creates a torus primitive. */
function createTorus(diameter, thickness, tessellation) {
if (diameter === void 0) { diameter = 1.0; }
if (thickness === void 0) { thickness = 0.33; }
if (tessellation === void 0) { tessellation = 32; }
if (tessellation < 3) {
throw "tessellation parameter out of range";
}
var positions = [];
var normals = [];
var textureCoordinates = [];
var indices = [];
var stride = tessellation + 1;
var translateTransform = Zia.Matrix4.createTranslation(new Zia.Vector3(diameter / 2, 0, 0), new Zia.Matrix4());
var transform = new Zia.Matrix4();
// First we loop around the main ring of the torus.
for (var i = 0; i <= tessellation; i++) {
var u = i / tessellation;
var outerAngle = i * Zia.MathUtil.TWO_PI / tessellation - Zia.MathUtil.PI_OVER_TWO;
// Create a transform matrix that will align geometry to
// slice perpendicularly though the current ring position.
Zia.Matrix4.createRotationY(outerAngle, transform).multiply(translateTransform);
// Now we loop along the other axis, around the side of the tube.
for (var j = 0; j <= tessellation; j++) {
var v = 1 - j / tessellation;
var innerAngle = j * Zia.MathUtil.TWO_PI / tessellation + Math.PI;
var dx = Math.cos(innerAngle), dy = Math.sin(innerAngle);
// Create a vertex.
var normal = new Zia.Vector3(dx, dy, 0);
var position = normal.clone(new Zia.Vector3()).multiplyScalar(thickness / 2);
var textureCoordinate = new Zia.Vector2(u, 1 - v);
position.applyMatrix4(transform);
normal.transformDirection(transform);
positions.push(position);
normals.push(normal);
textureCoordinates.push(textureCoordinate);
// And create indices for two triangles.
var nextI = (i + 1) % stride;
var nextJ = (j + 1) % stride;
indices.push(i * stride + j);
indices.push(nextI * stride + j);
indices.push(i * stride + nextJ);
indices.push(i * stride + nextJ);
indices.push(nextI * stride + j);
indices.push(nextI * stride + nextJ);
}
}
return {
positions: positions,
normals: normals,
textureCoordinates: textureCoordinates,
indices: indices
};
}
GeometricPrimitive.createTorus = createTorus;
;
})(GeometricPrimitive = Zia.GeometricPrimitive || (Zia.GeometricPrimitive = {}));
})(Zia || (Zia = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Zia;
(function (Zia) {
function addLighting(result) {
result.push("uniform vec3 uDirLight0Direction;");
result.push("uniform vec3 uDirLight0DiffuseColor;");
result.push("uniform vec3 uDirLight0SpecularColor;");
result.push("uniform vec3 uDirLight1Direction;");
result.push("uniform vec3 uDirLight1DiffuseColor;");
result.push("uniform vec3 uDirLight1SpecularColor;");
result.push("uniform vec3 uDirLight2Direction;");
result.push("uniform vec3 uDirLight2DiffuseColor;");
result.push("uniform vec3 uDirLight2SpecularColor;");
result.push("uniform vec3 uEyePosition;");
result.push("uniform vec3 uEmissiveColor;");
result.push("uniform vec3 uSpecularColor;");
result.push("uniform float uSpecularPower;");
result.push(Zia.SharedProgramCode.lighting);
}
function buildVertexShader(options) {
var result = [];
result.push("precision mediump float;");
// Attributes
result.push("attribute vec3 aVertexPosition;");
if (options.lightingEnabled) {
result.push("attribute vec3 aVertexNormal;");
}
if (options.vertexColorEnabled) {
result.push("attribute vec4 aVertexColor;");
}
if (options.textureEnabled) {
result.push("attribute vec2 aTextureCoord;");
}
// Uniforms
result.push("uniform mat4 uMVPMatrix;");
if (options.lightingEnabled) {
result.push("uniform mat4 uMMatrix;");
result.push("uniform mat3 uMMatrixInverseTranspose;");
}
result.push("uniform vec4 uDiffuseColor;");
// Varyings
result.push("varying vec4 vDiffuseColor;");
if (options.lightingEnabled) {
if (options.perPixelLightingEnabled) {
result.push("varying vec3 vPositionWS;");
result.push("varying vec3 vNormalWS;");
}
else {
result.push("varying vec3 vSpecularColor;");
addLighting(result);
result.push(Zia.SharedProgramCode.lightingVertex);
}
}
if (options.textureEnabled) {
result.push("varying vec2 vTextureCoord;");
}
// Code
result.push("void main(void) {");
result.push(" gl_Position = uMVPMatrix * vec4(aVertexPosition, 1.0);");
if (options.lightingEnabled) {
if (options.perPixelLightingEnabled) {
result.push(" vDiffuseColor = vec4(1, 1, 1, uDiffuseColor.a);");
result.push(" vPositionWS = (uMMatrix * vec4(aVertexPosition, 1.0)).xyz;");
result.push(" vNormalWS = normalize(uMMatrixInverseTranspose * aVertexNormal);");
}
else {
result.push(" ComputeCommonVSOutputWithLighting(vec4(aVertexPosition, 1.0), aVertexNormal);");
}
}
else {
result.push(" vDiffuseColor = uDiffuseColor;");
}
if (options.vertexColorEnabled) {
result.push(" vDiffuseColor *= aVertexColor;");
}
if (options.textureEnabled) {
result.push(" vTextureCoord = aTextureCoord;");
}
result.push("}");
return result.join('\n');
}
function buildFragmentShader(options) {
var result = [];
result.push("precision mediump float;");
result.push("varying vec4 vDiffuseColor;");
if (options.textureEnabled) {
result.push("varying vec2 vTextureCoord;");
result.push("uniform sampler2D uSampler;");
}
if (options.lightingEnabled) {
if (options.perPixelLightingEnabled) {
result.push("uniform vec4 uDiffuseColor;");
result.push("varying vec3 vPositionWS;");
result.push("varying vec3 vNormalWS;");
addLighting(result);
}
else {
result.push("varying vec3 vSpecularColor;");
}
}
result.push(Zia.SharedProgramCode.common);
result.push("void main(void) {");
result.push(" vec4 color = vDiffuseColor;");
if (options.textureEnabled) {
result.push(" color *= texture2D(uSampler, vTextureCoord);");
}
if (options.lightingEnabled) {
if (options.perPixelLightingEnabled) {
result.push(" vec3 eyeVector = normalize(uEyePosition - vPositionWS);");
result.push(" vec3 worldNormal = normalize(vNormalWS);");
result.push(" ColorPair lightResult = ComputeLights(eyeVector, worldNormal);");
result.push(" color.rgb *= lightResult.Diffuse;");
result.push(" AddSpecular(color, lightResult.Specular);");
}
else {
result.push(" AddSpecular(color, vSpecularColor.rgb);");
}
}
result.push(" gl_FragColor = color;");
result.push("}");
return result.join('\n');
}
/**
* A basic rendering effect with support for lighting and a single texture.
*/
var BasicProgram = (function (_super) {
__extends(BasicProgram, _super);
/**
* Constructs a new `BasicProgram`.
*
* @param {Zia.GraphicsDevice} graphicsDevice - The graphics device.
* @param {Boolean} [options.lightingEnabled=false] - Should lighting be enabled?
* @param {Boolean} [options.perPixelLightingEnabled=true] - Should per-pixel (as opposed to per-vertex) lighting be enabled?.
* @param {Boolean} [options.textureEnabled=false] - Should textures be enabled?
* @param {Boolean} [options.vertexColorEnabled=false] - Will you be using vertices that contain a color component?
*/
function BasicProgram(graphicsDevice, options) {
this._dirtyFlags = -1 /* All */;
this.modelMatrix = new Zia.Matrix4();
this.viewMatrix = new Zia.Matrix4();
this.projectionMatrix = new Zia.Matrix4();
this._modelView = new Zia.Matrix4();
this.diffuseColor = new Zia.Vector3(1, 1, 1);
this.emissiveColor = new Zia.Vector3();
this.specularColor = new Zia.Vector3(1, 1, 1);
this.specularPower = 16;
this.alpha = 1;
this.texture = null;
this.ambientLightColor = new Zia.Vector3();
this._directionalLight0 = new Zia.DirectionalLight(this, 0);
this._directionalLight1 = new Zia.DirectionalLight(this, 1);
this._directionalLight2 = new Zia.DirectionalLight(this, 2);
this._directionalLight0.enabled = true;
options = Zia.ObjectUtil.reverseMerge(options || {}, {
lightingEnabled: false,
perPixelLightingEnabled: true,
textureEnabled: false,
vertexColorEnabled: false
});
this._options = options;
var vertexShader = new Zia.VertexShader(graphicsDevice, buildVertexShader(options));
var fragmentShader = new Zia.FragmentShader(graphicsDevice, buildFragmentShader(options));
_super.call(this, graphicsDevice, vertexShader, fragmentShader);
}
Object.defineProperty(BasicProgram.prototype, "modelMatrix", {
get: function () {
return this._modelMatrix;
},
set: function (v) {
this._modelMatrix = v;
this._dirtyFlags |= 2 /* Model */ | 1 /* ModelViewProj */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "viewMatrix", {
get: function () {
return this._viewMatrix;
},
set: function (v) {
this._viewMatrix = v;
this._dirtyFlags |= 1 /* ModelViewProj */ | 4 /* EyePosition */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "projectionMatrix", {
get: function () {
return this._projectionMatrix;
},
set: function (v) {
this._projectionMatrix = v;
this._dirtyFlags |= 1 /* ModelViewProj */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "diffuseColor", {
get: function () {
return this._diffuseColor;
},
set: function (v) {
this._diffuseColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "emissiveColor", {
get: function () {
return this._emissiveColor;
},
set: function (v) {
this._emissiveColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "specularColor", {
get: function () {
return this._specularColor;
},
set: function (v) {
this._specularColor = v;
this._dirtyFlags |= 16 /* SpecularColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "specularPower", {
get: function () {
return this._specularPower;
},
set: function (v) {
this._specularPower = v;
this._dirtyFlags |= 32 /* SpecularPower */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "alpha", {
get: function () {
return this._alpha;
},
set: function (v) {
this._alpha = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "texture", {
get: function () {
return this._texture;
},
set: function (v) {
this._texture = v;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "ambientLightColor", {
get: function () {
return this._ambientLightColor;
},
set: function (v) {
this._ambientLightColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "directionalLight0", {
get: function () {
return this._directionalLight0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "directionalLight1", {
get: function () {
return this._directionalLight1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BasicProgram.prototype, "directionalLight2", {
get: function () {
return this._directionalLight2;
},
enumerable: true,
configurable: true
});
BasicProgram.prototype.enableDefaultLighting = function () {
if (!this._options.lightingEnabled) {
throw "Lighting must be enabled when creating this program.";
}
this.ambientLightColor = Zia.ProgramUtil.enableDefaultLighting(this._directionalLight0, this._directionalLight1, this._directionalLight2);
};
BasicProgram.prototype._onApply = function () {
// Recompute the model+view+projection matrix?
this._dirtyFlags = Zia.ProgramUtil.setModelViewProj(this, this._dirtyFlags, this._modelMatrix, this._viewMatrix, this._projectionMatrix, this._modelView);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((this._dirtyFlags & 8 /* MaterialColor */) != 0) {
Zia.ProgramUtil.setMaterialColor(this, this._options.lightingEnabled, this._alpha, this._diffuseColor, this._emissiveColor, this._ambientLightColor);
this._dirtyFlags &= ~8 /* MaterialColor */;
}
if ((this._dirtyFlags & 16 /* SpecularColor */) != 0) {
this.setUniform('uSpecularColor', this._specularColor);
this._dirtyFlags &= ~16 /* SpecularColor */;
}
if ((this._dirtyFlags & 32 /* SpecularPower */) != 0) {
this.setUniform('uSpecularPower', this._specularPower);
this._dirtyFlags &= ~32 /* SpecularPower */;
}
if (this._options.lightingEnabled) {
// Recompute the world inverse transpose and eye position?
this._dirtyFlags = Zia.ProgramUtil.setLightingMatrices(this, this._dirtyFlags, this._modelMatrix, this._viewMatrix);
}
this.setUniform('uSampler', this._texture);
this._directionalLight0._apply();
this._directionalLight1._apply();
this._directionalLight2._apply();
};
return BasicProgram;
})(Zia.Program);
Zia.BasicProgram = BasicProgram;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
/**
* A directional light structure, used by several of the built-in `Program` classes.
*/
var DirectionalLight = (function () {
/**
* Constructs a new `DirectionalLight`.
*
* @param {Zia.Program} program - The associated program.
* @param {Number} index - The index of this light (used to set uniforms correctly).
*/
function DirectionalLight(program, index) {
this._program = program;
this._index = index;
this.direction = new Zia.Vector3();
this.diffuseColor = new Zia.Vector3();
this.specularColor = new Zia.Vector3();
this.enabled = false;
}
Object.defineProperty(DirectionalLight.prototype, "direction", {
get: function () {
return this._direction;
},
set: function (v) {
this._direction = v;
this._directionChanged = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DirectionalLight.prototype, "diffuseColor", {
get: function () {
return this._diffuseColor;
},
set: function (v) {
this._diffuseColor = v;
this._diffuseColorChanged = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DirectionalLight.prototype, "specularColor", {
get: function () {
return this._specularColor;
},
set: function (v) {
this._specularColor = v;
this._specularColorChanged = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DirectionalLight.prototype, "enabled", {
get: function () {
return this._enabled;
},
set: function (v) {
this._enabled = v;
this._enabledChanged = true;
},
enumerable: true,
configurable: true
});
DirectionalLight.prototype._apply = function () {
if (this._directionChanged) {
this._setUniform("Direction", this._direction);
this._directionChanged = false;
}
if (this._diffuseColorChanged && this._enabled) {
this._setUniform("DiffuseColor", this._diffuseColor);
this._diffuseColorChanged = false;
}
if (this._specularColorChanged && this._enabled) {
this._setUniform("SpecularColor", this._specularColor);
this._specularColorChanged = false;
}
if (this._enabledChanged) {
if (!this._enabled) {
this._setUniform("DiffuseColor", DirectionalLight._zero);
this._setUniform("SpecularColor", DirectionalLight._zero);
}
this._enabledChanged = false;
}
};
DirectionalLight.prototype._setUniform = function (name, value) {
this._program.setUniform("uDirLight" + this._index + name, value);
};
DirectionalLight._zero = new Zia.Vector3();
return DirectionalLight;
})();
Zia.DirectionalLight = DirectionalLight;
})(Zia || (Zia = {}));
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Zia;
(function (Zia) {
function addLighting(result) {
result.push("uniform vec3 uDirLight0Direction;");
result.push("uniform vec3 uDirLight0DiffuseColor;");
result.push("#define uDirLight0SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uDirLight1Direction;");
result.push("uniform vec3 uDirLight1DiffuseColor;");
result.push("#define uDirLight1SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uDirLight2Direction;");
result.push("uniform vec3 uDirLight2DiffuseColor;");
result.push("#define uDirLight2SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uEyePosition;");
result.push("uniform vec3 uEmissiveColor;");
result.push("#define uSpecularColor vec3(0,0,0)");
result.push("#define uSpecularPower 0");
result.push(Zia.SharedProgramCode.lighting);
}
function buildVertexShader(options) {
var result = [];
result.push("precision mediump float;");
// Attributes
result.push("attribute vec3 aVertexPosition;");
result.push("attribute vec3 aVertexNormal;");
result.push("attribute vec2 aTextureCoord;");
// Uniforms
result.push("uniform mat4 uMVPMatrix;");
result.push("uniform mat4 uMMatrix;");
result.push("uniform mat3 uMMatrixInverseTranspose;");
result.push("uniform vec4 uDiffuseColor;");
result.push("uniform float uEnvironmentMapAmount;");
result.push("uniform float uFresnelFactor;");
result.push("uniform vec3 uDirLight0Direction;");
result.push("uniform vec3 uDirLight0DiffuseColor;");
result.push("#define uDirLight0SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uDirLight1Direction;");
result.push("uniform vec3 uDirLight1DiffuseColor;");
result.push("#define uDirLight1SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uDirLight2Direction;");
result.push("uniform vec3 uDirLight2DiffuseColor;");
result.push("#define uDirLight2SpecularColor vec3(0,0,0)");
result.push("uniform vec3 uEyePosition;");
result.push("uniform vec3 uEmissiveColor;");
result.push("#define uSpecularColor vec3(0,0,0)");
result.push("#define uSpecularPower 0");
result.push(Zia.SharedProgramCode.lighting);
// Varyings
result.push("varying vec4 vDiffuseColor;");
result.push("varying vec3 vSpecularColor;");
result.push("varying vec2 vTextureCoord;");
result.push("varying vec3 vEnvCoord;");
// Code
result.push("float ComputeFresnelFactor(vec3 eyeVector, vec3 worldNormal) {");
result.push(" float viewAngle = dot(eyeVector, worldNormal);");
result.push(" return pow(max(1.0 - abs(viewAngle), 0.0), uFresnelFactor) * uEnvironmentMapAmount;");
result.push("}");
result.push("void main(void) {");
result.push(" gl_Position = uMVPMatrix * vec4(aVertexPosition, 1.0);");
result.push(" vec4 positionWS = uMMatrix * vec4(aVertexPosition, 1.0);");
result.push(" vec3 eyeVector = normalize(uEyePosition - positionWS.xyz);");
result.push(" vec3 worldNormal = normalize(uMMatrixInverseTranspose * aVertexNormal);");
result.push(" ColorPair lightResult = ComputeLights(eyeVector, worldNormal);");
result.push(" vDiffuseColor = vec4(lightResult.Diffuse, uDiffuseColor.a);");
if (options.fresnelEnabled) {
result.push(" vSpecularColor.rgb = vec3(ComputeFresnelFactor(eyeVector, worldNormal));");
}
else {
result.push(" vSpecularColor.rgb = vec3(uEnvironmentMapAmount);");
}
result.push(" vTextureCoord = aTextureCoord;");
result.push(" vEnvCoord = reflect(-eyeVector, worldNormal);");
result.push("}");
return result.join('\n');
}
function buildFragmentShader(options) {
var result = [];
result.push("precision mediump float;");
result.push("varying vec4 vDiffuseColor;");
result.push("varying vec3 vSpecularColor;");
result.push("varying vec2 vTextureCoord;");
result.push("uniform sampler2D uSampler;");
result.push("varying vec3 vEnvCoord;");
result.push("uniform samplerCube uEnvironmentMapSampler;");
result.push("uniform vec3 uEnvironmentMapSpecular;");
result.push("void main(void) {");
result.push(" vec4 color = vDiffuseColor;");
result.push(" color *= texture2D(uSampler, vTextureCoord);");
result.push(" vec4 envmap = textureCube(uEnvironmentMapSampler, vEnvCoord) * color.a;");
result.push(" color.rgb = mix(color.rgb, envmap.rgb, vSpecularColor.rgb);");
if (options.environmentMapSpecularEnabled) {
result.push(" color.rgb += uEnvironmentMapSpecular * envmap.a;");
}
result.push(" gl_FragColor = color;");
result.push("}");
return result.join('\n');
}
/**
* A rendering effect with support for an environment map cube texture.
*/
var EnvironmentMapProgram = (function (_super) {
__extends(EnvironmentMapProgram, _super);
/**
* Constructs a new `EnvironmentMapProgram`.
*
* @param {Zia.GraphicsDevice} graphicsDevice - The graphics device.
* @param {Object} [options] - TODO
*/
function EnvironmentMapProgram(graphicsDevice, options) {
this._dirtyFlags = -1 /* All */;
this.modelMatrix = new Zia.Matrix4();
this.viewMatrix = new Zia.Matrix4();
this.projectionMatrix = new Zia.Matrix4();
this._modelView = new Zia.Matrix4();
this.diffuseColor = new Zia.Vector3(1, 1, 1);
this.emissiveColor = new Zia.Vector3();
this.alpha = 1;
this.texture = null;
this.ambientLightColor = new Zia.Vector3();
this._environmentMap = null;
this.environmentMapAmount = 1;
this.environmentMapSpecular = new Zia.Vector3();
this.fresnelFactor = 1;
this._directionalLight0 = new Zia.DirectionalLight(this, 0);
this._directionalLight1 = new Zia.DirectionalLight(this, 1);
this._directionalLight2 = new Zia.DirectionalLight(this, 2);
this._directionalLight0.enabled = true;
options = Zia.ObjectUtil.reverseMerge(options || {}, {
environmentMapSpecularEnabled: false,
fresnelEnabled: true
});
this._options = options;
var vertexShader = new Zia.VertexShader(graphicsDevice, buildVertexShader(options));
var fragmentShader = new Zia.FragmentShader(graphicsDevice, buildFragmentShader(options));
_super.call(this, graphicsDevice, vertexShader, fragmentShader);
}
Object.defineProperty(EnvironmentMapProgram.prototype, "modelMatrix", {
get: function () { return this._modelMatrix; },
set: function (v) {
this._modelMatrix = v;
this._dirtyFlags |= 2 /* Model */ | 1 /* ModelViewProj */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "viewMatrix", {
get: function () { return this._viewMatrix; },
set: function (v) {
this._viewMatrix = v;
this._dirtyFlags |= 1 /* ModelViewProj */ | 4 /* EyePosition */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "projectionMatrix", {
get: function () { return this._projectionMatrix; },
set: function (v) {
this._projectionMatrix = v;
this._dirtyFlags |= 1 /* ModelViewProj */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "diffuseColor", {
get: function () { return this._diffuseColor; },
set: function (v) {
this._diffuseColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "emissiveColor", {
get: function () { return this._emissiveColor; },
set: function (v) {
this._emissiveColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "alpha", {
get: function () { return this._alpha; },
set: function (v) {
this._alpha = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "ambientLightColor", {
get: function () { return this._ambientLightColor; },
set: function (v) {
this._ambientLightColor = v;
this._dirtyFlags |= 8 /* MaterialColor */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "directionalLight0", {
get: function () { return this._directionalLight0; },
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "directionalLight1", {
get: function () { return this._directionalLight1; },
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "directionalLight2", {
get: function () { return this._directionalLight2; },
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "texture", {
get: function () { return this._texture; },
set: function (v) { this._texture = v; },
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "environmentMap", {
get: function () { return this._environmentMap; },
set: function (v) { this._environmentMap = v; },
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "environmentMapAmount", {
get: function () { return this._environmentMapAmount; },
set: function (v) {
this._environmentMapAmount = v;
this._dirtyFlags |= 64 /* EnvironmentMapAmount */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "environmentMapSpecular", {
get: function () { return this._environmentMapSpecular; },
set: function (v) {
this._environmentMapSpecular = v;
this._dirtyFlags |= 128 /* EnvironmentMapSpecular */;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentMapProgram.prototype, "fresnelFactor", {
get: function () { return this._fresnelFactor; },
set: function (v) {
this._fresnelFactor = v;
this._dirtyFlags |= 256 /* FresnelFactor */;
},
enumerable: true,
configurable: true
});
EnvironmentMapProgram.prototype.enableDefaultLighting = function () {
this.ambientLightColor = Zia.ProgramUtil.enableDefaultLighting(this._directionalLight0, this._directionalLight1, this._directionalLight2);
};
EnvironmentMapProgram.prototype._onApply = function () {
// Recompute the model+view+projection matrix?
this._dirtyFlags = Zia.ProgramUtil.setModelViewProj(this, this._dirtyFlags, this._modelMatrix, this._viewMatrix, this._projectionMatrix, this._modelView);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((this._dirtyFlags & 8 /* MaterialColor */) != 0) {
Zia.ProgramUtil.setMaterialColor(this, this._options.lightingEnabled, this._alpha, this._diffuseColor, this._emissiveColor, this._ambientLightColor);
this._dirtyFlags &= ~8 /* MaterialColor */;
}
this.setUniform('uSampler', this._texture);
this.setUniform('uEnvironmentMapSampler', this._environmentMap);
if ((this._dirtyFlags & 64 /* EnvironmentMapAmount */) != 0) {
this.setUniform('uEnvironmentMapAmount', this._environmentMapAmount);
this._dirtyFlags &= ~64 /* EnvironmentMapAmount */;
}
if ((this._dirtyFlags & 128 /* EnvironmentMapSpecular */) != 0) {
this.setUniform('uEnvironmentMapSpecular', this._environmentMapSpecular);
this._dirtyFlags &= ~128 /* EnvironmentMapSpecular */;
}
if ((this._dirtyFlags & 256 /* FresnelFactor */) != 0) {
this.setUniform('uFresnelFactor', this._fresnelFactor);
this._dirtyFlags &= ~256 /* FresnelFactor */;
}
// Recompute the world inverse transpose and eye position?
this._dirtyFlags = Zia.ProgramUtil.setLightingMatrices(this, this._dirtyFlags, this._modelMatrix, this._viewMatrix);
this._directionalLight0._apply();
this._directionalLight1._apply();
this._directionalLight2._apply();
};
return EnvironmentMapProgram;
})(Zia.Program);
Zia.EnvironmentMapProgram = EnvironmentMapProgram;
})(Zia || (Zia = {}));
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//-----------------------------------------------------------------------------
// Common.fxh
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
var Zia;
(function (Zia) {
Zia.SharedProgramCode = {
common: [
"void AddSpecular(inout vec4 color, vec3 specular) {",
" color.rgb += specular * color.a;",
"}"
].join('\n'),
lighting: [
"struct ColorPair {",
" vec3 Diffuse;",
" vec3 Specular;",
"};",
"ColorPair ComputeLights(vec3 eyeVector, vec3 worldNormal) {",
" mat3 lightDirections;",
" mat3 lightDiffuse;",
" mat3 lightSpecular;",
" mat3 halfVectors;",
" for (int i = 0; i < 3; i++) {",
" lightDirections[i] = mat3(uDirLight0Direction, uDirLight1Direction, uDirLight2Direction) [i];",
" lightDiffuse[i] = mat3(uDirLight0DiffuseColor, uDirLight1DiffuseColor, uDirLight2DiffuseColor) [i];",
" lightSpecular[i] = mat3(uDirLight0SpecularColor, uDirLight1SpecularColor, uDirLight2SpecularColor)[i];",
" halfVectors[i] = normalize(eyeVector - lightDirections[i]);",
" }",
" vec3 dotL = worldNormal * -lightDirections;",
" vec3 dotH = worldNormal * halfVectors;",
" vec3 zeroL = step(vec3(0.0), dotL);",
" vec3 diffuse = zeroL * dotL;",
" vec3 specular = pow(max(dotH, vec3(0.0)) * zeroL, vec3(uSpecularPower));",
" ColorPair result;",
" result.Diffuse = (lightDiffuse * diffuse) * uDiffuseColor.rgb + uEmissiveColor;",
" result.Specular = (lightSpecular * specular) * uSpecularColor;",
" return result;",
"}"
].join('\n'),
lightingVertex: [
"void ComputeCommonVSOutputWithLighting(vec4 position, vec3 normal) {",
" vec4 positionWS = uMMatrix * position;",
" vec3 eyeVector = normalize(uEyePosition - positionWS.xyz);",
" vec3 worldNormal = normalize(uMMatrixInverseTranspose * normal);",
" ColorPair lightResult = ComputeLights(eyeVector, worldNormal);",
" vDiffuseColor = vec4(lightResult.Diffuse, uDiffuseColor.a);",
" vSpecularColor = lightResult.Specular;",
"}"
].join('\n')
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var Keyboard = (function () {
function Keyboard() {
this._pressedKeys = [];
var that = this;
this._onKeyDown = function (evt) {
var index = that._pressedKeys.indexOf(evt.keyCode);
if (index === -1) {
that._pressedKeys.push(evt.keyCode);
}
};
this._onKeyUp = function (evt) {
var index = that._pressedKeys.indexOf(evt.keyCode);
if (index >= 0) {
that._pressedKeys.splice(index, 1);
}
};
window.addEventListener('keydown', this._onKeyDown);
window.addEventListener('keyup', this._onKeyUp);
}
Keyboard.prototype.getState = function (result) {
if (result === void 0) { result = new Zia.KeyboardState(); }
result._setPressedKeys(this._pressedKeys);
return result;
};
Keyboard.prototype.destroy = function () {
window.removeEventListener('keydown', this._onKeyDown);
window.removeEventListener('keyup', this._onKeyUp);
};
return Keyboard;
})();
Zia.Keyboard = Keyboard;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
var KeyboardState = (function () {
function KeyboardState() {
}
KeyboardState.prototype._setPressedKeys = function (pressedKeys) {
this._pressedKeys = pressedKeys.slice(0);
};
KeyboardState.prototype.getPressedKeys = function () {
return this._pressedKeys;
};
KeyboardState.prototype.isKeyDown = function (keyCode) {
for (var index = 0; index < this._pressedKeys.length; index++) {
if (this._pressedKeys[index] === keyCode) {
return true;
}
}
return false;
};
KeyboardState.prototype.isKeyUp = function (keyCode) {
return !this.isKeyDown(keyCode);
};
return KeyboardState;
})();
Zia.KeyboardState = KeyboardState;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
(function (ButtonState) {
ButtonState[ButtonState["Released"] = 0] = "Released";
ButtonState[ButtonState["Pressed"] = 1] = "Pressed";
})(Zia.ButtonState || (Zia.ButtonState = {}));
var ButtonState = Zia.ButtonState;
var MouseState = (function () {
function MouseState() {
}
return MouseState;
})();
Zia.MouseState = MouseState;
var Mouse = (function () {
function Mouse(element, noPreventDefault) {
this._element = element;
this._pointerLocked = false;
var state = this._state = new MouseState();
state.pointerLocked = false;
state.x = null;
state.y = null;
state.deltaX = null;
state.deltaY = null;
state.scrollWheel = null;
state.leftButton = ButtonState.Released;
state.middleButton = ButtonState.Released;
state.rightButton = ButtonState.Released;
state.xButton1 = ButtonState.Released;
state.xButton2 = ButtonState.Released;
var previousState = null;
var pressedButtons = [];
var that = this;
var getButtonState = function (button) {
for (var i = 0; i < pressedButtons.length; i++) {
if (pressedButtons[i] === button) {
return ButtonState.Pressed;
}
}
return ButtonState.Released;
};
var updateState = function (evt, updateButtons) {
state.pointerLocked = that._pointerLocked;
if (state.pointerLocked) {
state.x = null;
state.y = null;
state.deltaX = (evt.movementX !== undefined) ? evt.movementX : evt.mozMovementX;
state.deltaY = (evt.movementY !== undefined) ? evt.movementY : evt.mozMovementY;
}
else {
state.x = evt.clientX;
state.y = evt.clientY;
if (previousState === null) {
previousState = {
x: state.x,
y: state.y
};
}
state.deltaX = state.x - previousState.x;
state.deltaY = state.y - previousState.y;
}
if (evt.type === "wheel") {
state.scrollWheel = (evt.deltaY < 0) ? 1 : -1;
}
else {
state.scrollWheel = 0;
}
if (updateButtons) {
state.leftButton = getButtonState(0);
state.middleButton = getButtonState(1);
state.rightButton = getButtonState(2);
state.xButton1 = getButtonState(3);
state.xButton2 = getButtonState(4);
}
previousState = {
x: state.x,
y: state.y
};
if (!noPreventDefault) {
evt.preventDefault();
}
};
this._onMouseDown = function (evt) {
if (evt.button !== -1) {
var index = pressedButtons.indexOf(evt.button);
if (index === -1) {
pressedButtons.push(evt.button);
}
}
updateState(evt, true);
};
this._onMouseUp = function (evt) {
if (evt.button !== -1) {
var index = pressedButtons.indexOf(evt.button);
if (index != -1) {
pressedButtons.splice(index, 1);
}
}
updateState(evt, true);
};
this._onMouseOut = function (evt) {
updateState(evt, false);
};
this._onMouseMove = function (evt) {
updateState(evt, false);
};
this._onWheel = function (evt) {
updateState(evt, false);
};
this._onContextMenu = function (evt) {
if (!noPreventDefault) {
evt.preventDefault();
}
};
element.addEventListener('mousedown', this._onMouseDown);
element.addEventListener('mouseup', this._onMouseUp);
element.addEventListener('mouseout', this._onMouseOut);
element.addEventListener('mousemove', this._onMouseMove);
element.addEventListener('wheel', this._onWheel);
element.addEventListener('contextmenu', this._onContextMenu);
element.requestPointerLock = element.requestPointerLock ||
element.msRequestPointerLock ||
element.mozRequestPointerLock ||
element.webkitRequestPointerLock;
document.exitPointerLock = document.exitPointerLock ||
document.msExitPointerLock ||
document.mozExitPointerLock ||
document.webkitExitPointerLock;
this._onPointerLockChange = function (evt) {
that._pointerLocked = (document.pointerLockElement === element
|| document.msPointerLockElement === element
|| document.mozPointerLockElement === element
|| document.webkitPointerLockElement === element);
};
document.addEventListener('pointerlockchange', this._onPointerLockChange);
document.addEventListener('mspointerlockchange', this._onPointerLockChange);
document.addEventListener('mozpointerlockchange', this._onPointerLockChange);
document.addEventListener('webkitpointerlockchange', this._onPointerLockChange);
}
Object.defineProperty(Mouse.prototype, "canLockPointer", {
get: function () {
return !!this._element.requestPointerLock;
},
enumerable: true,
configurable: true
});
Mouse.prototype.lockPointer = function () {
if (this._element.requestPointerLock) {
this._element.requestPointerLock();
}
};
Mouse.prototype.unlockPointer = function () {
if (!this._pointerLocked) {
return;
}
document.exitPointerLock();
};
Mouse.prototype.getState = function (result) {
if (result === void 0) { result = new MouseState(); }
var state = this._state;
result.pointerLocked = state.pointerLocked;
result.x = state.x;
result.y = state.y;
result.deltaX = state.deltaX;
result.deltaY = state.deltaY;
result.scrollWheel = state.scrollWheel;
result.leftButton = state.leftButton;
result.middleButton = state.middleButton;
result.rightButton = state.rightButton;
result.xButton1 = state.xButton1;
result.xButton2 = state.xButton2;
return result;
};
Mouse.prototype.destroy = function () {
this.unlockPointer();
this._element.removeEventListener('mousedown', this._onMouseDown);
this._element.removeEventListener('mouseup', this._onMouseUp);
this._element.removeEventListener('mouseout', this._onMouseOut);
this._element.removeEventListener('mousemove', this._onMouseMove);
this._element.removeEventListener('wheel', this._onWheel);
this._element.removeEventListener('contextmenu', this._onContextMenu);
document.removeEventListener('pointerlockchange', this._onPointerLockChange);
document.removeEventListener('mspointerlockchange', this._onPointerLockChange);
document.removeEventListener('mozpointerlockchange', this._onPointerLockChange);
document.removeEventListener('webkitpointerlockchange', this._onPointerLockChange);
};
return Mouse;
})();
Zia.Mouse = Mouse;
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
function throwOnGLError(err, funcName, args) {
throw WebGLDebugUtils.glEnumToString(err) + " was caused by call to: " + funcName;
}
function validateNoneOfTheArgsAreUndefined(functionName, args) {
for (var ii = 0; ii < args.length; ++ii) {
if (args[ii] === undefined) {
throw "undefined passed to gl." + functionName + "(" +
WebGLDebugUtils.glFunctionArgsToString(functionName, args) + ")";
}
}
}
Zia.DebugUtil = {
makeDebugContext: function (gl) {
return WebGLDebugUtils.makeDebugContext(gl, throwOnGLError, validateNoneOfTheArgsAreUndefined);
}
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
Zia.EnumUtil = {
hasFlag: function (value, flag) {
return (value & flag) === flag;
}
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
Zia.HtmlUtil = {
toggleFullScreen: function (element) {
if (element === void 0) { element = document.documentElement; }
if (!document.fullscreenElement &&
!document.mozFullScreenElement &&
!document.webkitFullscreenElement &&
!document.msFullscreenElement) {
if (element.requestFullscreen) {
element.requestFullscreen();
}
else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
}
else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
}
else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
};
})(Zia || (Zia = {}));
var Zia;
(function (Zia) {
Zia.ObjectUtil = {
reverseMerge: function (object, source) {
for (var key in source) {
if (source.hasOwnProperty(key) && !(key in object)) {
object[key] = source[key];
}
}
return object;
}
};
})(Zia || (Zia = {}));
|
exports.getSeed = () => ({
modelName: 'user',
className: 'User',
fields: [{
name: 'name',
type: 'STRING',
}, {
name: 'email',
type: 'STRING',
}],
})
|
angular.module('myApp', [])
.controller('MyController', ['$http', '$scope', function($http, $scope) {
$scope.order = 'age';
$scope.changeOrder = function() {
if ($scope.order === 'age') {
$scope.order = '-age';
} else {
$scope.order = 'age';
}
}
$http.get('api/test/all').then(function(response) {
$scope.persons = response.data;
});
$http.get('api/test/hello/name=Danny,lastname=Dynamit').then(function(response) {
$scope.welcome = response.data;
});
}]);
|
import React from 'react';
import { Link, withRouter, useHistory } from 'react-router-dom';
import styled from 'styled-components';
import Footer from '../../Components/Footer/Footer';
import { KAKAO_LOGIN_API } from '../../config';
import { setToken } from '../../utils/storage';
function Login() {
const history = useHistory();
const kakaoLoginHandler = () => {
window.Kakao.Auth.login({
success: (auth) => {
fetch(`${KAKAO_LOGIN_API}/users/login`, {
method: 'GET',
headers: {
Authorization: auth.access_token,
},
})
.then((res) => res.json())
.then((res) => {
if (res.token) {
setToken(res.token);
alert('로그인성공');
history.push('/main');
} else {
alert('다시 확인해 주세요.');
}
});
},
fail: function (err) {
console.log('a');
console.log('에러', err);
},
});
};
return (
<>
<Article>
<LoginBox>
<LoginForm>
<LoginInner>
<Head>로그인</Head>
<InputBox>
<IdText>
회원 아이디/스카이패스 회원번호
<Required>필수 입력</Required>
</IdText>
<IdInput type="text" />
<PwText>
비밀번호
<Required>필수 입력</Required>
</PwText>
<PwInput type="text" />
</InputBox>
<BtnBox>
<LoginBtn>로그인</LoginBtn>
<SnsText>
<SnsTitle>SNS 로그인</SnsTitle>
</SnsText>
<LoginBtn type="button" kakao onClick={kakaoLoginHandler}>
카카오 계정으로 로그인
</LoginBtn>
</BtnBox>
</LoginInner>
<BtnSignup href="/signup">회원가입</BtnSignup>
</LoginForm>
</LoginBox>
</Article>
<Footer />
</>
);
}
const Article = styled.div`
display: flex;
justify-content: center;
align-items: center;
background-color: #c1dcf9;
height: 100vh;
margin-top: 89px;
`;
const LoginBox = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 1250px;
height: 650px;
margin: 0 600px 0 600px;
`;
const LoginForm = styled.form`
display: flex;
flex-direction: column;
justify-content: space-between;
width: 530px;
height: 100%;
box-shadow: 4px 10px 20px 0 lightgray;
background-color: white;
`;
const LoginInner = styled.div`
display: flex;
flex-direction: column;
padding: 40px 60px 40px 60px;
`;
const Head = styled.h2`
margin-bottom: 26px;
font-size: 32px;
font-weight: 500;
`;
const InputBox = styled.div`
display: flex;
flex-direction: column;
`;
const IdText = styled.label`
padding-top: 10px;
margin-bottom: 10px;
color: gray;
`;
const Required = styled.span`
display: inline-block;
overflow: hidden;
white-space: nowrap;
text-indent: 100%;
position: relative;
width: 5px;
font-size: inherit;
vertical-align: bottom;
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 4px;
height: 4px;
border-radius: 50%;
background-color: #de001b;
}
`;
const IdInput = styled.input`
width: 410px;
height: 50px;
border: 0;
border-bottom: 1px solid #00256c;
&:hover {
border: rgb(87, 124, 192) 1px solid;
border-radius: 2px;
}
`;
const PwText = styled.label`
margin-top: 30px;
margin-bottom: 10px;
padding-top: 10px;
color: gray;
`;
const PwInput = styled.input`
width: 410px;
height: 50px;
border: 0;
border-bottom: 1px solid #00256c;
&:hover {
border: rgb(87, 124, 192) 1px solid;
border-radius: 2px;
}
`;
const BtnBox = styled.div`
display: flex;
flex-direction: column;
`;
const SnsText = styled.h3`
position: relative;
margin-top: 10px;
font-weight: 200;
text-align: center;
color: #555;
::before {
content: '';
display: block;
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 1px;
background: #d9dbe1;
}
`;
const SnsTitle = styled.span`
display: inline-block;
position: relative;
margin: 0 10px;
padding: 0 17px;
background: #fff;
font-weight: 600;
`;
const LoginBtn = styled.button`
width: 410px;
height: 60px;
border: 1.5px solid #fff;
border-radius: 2px;
margin: 30px 0 20px 0;
padding: 2px;
cursor: pointer;
background-color: ${(props) => (props.kakao ? '#FEE500' : '#00256c')};
color: ${(props) => (props.kakao ? 'black' : 'white')};
font-size: 18px;
font-weight: 600;
:hover {
border: rgb(82, 167, 182) 1.5px solid;
border-radius: 2px;
}
`;
const BtnSignup = styled(Link)`
display: flex;
width: 100%;
height: 70px;
justify-content: center;
align-items: center;
background-color: rgba(217, 232, 238, 0.521);
text-decoration: none;
font-size: 18px;
font-weight: bold;
color: black;
&:hover {
border: rgb(87, 124, 192) 1px solid;
border-radius: 2px;
}
`;
export default withRouter(Login);
|
const crypto = require('crypto');
const connection = require('./db');
const _collection = 'images';
class ImageService {
static getRandomKey(orgUrl = '' , prefix = ''){
const date = new Date();
const randomText = date.getMonth() + date.getDay() + date.getHours() + date.getMinutes();
const _randomText = orgUrl === '' ? randomText + ( Math.random() * 200 ) : randomText + ( Math.random() * 99 ) + orgUrl;
const randomKey = ( crypto.createHash('md5').update(_randomText).digest('hex').substring(0, 17) + randomText ).replace(/\-/,'_');
return prefix + '_' + randomKey;
}
static addCosImages( images ){
return new Promise( async (resolve, reject) =>{
if ( !images || images.length <= 0 ){
reject({
status:'err',
content:'上传图片为空'
});
return;
}
try {
const db = await connection( _collection );
const inserted = await db.insertMany( images );
resolve( inserted );
}catch( e ){
reject(e);
}
});
mongodb.connect(url, ( err, db) =>{
assert.equal(null,err);
const collection = db.collection(dbName);
collection.insertOne(data).then((doc,err) =>{
if (err){
fail({status:"err",content:"出现错误"});
}else{
success({status:"ok",content:"文章发表成功"});
}
});
});
}
async addCosImage(){
}
}
module.exports = ImageService;
|
'use strict';
const TABLE_NAME = "skill"
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.createTable(TABLE_NAME, {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
profile_id: {
type: Sequelize.INTEGER,
references: {
model: 'profile',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
instrument_id: {
type: Sequelize.INTEGER,
references: {
model: 'instrument',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
level: {
type: Sequelize.TEXT
},
week_frequency: {
type: Sequelize.INTEGER
}
})
},
down: async (queryInterface, Sequelize) => {
return queryInterface.dropTable(TABLE_NAME);
}
};
|
//获取dom对象
var $ = function(id) {
return typeof id === 'string' ? document.getElementById(id) : id;
};
// 弹窗构造函数
var Modal = function (id,html) {
this.html =html;
this.id = id;
this.open = false;
}
Modal.prototype.create = function () {
if(!this.open){
var modal = document.createElement('div');
modal.innerHTML = this.html;
modal.id = this.id;
document.body.appendChild(modal)
setTimeout(function () {
modal.classList.add('show')
})
this.open = true;
}
}
Modal.prototype.delete = function () {
if(this.open){
var modal = $(this.id);
modal.classList.add('hide');
setTimeout(function () {
document.body.removeChild(modal)
},200)
this.open = false;
}
}
var createIntance = (function () {
var instance;
return function () {
return instance || (instance = new Modal('modal','这是一个弹框'))
}
})()
var operate = {
setModal:null,
open:function () {
this.setModal = createIntance()
this.setModal.create()
},
delete:function () {
this.setModal ? this.setModal.delete() :''
}
}
console.log()
$('open').onclick = function() {
operate.open();
};
$('delete').onclick = function() {
operate.delete();
};
|
var db = require('../../../config/db.config');
var fs = require('fs');
const Questions = db.questionary;
exports.findAll = (req,res)=>{
Questions.findAll().then(data=>{
return res.json({
success: true,
message: "Data Found",
data: {'request':data},
})
}).catch(err=>{
return res.json({
success: false,
message: "failed"
})
})
}
|
robot.open("http://siterobot.justengland.c9.io/debug", function() {
robot.expect.val("SiteRobot Debug Page").ele("title") // The title ele should have a value
robot.expect.val("Client").ele("label[for='client']") // the label should have a value
robot.expect.val("value", "go!").attr("#submit", "value") // The input should have an attribute with a name of [value] and value of [go!]
}); // Open the webpage by url
|
function JotEditor () {
var textBox;
// this._textBox = textBox = document.createElement('textarea');
this._textBox = textBox = document.createElement('input');
textBox.type = "text";
textBox.className = "row";
textBox.style.border = "1px solid black";
this._inView = null; // the view we're editing
this._isNew = false; // if we're editing a new element
};
JotEditor.prototype.addEventListener = function (type, fn, useCapture) {
this._textBox.addEventListener(type, fn, useCapture);
};
JotEditor.prototype.changed = function () {
return (this._inView && this._inView.text != this._textBox.value);
};
JotEditor.prototype.value = function () {
return this._textBox.value;
};
JotEditor.prototype.isNew = function () {
return this._isNew;
};
JotEditor.prototype.setIsNew = function (isNew) {
this._isNew = isNew;
};
JotEditor.prototype.startEdit = function(view, offset, isNew) {
var textBox = this._textBox, textElement, childNodes, len, i;
if (this._inView) {
this.finishEdit();
}
this._inView = view;
this._isNew = isNew || false;
textElement = view._textElement;
textBox.style.width = textElement.offsetWidth + "px";
textBox.style.marginLeft = textElement.style.marginLeft;
textBox.value = this._text = view.text;
view.element.replaceChild(textBox, textElement);
textBox.setSelectionRange(offset, offset);
textBox.focus();
};
JotEditor.prototype.finishEdit = function() {
if (this._inView) {
this._inView.element.replaceChild(this._inView._textElement, this._textBox);
this._inView = null;
}
};
JotEditor.prototype.updateValue = function (text, pos) {
if (this._inView) { // can't set selection if not displayed
this._textBox.value = text;
this._textBox.setSelectionRange(pos, pos);
}
};
JotEditor.prototype.setSelection = function (start, end) {
if (this._inView) {
this._textBox.setSelectionRange(start, end);
}
};
JotEditor.prototype.getSelection = function () {
if (this._inView) {
return this._textBox.selectionStart;
} else {
return 0;
}
};
|
const MAX_VISIBLE_CATEGORIES = 2;
export const ALL_CATEGORIES_OPTION = {
key: 'all',
label: 'All categories',
};
export function isAllCategoriesSelected(selectedCategories) {
return _.includes(selectedCategories, ALL_CATEGORIES_OPTION.key);
}
export function getCategoriesDisplayLabel(categoryNames) {
const visibleCategories = _.slice(categoryNames, 0, MAX_VISIBLE_CATEGORIES);
if (categoryNames.length > MAX_VISIBLE_CATEGORIES) {
visibleCategories.push(`+ ${(categoryNames.length - MAX_VISIBLE_CATEGORIES)} more`);
}
return visibleCategories.join(', ');
}
|
define(['async!//maps.google.com/maps/api/js?sensor=false', 'underscore', 'jquery', 'signalr.hubs', 'riderTime'], function (googleMaps, _, $, hubs, RiderTime) {
var eventSlug = null;
var riderSlug = null;
function initialize() {
// retrieve basic information about the event rider (map default location and zoom, and marker default location)
$.getJSON('/api/v1/events/' + eventSlug + '/riders/' + riderSlug + '/').done(function (rider) {
var riderTime = new RiderTime(rider);
var mapOptions = {
center: { lat: rider.MapLatitude, lng: rider.MapLongitude },
zoom: rider.MapZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
position: { lat: rider.MarkerLatitude, lng: rider.MarkerLongitude },
map: map
});
// retrieve the routes associated with this rider
$.getJSON('/api/v1/events/' + eventSlug + '/riders/' + riderSlug + '/routes').done(function (routes) {
var lines = [];
// a rider may be riding on multiple routes throughout a race
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
// create a line for this route and draw it on the map
if (route.UnvisitedVertices != null && route.VisitedVertices != null)
{
var line = new google.maps.Polyline({
path: _.map(route.UnvisitedVertices, function (vertex) { return new google.maps.LatLng(vertex.Latitude, vertex.Longitude); }),
geodisc: true,
strokeColor: route.Color,
strokeOpacity: 1.0,
strokeWeight: 3
});
line.setMap(map);
lines.push(line);
var line = new google.maps.Polyline({
path: _.map(route.VisitedVertices, function (vertex) { return new google.maps.LatLng(vertex.Latitude, vertex.Longitude); }),
geodisc: true,
strokeColor: "#0000FF",
strokeOpacity: 1.0,
strokeWeight: 3
});
line.setMap(map);
lines.push(line);
} else {
var line = new google.maps.Polyline({
path: _.map(route.Vertices, function (vertex) { return new google.maps.LatLng(vertex.Latitude, vertex.Longitude); }),
geodisc: true,
strokeColor: route.Color,
strokeOpacity: 1.0,
strokeWeight: 3
});
line.setMap(map);
lines.push(line);
}
}
});
// update the marker location with the rider's last known position.
$.getJSON('/api/v1/events/' + eventSlug + '/riders/' + riderSlug + '/location').done(function (location) {
if (!location) {
return;
}
marker.setPosition({ lat: location.Latitude, lng: location.Longitude });
$('.travelled .miles .counter').html(location.TotalMiles.toFixed(2));
});
// start listening for location updates
var locationHub = $.connection.eventRiderLocationHub;
var messageHub = $.connection.eventRiderMessageHub;
$.connection.hub.logging = true;
locationHub.client.updateLocation = function (location) {
if (location.EventRiderID !== rider.EventRiderID) {
return;
}
marker.setPosition({ lat: location.Latitude, lng: location.Longitude });
$('.travelled .miles .counter').html(location.TotalMiles.toFixed(2));
};
messageHub.client.addRecentMessage = function (message) {
if (message.EventRiderID !== rider.EventRiderID) {
return;
}
var recentMessages = $('.recent-messages');
recentMessages.find('.no-messages').remove();
var existingMessages = recentMessages.find('.messages .message');
if (existingMessages.length === 5) {
existingMessages.last().remove();
}
$('.recent-messages .messages').prepend('<div class="message"><div class="post">' + message.Text + '</div><div class="author">' + message.Sender + '</div></div>');
};
$.connection.hub.start();
});
}
return {
setup: function (event, rider) {
eventSlug = event;
riderSlug = rider;
$(function () {
initialize();
});
}
};
});
|
/* eslint-env mocha */
'use strict';
const { ESLINT_KEY, organizeOptions } = require('#util');
const { isEmptyArray } = require('./test-util');
const { strict: assert } = require('assert');
describe
(
'organizeOptions',
() =>
{
it
(
'should wrap a string config value into "overrideConfigFile"',
() =>
{
const { eslintOptions, migratedOptions } = organizeOptions('Config/Path');
assert.equal(eslintOptions.cwd, process.cwd());
assert.equal(eslintOptions.overrideConfigFile, 'Config/Path');
assert(isEmptyArray(migratedOptions));
},
);
it
(
'should use the current directory as `cwd` if "cwd" is undefined',
() =>
{
const { eslintOptions } = organizeOptions({ });
assert.equal(eslintOptions.cwd, process.cwd());
},
);
it
(
'should normalize "cwd"',
() =>
{
const cwd = `${process.cwd()}/foo/..`;
const { eslintOptions } = organizeOptions({ cwd });
assert.equal(eslintOptions.cwd, process.cwd());
},
);
it
(
'should not fail if "cwd" is invalid',
() =>
{
const { eslintOptions } = organizeOptions({ cwd: null });
assert.equal(eslintOptions.cwd, null);
},
);
it
(
'should migrate "configFile" to "overrideConfigFile"',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ configFile: 'Config/Path' });
assert.equal(eslintOptions.overrideConfigFile, 'Config/Path');
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'configFile',
newName: 'overrideConfigFile',
formatChanged: false,
},
],
);
},
);
it
(
'should migrate an "envs" array to an "env" object',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ envs: ['foo:true', 'bar:false', 'baz'] });
assert.deepEqual
(eslintOptions.overrideConfig, { env: { foo: true, bar: false, baz: true } });
assert.deepEqual
(
migratedOptions,
[{ oldName: 'envs', newName: 'overrideConfig.env', formatChanged: true }],
);
},
);
it
(
'should migrate "extends"',
() =>
{
const { eslintOptions, migratedOptions } = organizeOptions({ extends: 'foo' });
assert.deepEqual(eslintOptions.overrideConfig, { extends: 'foo' });
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'extends',
newName: 'overrideConfig.extends',
formatChanged: false,
},
],
);
},
);
it
(
'should migrate a "globals" array to an object',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ globals: ['foo:true', 'bar:false', 'baz'] });
assert.deepEqual
(eslintOptions.overrideConfig, { globals: { foo: true, bar: false, baz: false } });
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'globals',
newName: 'overrideConfig.globals',
formatChanged: true,
},
],
);
},
);
it
(
'should migrate "ignorePattern" to "ignorePatterns"',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ ignorePattern: ['foo', 'bar', 'baz'] });
assert.deepEqual
(eslintOptions.overrideConfig, { ignorePatterns: ['foo', 'bar', 'baz'] });
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'ignorePattern',
newName: 'overrideConfig.ignorePatterns',
formatChanged: false,
},
],
);
},
);
it
(
'should migrate "parser"',
() =>
{
const { eslintOptions, migratedOptions } = organizeOptions({ parser: 'foo' });
assert.deepEqual(eslintOptions.overrideConfig, { parser: 'foo' });
assert.deepEqual
(
migratedOptions,
[{ oldName: 'parser', newName: 'overrideConfig.parser', formatChanged: false }],
);
},
);
it
(
'should migrate "parserOptions"',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ parserOptions: 'foo' });
assert.deepEqual(eslintOptions.overrideConfig, { parserOptions: 'foo' });
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'parserOptions',
newName: 'overrideConfig.parserOptions',
formatChanged: false,
},
],
);
},
);
it
(
'should migrate a "plugins" arrays',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ plugins: ['foo', 'bar'] });
assert.deepEqual(eslintOptions.overrideConfig, { plugins: ['foo', 'bar'] });
assert.deepEqual
(
migratedOptions,
[
{
oldName: 'plugins',
newName: 'overrideConfig.plugins',
formatChanged: false,
},
],
);
},
);
it
(
'should not migrate a "plugins" object',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ plugins: { foo: 'bar' } });
assert.deepEqual(eslintOptions.overrideConfig, { });
assert.deepEqual(eslintOptions.plugins, { foo: 'bar' });
assert(isEmptyArray(migratedOptions));
},
);
it
(
'should migrate "rules"',
() =>
{
const { eslintOptions, migratedOptions } = organizeOptions({ rules: 'foo' });
assert.deepEqual(eslintOptions.overrideConfig, { rules: 'foo' });
assert.deepEqual
(
migratedOptions,
[{ oldName: 'rules', newName: 'overrideConfig.rules', formatChanged: false }],
);
},
);
it
(
'should migrate "warnFileIgnored"',
() =>
{
const { migratedOptions, warnIgnored } = organizeOptions({ warnFileIgnored: true });
assert.equal(warnIgnored, true);
assert.deepEqual
(
migratedOptions,
[{ oldName: 'warnFileIgnored', newName: 'warnIgnored', formatChanged: false }],
);
},
);
it
(
'should migrate undefined legacy options',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions
(
{
configFile: undefined,
envs: undefined,
extends: undefined,
globals: undefined,
ignorePattern: undefined,
parser: undefined,
parserOptions: undefined,
rules: undefined,
},
);
assert.deepEqual
(
eslintOptions.overrideConfig,
{
env: undefined,
extends: undefined,
globals: undefined,
ignorePatterns: undefined,
parser: undefined,
parserOptions: undefined,
rules: undefined,
},
);
assert.deepEqual
(
migratedOptions.map(({ oldName }) => oldName),
[
'configFile',
'envs',
'extends',
'globals',
'ignorePattern',
'parser',
'parserOptions',
'rules',
],
);
},
);
it
(
'should migrate legacy options even if the "overrideConfig" target is invalid',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ overrideConfig: false, rules: { foo: 0 } });
assert.equal(eslintOptions.overrideConfig, false);
assert.deepEqual
(
migratedOptions,
[{ oldName: 'rules', newName: 'overrideConfig.rules', formatChanged: false }],
);
},
);
it
(
'should not migrate legacy options with "configType" "flat"',
() =>
{
const expectedOptions =
{
configFile: 1,
envs: 2,
extends: 3,
globals: 4,
ignorePattern: 5,
parser: 6,
parserOptions: 7,
plugins: ['foo', 'bar'],
rules: 8,
warnFileIgnored: true,
};
const { eslintOptions: actualOptions, migratedOptions, warnIgnored } =
organizeOptions({ configType: 'flat', ...expectedOptions });
assert.deepEqual(actualOptions, expectedOptions);
assert.equal(warnIgnored, undefined);
assert(isEmptyArray(migratedOptions));
},
);
describe
(
'should return a custom value for ESLint',
() =>
{
it
(
'with "configType" "eslintrc"',
() =>
{
const expected = { };
const { ESLint: actual } =
organizeOptions({ [ESLINT_KEY]: expected, configType: 'eslintrc' });
assert.equal(actual, expected);
},
);
it
(
'with "configType" "flat"',
() =>
{
assert.throws
(
() => organizeOptions({ [ESLINT_KEY]: null, configType: 'flat' }),
);
{
const expected = { };
const { ESLint: actual } =
organizeOptions({ [ESLINT_KEY]: expected, configType: 'flat' });
assert.equal(actual, expected);
}
},
);
},
);
it
(
'should fail if a forbidden option is specified',
() =>
{
const options =
{
cache: true,
cacheFile: '\0',
cacheLocation: '\0',
cacheStrategy: 'metadata',
errorOnUnmatchedPattern: true,
extensions: [],
globInputPaths: false,
};
assert.throws
(
() => organizeOptions(options),
({ code, message }) =>
code === 'ESLINT_INVALID_OPTIONS' &&
message.includes(Object.keys(options).join(', ')),
);
},
);
it
(
'should fail if "configType" is not a valid value',
() =>
{
assert.throws
(
() => organizeOptions({ configType: 'foo' }),
({ message }) => /\bconfigType\b/.test(message),
);
},
);
it
(
'should fail if "quiet" is not a valid value',
() =>
{
assert.throws
(
() => organizeOptions({ quiet: 'foo' }),
({ message }) => /\bquiet\b/.test(message),
);
},
);
it
(
'should fail if "warnIgnored" is not a valid value',
() =>
{
assert.throws
(
() => organizeOptions({ warnIgnored: 'foo' }),
({ message }) => /\bwarnIgnored\b/.test(message),
);
},
);
it
(
'should fail if "warnFileIgnored" is not a valid value',
() =>
{
assert.throws
(
() => organizeOptions({ warnFileIgnored: 'foo' }),
({ message }) => /\bwarnFileIgnored\b/.test(message),
);
},
);
it
(
'should not fail if "overrideConfig" is invalid',
() =>
{
const { eslintOptions, migratedOptions } =
organizeOptions({ overrideConfig: 'foo' });
assert.equal(eslintOptions.overrideConfig, 'foo');
assert.deepEqual(migratedOptions, []);
},
);
it
(
'should fail if "envs" is not an array or falsy',
() =>
{
assert.throws
(
() => organizeOptions({ envs: 'foo' }),
({ code, message }) =>
code === 'ESLINT_INVALID_OPTIONS' && /\benvs\b/.test(message),
);
},
);
it
(
'should fail if "globals" is not an array or falsy',
() =>
{
assert.throws
(
() => organizeOptions({ globals: { } }),
({ code, message }) =>
code === 'ESLINT_INVALID_OPTIONS' && /\bglobals\b/.test(message),
);
},
);
it
(
'should not modify the properties of a specified "overrideConfig" object',
() =>
{
const overrideConfig = { foo: 'bar' };
const options = { overrideConfig, parser: 'baz' };
organizeOptions(options);
assert.equal(options.overrideConfig, overrideConfig);
assert.deepEqual(overrideConfig, { foo: 'bar' });
},
);
it
(
'should merge "overrideConfig" with eslintrc config',
() =>
{
const overrideConfig = { root: true };
const { eslintOptions } =
organizeOptions({ configType: 'eslintrc', overrideConfig, parser: 'foo' });
assert.deepEqual(eslintOptions.overrideConfig, { parser: 'foo', root: true });
},
);
it
(
'should preserve "overrideConfig" with flat config',
() =>
{
const overrideConfig = { root: true };
const { eslintOptions } =
organizeOptions({ configType: 'flat', overrideConfig, parser: 'foo' });
assert.equal(eslintOptions.overrideConfig, overrideConfig);
},
);
},
);
|
const serializeError = require('serialize-error').serializeError;
const ipc = require('node-ipc');
function _handleError(error) {
this.set('Content-Type', 'application/json; charset=utf-8');
this.statusCode = error.code || error.statusCode || 500;
this.send(serializeError(error));
}
let socketAPI;
ipc.config.id = 'fan_controller';
ipc.config.retry = 1500;
ipc.connectTo(
'fanDriver',
() => {
ipc.of.fanDriver.on(
'connect',
() => console.info('Connected to FAN service')
);
ipc.of.fanDriver.on(
'disconnect',
() => console.info('Disconnected from FAN service')
);
ipc.of.fanDriver.on(
'fan.data',
(data) => {
if (!socketAPI) {
return;
}
socketAPI.emit('fan.data', data);
}
);
ipc.of.fanDriver.on(
'fan.start',
() => {
if (!socketAPI) {
return;
}
socketAPI.emit('fan.start');
}
);
ipc.of.fanDriver.on(
'fan.stop',
(speed) => {
if (!socketAPI) {
return;
}
socketAPI.emit('fan.stop', speed);
}
);
ipc.of.fanDriver.on(
'fan.error',
(error) => {
if (!socketAPI) {
return;
}
socketAPI.emit('fan.error', error);
}
);
}
);
async function sendToIPC(message, data) {
return new Promise((resolve, reject) => {
const errorHandler = (error) => {
ipc.of.fanDriver.off(message, messageHandler);
reject(error);
};
const messageHandler = (message) => {
ipc.of.fanDriver.off('error', errorHandler);
resolve(message);
};
ipc.of.fanDriver.once('error', errorHandler);
ipc.of.fanDriver.once(message, messageHandler);
ipc.of.fanDriver.emit(message, data);
});
}
async function requestPayload(req) {
return new Promise((resolve, reject) => {
let body = [];
req.on('data', chunk => body.push(chunk.toString()));
req.on('end', () => resolve(JSON.parse(body.join(''))));
req.on('error', error => reject(error));
})
}
module.exports = {
setSocket(socket) {
socketAPI = socket;
},
routes: {
get: {
speed: async (req, res) => {
try {
const speed = await sendToIPC('getSpeed');
res.json({ speed });
} catch (error) {
_handleError.bind(res)(error);
}
},
mode: async (req, res) => {
try {
const manual = await sendToIPC('getManualMode');
res.json({ manual });
} catch (error) {
_handleError.bind(res)(error);
}
}
},
post: {
speed: async (req, res) => {
try {
const payload = await requestPayload(req);
await sendToIPC('setSpeed', payload.speed);
res.json({ message: 'done' });
} catch (error) {
_handleError.bind(res)(error);
}
},
mode: async (req, res) => {
try {
const payload = await requestPayload(req);
await sendToIPC('setManualMode', payload.manual);
res.json({ message: 'done' });
} catch (error) {
_handleError.bind(res)(error);
}
}
}
}
}
|
import React, { Fragment } from "react";
import { API_ROOT, axiosWithCache } from "../../app/app-helpers";
import ReactGA from "react-ga";
export default class DownloadCatalogFilterTleButton extends React.Component {
state = {
isLoading: false,
errorMessage: "",
textFile: null,
};
linkRef = React.createRef();
fetchData = async () => {
this.setState({ errorMessage: "" });
this.setState({ isLoading: true });
try {
const result = await axiosWithCache(
`${API_ROOT}/tle/trusat_${this.props.catalogFilter}.txt`
);
// If replacing a previously generated file, revoke the object URL to avoid memory leaks.
if (this.state.textFile !== null) {
window.URL.revokeObjectURL(this.state.textFile);
}
this.setState({ textFile: result.data });
const href = window.URL.createObjectURL(
new Blob([this.state.textFile], {
type: "text/csv",
})
);
this.linkRef.current.download = `trusat_${this.props.catalogFilter}.txt`;
this.linkRef.current.href = href;
this.linkRef.current.click();
this.linkRef.current.href = "";
} catch (error) {
console.log(error);
this.setState({ errorMessage: error.response.data });
}
this.setState({ isLoading: false });
};
render() {
return this.props.tleCount === 0 ? null : (
<Fragment>
<span
className="catalog__button catalog__get-data-button"
onClick={() => {
ReactGA.event({
category: "TLE usage",
action: `Clicked download predictions button`,
label: `Download TLEs from ${this.props.catalogFilter}`,
});
this.fetchData();
}}
>
{this.state.isLoading
? "...Loading"
: `Download ${
this.props.catalogFilter.charAt(0).toUpperCase() +
this.props.catalogFilter.slice(1)
} TLEs`}
</span>
{this.state.errorMessage ? (
<p>Something went wrong... {this.state.errorMessage}</p>
) : null}
<a className="app__hide" href="/#" ref={this.linkRef}>
download
</a>
</Fragment>
);
}
}
|
define(function (require) {
var util = require('lib/util.js');
describe('an property', function () {
it('can be initialised with a value', function () {
var prop = util.property('initial value');
expect(prop()).to.equal('initial value');
});
it('accepts a function value', function () {
var prop = util.property(function () { return 'dynamic value'; });
expect(prop()).to.equal('dynamic value');
});
describe('setting a new value', function () {
it('updates the value', function () {
var prop = util.property('old value');
prop('new value');
expect(prop()).to.equal('new value');
});
it('returns the object that contains the property so it can be chained', function () {
var obj = {
prop: util.property()
};
expect(obj.prop('something new')).to.equal(obj);
});
});
describe('with a default value', function () {
it('is not default if truthy', function () {
var prop = util.property().withDefault('default');
prop('not default');
expect(prop()).to.equal('not default');
});
it('is default if false', function () {
var prop = util.property().withDefault('default for `false`');
prop(false);
expect(prop()).to.equal('default for `false`');
});
it('is default if null', function () {
var prop = util.property().withDefault('default for `null`');
prop(null);
expect(prop()).to.equal('default for `null`');
});
it('is default if undefined', function () {
var prop = util.property().withDefault('default for `undefined`');
prop(undefined);
expect(prop()).to.equal('default for `undefined`');
});
it('still returns the object when setting', function () {
var obj = {
prop: util.property().withDefault('whatever')
};
expect(obj.prop('something else')).to.equal(obj);
});
});
});
});
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsFence = {
name: 'fence',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 12v-2h-2V7l-3-3-2 2-2-2-2 2-2-2-3 3v3H3v2h2v2H3v2h2v4h14v-4h2v-2h-2v-2h2zm-5-5.17l1 1V10h-2V7.83l.41-.41.59-.59zm-4 0l.59.59.41.41V10h-2V7.83l.41-.41.59-.59zM11 14v-2h2v2h-2zm2 2v2h-2v-2h2zM7 7.83l1-1 .59.59.41.41V10H7V7.83zM7 12h2v2H7v-2zm0 4h2v2H7v-2zm10 2h-2v-2h2v2zm0-4h-2v-2h2v2z"/></svg>`
};
|
import Icon from "./iconLibrary/icon";
function App() {
return (
<div className="App">
<h1>Custom Icon Library</h1>
<Icon icon="TWITTER" color="black" size="40" />
<Icon icon="FACEBOOK" color="black" size="40" />
<Icon icon="LINKEDIN" color="black" size="40" />
<Icon icon="GITHUB" color="black" size="40" />
<Icon icon="VSCODE" color="black" size="40" />
</div>
);
}
export default App;
|
const fs = require('fs')
require('dotenv-safe').config()
const moment = require('moment')
const { WebClient } = require('@slack/web-api')
console.log('Getting started with Node Slack SDK')
// Create a new instance of the WebClient class with the token read from your environment variable
const web = new WebClient(process.env.SLACK_API_TOKEN)
// The current date
const currentTime = new Date().toTimeString()
async function saveAsCSV(filename, data) {
const file = fs.createWriteStream(filename)
file.write(
'author_handle, author_name, created_at, text, timestamp, tweet_source\n'
)
data.forEach(line => {
file.write(
`"${line.author_handle}", "${line.author_name}", "${line.created_at}", "${
line.text
}", "${line.timestamp}", "${line.tweet_source}"\n`
)
})
file.close()
}
;(async () => {
// Use the `auth.test` method to find information about the installing user
const res = await web.auth.test()
// Find your user id to know where to send messages to
const userId = res.user_id
const history = await web.channels.history({
channel: process.env.SLACK_CHANNEL,
})
// // Use the `chat.postMessage` method to send a message from this app
// await web.chat.postMessage({
// channel: userId,
// text: `The current time is ${currentTime}`,
// })
console.log(history.messages.length)
const botHistory = history.messages.filter(historyItem => {
return historyItem.hasOwnProperty('bot_id')
})
const botMessages = botHistory.map(historyItem => {
return historyItem.attachments[0]
})
const cleanedMessages = botMessages.map(message => {
try {
return {
author_handle: message.author_subname,
author_name: message.author_name,
created_at: moment(message.ts, 'X').toISOString(),
text: message.text.replace(/\r?\n|\r/g, ''),
timestamp: message.ts,
tweet_source: message.footer,
}
} catch (error) {
console.error(message)
}
})
console.dir(cleanedMessages)
console.log(cleanedMessages.length)
await saveAsCSV('output.csv', cleanedMessages)
})()
|
const initState = {}
const httpHistoryReducer = (state = initState, action) => {
switch (action.type) {
case 'RENDER_HISTORY_DATA':
console.log('this is added data', action.payload)
return action.payload
default:
return state;
}
};
export default httpHistoryReducer;
|
const myModule = require('./script');
const myModuleInstans = new myModule();
myModuleInstans.hello();
myModuleInstans.goodbye();
|
var assert = require('assert');
var fs = require('fs');
var PDFReader = require('../index');
function getTestFileBytes() {
return new Uint8Array(fs.readFileSync('./pdfs/50PAGE.pdf'));
}
describe('PDFReader', function () {
var pdfReader = new PDFReader(getTestFileBytes());
describe('#open()', function () {
it('should open without error', function (done) {
pdfReader.open().then(function (doc) {
done();
}).catch(function (err) {
done(err);
});
});
});
describe('#getPageCount', function () {
it('test file should have 51 pages', function (done) {
pdfReader.getPageCount().then(function (pageCount) {
if (pageCount !== 51) {
done(new Error('Page count is not 51'));
} else {
done();
}
}).catch(function (err) {
done(err);
});
});
});
describe('#getPageImage PNG', function () {
it('test file should export page 1 as PNG', function (done) {
pdfReader.getPageImage(1, {
format: 'png'
}).then(function (result) {
if ((result.constructor === Buffer || result.constructor === Uint8Array) && result.length) {
done();
} else {
done(new Error('Expected Uint8Array'));
}
}).catch(function (err) {
done(err);
});
});
});
describe('#getPageImage JPG', function () {
it('test file should export page 1 as JPG', function (done) {
pdfReader.getPageImage(1, {
format: 'jpg'
}).then(function (result) {
if ((result.constructor === Buffer || result.constructor === Uint8Array) && result.length) {
done();
} else {
done(new Error('Expected Uint8Array'));
}
}).catch(function (err) {
done(err);
});
});
});
});
|
function getHammingDistance(str1, str2){
var diff=0;
if(str1.length != str2.length){
console.log("Error! Strings are not equal");
} else {
for (var i=0; i<str1.length; i++){
if (str1.charAt(i) != str2.charAt(i)) diff++;
}
}
return diff;
}
function countSubstrPattern(strOriginal, strPattern){
var total=0;
var count=0;
for (var i=0; i<strOriginal.length; i++){ //Loop traversng each possible starting point of comparison on the original string.
for (var j=0; j<strPattern.length && i<=strOriginal.length - strPattern.length; j++){ //Loop just cycling on the pattern for comparison.
if (strPattern.charAt(j) == strOriginal.charAt(i+j)) count++; //If the a right letter on the pattern can be seen on the original on the right order, increment count.
}
if (count == strPattern.length) total++; //If count matches the length of the pattern, it means that the whole pattern matched; increases the total var.
count=0; //Resets the count to 0 for a comparison on a different starting point on the original string.
}
return total;
}
function isValidString(str, alphabet){
var test=0;
for (var i=0; i<str.length; i++){
if(alphabet.indexOf(str.charAt(i)) < 0) return false; //indexOf() returns -1 if its argument isn't found in the target array.
}
return true;
}
function getSkew(str, n){
var g=0;
var c=0;
for (var i=0; i<n; i++){
if(str.charAt(i) == "G") g++;
else if (str.charAt(i) == "C") c++;
}
return g-c;
}
function getMaxSkewN(str, n){
var skew = [];
for (var i=0; i<n; i++){
skew.push(getSkew(str,i+1)); //Push into the array all of the Skews of the given string until position n.
}
skew.sort(function(a, b){return b-a}); //Sort the array descendingly
return skew[0]; //Return the max value
}
function getMinSkewN(str, n){
var skew = [];
for (var i=0; i<n; i++){
skew.push(getSkew(str,i+1)); //Push into the array all of the Skews of the given string until position n.
}
skew.sort(function(a, b){return a-b}); //Sort the array ascendingly
return skew[0]; //Return the min value
}
function result(res){
console.log(res);
}
|
import React, { Component } from "react";
export default class App extends Component {
state = {
name: [],
};
componentDidMount() {
fetch("http://localhost:9000/students")
.then((response) => response.json())
.then((data) => {
// console.log("data students", data);
this.setState({
name: data,
});
});
}
render() {
console.log(this.state.name)
return (
<div>
{this.state.name.map((elem, index) => {
return <h1 key={index}>{elem.name}</h1>;
})}
</div>
);
}
}
|
import React from 'react'
import { Row } from 'react-bootstrap'
import PropTypes from 'prop-types'
const Section = (props) => {
return (
<Row className="justify-content-md-center top-spacer">
<h2 id={props.title.toLowerCase()} className='text-center'>{props.title}</h2>
<hr />
{ props.children }
</Row>
)
}
Section.propTypes = {
title: PropTypes.string.isRequired,
}
export default Section
|
var dispatcher = require('../dispatcher');
module.exports = {
testAction: function() {
dispatcher.dispatch({
title: 'hey',
type: 'testaction'
})
};
};
|
import React from 'react'
const NavBar = (props) => {
return (
<header className="App-header">
<a href="/">
<img
href="/"
src='https://api.nasa.gov/assets/img/favicons/favicon-192.png'
style={{ width: "100px", height: "100px" }}
className="App-logo"
alt="logo"
/>
</a>
{props.navItems.map((navItem, idx) =>
<a className="nav-a" key={idx} href={navItem.url}>{navItem.name}</a>
)}
<a href="https://github.com/DavidCibin/nasa-pics-and-mars-rover">
<img
src='https://i.ibb.co/BgGmrgg/Git-Hub-Mark-Light-64px.png'
style={{ width: "50px", height: "50px" }}
className="git-logo"
alt="logo"
/>
</a>
</header>
)
}
export default NavBar
|
const router = require('express').Router()
const Artist = require('../models').Artist
const Album = require('../models').Album
// list all artists
router.get('/', function (req, res) {
Artist
.findAll({attributes: ['id', 'name', 'genre']})
.then(function (artists) {
res.json(artists)
})
.catch(function (error) {
console.warn(error)
res.status(500).send('list all artists failed')
})
})
// show artist
router.get('/:id', function (req, res) {
Artist
.findById(req.params.id, {
attributes: ['id', 'name', 'genre'],
include: [{
model: Album,
attributes: ['id', 'title', 'year']
}]
})
.then(function (artist) {
res.json(artist)
})
.catch(function (error) {
console.warn(error)
res.status(500).send('show artist failed')
})
})
// create artist
router.post('/', function (req, res) {
Artist
.create(req.body)
.then(function (artist) {
res.location(req.baseUrl + '/' + artist.get('id'))
res.status(201).json(artist)
})
.catch(function (error) {
console.warn(error)
res.status(500).send('create artist failed')
})
})
// update artist
router.put('/:id', function (req, res) {
Artist
.findById(req.params.id)
.then(function (artist) {return artist.updateAttributes(req.body)})
.then(function (artist) {
res.status(201).json(artist)
})
.catch(function (error) {
console.warn(error)
res.status(500).send('update artist failed')
})
})
// delete artist
router.delete('/:id', function (req, res) {
Artist
.findById(req.params.id)
.then(function (artist) {return artist.destroy()})
.then(function () {
res.sendStatus(204)
})
.catch(function (error) {
console.warn(error)
res.status(500).send('delete artist failed')
})
})
module.exports = router
|
$(document).ready(function () {
function disableButton() {
$("#btnSubmit").prop('disabled', true);
}
function enableButton() {
$("#btnSubmit").prop('disabled', false);
}
$('#btnSubmit').click(function (e) {
e.preventDefault();
var isfoto = validate_foto();
var valid = $("#form-pinj-agri").validationEngine('validate');
if (valid == true && isfoto == true) {
alertify.confirm('Konfirmasi', 'Anda akan mengajukan pinjaman Agri. Lanjutkan? ',
function () {
set_ajax();
},
function () {
$('#modalPayment').modal('hide');
});
return false;
}
});
});
function validate_foto() {
var files = $("#cf_file").val();
var files1 = $("#progress_report_file").val();
var files2 = $("#hasil_panen_file1").val();
var files3 = $("#hasil_panen_file2").val();
var files4 = $("#hasil_panen_file3").val();
if (files == '') {
alert("Upload Contract File Anda!");
return false;
} else {
return true;
}
if (files1 == '') {
alert("Upload Progress Report Anda!");
return false;
} else {
return true;
}
if (files2 == '') {
alert("Upload Foto Hasil Panen Anda!");
return false;
} else {
return true;
}
if (files3 == '') {
alert("Upload Foto Hasil Panen 2 Anda!");
return false;
} else {
return true;
}
if (files4 == '') {
alert("Upload Foto Hasil Panen 3 Anda!");
return false;
} else {
return true;
}
}
function set_ajax() {
var a = new FormData(); // using additional FormData object
var b = []; // using an array
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
var data = new FormData(form);
var formValues = data.entries()
while (!(ent = formValues.next()).done) {
// Note the change here
//console.log(`${ent.value[0]}[]`, ent.value[1])
}
// Ajax Here
}
var send_data = new FormData(form); //create a FormData object
var firstform = jQuery(document.forms['form_name1']).serializeArray();
for (var i = 0; i < firstform.length; i++) {
send_data.append(firstform[i].name, firstform[i].value);
}
$.ajax({
type: "POST",
url: BASEURL + "submit-pinjaman-agri",
data: send_data,
processData: false,
contentType: false,
beforeSend: function () {
$('.next').prop('disabled', true);
},
success: function (html_data) {
/*alert(html_data);$('.next').prop('disabled', false);return false;*/
objdata = JSON.parse(html_data);
if (objdata.error == '1') {
$('.next').prop('disabled', false);
alertify.alert('Error Message!', objdata.message);
return false;
} else {
window.location.replace(BASEURL + 'dashboard');
return false;
}
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
|
'use strict'
const Manager = use('App/Models/Manager')
class ManagerController {
async index ({ view }) {
const managers = await Manager.all();
return view.render('managers', {managers: managers.toJSON()});
}
async create ({ request, response }) {
const manager = await Manager.create(request.only(['name']));
return response.redirect('back');
}
async edit ({ params, request, response, view }) {
const manager = await Manager.find(params.id);
// return view.render('edit', {job: job});
return view.render('managers_edit', {manager: manager.toJSON()});
}
async update ({ params, request, response }) {
const manager = await Manager.find(params.id)
manager.name = request.all().name;
await manager.save();
return response.redirect('/managers');
}
async delete ({ params, request, response }) {
const manager = await Manager.find(params.id)
await manager.delete();
return response.redirect('/managers');
}
}
module.exports = ManagerController
|
import React from 'react';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import './Navbar.css';
export default function Navbar() {
const dispatch = useDispatch();
const history = useHistory();
const handleLogout = () => {
dispatch({type: `LOGOUT`});
dispatch({type: `CLEAR_ALL`});
history.push(`/login`);
}
return(
<>
<div className="whitespace"></div>
<div className="navbar-container">
<div className="navbar-tab navbar-entries">
<button className="navbar-btn" onClick={()=>{history.push('/home')}}>Entries</button>
</div>
<div className="navbar-tab navbar-new">
<button className="navbar-btn" onClick={()=>{history.push('/new-entry')}}>New Entry</button>
</div>
<div className="navbar-tab navbar-settings">
<button className="navbar-btn" onClick={()=>{history.push('/settings')}}>Settings</button>
</div>
<div className="navbar-tab navbar-logout">
<button className="navbar-btn" onClick={handleLogout}>Logout</button>
</div>
</div>
</>
);
}
|
import React, {
Component,
} from 'react';
import PropTypes from 'prop-types';
import {
Animated,
PanResponder,
Platform,
StyleSheet,
TouchableOpacity,
ViewPropTypes,
View,
Text
} from 'react-native';
export default class SwipeRow extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this._panResponder = PanResponder.create({
onMoveShouldSetPanResponderCapture: this._handleMoveShouldSetPanResponderCapture.bind(this),
onPanResponderGrant: this._handlePanResponderGrant.bind(this),
onPanResponderMove: this._handlePanResponderMove.bind(this),
onPanResponderRelease: this._handlePanResponderEnd.bind(this),
onPanResponderTerminate: this._handlePanResponderEnd.bind(this),
onShouldBlockNativeResponder: (event, gestureState) => false,//表示是否用 Native 平台的事件处理,默认是禁用的,全部使用 JS 中的事件处理,注意此函数目前只能在 Android 平台上使用
});
//上一次滑动最后的left偏移量
this._previousLeft = 0;
//left偏移动画
this.state = {
currentLeft: new Animated.Value(this._previousLeft),
rightWidth: this.props.children[0].props.style.width ? this.props.children[0].props.style.width : 100,
swipeIndex:''
};
this._isOpen = false;
}
render() {
return (
<View style={[styles.swipeContainer, this.props.style]}>
<View style={styles.swipeActions}>
{this.props.children[0]}
</View>
{this.renderRowContent()}
</View>
);
}
renderRowContent() {
return (
<Animated.View
{...this._panResponder.panHandlers}
style={{
transform: [
{ translateX: this.props.index===this.state.swipeIndex?this.state.currentLeft:0 }
]
}}
>
{this.props.children[1]}
</Animated.View>
);
}
/**
* 是否需要成为move事件响应者,返回true直接走onPanResponderMove
* @param event
* @param gestureState
* @returns {boolean}
* @private
*/
_handleMoveShouldSetPanResponderCapture(event: Object, gestureState: Object, ): boolean {
//当垂直滑动的距离<10 水平滑动的距离>10的时候才让捕获事件
// console.log('_handleMoveShouldSetPanResponderCapture',this.props.index);
this.setState({swipeIndex:this.props.index})
return Math.abs(gestureState.dy) < 10 && Math.abs(gestureState.dx) > 10;
}
/**
* 表示申请成功,组件成为了事件处理响应者
* @param event
* @param gestureState
* @private
*/
_handlePanResponderGrant(event: Object, gestureState: Object): void {
// console.log('_handlePanResponderGrant');
}
/**
* 处理滑动事件
* @param event
* @param gestureState
* @private
*/
_handlePanResponderMove(event: Object, gestureState: Object): void {
if (this._previousLeft === null) {
this._previousLeft = this.state.currentLeft._value
}
let nowLeft = this._previousLeft + gestureState.dx * 1;
//右滑最大距离为0(边界值)
nowLeft = Math.min(nowLeft, 0);
this.state.currentLeft.setValue(
nowLeft,
);
}
/**
* 结束事件的时候回调
* @param event
* @param gestureState
* @private
*/
_handlePanResponderEnd(event: Object, gestureState: Object): void {
if (this._isOpen) {
if (Math.abs(this.state.currentLeft._value) >= this.state.rightWidth) {
this._animateToOpenPosition();
} else {
this._animateToClosedPosition();
}
} else {
if (Math.abs(this.state.currentLeft._value) >= this.state.rightWidth / 3) {
this._animateToOpenPosition();
} else {
this._animateToClosedPosition();
}
}
this._previousLeft = null;
}
_shouldAnimateRemainder(gestureState: Object): boolean {
/**
* If user has swiped past a certain distance, animate the rest of the way
* if they let go
*/
return (
Math.abs(gestureState.dx) > this.state.rightWidth / 3 ||
gestureState.vx > 0.3
);
}
_animateToOpenPosition(): void {
this._isOpen = true;
this._animateTo(-this.state.rightWidth);
}
_animateToClosedPosition(duration: number = this.state.rightWidth * 3): void {
this._isOpen = false;
this._animateTo(0, duration);
}
_animateTo(toValue, duration = this.state.rightWidth * 3, callback): void {
Animated.spring(
this.state.currentLeft,
{
toValue,
}
).start((value) => {
});
}
}
const styles = StyleSheet.create({
swipeContainer: {
width: '100%',
},
swipeActions: {
// backgroundColor: 'white',
width: '100%',
overflow: 'hidden',
...StyleSheet.absoluteFillObject,
flexDirection: 'row',
justifyContent: 'flex-end'
},
});
|
let memGrid;
const topPad = 50
function setup() {
let canvasParent = document.getElementById("canvascontainer")
let canvas = createCanvas(canvasParent.clientWidth, canvasParent.clientHeight);
canvas.parent(canvasParent);
/*
console.log("width:" + canvasParent.clientWidth)
console.log("height:" + canvasParent.clientHeight)
*/
background(0);
frameRate(10);
memGrid = new Grid(width / 2 - 110 * 2,
height / 2 - 110 * 2 + topPad,
100, 100, 10, 4, 4,
color(0, 120, 255));
}
function draw() {
background(0, 155, 255);
memGrid.show();
}
function mousePressed(event) {
if (event.type == "mousedown") {
col = Math.floor((event.x - memGrid.x) / (memGrid.width + memGrid.pad));
row = Math.floor((event.y - memGrid.y) / (memGrid.height + memGrid.pad));
if (!(col < 0 || row < 0) && !(col >= memGrid.cols || row >= memGrid.rows)) {
memGrid.grid[row][col] = true;
}
}
}
class Grid {
constructor(x, y, width, height, pad, rows, cols, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.pad = pad;
this.rows = rows;
this.cols = cols;
this.color = color;
this.grid = [];
for (let i = 0; i < this.rows; i++) {
let tmp = [];
for (let j = 0; j < this.cols; j++) {
tmp.push(false);
}
this.grid.push(tmp)
}
}
show() {
noStroke();
fill(this.color);
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
if (this.grid[i][j]) {
fill(255);
} else {
fill(this.color)
}
rect(this.x + (this.width + this.pad) * j,
this.y + (this.height + this.pad) * i,
this.width, this.height, 10)
}
}
}
}
|
// var moment = require('moment');
// moment().format();
|
import React from 'react'
import styled from 'styled-components'
const StyledDiv = styled.div`
display: flex;
width: 100%;
`
const StyledCard = styled.div`
background: WHITESMOKE;
border-radius: 2px;
height: 125px;
margin: 1rem;
width: 20%;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
&:hover {
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}
h2 {
text-align: center;
color: black;
transition: all 0.5s ease-in-out;
&:hover {
color: darkblue;
transition: all 0.5s ease-in-out;
}
}
`
const Cards = ({ onLocations }) => {
console.log('data', onLocations)
return (
<StyledDiv>
{onLocations.map((loc) => (
<StyledCard className="card">
<h2>{loc.locname}</h2>
</StyledCard>
))}
</StyledDiv>
)
}
export default Cards
|
// 定义一些状态
export default {
}
|
import React, { Component } from 'react';
import * as QR from 'qrcode-generator';
class QRCodeImg extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
if (!this.props.NanoAddress) {
return null;
}
let typeNumber = 4;
let errorCorrectionLevel = 'L';
let qr = QR(typeNumber, errorCorrectionLevel);
qr.addData(this.props.NanoAddress);
qr.make();
return (
<img src={qr.createDataURL(4)} alt="QR Code"/>
);
}
}
export default QRCodeImg;
|
var express = require("express");
var bodyParser = require("body-parser");
var expressHbs = require('express-handlebars');
var parser = bodyParser.urlencoded({extended:false});
var app = express();
app.use(express.static("public"));
app.engine('.hbs', expressHbs({defaultViews: 'home_views', extname: '.hbs'}));
app.set('view engine', '.hbs');
//app.set("view engine","ejs");
//app.set("views","./views");
app.listen(3000);
var Mang = ["HTML5 & CSS3","NodeJS","ReactJS","Java-Spring"];
app.post("/getNode",function(req,res){
res.send(Mang)
});
app.get("/",function(request,response){
response.render("home_views");
});
app.post("/add",parser,function(req,res){
var newNote = req.body.note;
Mang.push(newNote);
res.send(Mang);
})
app.post("/delete",parser,function(req,res){
var id = req.body.idXoa;
Mang.splice(id,1);
res.send(Mang);
})
app.post("/update",parser,function(req,res){
var id = req.body.idSua;
Mang[id] = req.body.textSua;
res.send(Mang);
})
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setDefaultCompany } from 'ducks/DefaultCompany';
import kroLogo from 'images/powered-by-kro.png';
import asOneLogo from 'images/working-as-one.png';
import Box from 'components/Box';
import Button from 'components/Button';
import './style.css';
class CompanySelect extends Component {
constructor(props) {
super(props);
this.buttonClicked = this.buttonClicked.bind(this);
this.state = {
selected: null
};
}
buttonClicked() {
if (this.state.selected) this.props.selectCompany(this.state.selected);
}
companySelected(company_id) {
return () => {
this.setState({ selected: company_id });
};
}
listCompanies() {
return this.props.companies.map(company => {
let province = this.props.provinces.find(
({ id }) => id === company.province
);
return (
<li
key={company.id}
onClick={this.companySelected(company.id)}
className={this.state.selected === company.id ? 'selected' : ''}
>
<div className="company-name">{company.name}</div>
<div className="company-location">
{company.city}, {province ? province.name : ''}
</div>
</li>
);
});
}
render() {
return (
<div className="company-select">
<img className="kro-logo" src={kroLogo} alt="Powered by KRO" />
<img className="as-one-logo" src={asOneLogo} alt="Working as One" />
<Box className="the-form">
<div className="prompt text-center">
Please select a default company:
</div>
<ul>{this.listCompanies()}</ul>
<Button click={this.buttonClicked}>Select</Button>
</Box>
</div>
);
}
}
const mapStateToProps = state => ({
companies: state.companies.items,
provinces: state.provinces.items
});
const mapDispatchToProps = dispatch => ({
selectCompany: company_id => {
dispatch(setDefaultCompany(company_id));
}
});
export default connect(mapStateToProps, mapDispatchToProps)(CompanySelect);
|
/*
*
* TaskForm constants
*
*/
export const CHANGE_SUBJECT = 'app/TaskForm/CHANGE_SUBJECT';
export const CHANGE_STARTTIME = 'app/TaskForm/CHANGE_STARTTIME';
export const CHANGE_ENDTIME = 'app/TaskForm/CHANGE_ENDTIME';
export const CHANGE_NEWCOWORKER = 'app/TaskForm/CHANGE_NEWCOWORKER';
export const CHANGE_COWORKERS = 'app/TaskForm/CHANGE_COWORKERS';
export const CHANGE_CONTENT = 'app/TaskForm/CHANGE_CONTENT';
export const CREATE_TASK = 'app/TaskForm/CREATE_TASK';
export const UPDATE_TASK = 'app/TaskForm/UPDATE_TASK';
export const ADD_COWORKER = 'app/TaskForm/ADD_COWORKER';
export const COWORKER_ADDED = 'app/TaskForm/COWORKER_ADDED';
export const LOAD_AVAILABLE_COWORKERS = 'app/TaskForm/LOAD_AVAILABLE_COWORKERS';
export const AVAILABLE_COWORKERS_LOADED = 'app/TaskForm/AVAILABLE_COWORKERS_LOADED';
export const FILL_TASKINFO = 'app/TaskForm/FILL_TASKINFO';
export const INIT_CREATFORM = 'app/TaskForm/INIT_CREATFORM';
|
var app= require('express').Router();
var fb= require('./fbconfig');
var utils= require('./utils');
var personaldetailsobj= {
getall:(req,res)=>{
fb.ref('/personaldetails').once('value',success=>{
let personaldetails = utils.fbtoarr(success.val());
return res.send(personaldetails);
})
},
add:(req,res)=> {
let p= req.body;
fb.ref('personaldetails'). push(p).then(success=> {
return res.send(success);
})
}
};
module.exports= personaldetailsobj;
|
import React from 'react';
import {createStackNavigator} from 'react-navigation-stack';
import ReportDetails from '../screens/StudentScreens/ReportDetails';
import MyReportsScreen from '../screens/StudentScreens/MyReportsScreen';
export const AppStackNavigator = createStackNavigator({
ReportsList : {
screen : MyReportsScreen,
navigationOptions:{
headerShown : false
}
},
HomeworkDetails : {
screen : ReportDetails,
navigationOptions:{
headerShown : false
}
}
},
{
initialRouteName: 'ReportsList'
}
);
|
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
import { connect } from 'react-redux'
import BackButton from '../Components/BackButton'
class LaunchDetails extends React.Component{
static navigationOptions = {
header: null
}
render(){
const { missionName, launchYear, rocket, telemetry, launchSite, launchSuccess, details } = this.props.launch
return (
<View>
<BackButton navigation={this.props.navigation}/>
<Text>{missionName}</Text>
<Text>{launchYear}</Text>
<Text>{details? details : 'No further details'}</Text>
<Text>{rocket.rocket_name}</Text>
</View>
)
}
}
const mapStateToProps = ({ launches }, ownProps) => {
const flightNum = ownProps.navigation.getParam('flightNum')
return {
launch: launches.find(launch => launch.flight_number === flightNum)
}
}
export default connect(mapStateToProps, null)(LaunchDetails)
|
const path = require('path')
describe('wdio-image-comparison-service check methods folder options', () => {
const baselineFolder = browser.config.services.includes('sauce')
? 'tests/sauceLabsBaseline'
: 'localBaseline'
beforeEach(async () => {
await browser.url('')
await browser.pause(500)
})
// Chrome remembers the last postion when the url is loaded again, this will reset it.
afterEach(async () => await browser.execute('window.scrollTo(0, 0);', []))
describe('checkFullPageScreen method with folder options', () => {
it('should set all folders using method options', async () => {
const testOptions = {
actualFolder: path.join(process.cwd(), './.tmp/checkActual'),
baselineFolder: path.join(
process.cwd(),
`./${baselineFolder}/checkBaseline`
),
diffFolder: path.join(process.cwd(), './.tmp/testDiff'),
returnAllCompareData: true,
}
const results = await browser.checkFullPageScreen(
'fullPageCheckFolders',
testOptions
)
expect(results.folders.actual).toMatch(
testOptions.actualFolder.replace('./', '')
)
expect(results.folders.baseline).toMatch(
testOptions.baselineFolder.replace('./', '')
)
// expect(results.folders.diff).toMatch(testOptions.diffFolder.replace('./', ''));
})
})
describe('checkScreen method with folder options', () => {
it('should set all folders using checkScreen method options', async () => {
const testOptions = {
actualFolder: path.join(process.cwd(), './.tmp/checkActual'),
baselineFolder: path.join(
process.cwd(),
`./${baselineFolder}/checkBaseline`
),
diffFolder: path.join(process.cwd(), './.tmp/testDiff'),
returnAllCompareData: true,
}
const results = await browser.checkScreen(
'screenCheckFolders',
testOptions
)
expect(results.folders.actual).toMatch(
testOptions.actualFolder.replace('./', '')
)
expect(results.folders.baseline).toMatch(
testOptions.baselineFolder.replace('./', '')
)
// expect(results.folders.diff).toMatch(testOptions.diffFolder.replace('./', ''));
})
})
describe('checkElement method with folder options', () => {
it('should set all folders using checkElement method options', async () => {
const testOptions = {
actualFolder: path.join(process.cwd(), './.tmp/checkActual'),
baselineFolder: path.join(
process.cwd(),
`./${baselineFolder}/checkBaseline`
),
diffFolder: path.join(process.cwd(), './.tmp/testDiff'),
returnAllCompareData: true,
}
const results = await browser.checkElement(
await $('.uk-button:nth-child(1)'),
'elementCheckFolders',
testOptions
)
expect(results.folders.actual).toMatch(
testOptions.actualFolder.replace('./', '')
)
expect(results.folders.baseline).toMatch(
testOptions.baselineFolder.replace('./', '')
)
//expect(results.folders.diff).toMatch(testOptions.diffFolder.replace('./', ''));
})
})
})
|
// Write a function, given 2 positive intergers, find out if the two numbers have the same frequency of digits
// function must have complexities:
// Time O(N)
function sameFrequency(num1, num2) {
// DO stuff
// convert intergers to strings
num1 = num1.toString();
num2 = num2.toString();
// if number lengths arent the same return false
if (num1.length != num2.length) {
return false;
}
// Create object for num 1 freq
let freq = {};
// loop through num1 to populate freq object
for (let num in num1) {
let number = num1[num];
if (freq[number]) {
freq[number]++;
} else {
freq[number] = 1;
}
}
// loop through number 2 to find if keys match nums
for (let num in num2) {
let number = num2[num];
if (!freq[number]) {
return false;
} else {
freq[number] -= 1;
}
}
return true;
}
console.log(sameFrequency(182, 281)); //true
console.log(sameFrequency(34, 14)); //false
console.log(sameFrequency(3589578, 5879385)); //true
console.log(sameFrequency(22, 222)); //true
|
const express = require('express');
const uuid = require('uuid');
const fs = require('fs');
const app = express();
const {getElementById,createElement,updateElement,deleteElement} = require('./controller/controller');
let data = require('./data.json');
app.use(express.urlencoded({extended:true}));
app.use(express.json())
// get all data
app.get('/product',(req,res) =>{
res.send(data);
});
// get element by ID
app.get('/product/:Id',(req,res) =>{
getElementById(req,res);
});
// post (create elemant in data)
app.post('/product', (req, res) => {
createElement(req,res);
})
// updated product
app.put('/product/:Id', (req,res,next) =>{
updateElement(req,res);
})
// deleted products
app.delete('/product/:Id', (req,res) =>{
deleteElement(req,res);
})
app.listen(8080, () =>{console.log('Server is running ...')})
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import urls from 'textCleanup/constants/urls';
import AssessmentApp from 'textCleanup/containers/AssessmentApp';
import FieldSelection from 'textCleanup/containers/FieldSelection';
import Items from 'textCleanup/containers/Items/App';
export default (
<Route path={urls.assessment.url} >
<IndexRoute component={AssessmentApp} />
<Route path={urls.fields.url} component={FieldSelection} />
<Route path={urls.endpoints.url} component={Items} />
</Route>
);
|
Ext.define('CustomApp', {
extend: 'Rally.app.App',
requires:['Rally.ui.renderer.template.FormattedIDTemplate','Rally.ui.grid.plugin.PercentDonePopoverPlugin'],
componentCls: 'app',
title: 'BPO Portfolio View',
launch: function() {
this.add({
xtype: 'rallyownerfilter',
itemId: 'ownerComboBox',
stateful: true,
stateId: this.getContext().getScopedStateId('ownercombobox'),
model: 'PortfolioItem/Initiative',
listeners: {
select: this._onLoad,
ready: this._onLoad,
scope: this
}
});
},
_onLoad: function(){
// Radian
// var project_oid = '/project/37192747640';
var initiativestore = Ext.create('Rally.data.WsapiDataStore', {
model: 'PortfolioItem/Initiative',
// context: {
// project: project_oid,
// projectScopeDown: true,
// projectScopeUp: false
// },
pageSize: 200,
limit: 10000,
autoLoad: true,
storeId: 'initiativestore',
filters: [this._getOwnerFilter()],
fetch: [
'FormattedID','Name','Owner'
],
listeners: {
load: function(store, data, success) {
this._onInitiativesLoaded(store, data);
},
scope: this
}
});
},
_onInitiativesLoaded: function(store_initiatives, data) {
// Radian
// var project_oid = '/project/37192747640';
var themeStore = Ext.create('Rally.data.WsapiDataStore', {
model: 'PortfolioItem/Theme',
// context: {
// project: project_oid,
// projectScopeDown: true,
// projectScopeUp: false
// },
pageSize: 200,
limit: 10000,
autoLoad: true,
storeId: 'themestore',
fetch: [
'FormattedID','Name','Parent'
],
listeners: {
load: function(store, data, success) {
this._onThemesLoaded(store, data);
},
scope: this
}
});
},
_onThemesLoaded: function(store_themes) {
// Radian
// var project_oid = '/project/37192747640';
var filters = Ext.create('Rally.data.QueryFilter', {
property: 'FormattedID',
operator: '=',
value: 'F1'
});
var initiativeStore = Ext.StoreMgr.lookup('initiativestore');
initiativeStore.each(function(record,id){
filters = filters.or(Ext.create('Rally.data.QueryFilter', {
property: 'Parent.Parent.FormattedID',
operator: '=',
value: record.get('FormattedID')
}));
});
var featureStore = Ext.create('Rally.data.WsapiDataStore', {
model: 'PortfolioItem/Feature',
// context: {
// project: project_oid,
// projectScopeDown: true,
// projectScopeUp: false
// },
autoLoad: true,
storeId: 'featurestore',
pageSize: 200,
limit: 20000,
fetch: [
'FormattedID','Name','Parent','State','Owner','PercentDoneByStoryPlanEstimate'
],
filters: filters,
listeners: {
load: function(store, data, success) {
this._onFeaturesLoaded(store, data);
},
scope: this
}
});
},
_onFeaturesLoaded: function(store_features,data){
that = this;
that._featureList = [];
var themeStore = Ext.StoreMgr.lookup('themestore');
Ext.Array.each(data, function(record) {
theme = record.get('Parent');
themeinstore = themeStore.findRecord('FormattedID',theme.FormattedID);
initiative = themeinstore.get('Parent');
that._featureList.push({
initiative: initiative,
Name: record.get('Name'),
State: record.get('State'),
FormattedID: record.get('FormattedID'),
_ref: record.get('_ref'),
Owner: record.get('Owner'),
Parent: record.get('Parent'),
PercentDoneByStoryPlanEstimate: record.get('PercentDoneByStoryPlanEstimate')
});
});
var summaryStore = Ext.create('Rally.data.custom.Store', {
storeId: 'featureStore',
data: that._featureList,
autoScroll: true,
pageSize: 500,
columnLines: true,
groupField: 'initiative',
groupDir: 'ASC',
getGroupString: function(record) {
var initiative = record.get('initiative');
return (initiative.FormattedID + ' - ' + initiative.Name) || 'No Initiative';
}
});
var grid2 = Ext.create('Ext.Container', {
items: [{
id: 'grid2',
xtype: 'rallygrid',
store: summaryStore,
columnCfgs: [
{
text: 'FormattedID',
dataIndex: 'FormattedID',
flex: 1,
xtype: 'templatecolumn',
tpl: Ext.create('Rally.ui.renderer.template.FormattedIDTemplate')
},
{
text: 'Name', dataIndex: 'Name', flex: 10
},
{
text: 'State',
dataIndex: 'State',
flex: 1,
renderer: function(value, meta, record) {
if(!value) { return ''; }
return value.Name;
}
// doSort: function(state) {
// }
},
{
text: '% done (points)',
flex: 2,
dataIndex: 'PercentDoneByStoryPlanEstimate',
xtype: 'templatecolumn',
tpl: Ext.create('Rally.ui.renderer.template.progressbar.PercentDoneByStoryPlanEstimateTemplate')
},
{
text: 'Owner',
dataIndex: 'Owner', flex: 2,
renderer: function(value, meta, record) {
return value._refObjectName;
}
}
],
// context: this.getContext(),
features: [{
ftype: 'groupingsummary',
groupHeaderTpl: '{name} ({rows.length})',
startCollapsed: true
}],
// plugins: ['rallypercentdonepopoverplugin'],
showPagingToolbar: false
}]
});
/* Ext.create('Ext.window.Window', {
width: 800,
height: 500,
layout: 'fit',
items: grid,
tbar: [{
xtype: 'button',
text: 'Only show I46',
enableToggle: true,
handler: function() {
summaryStore.clearFilter();
if (this.pressed) {
summaryStore.filter('FormattedID', 'I46');
}
}
},{
xtype: 'button',
text: 'Increase count',
handler: function() {
// If the snapshot is undefined it means, that store.data holds all items (unfiltered)
var data = summaryStore.snapshot || summaryStore.data;
data.each(function(record) {
record.set('Name', record.get('Name') + 'SEAN');
});
}
}]
}).hide(); */
if (this.down('#grid2')) {
this.down('#grid2').destroy();
}
this.add(grid2);
},
_getOwnerFilter: function() {
combo = this.down('#ownerComboBox');
var comboval = combo.getValue();
if(!comboval){
comboval = combo.stateValue;
}
if(String(comboval).indexOf('-1') > -1){
comboval = null;
}
return {
property: 'Owner',
operator: '=',
value: comboval
};
}
});
|
/// <reference path="../ProductList/ProductList.js" />
/*******************Store Model************************/
var m_pro_pricemasterid = { name: 'price_master_id', type: 'string' };
var m_pro_base = [
{ name: 'product_image', type: 'string' },
{ name: 'product_id', type: 'string' },
{ name: 'brand_name', type: 'string' },
{ name: 'product_name', type: 'string' },
{ name: 'prod_sz', type: 'string' }
];
var m_pro_type = { name: 'combination', type: 'string' };
var m_pro_pricetype = { name: 'price_type', type: 'string' };
var m_pro_pricetypeid = { name: 'price_type_id', type: 'string' };
var m_pro_type_id = { name: 'combination_id', type: 'string' };
var m_pro_spec = { name: 'product_spec', type: 'string' };
var m_pro_pricelist = { name: 'product_price_list', type: 'string' };
var m_pro_status = { name: 'product_status', type: 'string' };
var m_pro_status_id = { name: 'product_status_id', type: 'string' };
var m_pro_freight = { name: 'product_freight_set', type: 'string' };
var m_pro_mode = { name: 'product_mode', type: 'string' };
var m_pro_tax = { name: 'tax_type', type: 'string' };
var m_pro_sort = { name: 'product_sort', type: 'string' };
var m_pro_create = { name: 'product_createdate', type: 'string' };
var m_pro_start = { name: 'product_start', type: 'string' };
var m_pro_end = { name: 'product_end', type: 'string' };
var m_pro_site = { name: 'site_name', type: 'string' };
var m_pro_site_id = { name: 'site_id', type: 'string' };
var m_pro_level = { name: 'level', type: 'string' };
var m_pro_master_user_id = { name: 'master_user_id', type: 'string' };
var m_pro_userlevel = { name: 'user_level', type: 'string' };
var m_pro_pricestatus = { name: 'price_status', type: 'string' };
var m_pro_itemmoney = { name: 'price', type: 'string' };
var m_pro_itemeventmoney = { name: 'event_price', type: 'string' };
var m_pro_eventstart = { name: 'event_start', type: 'string' };
var m_pro_eventend = { name: 'event_end', type: 'string' };
var m_pro_kuser = { name: 'user_name', type: 'string' };
var m_pro_applytype = { name: '', type: 'string' };
var m_pro_email = { name: 'user_email', type: 'string' };
var m_pro_cost = { name: 'cost', type: 'string' };
var m_pro_eventcost = { name: 'event_cost', type: 'string' };
var m_pro_event_price_discount = { name: 'event_price_discount', type: 'string' };
var m_pro_event_cost_discount = { name: 'event_cost_discount', type: 'string' };
var m_pro_pricetype = { name: 'price_type', type: 'string' };
/*******************GRID COLUMNS***********************/
var c_pro_del = {
header: DELETE, width: 40, align: 'center', menuDisabled: true, xtype: 'actioncolumn', items: [{
icon: '../../../Content/img/icons/cross.gif',
handler: function (grid, rowIndex, colIndex) {
var priceMasterId = s_store.getAt(rowIndex).get('price_master_id');
Ext.Msg.confirm(NOTICE, CONFIRM_DEL, function (btn) {
if (btn == "yes") {
s_store.removeAt(rowIndex);
}
});
}
}]
};
var c_pro_base = [
{ header: PRODUCT_IMAGE, /*colName: 'product_image', hidden: true,*/ xtype: 'templatecolumn', tpl: '<div style="width:50px;height:50px"><img width="50px" height="50px" src="{product_image}" /><div>', width: 60, align: 'center', sortable: false, menuDisabled: true },
{ header: PRODUCT_ID, dataIndex: 'product_id',/* colName: 'product_id', hidden: true, xtype: 'templatecolumn', tpl: '<a href=# onclick="javascript:showDetail({product_id})" >{product_id}</a>', */width: 60, align: 'center', sortable: false, menuDisabled: true },
{
header: PRODUCT_NAME,/* colName: 'product_name', hidden: true,*/ dataIndex: 'product_name', width: 180, align: 'left', sortable: false, menuDisabled: true
/*,
renderer: function (value, cellmeta, record) {
return value + (record.data.prod_sz ? ' (' + record.data.prod_sz + ')' : '');
}*/
},
{ header: BRAND_NAME,/* colName: 'brand_id', hidden: true,*/ dataIndex: 'brand_name', width: 120, align: 'left', sortable: false, menuDisabled: true }
];
//商品類型
var c_pro_type = {
header: PRODUCT_TYPE, /*colName: 'combination', hidden: true,*/ dataIndex: 'combination', width: 80, align: 'center', sortable: false, menuDisabled: true
};
//價格類型
var c_pro_pricetype = {
header: PRICE_TYPE, /*colName: 'price_type',*/ dataIndex: 'price_type', width: 80, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_spec = {
header: PRODUCT_SPEC, /*colName: 'product_spec', hidden: true,*/ dataIndex: 'product_spec', width: 80, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_status = {
header: PRODUCT_STATUS, /*colName: 'product_status', hidden: true,*/ dataIndex: 'product_status', width: 90, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_site = {
header: SITE, /*colName: 'site_id', hidden: true,*/ dataIndex: 'site_name', width: 80, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_userlevel = {
header: USER_LEVEL, /*colName: 'user_level', hidden: true,*/ dataIndex: 'user_level', width: 100, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_pricestatus = {
header: PRICE_STATUS,/* colName: 'price_status', hidden: true,*/ dataIndex: 'price_status', width: 120, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_itemoney = {
header: ITEM_MONEY,/* colName: 'price', hidden: true,*/ dataIndex: 'price', width: 80, align: 'center', sortable: false, menuDisabled: true
};
var c_pro_cost = { header: COST, /*colName: 'cost', hidden: true,*/ dataIndex: 'cost', width: 80, align: 'center', sortable: false, menuDisabled: true };
var c_pro_eventcost = {
header: EVENT_COST, /*colName: 'cost', hidden: true,*/
dataIndex: 'event_cost',
width: 80,
align: 'center',
sortable: false,
menuDisabled: true
};
var c_pro_eventcost_edit = {
header: EVENT_COST, /*colName: 'cost', hidden: true,*/
dataIndex: 'event_cost',
width: 80,
align: 'center',
sortable: false,
menuDisabled: true,
//添加 可編輯 add by zhuoqin0830w 2015/02/10
field: { xtype: 'numberfield', minValue: 0, allowBlank: false, regex: /^[0-9]*$/ }
};
var c_pro_event_price_discount = {
header: EVENT_PRICE_DISCOUNT, /*colName: 'event_price_discount', hidden: true,*/
dataIndex: 'event_price_discount',
width: 80, align: 'center',
sortable: false,
hidden: location.search.substr(location.search.lastIndexOf('=') + 1) == 2 ? true : false, // 判斷選擇按鈕是 原價選擇還是折扣價選擇 edit by zhuoqin0830w 2015/02/10
menuDisabled: true,
field: { xtype: 'numberfield', allowBlank: false, minValue: 1, maxValue: 99, regex: /^[0-9]*$/ }
};//edit by hjiajun1211w 2014/08/07 確保輸入合法性
var c_pro_event_cost_discount = {
header: EVENT_COST_DISCOUNT, /*colName: 'event_cost_discount', hidden: true,*/
dataIndex: 'event_cost_discount',
width: 80, align: 'center',
sortable: false,
hidden: location.search.substr(location.search.lastIndexOf('=') + 1) == 2 ? true : false, // 判斷選擇按鈕是 原價選擇還是折扣價選擇 edit by zhuoqin0830w 2015/02/10
menuDisabled: true,
field: { xtype: 'numberfield', allowBlank: false, minValue: 1, maxValue: 100, regex: /^[0-9]*$/ }
};//edit by hjiajun1211w 2014/08/07 確保輸入合法性
var c_pro_itemeventmoney_edit = {
header: ITEM_EVENT_MONEY, /*colName: 'event_price', hidden: true,*/
dataIndex: 'event_price',
width: 80,
align: 'center',
sortable: false,
menuDisabled: true,
//添加 可編輯 add by zhuoqin0830w 2015/02/10
field: { xtype: 'numberfield', minValue: 0, allowBlank: false, regex: /^[0-9]*$/ }
};
var c_pro_itemeventmoney = {
header: ITEM_EVENT_MONEY, /*colName: 'event_price', hidden: true,*/
dataIndex: 'event_price',
width: 80,
align: 'center',
sortable: false,
menuDisabled: true
};
var c_pro_eventstart = {
header: EVENT_START, dataIndex: 'event_start', width: 140, align: 'center', sortable: false, menuDisabled: true,
renderer: function (val) {
if (Ext.Date.format(new Date(val), 'Y/m/d') == '1970/01/01')
return '';
return Ext.Date.format(new Date(val), 'Y/m/d H:i:s');
}, field: {
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
allowBlank: false, format: 'Y/m/d H:i:s',
time: { hour: 0, min: 0, sec: 0 }// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
}
};
var c_pro_eventend = {
header: EVENT_END, dataIndex: 'event_end', width: 140, align: 'center', sortable: false, menuDisabled: true,
renderer: function (val) {
if (Ext.Date.format(new Date(val), 'Y/m/d') == '1970/01/01')
return '';
return Ext.Date.format(new Date(val), 'Y/m/d H:i:s');
}, field: {
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
allowBlank: false, format: 'Y/m/d H:i:s',
time: { hour: 23, min: 59, sec: 59 }// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
}
};
var pageSize = 15;
//站台價格列
var site = new Array();
site = site.concat(m_pro_base);
site.push(m_pro_type);
site.push(m_pro_type_id);
site.push(m_pro_status);
site.push(m_pro_status_id);
site.push(m_pro_site);
site.push(m_pro_site_id);
site.push(m_pro_level);
site.push(m_pro_master_user_id);
site.push(m_pro_userlevel);
site.push(m_pro_pricestatus);
site.push(m_pro_itemmoney);
site.push(m_pro_itemeventmoney);
site.push(m_pro_cost);
site.push(m_pro_eventcost);
site.push(m_pro_eventstart);
site.push(m_pro_eventend);
site.push(m_pro_event_price_discount);
site.push(m_pro_event_cost_discount);
site.push(m_pro_pricetype);
site.push(m_pro_pricetypeid);
site.push(m_pro_pricemasterid);
site.push({ name: 'prepaid', type: 'int' });
Ext.define('GIGADE.SITEPRODUCT', {
extend: 'Ext.data.Model',
fields: site
});
var s_store = Ext.create('Ext.data.Store', {
pageSize: pageSize,
model: 'GIGADE.SITEPRODUCT',
proxy: {
type: 'ajax',
url: '/ProductSelect/QueryProList',
actionMethods: 'post',
reader: {
type: 'json',
root: 'item',
totalProperty: 'totalCount'
}
}
});
s_store.on("beforeload", function () {
Ext.apply(s_store.proxy.extraParams, {
brand_id: Ext.getCmp('') ? Ext.getCmp('').getValue() : ''
});
});
var frm;
Ext.onReady(function () {
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth();
var day = myDate.getDate();
var hour = myDate.getHours();
// 獲取 按鈕選擇的 值 判斷 打開那一個 tab add by zhuoqin0830w 2015/01/10
var priceCondition = location.search.substr(location.search.lastIndexOf('=') + 1);
if (priceCondition == "1") {
frm = Ext.create('Ext.form.Panel', {
layout: 'anchor',
id: 'frm',
width: 1185,
border: false,
padding: '5 0',
defaults: { anchor: '95%', msgTarget: "side" },
items: [{
xtype: 'fieldcontainer',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'numberfield',
fieldLabel: EVENT_PRICE_DISCOUNT,
id: 'epDis',
margin: '0 5px',
colName: 'epDis',
name: 'epDis',
//value: 88,
maxValue: 99,
minValue: 1,
regex: /^[0-9]*$/
}, {
xtype: 'button',
margin: '0px 60px 0px 0px',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('epDis').getValue(); //獲取活動售價折數
if (Ext.getCmp('epDis').isValid()) { //add by hjiajun1211w 2014/08/07 控制輸入的活動售價折數的正確性
//for (var i = 0, j = s_store.getCount() ; i < j; i++) {
// var record = s_store.getAt(i);
// record.set('event_price_discount', val);
// record.set('event_price', (record.get('price') * (val * 0.01)).toFixed(0));
//}
var jsonArr = new Array();
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_price_discount', val);
var cost_discount;
if (record.data.event_cost_discount == "") { cost_discount = 0; }
else { cost_discount = record.data.event_cost_discount; }
jsonArr.push({
//eidt by zhuoqin0830w 更改商品活動成本驗算公式使活動價乘以折扣 傳值給後臺 2015/03/03
price_master_id: record.data.price_master_id,
price: record.data.price,
event_price_discount: val,
event_cost: record.data.event_cost,
event_cost_discount: cost_discount
});
}
ArithmeticalDiscount(s_store, jsonArr, "price_master_id", "event_price", "event_price_discount");//計算折扣
}
}
}
}, {
xtype: 'displayfield',
value: EVENT_PRICE_DISCOUNT_DESC_TWO
}]
}, {
xtype: 'fieldcontainer',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'numberfield',
fieldLabel: EVENT_COST_DISCOUNT,
id: 'ecDis',
margin: '0 5px',
colName: 'ecDis',
name: 'ecDis',
//value: 88,
maxValue: 100,
minValue: 1,
regex: /^[0-9]*$/
}, {
xtype: 'button',
id: 'btn_ecDis',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('ecDis').getValue(); //獲取活動成本折數
if (Ext.getCmp('ecDis').isValid()) { //add by hjiajun1211w 2014/08/07 控制輸入的活動成本折數的正確性
//for (var i = 0, j = s_store.getCount() ; i < j; i++) {
// var record = s_store.getAt(i);
// record.set('event_cost_discount', val);
// record.set('event_cost', (record.get('cost') * (val * 0.01)).toFixed(0));
//}
var jsonArr = new Array();
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
var price_discount;
if (record.data.event_price_discount == "") { price_discount = 0; }
else { price_discount = record.data.event_price_discount; }
record.set('event_cost_discount', val);
jsonArr.push({
//eidt by zhuoqin0830w 更改商品活動成本驗算公式使活動價乘以折扣 傳值給後臺 2015/03/03
price_master_id: record.data.price_master_id,
event_price: record.data.event_price,
event_cost_discount: val
});
}
ArithmeticalDiscount(s_store, jsonArr, "price_master_id", "event_cost", "event_cost_discount");//計算折扣
}
}
}
}, {//add by zhuoqin0830w 2015/04/02 添加 依原成本設定值
xtype: 'checkbox',
margin: '0 5 0 5',
boxLabel: AS_OLD_COST_VALUE,//依原成本設定值
id: 'chkCost',
colName: 'chkCost',
handler: function () {
getCost();
}
}, {
xtype: 'displayfield',
value: EVENT_COST_DISCOUNT_DESC
}]
}, {
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
format: 'Y/m/d H:i:s',
fieldLabel: EVENT_START,
time: { hour: 0, min: 0, sec: 0 },// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
id: 'time_start',
name: 'time_start',
margin: '0 5px',
editable: false
//value: new Date(year, month, day, hour, 0, 0, 0)
}, {
xtype: 'button',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('time_start').getValue();//獲取開始時間
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_start', val);
}
}
}
}]
}, {
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
fieldLabel: EVENT_END,
time: { hour: 23, min: 59, sec: 59 },// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
id: 'time_end',
name: 'time_end',
margin: '0 5px',
editable: false,
format: 'Y/m/d H:i:s'
//value: new Date(year, month, day, hour, 0, 0, 0)
}, {
xtype: 'button',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('time_end').getValue();//獲取開始時間
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_end', val);
}
}
}
}]
}]
});
} else if (priceCondition == "2") {
frm = Ext.create('Ext.form.Panel', {
layout: 'anchor',
id: 'frm',
width: 1185,
border: false,
padding: '5 0',
defaults: { anchor: '95%', msgTarget: "side" },
items: [{
xtype: 'fieldcontainer',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'numberfield',
fieldLabel: SINGLE_PRODUCT_EVENT_PRICE,//活動售價
id: 'epDis',
margin: '0 5px',
colName: 'epDis',
name: 'epDis',
//maxValue: 1000,
regex: /^[0-9]*$/
}, {
xtype: 'button',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('epDis').getValue();
if (Ext.getCmp('epDis').isValid()) {
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_price', val);
}
}
}
}
}]
}, {
xtype: 'fieldcontainer',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'numberfield',
fieldLabel: SINGLE_PRODUCT_EVENT_COST,//活動成本
id: 'ecDis',
margin: '0 5px',
colName: 'ecDis',
name: 'ecDis',
//maxValue: 1000,
regex: /^[0-9]*$/
}, {
xtype: 'button',
id: 'btn_ecDis',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('ecDis').getValue();
if (Ext.getCmp('ecDis').isValid()) {
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_cost', val);
}
}
}
}
}, {//add by zhuoqin0830w 2015/04/02 添加 依原成本設定值
xtype: 'checkbox',
margin: '0 10 0 10',
boxLabel: AS_OLD_COST_VALUE,//依原成本設定值
id: 'chkCost',
colName: 'chkCost',
handler: function () {
getCost();
}
}]
}, {
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
format: 'Y/m/d H:i:s',
fieldLabel: EVENT_START,
time: { hour: 0, min: 0, sec: 0 },// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
id: 'time_start',
name: 'time_start',
margin: '0 5px',
editable: false
//value: new Date(year, month, day, hour, 0, 0, 0)
}, {
xtype: 'button',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('time_start').getValue();//獲取開始時間
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_start', val);
}
}
}
}]
}, {
xtype: 'fieldcontainer',
layout: 'hbox',
anchor: '100%',
layout: {
type: 'hbox',
padding: '10',
pack: 'start',
align: 'top'
},
items: [{
xtype: 'datetimefield',
disabledMin: false,
disabledSec: false,
fieldLabel: EVENT_END,
time: { hour: 23, min: 59, sec: 59 },// add by zhuoqin0830w 自定義時間空間的值 2015/03/18
id: 'time_end',
name: 'time_end',
margin: '0 5px',
editable: false,
format: 'Y/m/d H:i:s'
//value: new Date(year, month, day, hour, 0, 0, 0)
}, {
xtype: 'button',
text: MODIFY_LIST,
listeners: {
click: function () {
var val = Ext.getCmp('time_end').getValue();//獲取開始時間
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_end', val);
}
}
}
}]
}]
});
}
//價格列表的column
var siteColumns = new Array();
siteColumns.push(c_pro_del);
siteColumns = siteColumns.concat(c_pro_base);
siteColumns.push(c_pro_type);
siteColumns.push(c_pro_pricetype);
//siteColumns.push(c_pro_spec);
siteColumns.push(c_pro_status);
siteColumns.push(c_pro_site);
siteColumns.push(c_pro_userlevel);
//siteColumns.push(c_pro_pricestatus);
siteColumns.push(c_pro_itemoney);
siteColumns.push(c_pro_cost);
//獲取 按鈕選擇的 值 判斷 活動價和活動成本可編輯 add by zhuoqin0830w 2015/01/10
if (location.search.substr(location.search.lastIndexOf('=') + 1) == "1") {
siteColumns.push(c_pro_itemeventmoney);
siteColumns.push(c_pro_eventcost);
} else if (location.search.substr(location.search.lastIndexOf('=') + 1) == "2") {
siteColumns.push(c_pro_itemeventmoney_edit);
siteColumns.push(c_pro_eventcost_edit);
}
siteColumns.push(c_pro_event_price_discount);
siteColumns.push(c_pro_event_cost_discount);
//siteColumns.push(c_pro_eventdate);
siteColumns.push(c_pro_eventstart);
siteColumns.push(c_pro_eventend);
var siteProGrid = Ext.create('Ext.grid.Panel', {
hidden: true,
id: 'siteProGrid',
store: s_store,
height: document.documentElement.clientHeight <= 700 ? document.documentElement.clientHeight - 272 : document.documentElement.clientHeight - 252,
columnLines: true,
columns: siteColumns,
listeners: {
viewready: function () {
setShow(siteProGrid, 'colName');
},
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
plugins: [Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
]
});
siteProGrid.on({
edit: function (editor, e) {
if (e.field == 'event_price_discount') {
// e.record.set('event_price', (e.record.get('price') * (e.value * 0.01)).toFixed(0));
//eidt by zhuoqin0830w 更改商品活動成本驗算公式使活動價乘以折扣 傳值給後臺 2015/03/03
var cost_discount;
if (e.record.data.event_cost_discount == "") { cost_discount = 0; }
else { cost_discount = e.record.data.event_cost_discount; }
var jsonArr = [{ price_master_id: e.record.data.price_master_id, price: e.record.data.price, event_price_discount: e.value, event_cost: e.record.data.event_cost, event_cost_discount: cost_discount }];
ArithmeticalDiscount(s_store, jsonArr, "price_master_id", "event_price", "event_price_discount");
}
else if (e.field == 'event_cost_discount') {
// e.record.set('event_cost', (e.record.get('cost') * (e.value * 0.01)).toFixed(0));
//eidt by zhuoqin0830w 更改商品活動成本驗算公式使活動價乘以折扣 傳值給後臺 2015/03/03
var jsonArr = [{ price_master_id: e.record.data.price_master_id, event_price: e.record.data.event_price, event_cost_discount: e.value }];
ArithmeticalDiscount(s_store, jsonArr, "price_master_id", "event_cost", "event_cost_discount");
}
}
});
var save_button = Ext.create('Ext.form.Panel', {
layout: 'column',
id: 'save_button',
width: 200,
border: false,
padding: '5 5',
buttons: [
{
id: 'eventUpdate',
xtype: 'button', text: BTN_SAVE,
listeners: {
click: Save
}
},
{
xtype: 'button', text: CANCEL,
listeners: {
click: function () { Search(); }
}
}]
});
Ext.create('Ext.Viewport', {
layout: 'anchor',
border: false,
items: [frm, siteProGrid, save_button],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
siteProGrid.height = document.documentElement.clientHeight <= 700 ? document.documentElement.clientHeight - 242 : document.documentElement.clientHeight - 260;
this.doLayout();
},
afterrender: function () {
ToolAuthorityQuery(function () {
setTimeout(Search, 500);
});
}
}
});
});
function Search() {
//進行截取,并讀取 商品ID edit by zhuoqin0830w 2015/02/10
s_store.load({
params: { priceMasterIds: location.search.substring(location.search.indexOf('=') + 1, location.search.lastIndexOf('&')) },
callback: function () {
Ext.each(s_store.data.items, function () {
if (this.data.prepaid == 1) {
this.data.event_cost_discount = 100;
}
});
}
});
Ext.getCmp('siteProGrid').show();
}
//計算折扣
function ArithmeticalDiscount(store, jsonArr, key, colVal, type) {
Ext.Ajax.request({
url: '/ProductSelect/ArithmeticalDiscount',
method: "POST",
params: { priceMasterCustoms: Ext.encode(jsonArr), type: type },
success: function (form, action) {
var results = Ext.decode(form.responseText);
Ext.each(results, function () {
store.findRecord(key, this[key]).set(colVal, this[colVal]);
//add by zhuoqin0830w 2015/02/27 更改商品活動成本驗算公式使活動價乘以折扣
if (colVal == "event_price")
store.findRecord(key, this[key]).set('event_cost', this["event_cost"]);
});
}
});
}
Save = function () {
Ext.Msg.confirm(CONFIRM, AREYOUSURE, function (btn) {
if (btn == 'yes') {
var myMask = new Ext.LoadMask(Ext.getBody(), {
msg: 'Loading...'
}); //edit by wangwei0216w 2014/08/6 (為儲存修改按鈕添加遮蓋層,解決多次點擊彈出多個保存成功問題)
myMask.show();
if (s_store.getCount() < 1) {
return;
}
var priceMasters = [];
//add by zhuoqin0830w 2015/04/02 獲取 依原成本設定值 是否選中
var chkCost = Ext.getCmp("chkCost").getValue();
//依折數修改
//獲取 按鈕選擇的 值 判斷 是否為折扣價 add by zhuoqin0830w 2015/01/10
if (location.search.substr(location.search.lastIndexOf('=') + 1) == "1") {
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
var event_price_discount = record.get("event_price_discount");
var event_cost_discount = chkCost == true ? 0 : record.get("event_cost_discount");
var event_starts = record.get("event_start");
var event_ends = record.get("event_end");
if (!event_price_discount) {
myMask.hide();
Ext.Msg.alert(INFORMATION, EVENT_PRICE_DISCOUNT_ISNULL);
return;
}
if (event_starts == "1970/01/01 08:00:00" || event_ends == "1970/01/01 08:00:00" || event_starts == "" || event_ends == "") {
myMask.hide();
Ext.Msg.alert(INFORMATION, '請輸入活動時間');
return;
}
if (new Date(record.get("event_start")).getTime() / 1000 >= new Date(record.get("event_end")).getTime() / 1000) {
myMask.hide();
Ext.Msg.alert(INFORMATION, '請輸入正確的活動時間區間!');
return;
}
//eidt by zhuoqin0830w 2015/04/02 判斷 依原成本設定值 是否選中
if (!chkCost) {
if (!event_cost_discount) {
myMask.hide();
Ext.Msg.alert(INFORMATION, EVENT_COST_DISCOUNT_ISNULL);
return;
}
}
///edit by wwei0216w 價格為0時不允許保存 2015/12/28
if (record.get("event_price") == 0 || record.get("event_cost") == 0){
Ext.Msg.alert('消息', '活動售價,活動成本不能為0!');
myMask.hide();
return
}
priceMasters.push({
"product_id": record.get("product_id"),
"price_master_id": record.get("price_master_id"),
"combination": record.get("combination_id"),
"price_type": record.get("price_type_id"),
"event_price_discount": event_price_discount,
"event_cost_discount": event_cost_discount,
"event_price": record.get("event_price"),
"event_cost": record.get("event_cost"),
"event_start": new Date(record.get("event_start")).getTime() / 1000,
"event_end": new Date(record.get("event_end")).getTime() / 1000
});
}
Ext.Ajax.request({
url: '/ProductSelect/SavePriceMaster',
params: {
priceMasters: JSON.stringify(priceMasters),
priceCondition: location.search.substr(location.search.lastIndexOf('=') + 1),
chkCost: Ext.getCmp("chkCost").getValue() == true ? 0 : 1
},
timeout: 360000,
success: function (response) {
var res = Ext.decode(response.responseText);
if (res.success) {
Ext.Msg.alert(INFORMATION, SUCCESS);
}
else {
Ext.Msg.alert(INFORMATION, FAILURE);
}
myMask.hide();
},
failure: function (response, opts) {
if (response.timedout) {
Ext.Msg.alert(INFORMATION, TIME_OUT);
}
myMask.hide();
}
});
}
//個別輸入
if (location.search.substr(location.search.lastIndexOf('=') + 1) == "2") {
var event_cp = 0;
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
var event_cost = record.get("event_cost");
var event_price = record.get("event_price");
var event_starts = record.get("event_start");
var event_ends = record.get("event_end");
if (event_starts == "1970/01/01 08:00:00" || event_ends == "1970/01/01 08:00:00" || event_starts == "" || event_ends == "") {
myMask.hide();
Ext.Msg.alert(INFORMATION, '請輸入活動時間');
return;
}
if (new Date(record.get("event_start")).getTime() / 1000 >= new Date(record.get("event_end")).getTime() / 1000) {
myMask.hide();
Ext.Msg.alert(INFORMATION, '請輸入正確的活動時間區間!');
return;
}
if (event_cost == '0' || event_price == '0') {
//event_cp = i + 1;
myMask.hide();
Ext.Msg.alert("消息", "活動價或活動成本為0,不能保存");
return;
}
priceMasters.push({
"product_id": record.get("product_id"),
"price_master_id": record.get("price_master_id"),
"combination": record.get("combination_id"),
"price_type": record.get("price_type_id"),
"event_price": record.get("event_price"),
"event_cost": record.get("event_cost"),
"event_start": new Date(record.get("event_start")).getTime() / 1000,
"event_end": new Date(record.get("event_end")).getTime() / 1000
});
}
if (event_cp > 0) {
//Ext.Msg.confirm(CONFIRM, '活動價或活動成本為0,確定保存嗎?', function (btntwo) {
// if (btntwo == 'yes') {
// Ext.Ajax.request({
// url: '/ProductSelect/SavePriceMaster',
// params: {
// priceMasters: JSON.stringify(priceMasters),
// priceCondition: location.search.substr(location.search.lastIndexOf('=') + 1),
// chkCost: Ext.getCmp("chkCost").getValue() == true ? 0 : 1
// },
// timeout: 360000,
// success: function (response) {
// var res = Ext.decode(response.responseText);
// if (res.success) {
// Ext.Msg.alert(INFORMATION, SUCCESS);
// }
// else {
// Ext.Msg.alert(INFORMATION, FAILURE);
// }
// myMask.hide();
// },
// failure: function (response, opts) {
// if (response.timedout) {
// Ext.Msg.alert(INFORMATION, TIME_OUT);
// }
// myMask.hide();
// }
// });
// } else {
// myMask.hide();
// return;
// }
//})
} else {
Ext.Ajax.request({
url: '/ProductSelect/SavePriceMaster',
params: {
priceMasters: JSON.stringify(priceMasters),
priceCondition: location.search.substr(location.search.lastIndexOf('=') + 1),
chkCost: Ext.getCmp("chkCost").getValue() == true ? 0 : 1
},
timeout: 360000,
success: function (response) {
var res = Ext.decode(response.responseText);
if (res.success) {
Ext.Msg.alert(INFORMATION, SUCCESS);
}
else {
Ext.Msg.alert(INFORMATION, FAILURE);
}
myMask.hide();
},
failure: function (response, opts) {
if (response.timedout) {
Ext.Msg.alert(INFORMATION, TIME_OUT);
}
myMask.hide();
}
});
}
}
}
})
}
//add by zhuoqin0830w 2015/04/02 添加 依原成本設定值
function getCost() {
if (Ext.getCmp("chkCost").getValue()) {
Ext.getCmp("btn_ecDis").setDisabled(true);
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_cost', s_store.getAt(i).data.cost);
}
} else {
Ext.getCmp("btn_ecDis").setDisabled(false);
for (var i = 0, j = s_store.getCount() ; i < j; i++) {
var record = s_store.getAt(i);
record.set('event_cost', '0');
}
}
}
|
/*
* JS for startScreen generated by Appery.io
*/
Apperyio.getProjectGUID = function() {
return '566c72a3-f7ce-435a-932b-efebe1a73adf';
};
function navigateTo(outcome, useAjax) {
Apperyio.navigateTo(outcome, useAjax);
}
// Deprecated
function adjustContentHeight() {
Apperyio.adjustContentHeightWithPadding();
}
function adjustContentHeightWithPadding(_page) {
Apperyio.adjustContentHeightWithPadding(_page);
}
function setDetailContent(pageUrl) {
Apperyio.setDetailContent(pageUrl);
}
Apperyio.AppPages = [{
"name": "infoScreen",
"location": "#infoScreen"
}, {
"name": "startScreen",
"location": "#startScreen"
}, {
"name": "scanScreen",
"location": "#scanScreen"
}];
startScreen_js = function(runBeforeShow) {
/* Object & array with components "name-to-id" mapping */
var n2id_buf = {
'mobilelabel_11': 'startScreen_mobilelabel_11',
'mobilegrid_2': 'startScreen_mobilegrid_2',
'mobilegridcell_3': 'startScreen_mobilegridcell_3',
'mobilelabel_7': 'startScreen_mobilelabel_7',
'mobilegridcell_4': 'startScreen_mobilegridcell_4',
'txtUserName': 'startScreen_txtUserName',
'mobilegridcell_5': 'startScreen_mobilegridcell_5',
'mobilelabel_8': 'startScreen_mobilelabel_8',
'mobilegridcell_6': 'startScreen_mobilegridcell_6',
'txtPassword': 'startScreen_txtPassword',
'mobilegridcell_12': 'startScreen_mobilegridcell_12',
'mobilegridcell_13': 'startScreen_mobilegridcell_13',
'btnLogin': 'startScreen_btnLogin'
};
if ("n2id" in window && window.n2id !== undefined) {
$.extend(n2id, n2id_buf);
} else {
window.n2id = n2id_buf;
}
if (navigator.userAgent.indexOf("IEMobile") != -1) {
//Fix for jQuery Mobile's footer in Cordova webview on WP8 devices
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode("@media screen and (orientation: portrait){@-ms-viewport {width: 320px; height: 536px;user-zoom: fixed;max-zoom: 1;min-zoom: 1;}}" + "@media screen and (orientation:landscape){@-ms-viewport{width:480px;user-zoom:fixed;max-zoom:1;min-zoom:1;}}"));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
Apperyio.CurrentScreen = 'startScreen';
/*
* Nonvisual components
*/
var datasources = [];
restservice1 = new Apperyio.DataSource(LoginService, {
'onBeforeSend': function(jqXHR) {
},
'onComplete': function(jqXHR, textStatus) {
Apperyio.refreshScreenFormElements("startScreen");
},
'onSuccess': function(data) {},
'onError': function(jqXHR, textStatus, errorThrown) {
alert("Invalid credentials! Please try again");
},
'responseMapping': [{
'PATH': ['AppUserId'],
'ID': '___local_storage___',
'ATTR': 'userid'
}, {
'PATH': ['AppRoleId'],
'ID': '___local_storage___',
'ATTR': 'roleid'
}, {
'PATH': ['AppRoleId'],
'ID': '___js___',
'ATTR': 'redirectBasedOnRole',
'TRANSFORMATION': function(value, element) {
var text = value;
localStorage.setItem("isRegistration", false);
localStorage.setItem("isPassThrough", false);
localStorage.setItem("isAmbulance", false);
localStorage.setItem("isRescue", false);
localStorage.setItem("isDoctor", false);
localStorage.setItem("isStatusUpdateRequired", false);
localStorage.setItem("isJustSavingOnce", false);
localStorage.setItem("showInfo", false);
if (text == 1) {
alert("Please use portal");
}
if (text > 1) {
if (text == 2) {
localStorage.setItem("isRegistration", true);
localStorage.setItem("isJustSavingOnce", true);
} else if (text == 3) {
localStorage.setItem("isPassThrough", true);
localStorage.setItem("isJustSavingOnce", true);
} else if (text == 4) {
localStorage.setItem("isAmbulance", true);
localStorage.setItem("isJustSavingOnce", true);
localStorage.setItem("showInfo", true);
} else if (text == 5) {
localStorage.setItem("isRescue", true);
localStorage.setItem("isStatusUpdateRequired", true);
localStorage.setItem("showInfo", true);
} else if (text == 6) {
localStorage.setItem("isDoctor", true);
localStorage.setItem("isStatusUpdateRequired", true);
localStorage.setItem("showInfo", true);
}
Apperyio.navigateTo('scanScreen', {
reverse: false
});
}
}
}],
'requestMapping': [{
'PATH': ['Username'],
'TYPE': 'STRING',
'ID': 'txtUserName',
'ATTR': 'value'
}, {
'PATH': ['Password'],
'TYPE': 'STRING',
'ID': 'txtPassword',
'ATTR': 'value'
}]
});
datasources.push(restservice1);
/*
* Events and handlers
*/
// Before Show
var startScreen_beforeshow = function() {
Apperyio.CurrentScreen = "startScreen";
for (var idx = 0; idx < datasources.length; idx++) {
datasources[idx].__setupDisplay();
}
};
// On Load
var startScreen_onLoad = function() {
startScreen_elementsExtraJS();
// TODO fire device events only if necessary (with JS logic)
startScreen_deviceEvents();
startScreen_windowEvents();
startScreen_elementsEvents();
};
// screen window events
var startScreen_windowEvents = function() {
$('#startScreen').bind('pageshow orientationchange', function() {
var _page = this;
adjustContentHeightWithPadding(_page);
});
};
// device events
var startScreen_deviceEvents = function() {
document.addEventListener("deviceready", function() {
});
};
// screen elements extra js
var startScreen_elementsExtraJS = function() {
// screen (startScreen) extra code
};
// screen elements handler
var startScreen_elementsEvents = function() {
$(document).on("click", "a :input,a a,a fieldset label", function(event) {
event.stopPropagation();
});
$(document).off("click", '#startScreen_mobilecontainer1 [name="btnLogin"]').on({
click: function() {
if (!$(this).attr('disabled')) {
try {
restservice1.execute({})
} catch (ex) {
console.log(ex.name + ' ' + ex.message);
hideSpinner();
};
}
},
}, '#startScreen_mobilecontainer1 [name="btnLogin"]');
};
$(document).off("pagebeforeshow", "#startScreen").on("pagebeforeshow", "#startScreen", function(event, ui) {
startScreen_beforeshow();
});
if (runBeforeShow) {
startScreen_beforeshow();
} else {
startScreen_onLoad();
}
};
$(document).off("pagecreate", "#startScreen").on("pagecreate", "#startScreen", function(event, ui) {
Apperyio.processSelectMenu($(this));
startScreen_js();
});
scanScreen_js = function(runBeforeShow) {
/* Object & array with components "name-to-id" mapping */
var n2id_buf = {
'mobilebutton_150': 'scanScreen_mobilebutton_150',
'mobilecollapsibleset_142': 'scanScreen_mobilecollapsibleset_142',
'mobilecollapsblock_143': 'scanScreen_mobilecollapsblock_143',
'settingsBl': 'scanScreen_settingsBl',
'mobilecollapsblockcontent_145': 'scanScreen_mobilecollapsblockcontent_145',
'mobilelabel_21': 'scanScreen_mobilelabel_21',
'cmdCheckPoint': 'scanScreen_cmdCheckPoint',
'cmdCheckPoint-0': 'scanScreen_cmdCheckPoint-0',
'lblChooseAction': 'scanScreen_lblChooseAction',
'cmdRegAction': 'scanScreen_cmdRegAction',
'cmdRegAction-0': 'scanScreen_cmdRegAction-0',
'cmbPassActions': 'scanScreen_cmbPassActions',
'cmbPassActions-0': 'scanScreen_cmbPassActions-0',
'cmbAmbulanceActions': 'scanScreen_cmbAmbulanceActions',
'cmbAmbulanceActions-0': 'scanScreen_cmbAmbulanceActions-0',
'btnSaveSettings': 'scanScreen_btnSaveSettings',
'mobilecollapsblock_146': 'scanScreen_mobilecollapsblock_146',
'scanBlock': 'scanScreen_scanBlock',
'mobilecollapsblockcontent_148': 'scanScreen_mobilecollapsblockcontent_148',
'btnScanTag': 'scanScreen_btnScanTag',
'txtNFCTag': 'scanScreen_txtNFCTag',
'scanStatus': 'scanScreen_scanStatus',
'lblChooseStatus': 'scanScreen_lblChooseStatus',
'cmbRescueActions': 'scanScreen_cmbRescueActions',
'cmbRescueActions-0': 'scanScreen_cmbRescueActions-0',
'cmbDoctorActions': 'scanScreen_cmbDoctorActions',
'cmbDoctorActions-0': 'scanScreen_cmbDoctorActions-0',
'lessInfoGrid': 'scanScreen_lessInfoGrid',
'mobilegridcell_85': 'scanScreen_mobilegridcell_85',
'mobilelabel_89': 'scanScreen_mobilelabel_89',
'mobilegridcell_86': 'scanScreen_mobilegridcell_86',
'lblFirstName': 'scanScreen_lblFirstName',
'mobilegridcell_87': 'scanScreen_mobilegridcell_87',
'mobilelabel_90': 'scanScreen_mobilelabel_90',
'mobilegridcell_88': 'scanScreen_mobilegridcell_88',
'lblLastName': 'scanScreen_lblLastName',
'mobilegridcell_91': 'scanScreen_mobilegridcell_91',
'mobilelabel_99': 'scanScreen_mobilelabel_99',
'mobilegridcell_92': 'scanScreen_mobilegridcell_92',
'lblGender': 'scanScreen_lblGender',
'mobilegridcell_93': 'scanScreen_mobilegridcell_93',
'mobilelabel_98': 'scanScreen_mobilelabel_98',
'mobilegridcell_94': 'scanScreen_mobilegridcell_94',
'lblAge': 'scanScreen_lblAge',
'mobilegridcell_95': 'scanScreen_mobilegridcell_95',
'mobilelabel_97': 'scanScreen_mobilelabel_97',
'mobilegridcell_96': 'scanScreen_mobilegridcell_96',
'lblBloodGroup': 'scanScreen_lblBloodGroup',
'mobilegridcell_100': 'scanScreen_mobilegridcell_100',
'mobilelabel_104': 'scanScreen_mobilelabel_104',
'mobilegridcell_101': 'scanScreen_mobilegridcell_101',
'lblGroupCount': 'scanScreen_lblGroupCount',
'mobilegridcell_102': 'scanScreen_mobilegridcell_102',
'mobilelabel_110': 'scanScreen_mobilelabel_110',
'mobilegridcell_103': 'scanScreen_mobilegridcell_103',
'lblEmergencyContact': 'scanScreen_lblEmergencyContact',
'mobilegridcell_111': 'scanScreen_mobilegridcell_111',
'mobilelabel_113': 'scanScreen_mobilelabel_113',
'mobilegridcell_112': 'scanScreen_mobilegridcell_112',
'lblEmergencyContactNumber': 'scanScreen_lblEmergencyContactNumber',
'mobilegridcell_126': 'scanScreen_mobilegridcell_126',
'mobilelabel_128': 'scanScreen_mobilelabel_128',
'mobilegridcell_127': 'scanScreen_mobilegridcell_127',
'lblMedicalConditon': 'scanScreen_lblMedicalConditon',
'btnSaveStatus': 'scanScreen_btnSaveStatus',
'registerGrid': 'scanScreen_registerGrid',
'mobilegridcell_30': 'scanScreen_mobilegridcell_30',
'mobilelabel_35': 'scanScreen_mobilelabel_35',
'mobilegridcell_31': 'scanScreen_mobilegridcell_31',
'txtFirstName': 'scanScreen_txtFirstName',
'mobilegridcell_32': 'scanScreen_mobilegridcell_32',
'mobilelabel_36': 'scanScreen_mobilelabel_36',
'mobilegridcell_33': 'scanScreen_mobilegridcell_33',
'txtLastName': 'scanScreen_txtLastName',
'mobilegridcell_40': 'scanScreen_mobilegridcell_40',
'mobilelabel_58': 'scanScreen_mobilelabel_58',
'mobilegridcell_41': 'scanScreen_mobilegridcell_41',
'cmbGender': 'scanScreen_cmbGender',
'cmbGender-0': 'scanScreen_cmbGender-0',
'mobilegridcell_42': 'scanScreen_mobilegridcell_42',
'mobilelabel_63': 'scanScreen_mobilelabel_63',
'mobilegridcell_43': 'scanScreen_mobilegridcell_43',
'txtAge': 'scanScreen_txtAge',
'mobilegridcell_44': 'scanScreen_mobilegridcell_44',
'mobilelabel_64': 'scanScreen_mobilelabel_64',
'mobilegridcell_45': 'scanScreen_mobilegridcell_45',
'cmbBloodGroup': 'scanScreen_cmbBloodGroup',
'cmbBloodGroup-0': 'scanScreen_cmbBloodGroup-0',
'mobilegridcell_46': 'scanScreen_mobilegridcell_46',
'mobilelabel_67': 'scanScreen_mobilelabel_67',
'mobilegridcell_47': 'scanScreen_mobilegridcell_47',
'txtPhonenumber': 'scanScreen_txtPhonenumber',
'mobilegridcell_48': 'scanScreen_mobilegridcell_48',
'mobilelabel_69': 'scanScreen_mobilelabel_69',
'mobilegridcell_49': 'scanScreen_mobilegridcell_49',
'groupCount': 'scanScreen_groupCount',
'mobilegridcell_50': 'scanScreen_mobilegridcell_50',
'mobilelabel_71': 'scanScreen_mobilelabel_71',
'mobilegridcell_51': 'scanScreen_mobilegridcell_51',
'txtEmergencyContact': 'scanScreen_txtEmergencyContact',
'mobilegridcell_52': 'scanScreen_mobilegridcell_52',
'mobilelabel_73': 'scanScreen_mobilelabel_73',
'mobilegridcell_53': 'scanScreen_mobilegridcell_53',
'txtEmergencyContactNumber': 'scanScreen_txtEmergencyContactNumber',
'mobilegridcell_54': 'scanScreen_mobilegridcell_54',
'mobilelabel_76': 'scanScreen_mobilelabel_76',
'mobilegridcell_55': 'scanScreen_mobilegridcell_55',
'SMSPackage': 'scanScreen_SMSPackage',
'mobilegridcell_81': 'scanScreen_mobilegridcell_81',
'mobilelabel_125': 'scanScreen_mobilelabel_125',
'mobilegridcell_82': 'scanScreen_mobilegridcell_82',
'txaMedicalCondition': 'scanScreen_txaMedicalCondition',
'btnSaveUser': 'scanScreen_btnSaveUser'
};
if ("n2id" in window && window.n2id !== undefined) {
$.extend(n2id, n2id_buf);
} else {
window.n2id = n2id_buf;
}
if (navigator.userAgent.indexOf("IEMobile") != -1) {
//Fix for jQuery Mobile's footer in Cordova webview on WP8 devices
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode("@media screen and (orientation: portrait){@-ms-viewport {width: 320px; height: 536px;user-zoom: fixed;max-zoom: 1;min-zoom: 1;}}" + "@media screen and (orientation:landscape){@-ms-viewport{width:480px;user-zoom:fixed;max-zoom:1;min-zoom:1;}}"));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
Apperyio.CurrentScreen = 'scanScreen';
/*
* Nonvisual components
*/
var datasources = [];
getCheckPoints = new Apperyio.DataSource(GetCheckPoints, {
'onBeforeSend': function(jqXHR) {
},
'onComplete': function(jqXHR, textStatus) {
if (localStorage.getItem("chosenCheckpoint") === null && localStorage.getItem("chosenAction") === null) {
localStorage.setItem("areSettingsFine", 0);
localStorage.setItem("chosenCheckpoint", "0");
localStorage.setItem("chosenCheckpoint", "0");
}
if (localStorage.getItem("chosenCheckpoint") != "0") {
var dropDown = $('[name=cmdCheckPoint]');
var newData = localStorage.getItem("chosenCheckpoint");
dropDown.Selected = newData;
}
if (localStorage.getItem("chosenCheckpoint") != "0" && localStorage.getItem("chosenAction") != "0") localStorage.setItem("areSettingsFine", 1);
else localStorage.setItem("areSettingsFine", 0);
Apperyio.refreshScreenFormElements("scanScreen");
},
'onSuccess': function(data) {},
'onError': function(jqXHR, textStatus, errorThrown) {},
'responseMapping': [{
'PATH': ['$'],
'ID': 'cmdCheckPoint-0',
'SET': [{
'PATH': ['CheckPointId'],
'ID': 'cmdCheckPoint-0',
'ATTR': 'value'
}, {
'PATH': ['CheckPointName'],
'ID': 'cmdCheckPoint-0',
'ATTR': '@'
}]
}],
'requestMapping': []
});
datasources.push(getCheckPoints);
getUserProfile = new Apperyio.DataSource(GetUserProfile, {
'onBeforeSend': function(jqXHR) {
},
'onComplete': function(jqXHR, textStatus) {
Apperyio.refreshScreenFormElements("scanScreen");
},
'onSuccess': function(data) {},
'onError': function(jqXHR, textStatus, errorThrown) {},
'responseMapping': [{
'PATH': ['FirstName'],
'ID': 'lblFirstName',
'ATTR': '@'
}, {
'PATH': ['LastName'],
'ID': 'lblLastName',
'ATTR': '@'
}, {
'PATH': ['Gender'],
'ID': 'lblGender',
'ATTR': '@'
}, {
'PATH': ['Age'],
'ID': 'lblAge',
'ATTR': '@'
}, {
'PATH': ['BloodGroup'],
'ID': 'lblBloodGroup',
'ATTR': '@'
}],
'requestMapping': [{
'PATH': ['NFCTagId'],
'TYPE': 'STRING',
'ID': 'txtNFCTag',
'ATTR': '@'
}]
});
datasources.push(getUserProfile);
createNewUserProfile = new Apperyio.DataSource(CreateNewUserProfile, {
'onBeforeSend': function(jqXHR) {
},
'onComplete': function(jqXHR, textStatus) {
Apperyio.refreshScreenFormElements("scanScreen");
},
'onSuccess': function(data) {},
'onError': function(jqXHR, textStatus, errorThrown) {},
'responseMapping': [],
'requestMapping': [{
'PATH': ['firstName'],
'TYPE': 'STRING',
'ID': 'txtFirstName',
'ATTR': 'value'
}, {
'PATH': ['nfctag'],
'TYPE': 'STRING',
'ID': 'txtNFCTag',
'ATTR': '@'
}, {
'PATH': ['age'],
'TYPE': 'STRING',
'ID': 'txtAge',
'ATTR': 'value'
}, {
'PATH': ['gender'],
'TYPE': 'STRING',
'ID': 'cmbGender',
'ATTR': 'value'
}, {
'PATH': ['SMSPackage'],
'TYPE': 'STRING',
'ID': 'SMSPackage',
'ATTR': 'value'
}, {
'PATH': ['firstCheckpoint'],
'TYPE': 'STRING',
'ID': 'cmdCheckPoint',
'ATTR': 'value'
}, {
'PATH': ['appUserId'],
'TYPE': 'STRING',
'ID': '___local_storage___',
'ATTR': 'userid'
}, {
'PATH': ['lastName'],
'TYPE': 'STRING',
'ID': 'txtLastName',
'ATTR': 'value'
}, {
'PATH': ['bloodGroup'],
'TYPE': 'STRING',
'ID': 'cmbBloodGroup',
'ATTR': 'value'
}, {
'PATH': ['phonenumber'],
'TYPE': 'STRING',
'ID': 'txtPhonenumber',
'ATTR': 'value'
}, {
'PATH': ['groupcount'],
'TYPE': 'STRING',
'ID': 'groupCount',
'ATTR': 'value'
}, {
'PATH': ['emergencyContact'],
'TYPE': 'STRING',
'ID': 'txtEmergencyContact',
'ATTR': 'value'
}, {
'PATH': ['emergencyContactNumber'],
'TYPE': 'STRING',
'ID': 'txtEmergencyContactNumber',
'ATTR': 'value'
}, {
'PATH': ['medicalCondition'],
'TYPE': 'STRING',
'ID': 'txaMedicalCondition',
'ATTR': 'value'
}]
});
datasources.push(createNewUserProfile);
saveLog = new Apperyio.DataSource(logActivityWithStatus, {
'onBeforeSend': function(jqXHR) {
},
'onComplete': function(jqXHR, textStatus) {
Apperyio.refreshScreenFormElements("scanScreen");
},
'onSuccess': function(data) {},
'onError': function(jqXHR, textStatus, errorThrown) {},
'responseMapping': [],
'requestMapping': [{
'PATH': ['nfctagid'],
'TYPE': 'STRING',
'ID': 'txtNFCTag',
'ATTR': '@'
}, {
'PATH': ['checkpointId'],
'TYPE': 'STRING',
'ID': '___local_storage___',
'ATTR': 'chosenCheckpoint'
}, {
'PATH': ['action'],
'TYPE': 'STRING',
'ID': '___local_storage___',
'ATTR': 'chosenAction'
}, {
'PATH': ['appuserid'],
'TYPE': 'STRING',
'ID': '___local_storage___',
'ATTR': 'userid'
}]
});
datasources.push(saveLog);
/*
* Events and handlers
*/
// Before Show
var scanScreen_beforeshow = function() {
Apperyio.CurrentScreen = "scanScreen";
for (var idx = 0; idx < datasources.length; idx++) {
datasources[idx].__setupDisplay();
}
};
// On Load
var scanScreen_onLoad = function() {
scanScreen_elementsExtraJS();
try {
getCheckPoints.execute({})
} catch (ex) {
console.log(ex.name + ' ' + ex.message);
hideSpinner();
};
toggle('scanScreen_cmbPassActions', 'mob', localStorage.getItem('isPassThrough'));
toggle('scanScreen_cmbRescueActions', 'mob', localStorage.getItem('isRescue'));
toggle('scanScreen_cmbDoctorActions', 'mob', localStorage.getItem('isDoctor'));
toggle('scanScreen_cmdRegAction', 'mob', localStorage.getItem('isRegistration'));
toggle('scanScreen_lblChooseAction', 'mob', localStorage.getItem('isJustSavingOnce'));
toggle('scanScreen_lblChooseStatus', 'mob', localStorage.getItem('isStatusUpdateRequired'));
toggle('scanScreen_cmbAmbulanceActions', 'mob', localStorage.getItem('isAmbulance'));
toggle('scanScreen_registerGrid', 'mob', localStorage.getItem('isRegistration'));
toggle('scanScreen_lessInfoGrid', 'mob', localStorage.getItem('showInfo'));
toggle('scanScreen_btnSaveStatus', 'mob', localStorage.getItem('isStatusUpdateRequired'));
toggle('scanScreen_registerGrid', 'mob', localStorage.getItem('isRegistration'));
toggle('scanScreen_btnSaveUser', 'mob', 'true');
// TODO fire device events only if necessary (with JS logic)
scanScreen_deviceEvents();
scanScreen_windowEvents();
scanScreen_elementsEvents();
};
// screen window events
var scanScreen_windowEvents = function() {
$('#scanScreen').bind('pageshow orientationchange', function() {
var _page = this;
adjustContentHeightWithPadding(_page);
});
};
// device events
var scanScreen_deviceEvents = function() {
document.addEventListener("deviceready", function() {
});
};
// screen elements extra js
var scanScreen_elementsExtraJS = function() {
// screen (scanScreen) extra code
/* mobilecollapsblock_143 */
$("#scanScreen_mobilecollapsblock_143 .ui-collapsible-heading-toggle").attr("tabindex", "31");
/* cmdCheckPoint */
$("#scanScreen_cmdCheckPoint").parent().find("a.ui-btn").attr("tabindex", "3");
/* cmdRegAction */
$("#scanScreen_cmdRegAction").parent().find("a.ui-btn").attr("tabindex", "4");
/* cmbPassActions */
$("#scanScreen_cmbPassActions").parent().find("a.ui-btn").attr("tabindex", "25");
/* cmbAmbulanceActions */
$("#scanScreen_cmbAmbulanceActions").parent().find("a.ui-btn").attr("tabindex", "30");
/* mobilecollapsblock_146 */
$("#scanScreen_mobilecollapsblock_146 .ui-collapsible-heading-toggle").attr("tabindex", "31");
/* cmbRescueActions */
$("#scanScreen_cmbRescueActions").parent().find("a.ui-btn").attr("tabindex", "26");
/* cmbDoctorActions */
$("#scanScreen_cmbDoctorActions").parent().find("a.ui-btn").attr("tabindex", "28");
/* cmbGender */
$("#scanScreen_cmbGender").parent().find("a.ui-btn").attr("tabindex", "13");
/* cmbBloodGroup */
$("#scanScreen_cmbBloodGroup").parent().find("a.ui-btn").attr("tabindex", "15");
/* SMSPackage */
$("#scanScreen_SMSPackage").parent().find(".ui-flipswitch-on").attr("tabindex", "24");
$("#scanScreen_SMSPackage").val("on").flipswitch('refresh');
};
// screen elements handler
var scanScreen_elementsEvents = function() {
$(document).on("click", "a :input,a a,a fieldset label", function(event) {
event.stopPropagation();
});
$(document).off("click", '#scanScreen_mobileheader [name="mobilebutton_150"]').on({
click: function() {
if (!$(this).attr('disabled')) {
Apperyio.navigateTo('startScreen', {
reverse: false
});
}
},
}, '#scanScreen_mobileheader [name="mobilebutton_150"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmdCheckPoint"]').on({
change: function() {
setVar_('chosenCheckpoint', 'scanScreen_cmdCheckPoint', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmdCheckPoint"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmdRegAction"]').on({
change: function() {
setVar_('chosenAction', 'scanScreen_cmdRegAction', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmdRegAction"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmbPassActions"]').on({
change: function() {
setVar_('chosenAction', 'scanScreen_cmbPassActions', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmbPassActions"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmbAmbulanceActions"]').on({
change: function() {
setVar_('chosenAction', 'scanScreen_cmbAmbulanceActions', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmbAmbulanceActions"]');
$(document).off("click", '#scanScreen_mobilecontainer [name="btnSaveSettings"]').on({
click: function() {
if (!$(this).attr('disabled')) {
var checkpoint = localStorage.getItem("chosenCheckpoint");
var action = localStorage.getItem("chosenAction");
if (checkpoint == "0" || action == "0") {
localStorage.setItem("areSettingsFine", 0);
$("collapseBlock").collapsible("expand");
alert("Please select valid options");
} else {
localStorage.setItem("areSettingsFine", 1);
$("collapseBlock").collapsible("collapse");
alert("Settings saved");
};
}
},
}, '#scanScreen_mobilecontainer [name="btnSaveSettings"]');
$(document).off("click", '#scanScreen_mobilecontainer [name="btnScanTag"]').on({
click: function() {
if (!$(this).attr('disabled')) { //Scan the tag
//If it is user registration mode
// Allow user to enter the details
// Save will be called to save the profile and log will be called to log the first event
//If it anything apart from rescue, ambulance and doctor mode
// log activity will be called;
}
},
}, '#scanScreen_mobilecontainer [name="btnScanTag"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmbRescueActions"]').on({
change: function() {
setVar_('chosenAction', 'scanScreen_cmbRescueActions', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmbRescueActions"]');
$(document).off("change", '#scanScreen_mobilecontainer [name="cmbDoctorActions"]').on({
change: function() {
setVar_('chosenAction', 'scanScreen_cmbDoctorActions', 'value', '', this);
},
}, '#scanScreen_mobilecontainer [name="cmbDoctorActions"]');
$(document).off("click", '#scanScreen_mobilecontainer [name="btnSaveStatus"]').on({
click: function() {
if (!$(this).attr('disabled')) {
setVar_('chosenCheckpoint', 'scanScreen_cmdCheckPoint', 'value', '', this);
try {
saveLog.execute({})
} catch (ex) {
console.log(ex.name + ' ' + ex.message);
hideSpinner();
};
}
},
}, '#scanScreen_mobilecontainer [name="btnSaveStatus"]');
$(document).off("click", '#scanScreen_mobilecontainer [name="btnSaveUser"]').on({
click: function() {
if (!$(this).attr('disabled')) {
setVar_('chosenCheckpoint', 'scanScreen_cmdCheckPoint', 'value', '', this);
try {
createNewUserProfile.execute({})
} catch (ex) {
console.log(ex.name + ' ' + ex.message);
hideSpinner();
};
try {
saveLog.execute({})
} catch (ex) {
console.log(ex.name + ' ' + ex.message);
hideSpinner();
};
}
},
}, '#scanScreen_mobilecontainer [name="btnSaveUser"]');
};
$(document).off("pagebeforeshow", "#scanScreen").on("pagebeforeshow", "#scanScreen", function(event, ui) {
scanScreen_beforeshow();
});
if (runBeforeShow) {
scanScreen_beforeshow();
} else {
scanScreen_onLoad();
}
};
$(document).off("pagecreate", "#scanScreen").on("pagecreate", "#scanScreen", function(event, ui) {
Apperyio.processSelectMenu($(this));
scanScreen_js();
});
infoScreen_js = function(runBeforeShow) {
/* Object & array with components "name-to-id" mapping */
var n2id_buf = {
'mobilelabel_1': 'infoScreen_mobilelabel_1'
};
if ("n2id" in window && window.n2id !== undefined) {
$.extend(n2id, n2id_buf);
} else {
window.n2id = n2id_buf;
}
if (navigator.userAgent.indexOf("IEMobile") != -1) {
//Fix for jQuery Mobile's footer in Cordova webview on WP8 devices
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode("@media screen and (orientation: portrait){@-ms-viewport {width: 320px; height: 536px;user-zoom: fixed;max-zoom: 1;min-zoom: 1;}}" + "@media screen and (orientation:landscape){@-ms-viewport{width:480px;user-zoom:fixed;max-zoom:1;min-zoom:1;}}"));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
Apperyio.CurrentScreen = 'infoScreen';
/*
* Nonvisual components
*/
var datasources = [];
/*
* Events and handlers
*/
// Before Show
var infoScreen_beforeshow = function() {
Apperyio.CurrentScreen = "infoScreen";
for (var idx = 0; idx < datasources.length; idx++) {
datasources[idx].__setupDisplay();
}
};
// On Load
var infoScreen_onLoad = function() {
infoScreen_elementsExtraJS();
// TODO fire device events only if necessary (with JS logic)
infoScreen_deviceEvents();
infoScreen_windowEvents();
infoScreen_elementsEvents();
};
// screen window events
var infoScreen_windowEvents = function() {
$('#infoScreen').bind('pageshow orientationchange', function() {
var _page = this;
adjustContentHeightWithPadding(_page);
});
};
// device events
var infoScreen_deviceEvents = function() {
document.addEventListener("deviceready", function() {
});
};
// screen elements extra js
var infoScreen_elementsExtraJS = function() {
// screen (infoScreen) extra code
};
// screen elements handler
var infoScreen_elementsEvents = function() {
$(document).on("click", "a :input,a a,a fieldset label", function(event) {
event.stopPropagation();
});
};
$(document).off("pagebeforeshow", "#infoScreen").on("pagebeforeshow", "#infoScreen", function(event, ui) {
infoScreen_beforeshow();
});
if (runBeforeShow) {
infoScreen_beforeshow();
} else {
infoScreen_onLoad();
}
};
$(document).off("pagecreate", "#infoScreen").on("pagecreate", "#infoScreen", function(event, ui) {
Apperyio.processSelectMenu($(this));
infoScreen_js();
});
|
"use strict";
// *** LOOPIES *** //
// a conditional runs once if the condition is true, but a loop allows you to run the same block of code based on whether or not a condition remains true
// for (setup, condition, increment) {} keeps looping until the condition is met, and increments as given
// const colors = ['red', 'orange', 'blue', 'yellow', 'green']
// const colorLoop = () => {
// let domString = '';
// for (let i = 0; i < colors.length; i++) {
// domString += `<h1>${colors[i]}</h1>`;
// }
// console.log(domString)
// }
// colorLoop()
// // for in loop works for objects; for of loops could work too
// const colorLoop2 = () => {
// let domString = '';
// let color;
// for (color of colors) {
// domString += `<h1>${color}</h1>`;
// }
// console.log(domString)
// }
// colorLoop2()
|
export { default } from './interceptor'
|
myApp.controller("WorldController",function($scope, $location, $stateParams,$ionicSlideBoxDelegate,$ionicModal,$ionicScrollDelegate,$timeout) {
$scope.playJulio = function(){
console.log("pressed julio");
};
$scope.callSlide = function(theIndex){
console.log("WORLD pressed slide"+theIndex);
$ionicSlideBoxDelegate.$getByHandle('WorldSwipe').slide(theIndex);
};
$scope.parallax=function(eventData) {
var yTilt = Math.round((-eventData.beta + 90) * (40 / 180) - 40);
var xTilt = Math.round(-eventData.gamma * (40 / 180) - 20);
if (xTilt > 0) {
xTilt = -xTilt;
} else if (xTilt < -40) {
xTilt = -(xTilt + 80);
}
var backgroundPositionVal = xTilt + 'px ' + yTilt + 'px';
console.log("defaultorientaitonevent WORLD "+xTilt+" "+yTilt);
console.log("defaultorientaitonevent WORLD "+xTilt+" "+yTilt);
$('.leftCorner').stop();
$('.leftCorner').animate({
'background-position-x': xTilt + 'px',
'background-position-y': yTilt + 'px'
}, 10);
$('.rightcone').stop();
$('.rightcone').animate({
'background-position-x': xTilt + 'px',
'background-position-y': yTilt + 'px'
}, 10);
}
$scope.slideChanged = function(index) {
console.log("world slide changed!"+index);
$ionicScrollDelegate.scrollTop(true);
var slide = document.getElementsByClassName("slider");
var alt = 800;
switch (index) {
case 1:
alt = 768;
break;
case 2:
alt = 571+265;
break;
case 3:
alt = 768;
break;
case 4:
alt = 680;
break;
default:
alt=800;
break;
}
//angular.element(document.getElementsByClassName("slider")).height(alt);
//angular.element(document.getElementsByClassName("scroll")).height(alt);
//angular.element(document.getElementsByClassName("slider-slides")).height(alt);
angular.element(document.getElementsByClassName("slider")).css("height",alt+"px");
angular.element(document.getElementsByClassName("scroll")).css("height",alt+"px");
angular.element(document.getElementsByClassName("slider-slides")).css("height",alt+"px");
//console.log("WORLD slide changed!" + index + " height:" + angular.element(document.getElementsByClassName("slider")).height());
/*$timeout( function() {
$ionicScrollDelegate.resize();
}, 50);*/
};
$scope.$on('$ionicView.afterLeave', function () {
console.log("World afterLeave");
//window.removeEventListener('deviceorientation', $scope.parallax, true);
TweenLite.to(document.getElementById('worldconeleft'), 0, {opacity:0});
TweenLite.to(document.getElementById('worldconeright'), 0, {opacity:0});
});
$scope.$on('$ionicView.afterEnter', function () {
TweenLite.to(document.getElementById('worldconeleft'), 0.3, {delay:0.3,css:{transform:"translateX(0px)"},ease:Sine.easeInOut});
TweenLite.to(document.getElementById('worldconeright'), 0.3, {delay:0.3,css:{transform:"translateX(0px)"},ease:Sine.easeInOut});
//window.addEventListener('deviceorientation', $scope.parallax , false);
TweenLite.to(document.getElementById('worldmenu'), 0.3, {opacity:1,ease:Sine.easeInOut}).delay(0.3);
});
$scope.$on('$ionicView.beforeEnter', function () {
TweenLite.to(document.getElementById('worldmenu'), 0, {opacity:0});
var video=document.getElementById('videoPOP');
TweenLite.to(video, 0, {css:{transform:"translateX(1024px)"}});
console.log("beforeEnter KPMGcontroller");
TweenLite.to(document.getElementById('worldconeleft'), 0, {css:{transform:"translateX(-272px)"},ease:Sine.easeInOut,opacity:1});
TweenLite.to(document.getElementById('worldconeright'), 0, {css:{transform:"translateX(93px)"},ease:Sine.easeInOut,opacity:1});
});
$scope.playVideo = function(theVid) {
console.log("playvideo");
var vid = document.getElementById("myVideoPlayer");
$scope.videoSrc=theVid;
var video=document.getElementById('videoPOP');
//TweenLite.to(vid, 2, {backgroundColor:"#ff0000", left:"0px", ease:Power2.easeInOut});
TweenLite.to(video, 0.5, {css:{transform:"translateX(0px)"}});
}
$scope.videoClose = function() {
console.log("closing video");
var vid = document.getElementById("myVideoPlayer");
vid.pause();
var video=document.getElementById('videoPOP');
TweenLite.to(video, 0.5, {css:{transform:"translateX(1024px)"},ease:Sine.easeInOut});
}
});
|
// Generated by CoffeeScript 1.3.3
/*
slideBaseClient-plugin-alone.js
------------------------------------------------
author: [Takeharu Oshida](http://about.me/takeharu.oshida)
version: 0.1
licence: [MIT](http://opensource.org/licenses/mit-license.php)
*/(function(){var e;e=new sbClient.Model.Plugin({name:"alone",element:"<div id='#alone' class='pluginOption'>\n <input type='checkbox' name='alone' value='enable'>Leave me alone\n</div>",initialScript:function(){return $('[name="alone"]').bind("change",function(){var e;return e=this,_.each(sbClient.pushMethods,function(t,n){return sbClient.pushMethods[n]=$(e).attr("checked")!=="checked"})})}})}).call(this);
|
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('param_type').del()
.then(function () {
// Inserts seed entries
return knex('param_type').insert([
{id: 1, name: 'Grant价格', desc:'((stage_count-free_count)-(stage_count-free_count)/discount_unit)*price_per_stage'}
]);
});
};
|
const router = require('express').Router();
const commentController = require('../../controllers/admin/comment');
const { isAuthenticated, isAdmin } = require('../../middleware/authenticated');
router.all('/*', isAuthenticated, isAdmin,(req, res, next) => {
next();
});
router.get("/",commentController.getComments);
router.post("/approve-comment", commentController.updateApproveComment);
router.delete("/:id", commentController.deleteComment);
router.post("/:id", commentController.postComment);
module.exports = router;
|
// Valider med et RegExp, at en tekststreng kun indeholder nogle positive heltal, adskilt med komma.
let regex = /^([1-9]\d*,)*[1-9]\d*$/;
let string1 = 'test';
let string2 = '0';
let string3 = '1,2,3,4,50';
let string4 = '-1';
let string5 = '7';
let string6 = 'daw7,6';
console.log(regex.test(string1));
console.log(regex.test(string2));
console.log(regex.test(string3));
console.log(regex.test(string4));
console.log(regex.test(string5));
console.log(regex.test(string6));
|
$(document).ready(function(){
document.querySelector('.welcome').style.display = "block";
});
let origBoard,
huPlayer = '',
aiPlayer = '',
level = "",
yourScore = 0,
aiScore = 0;
const winCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[6, 4, 2],
],
cells = document.querySelectorAll('.cell'),
XBtn = document.getElementById('X'),
OBtn = document.getElementById('O'),
easyBtn = document.getElementById('easy'),
mediumBtn = document.getElementById('medium'),
hardBtn = document.getElementById('hard'),
startBtn = document.getElementById('startBtn'),
settingsBtn = document.getElementById('settings'),
levelName = document.getElementById('levelName');
XBtn.addEventListener('click', function(){
huPlayer = 'X';
aiPlayer = 'O';
document.querySelector('.turnMessage').style.display = 'block';
});
OBtn.addEventListener('click', function(){
huPlayer = 'O';
aiPlayer = 'X';
document.querySelector('.turnMessage').style.display = 'block';
});
easyBtn.addEventListener('click', function(){
level = "easy";
levelName.innerText = " "+ "Easy";
});
mediumBtn.addEventListener('click', function(){
level = "medium";
levelName.innerText = " " + "Medium";
});
hardBtn.addEventListener('click', function(){
level = "hard";
levelName.innerText = " " + "Hard";
});
startBtn.addEventListener('click', function(){
document.querySelector('.welcome').style.display = "none";
startGame();
});
settingsBtn.addEventListener('click', function(){
document.querySelector('.endGame').style.display = 'none';
document.querySelector('.welcome').style.display = "block";
document.getElementById('aiScore').innerText= 0;
document.getElementById('yourScore').innerText= 0;
});
function startGame(){
document.querySelector('.endGame').style.display = 'none';
document.querySelector('.turnMessage').style.display = "none";
origBoard = Array.from(Array(9).keys());
for (let i = 0; i < cells.length; i++){
cells[i].innerText = '';
cells[i].style.removeProperty('background-color');
cells[i].addEventListener('click', turnClick, false);
}
};
function turnClick(square){
if(typeof origBoard[square.target.id] == 'number'){
turn(square.target.id, huPlayer);
if(!checkWin(origBoard, huPlayer) && !checkTie())
if(level === "easy"){
turn(easy(), aiPlayer);
} else if (level === "medium"){
turn(medium(), aiPlayer);
} else{
turn(hard(), aiPlayer);
}
}
};
function turn(squareId, player){
origBoard[squareId] = player;
document.getElementById(squareId).innerText = player;
let gameWon = checkWin(origBoard, player);
if (gameWon) gameOver(gameWon);
};
function checkWin (board, player){
let plays = board.reduce ((a, e, i) =>
(e === player) ? a.concat(i) : a, []);
let gameWon = null;
for (let [index, win] of winCombos.entries()) {
if (win.every(elem => plays.indexOf(elem)> -1)){
gameWon = {index: index, player: player};
break;
}
}
return gameWon;
};
function gameOver(gameWon){
for (let index of winCombos[gameWon.index]){
document.getElementById(index).style.backgroundColor =
gameWon.player == huPlayer ? "#0c6ea3" : "#849974";
}
for (let i = 0; i < cells.length; i++){
cells[i].removeEventListener('click', turnClick, false);
}
declareWinner(gameWon.player === huPlayer ? 'You win!' : 'You lose.');
};
function declareWinner(who){
document.querySelector('.endGame').style.display = 'block';
document.querySelector('.endGameText').innerText = who;
if(who === "You win!"){
yourScore +=1;
document.getElementById('yourScore').innerText = yourScore;
}else if(who === "You lose."){
aiScore +=1;
document.getElementById('aiScore').innerText = aiScore;
}
};
function emptySquares(){
return origBoard.filter( s => typeof s == 'number');
};
function easy(){
return emptySquares()[0]; // get the first empty square
};
function medium(){
return minimaxMed(origBoard, aiPlayer).index;
};
function hard(){
return minimaxHard(origBoard, aiPlayer).index;
};
function checkTie(){
if (emptySquares().length == 0){
for (let i = 0; i < cells.length; i++){
cells[i].style.backgroundColor = '#E3BAB3';
cells[i].removeEventListener('click', turnClick, false);
}
declareWinner('Tie Game!');
return true;
}
return false;
};
function minimaxMed(newBoard, player){
let availSpots = emptySquares();
if(checkWin(newBoard, player)){
return {score:-10};
}else if (checkWin(newBoard, aiPlayer)){
return {score:10};
}else if (availSpots.length === 0){
return {score: 0};
}
let moves = [];
for (let i = 0; i <availSpots.length; i++){
let move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;
if(player == aiPlayer){
let result = minimaxMed(newBoard, huPlayer);
move.score = result.score;
} else {
let result = minimaxMed(newBoard, aiPlayer);
move.score = result.score;
}
newBoard[availSpots[i]] = move.index;
moves.push(move);
}
let bestMove;
if(player === aiPlayer){
let bestScore = -10000;
for ( let i = 0; i < moves.length; i++){
if(moves[i].score > bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
let bestScore = 10000;
for (let i = 0; i < moves.length; i++){
if(moves[i].score < bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}
function minimaxHard(newBoard, player) {
var availSpots = emptySquares();
if (checkWin(newBoard, huPlayer)) {
return {score: -10};
} else if (checkWin(newBoard, aiPlayer)) {
return {score: 10};
} else if (availSpots.length === 0) {
return {score: 0};
}
var moves = [];
for (var i = 0; i < availSpots.length; i++) {
var move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;
if (player == aiPlayer) {
var result = minimaxHard(newBoard, huPlayer);
move.score = result.score;
} else {
var result = minimaxHard(newBoard, aiPlayer);
move.score = result.score;
}
newBoard[availSpots[i]] = move.index;
moves.push(move);
}
var bestMove;
if(player === aiPlayer) {
var bestScore = -10000;
for(var i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 10000;
for(var i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}
|
import React, { Component, useState ,useContext, useReducer} from 'react'
const Context = React.createContext();
const { Provider } = Context;
function FruitAdd(props) {
const context = useContext(Context);
const {fruits,dispatch}=context;
const [fname, setPname] = useState('');
const onAddFruit = e => {
if (e.key == 'Enter') {
// setFruits([...fruits, fname])
dispatch({type:"add",newF:fname});
setPname("");
}
}
return (
<div>
<input type="text" value={fname} onChange={e => setPname(e.target.value)} onKeyDown={onAddFruit} />
</div>
)
}
function FruitList({ fruits, setFruit }) {
return (<ul>
{fruits.map((item, index) => <li key={index} onClick={() => { setFruit(item) }}>{item}</li>)}
</ul>
);
}
function FruitReducer(state,action){
switch (action.type){
case "init":return ""
case "add":return [...state,action.newF];
default:return state;
}
}
export default function HookTest() {
const [fruit, setFruit] = useState('草莓');
//const [fruits, setFruits] = useState(['草莓', '香蕉']);
const [fruits, dispatch] = useReducer(FruitReducer,['草莓', '香蕉']);
return (
// <>
// <Provider value={{ fruits, setFruits }}>
// <p>
// {fruit === '' ? '请选择喜欢的水果' : `您选择的是${fruit}`}
// </p>
// <FruitAdd />
// <FruitList fruits={fruits} setFruit={setFruit} />
// </Provider>
// </>
<>
<Provider value={{fruits,dispatch}}>
<div>{fruit == '' ? '请选择你喜欢的水果' : `你选择的水果是${fruit}`}</div>
<FruitAdd />
<FruitList fruits={fruits} setFruit={setFruit} />
</Provider>
</>
)
}
|
import React, { Component } from 'react';
import HeaderMain from "./Header";
import {
Grid
} from '@material-ui/core'
class MainLayout extends Component {
render() {
//console.log('render Home')
const { children } = this.props
return (
<div>
<HeaderMain />
<div>
{ children }
</div>
</div>
);
}
}
export default MainLayout
|
import React from 'react'
import ReactEcharts from 'echarts-for-react'
const DepositTrend = () => {
const onChartReady = (echart) => {
console.log('echart is ready', echart)
}
const onChartLegendselectchanged = (param, echart) => {
console.log(param, echart)
}
const onChartClick = (param, echart) => {
console.log(param, echart)
}
const getOtion = () => {
const option = {
backgroundColor:'#ffffff',
title: {
x:'15px',
y:'10px',
text: '存款趋势',
},
legend: {
data:['存款','取款'],
right:'18px',
top:'32px'
},
tooltip: {
trigger: 'axis'
},
grid: {
top:'70px',
left: '4%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis : [
{
type : 'category',
boundaryGap : false,
data : ['4-24','4-25','4-26','4-27','4-28','4-29','4-30']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'存款',
type:'line',
hoverAnimation:true,
areaStyle: {normal:{color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: 'rgba(22,110,183,.8)' // 0% 处的颜色
}, {
offset: 1, color: 'rgba(255,255,255,.3)' // 100% 处的颜色
}],
globalCoord: false // 缺省为 false
}}},
itemStyle:{
normal:{
color:'#166eb7',
borderColor:'#166eb7'
}
},
data:[120, 220, 101, 110, 90, 230, 55],
},
{
name:'取款',
type:'line',
areaStyle: {normal:{color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: 'rgba(1,154,98,.8)' // 0% 处的颜色
}, {
offset: 1, color: 'rgba(255,255,255,.3)' // 100% 处的颜色
}],
globalCoord: false // 缺省为 false
}}},
itemStyle:{
normal:{
color:'#019a62',
borderColor:'#019a62'
}
},
data:[100, 182, 191, 234, 100, 330, 310]
}
]
};
return option
}
let onEvents = {
click: onChartClick,
legendselectchanged: onChartLegendselectchanged,
}
let code = 'let onEvents = {\n' +
" 'click': onChartClick,\n" +
" 'legendselectchanged': onChartLegendselectchanged\n" +
'}\n\n' +
'<ReactEcharts \n' +
' option={getOtion()} \n' +
' style={{height: 300}} \n' +
' onChartReady={onChartReady} \n' +
' onEvents={onEvents} />'
return (
<div className="examples">
<div className="parent" style={{position:'relative'}}>
{/* <label> Chart With event <strong> onEvents </strong>: (Click the chart, and watch the console)</label>*/}
<div style={{position:'absolute',top:'10px',right:'20px',zIndex:'2'}}>单位 万元</div>
<ReactEcharts
option={getOtion()}
style={{ height: 300 }}
onChartReady={onChartReady}
/>
</div>
</div>
)
}
export default DepositTrend
|
jQuery(document).ready(function($) {
var scrollLink = $('.scroll');
//Smooth scrolling
scrollLink.click(function(e){
e.preventDefault();
$('body, html').animate({
scrollTop: $(this.hash).offset().top - 70
}, 500)
})
//Menu scroll active class
$(window).scroll(function(){
var scrollbarLocation = $(this).scrollTop();
scrollLink.each(function(){
var sectionOffset = $(this.hash).offset().top;
if (sectionOffset - 75 <= scrollbarLocation ) {
$(this).parent().addClass('active');
$(this).parent().siblings().removeClass('active')
}
})
})
});
|
(function () {
'use strict';
angular
.module('StationCreator')
.directive('actionSelector', ActionSelector);
ActionSelector.$inject = [
'$log', '$translate'
];
function ActionSelector(
$log, $translate
) {
return {
restrict: 'E',
transclude: true,
replace: true,
template: (
'<md-input-container>' +
'<md-select ' +
'ng-model="ctrl.selectionTemp" ' +
'placeholder="{{ name | translate }}"' +
'>' +
'<md-optgroup>' +
'<label>{{ name | translate }}</label>' +
'<md-option ng-value="opt" ng-repeat="opt in opts">' +
'{{ opt | translate }}' +
'</md-option>' +
'</md-optgroup>' +
'</md-select>' +
'<md-input-container ng-if="ctrl.selectionAttrNeeded">' +
'<input type="text" ' +
'ng-model="ctrl.selectionAttr" ' +
'ng-change="ctrl.selectionChange()" ' +
'/>' +
'</md-input-container>' +
'</md-input-container>'
),
scope: {
opts: '=',
selection: '=',
name: '@'
},
link: function ($scope, $element, $attr, ctrl) {
ctrl.selectionTemp = $scope.selection || '';
if ( ctrl.selectionTemp.split(':').length > 1 ) {
ctrl.selectionAttr = ctrl.selectionTemp.split(':')[1];
ctrl.selectionTemp = ctrl.selectionTemp.split(':')[0] + ':';
}
$scope.$watch('ctrl.selectionTemp', function (selection) {
if ( selection && selection.split(':').length > 1 ) {
ctrl.selectionAttrNeeded = true;
$scope.selection = ctrl.selectionTemp + ctrl.selectionAttr;
} else {
ctrl.selectionAttrNeeded = false;
$scope.selection = selection;
}
});
$scope.$watch('ctrl.selectionAttr', function (selectionAttr) {
if (selectionAttr) {
$scope.selection = ctrl.selectionTemp + selectionAttr;
}
});
},
controller: ActionSelectorController,
controllerAs: 'ctrl'
};
function ActionSelectorController ($scope, $element, $attrs) {
var ctrl = this;
// $log.info('ActionSelectorController');
// ...
}
}
})();
|
const { Command } = require("discord.js-commando");
const { MessageEmbed } = require("discord.js");
const { oneLine } = require("common-tags");
const moment = require("moment-timezone");
module.exports = class PollCommand extends Command {
constructor(client) {
super(client, {
name: "poll",
group: "polls",
memberName: "poll",
description: "Creates a poll with up to 10 choices.",
examples: [
'poll "What\'s your favourite food?" "Hot Dogs,Pizza,Burgers,Fruits,Veggies" 10'
],
args: [
{
key: "question",
prompt: "What is the poll question?",
type: "string",
validate: question => {
if (question.length < 101 && question.length > 11) return true;
return "Polling questions must be between 10 and 100 characters in length.";
}
},
{
key: "options",
prompt: "What options do you want for the poll? (surround with quotes, separate by comma)",
type: "string",
validate: options => {
var optionsList = options.split(",");
if (optionsList.length > 1) return true;
return "Polling options must be greater than one.";
}
},
{
key: "runtime",
prompt: "How long should the poll last? (1 to 60 minutes)",
type: "integer",
default: 5,
validate: runtime => {
if (runtime >= 1 && runtime <= 60) return true;
return "Polling time must be between 1 and 60.";
}
}
]
});
}
async run(msg, { question, options, runtime }) {
var emojiList = [
"1⃣",
"2⃣",
"3⃣",
"4⃣",
"5⃣",
"6⃣",
"7⃣",
"8⃣",
"9⃣",
"🔟"
];
var optionsList = options.split(",");
var optionsText = "";
for (var i = 0; i < optionsList.length; i++) {
optionsText += emojiList[i] + " " + optionsList[i] + "\n";
}
var embed = new MessageEmbed()
.setTitle(question)
.setDescription(optionsText)
.setAuthor(msg.author.username, msg.author.displayAvatarURL())
.setColor(0xd53c55)
const runtimeTimestamp = moment().tz("America/New_York").add(runtime,'minutes');
if (runtime) {
embed.setFooter(`Poll is open until ${runtimeTimestamp.calendar()} ${runtimeTimestamp.format("zz")}`);
}
//msg.delete(); // Remove the user's command message
let message = await msg.channel.send({ embed }); // Definitely use a 2d array here..
var reactionArray = [];
for (var i = 0; i < optionsList.length; i++) {
reactionArray[i] = await message.react(emojiList[i]);
}
if (runtime) {
setTimeout(async () => {
// Re-fetch the message and get reaction counts
message = await message.channel.messages.fetch(message.id);
var reactionCountsArray = [];
for (var i = 0; i < optionsList.length; i++) {
reactionCountsArray[i] =
message.reactions.get(emojiList[i]).count - 1;
}
// Find winner(s)
var max = -Infinity,
indexMax = [];
for (var i = 0; i < reactionCountsArray.length; ++i)
if (reactionCountsArray[i] > max)
(max = reactionCountsArray[i]), (indexMax = [i]);
else if (reactionCountsArray[i] === max) indexMax.push(i);
// Display winner(s)
console.log(reactionCountsArray); // Debugging votes
var winnersText = "";
if (reactionCountsArray[indexMax[0]] == 0) {
winnersText = "No one voted!";
} else {
for (var i = 0; i < indexMax.length; i++) {
winnersText +=
emojiList[indexMax[i]] +
" " +
optionsList[indexMax[i]] +
" (" +
reactionCountsArray[indexMax[i]] +
" vote(s))\n";
}
}
embed.addField("**Winner(s):**", winnersText);
embed.setFooter(
`The poll is now closed! It lasted ${runtime} minute(s)`
);
embed.setTimestamp();
message.edit("", embed);
}, runtime * 60 * 1000);
}
}
};
|
$(() => {
hentAlleBestillinger();
});
function hentAlleBestillinger() {
$.get("Holberg/hentAlle", (bestillinger) => {
formaterAlleBestillinger(bestillinger);
}
);
}
function formaterAlleBestillinger(bestillinger) {
let ut = "<table class='table table-striped'>" +
"<tr>" +
"<th>Pizza Type</th>" +
"<th>Tykkelse</th>" +
"<th>Antall</th>" +
"<th>Navn</th>" +
"<th>Adresse</th>" +
"<th>Telefon Nr</th>" +
"</tr>";
for (let b of bestillinger) {
// used this i dunno : https://hackernoon.com/accessing-nested-objects-in-javascript-f02f1bd6387f
// Didn't really use this but good to have: https://stackoverflow.com/questions/2098276/nested-json-objects-do-i-have-to-use-arrays-for-everything
const type = b && b.pizza ? b.pizza.type : null;
const navn = b && b.kunde ? b.kunde.navn : null;
const adresse = b && b.kunde ? b.kunde.adresse : null;
const tlfNr = b && b.kunde ? b.kunde.tlfNr : null;
ut += "<tr>" +
// user && user.personalInfo ? user.personalInfo.name : null
// "<td>" + b.pizza.type + "</td>" + // kan man ha nested objects i JSON?
// "<td>" + b && b.pizza ? b.pizza.type : null + "</td>" + // kan man ha nested objects i JSON?
"<td>" + type + "</td>" +
"<td>" + (b.tykk ? "Tykk" : "Tynn") + "</td>" + // tester fordi jeg dum og bruker bool i type erklæring
"<td>" + b.antall + "</td>" +
"<td>" + navn + "</td>" +
"<td>" + adresse + "</td>" +
"<td>" + tlfNr + "</td>" +
"</tr>";
}
ut += "</table>"
$("#inDiv").html(ut);
}
// Woop også bare liftet fra 1700 ukesoppgaver vet ikke om kommer til å brukes
function slettKunde(id) {
const url = "Kunde/Slett?id=" + id;
$.get(url, (OK) => {
if (OK) {
window.location.href = "index.html";
} else {
$("#feil").html("Feil hos server");
}
});
}
|
'use strict';
// client === {clientName, phone, email, companyName, address, city, state, zip,
// projectName, projectAddress, projectContact, projectDescription}
// options === {brochure: bool, credit: bool, contract: bool, capture: dataURL}
// pricing === {grandMonthly, term, totalQuantity,
// collection: [{
// inputFixture: dataArray[index].fixture,
// fixture: el.existingFixture,
// inputDescription: dataArray[index].description,
// description: el.name,
// count: dataArray[index].count,
// hardCostEach: hardCostEach,
// productSubEach: productSubEach,
// installSubEach: installSubEach,
// total: total,
// maintenance: maintenance,
// tax: tax,
// loan: loan,
// monthlyPayment: monthlyPayment
// }]}
// survey === [
// area === {name, fixtures}
// fixture === {name, label, replacements, notes, icon, savedPhotos}
// replacement === {color, count, domIf, elevation, icon, label, name, openQty, showButtons, tallies}
// tally === {tally0, tally1, tally2, tally3}
// ]
module.exports = {
capFirst(str) {
const normal = str.toLowerCase();
const [first, ...rest] = normal.split('');
const cap = first.toUpperCase();
const capArray = [cap, ...rest];
return capArray.join('');
},
saveSurveyData(args) {
const {
className,
client,
orderNum,
pdfFile,
pricing,
repData,
survey,
user
} = args;
const DbClass = Parse.Object.extend(className);
const dbClass = new DbClass();
// TODO:
// make proper acl's so any rep who belongs to a particular company may edit
// any survey from other reps in that company for validation or follow-up purposes
// // lock SentQuotes down so only the rep who created it may read from it in the future
// var surveyACL = new Parse.ACL();
// surveyACL.setReadAccess(user, true);
// surveyACL.setWriteAccess(user, false);
// dbClass.setACL(surveyACL);
const clientKeys = Object.keys(client);
clientKeys.forEach(key => {
const value = (client[key] && typeof client[key] === 'string') ?
client[key].toLowerCase() :
client[key];
dbClass.set(key, value);
});
if (orderNum) {
dbClass.set('orderNum', orderNum);
}
if (pdfFile) {
dbClass.set('pdf', pdfFile);
}
dbClass.set('client', client);
dbClass.set('pricing', pricing);
dbClass.set('monthly', Number(pricing.grandMonthly));
dbClass.set('quantity', pricing.totalQuantity);
dbClass.set('term', Number(pricing.term));
dbClass.set('repCompanyName', repData.get('repCompanyName'));
dbClass.set('rep', user);
dbClass.set('repFirstName', user.get('first').toLowerCase());
dbClass.set('repLastName', user.get('last').toLowerCase());
dbClass.set('survey', survey);
return dbClass.save();
}
};
|
const Offer = require('../model/Offer')
const checkPrivileges = require('../util/offerFunctions').checkPrivileges
module.exports = {
method: 'GET',
path: '/api/offers/{id}',
options: {
handler: async (request, h) => {
return request.pre.offer
},
auth: {
strategy: 'jwt'
},
pre: [
{ method: checkPrivileges, assign: 'offer' }
],
description: 'Retuns offer with provided id',
notes: 'Retuns offer with provided id',
tags: ['api', 'offer']
}
}
|
import {onGet,onPost} from "../main";
// 保存合同
export const saveContract = params=>{
return onPost('deal/saveContract',params)
}
// 查询合同模板详细
export const queryTemplateInfo= params=>{
return onPost('deal/queryDetailed',params)
}
// 查询客户列表
export const queryCustomerList= params=>{
return onPost('customer/queryContractCustomer',params)
}
// 查询客户列表
export const queryContractTemplateList= params=>{
return onPost('deal/queryContractListByType',params)
}
// 查询业主、客户姓名及电话
export const queryPayerInfo= params=>{
return onPost('deal/queryPayerInfo',params)
}
|
/*
* Counting Vowels - Two Ways
* Zack Sargent, April 26th, 2021
* Node v15.5.0
*/
// Imperative Way:
function countVowels1(string) {
let totalVowels = 0;
for (const char of string.toLowerCase()) {
switch (char) {
case "a":
case "e":
case "i":
case "o":
case "u":
totalVowels++;
break;
default:
break;
}
}
return totalVowels;
}
// Functional Way:
countVowels2 = string =>
Array.from(string.toLowerCase())
.filter(char => "aeiou".includes(char))
.length
// Tests:
const testStrings = ["\t", "Hello World!", "Green Table", "eeeeeEe", "eeeeeAe" ];
for (const test of testStrings) {
const v1 = countVowels1(test);
const v2 = countVowels2(test);
console.log(`String: ${test} \tResult: ${v1} \tWorked: ${v1 === v2}`);
}
|
//app.js
const util = require('./utils/util.js')
App({
onLaunch: function () {
// 登录
wx.login({
success: res => {
wx.request({
url: `https://gy.lianwuyun.cn/api//Wxmini/login/${res.code}`,
success: res => {
let self= this;
let wxid = res.data.results.openid
this.globalData.wxid = res.data.results.openid
// 判断是否已经是注册会员
wx.request({
url: `${util.apiPath}/FE/UserBasic/isMember/${wxid}`,
success: res => {
if (res.data.code == 200) {
this.globalData.token = res.data.results.token
this.globalData.phone = res.data.results.phone
this.globalData.memeberInfo = res.data.results
this.globalData.customer_name = res.data.results.customer_name
this.globalData.name = res.data.results.name
wx.setStorageSync("token", res.data.results.token)
}
}
})
}
})
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
// 获取七牛token
wx.request({
url: `${util.apiPath}/FE/UserBasic/qiniuToken`,
method: 'GET',
success: res => {
if (res.data.code == 200) {
this.globalData.qiToken = res.data.results.token
}
}
})
},
globalData: {
userInfo: null,
memeberInfo: {},
name:'',
customer_name:'',
token: '',
qiToken: '',
phone: '',
wxid: '',
}
})
|
import { classNameBindings, classNames } from '@ember-decorators/component';
import BaseCarouselSlide from 'ember-bootstrap/components/base/bs-carousel/slide';
@classNameBindings('left', 'next', 'prev', 'right')
@classNames('item')
export default class CarouselSlide extends BaseCarouselSlide {}
|
import Vue from 'vue'
import vClickOutside from 'v-click-outside'
import '~/assets/argon/vendor/nucleo/css/nucleo.css'
import '~/assets/argon/vendor/font-awesome/css/font-awesome.css'
import '~/assets/argon/scss/argon.scss'
import '~/assets/argon/scss/bvFill.scss'
import '~/assets/argon/scss/my-shit.scss'
import VueLazyload from 'vue-lazyload'
import globalComponents from './globalComponents'
import globalDirectives from './globalDirectives'
Vue.use(globalComponents)
Vue.use(globalDirectives)
Vue.use(VueLazyload)
// Replace custom click-outside directive with vClickOutside (IOS fix)
Vue.use(vClickOutside)
|
function shhh(sentence) {
const low = sentence.toLowerCase();
return `"${low.charAt(0).toUpperCase() + low.slice(1)}", whispered Edabit.`;
}
const result = shhh("tHaT'S Pretty awesOme");
console.log(result);
// Test.assertEquals(shhh("HI THERE!"), "\"Hi there!\", whispered Edabit.")
// Test.assertEquals(shhh("cool cool cool"), "\"Cool cool cool\", whispered Edabit.")
// Test.assertEquals(shhh("YEAH yeah YEAH yeah"), "\"Yeah yeah yeah yeah\", whispered Edabit.")
// Test.assertEquals(shhh(""), "\"\", whispered Edabit.")
|
/**
* Created by leonard on 2016/11/26.
*/
var SuperType = function () {
this.property = true;
};
SuperType.prototype.getSuperValue = function () {
return this.property;
};
// 原型链继承
// 主要问题:
// 1. 假若父类有一个属性是引用类型,则所有的子类公用该属性
// 2. 没办法在不影响所有子类对象示例的情况下,向父类的构造函数传递参数
// 故实践中很少单独使用原型链继承
var SubType1 = function () {
this.subproperty = false;
};
SubType1.prototype = new SuperType();
SubType1.prototype.getSubValue = function () {
return this.subproperty;
};
var child1 = new SubType1();
// 借用构造函数
// 仅解决了不能向父类的构造函数传递参数的问题,但引入了更多的问题
// 故实践中也很少单独使用
var SubType2 = function () {
SuperType.call(this); // 可以在此处向父类构造函数传递参数
this.subproperty = false;
};
var child2 = new SubType2();
// 组合继承
// 融化了原型链继承和利用构造函数继承的方式
// 是 JavaScript 中最常用的继承模式
// 不过也存在一个问题:
// 无论什么情况下,都会调用两次父类构造函数:
// 一次是在创建子类原型的时候,
// 还有一次是在子类构造函数的内部
var SubType3 = function () {
SuperType.call(this);
this.subproperty = false;
};
SubType3.prototype = new SuperType();
SubType3.prototype.getSubValue = function () {
return this.subproperty;
};
var child3 = new SubType3();
child3.getSubValue();
// 寄生组合继承
// 利用寄生的方式,不仅解决了组合继承的小问题,同时还封装了继承的操作
var inherits = function (Parent, Child) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F(); // 创建并指向
Child.prototype.constructor = Child; // 增强
};
var SubType4 = function () {
SuperType.call(this);
this.subproperty = false;
};
inherits(SuperType, SubType4);
SubType4.prototype.getSubValue = function () {
return this.subproperty;
};
var child4 = new SubType4();
|
var census = require('./../census');
var db = require('./../database');
var updateDelay = 1000 * 60 * 60 * 24 * 7;
var updateTimeout;
db.UpdateHistory.findById('vehicle').then(function (record) {
if (record) {
var diff = new Date() - record.lastUpdate;
if (diff > updateDelay) {
refresh();
} else {
updateTimeout = setTimeout(refresh, diff);
}
} else {
refresh();
}
});
module.exports.refresh = refresh;
module.exports.getAllVehicles = function (callback) {
var options = {
include: {
model: db.VehicleFaction,
as: 'faction'
}
};
db.Vehicle.findAll(options)
.then(function (data) {
var jsonData = data.map(function (d) {
var jData = d.toJSON();
jData.factions = jData.faction.map(function (f) { return f.factionId});
delete jData.faction;
return jData;
});
callback(null, jsonData);
})
.catch(function (error) {
callback(error);
});
};
function refresh(callback) {
console.log('Updating vehicle');
if (callback === undefined) {
callback = function (error) {
if (error) {
console.log('Update failed: vehicle, ', error);
}
console.log('Update complete: vehicle');
};
}
census.vehicle.getAllVehicles(function (error, data) {
if (error) {
return callback(error);
}
if (data === undefined) {
return callback(null);
}
var records = data.map(function (d) {
return {
id: d.vehicle_id,
name: d.name ? d.name.en : null,
description: d.description ? d.description.en : null,
cost: d.cost,
costResourceId: d.cost_resource_id,
imageId: d.image_id
};
});
db.Vehicle.bulkCreate(records, {
updateOnDuplicate: ['name', 'description', 'cost', 'costResourceId', 'imageId']
}).then(function () {
census.vehicle.getAllVehicleFactions(function (error, data) {
if (error) {
return callback(error);
}
if (data === undefined) {
return callback(null);
}
var records = data.map(function (d) {
return {
vehicleId: d.vehicle_id,
factionId: d.faction_id
};
});
db.VehicleFaction.bulkCreate(records, {
ignoreDuplicates: true
}).then(function () {
db.UpdateHistory.upsert({
id: 'vehicle',
lastUpdate: new Date()
});
clearTimeout(updateTimeout);
updateTimeout = setTimeout(refresh, updateDelay);
callback();
}).catch(function (error) {
callback(error);
});
});
}).catch(function (error) {
callback(error);
});
});
}
|
var saxn = require('saxn-saxjs');
var sax = require('sax').createStream(false, {lowercasetags:true, trim:true});
var fs = require('fs');
var util = require('util');
var html = '';
var parser = saxn.createSaxnSaxjsParser(sax, {
'table:table': function(tag) {
var tableName = tag.attributes['table:name'];
html += '<h1 id="' + tableName + '">' + tableName + '</h1>\n';
html += '<table>\n';
return {
'table:table-row': function() {
html += '<tr>\n';
return {
'table:table-cell': function(tag) {
html += '<td';
if(tag.attributes['table:number-columns-spanned']) {
html += ' colspan="' + tag.attributes['table:number-columns-spanned'] + '"';
}
if(tag.attributes['table:number-rows-spanned']) {
html += ' rowspan="' + tag.attributes['table:number-rows-spanned'] + '"';
}
html += '>';
return {
'text:a': function(tag) {
var href = tag.attributes['xlink:href'].replace(/\..*/, '');
html += '<a href="' + href + '">';
return {
$text: function(text) {
html += text;
},
$end: function() { // text:a
html += '</a>';
}
};
},
$text: function(text) {
html += text;
},
$end: function() { // table:table-cell
html += '</td>\n';
}
};
},
$end: function() { // table:table-row
html += '</tr>\n';
}
};
},
$end: function() { // table:table
html += '</table> <!-- ' + tableName + ' -->\n';
}
};
}
});
var readStream = fs.createReadStream(process.argv[2], { encoding: 'utf8' });
readStream.on('data', function(data) { parser(data); });
readStream.on('end', function() {
process.stdout.write(html);
});
|
import React from 'react';
import Card from '../../components/Card/Card';
import { Container, Grid } from '@material-ui/core';
import './Home.css';
function Home() {
return (
<div className="home">
<h1>Home Page</h1>
<Container fixed>
<Grid container spacing={1}>
<Grid container item xs={12} spacing={3}>
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
<Card />
</Grid>
</Grid>
</Container>
</div>
)
}
export default Home
|
// 对象的字面量增强
const age = 15
const obj = {
name: 'andy',
// age: 15,
age, // 同名直接放入
// foo: function () {
// console.log(this);
// },
// 等价于
foo(){
console.log(this);
},
// 计算属性-表达式当成属性 [ 表达式 ] ,这个属性是动态生成的
[Math.random()]: '123123'
}
|
var a = 2;
var b = 1;
document.write("a is "+a);
document.write("<br>"); document.write("<br>");
document.write("b is "+b);
document.write("<br>"); document.write("<br>");
var result = --a - --b + ++b + b--;
// --a is 1 and a is 1
// --b is 0 and b is 0
// ++b is 1 and b is 1
// b-- is 1 and b is 0
document.write("result is "+result);
|
import { Data } from '../../CharacterDataStructure'
import { valueRender, skillDurationRender, targetRender, changeRender } from '../../Descriptions.js';
Data.descriptionGenerators.ApplyDamageAbsorbingShieldTarget = (character, skill, effect) => {
return `grant target damage-absorbing shield for ${valueRender(character, effect)} hp ${skillDurationRender(character, effect)} `
}
Data.descriptionGenerators.DamageAbsorbingShield = (character, condition, effect) => {
return `${Math.round(effect.params.value)} hp`
}
Data.descriptionGenerators.ApplyPercentDamageReduction = (character, skill, effect) => {
return `reduce damage taken by target by ${Math.abs(effect.params.value * 100)}% ${skillDurationRender(character, effect)}`
}
Data.descriptionGenerators.ApplyBasicCondition = (character, skill, effect) => {
return `${changeRender(effect.params.value)} ${targetRender(skill, false)}'s ${effect.params.attribute} by ${Math.abs(effect.params.value * 100)}% ${skillDurationRender(character, effect)}`
}
Data.descriptionGenerators.ApplyLifesteal = (character, skill, effect) => {
return `grants ${targetRender(skill)} ${effect.params.value * 100}% lifesteal ${skillDurationRender(character, effect)}`
}
Data.descriptionGenerators.ApplyStun = (character, skill, effect) => {
return `stuns ${targetRender(skill)} ${skillDurationRender(character, effect)}`
}
|
import React, { useEffect } from "react";
import classes from "./projectsList.module.css";
import Layout from "../../../Layout/Layout";
import {
Box,
Button,
Checkbox,
FormControlLabel,
FormGroup,
Grid,
Paper,
Slider,
TextField,
} from "@material-ui/core";
import { Autocomplete } from "@material-ui/lab";
import CheckboxesTags from "./CheckboxesTags";
import AdvertisementBaner from "./AdvertisementBaner";
import { scrollHandler } from "../../../helper/general";
function valuetext(value) {
return `${value}°C`;
}
const ProjectsList = () => {
const top100Films = [{ title: "فوری" }, { title: "برجسته" }];
const marks = [
{
value: 0,
label: "1,000,000",
},
{
value: 100,
label: "15,000,000",
},
];
const [value, setValue] = React.useState([20, 37]);
const handleChange = (event, newValue) => {
setValue(newValue);
};
useEffect(() => {
scrollHandler(0, 0);
}, []);
return (
<Layout>
<Paper elevation={3} className={classes.urlPage}>
پارک جاب/ پروژه ها/ طراحی و گرافیک
</Paper>
<Grid item xs={12} className={classes.formBoxFilter}>
<form className={classes.formPrici} noValidate autoComplete="off">
<div className={classes.search}>
{" "}
<TextField
id="outlined-basic"
label="جستوجو در عنوان و توضیحات"
placeholder="یک کلمه بنویسید"
variant="outlined"
className={classes.searchBox}
/>
</div>
<div style={{ width: "30%" }}>
{" "}
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => (
<TextField
{...params}
label="نوع پروژه"
variant="outlined"
style={{
backgroundColor: "#fff",
width: "100%",
}}
/>
)}
/>
</div>
<div style={{ width: "30%" }}>
{" "}
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => (
<TextField
{...params}
label="نمایش بر اساس"
variant="outlined"
style={{
backgroundColor: "#fff",
width: "100%",
}}
/>
)}
/>
</div>
</form>
<Grid container style={{ margin: "1rem" }}>
<Grid item md={3} xs={12}>
<label>قیمت</label>
<Box sx={{ width: "80%", marginTop: "1.5rem" }}>
<Slider
getAriaLabel={() => "Temperature range"}
value={value}
onChange={handleChange}
valueLabelDisplay="auto"
getAriaValueText={valuetext}
marks={marks}
/>
</Box>
</Grid>
<Grid item md={2} xs={12}>
<label>مهارت های شما</label>
<FormGroup style={{ marginTop: "1.5rem" }}>
<FormControlLabel
control={<Checkbox />}
label="مهارت های رزومه من"
/>
</FormGroup>
</Grid>
<Grid item md={4} xs={12}>
<CheckboxesTags />
</Grid>
<Grid
className={classes.btnBox}
item
md={3}
xs={12}
style={{ display: "flex" }}
justifyContent="center"
alignItems="center"
>
<Button variant="contained" color="primary">
اعمال فیلترها
</Button>
<Button
style={{
backgroundColor: "#CFCFD1",
fontWeight: "bold",
borderStyle: "none",
marginRight: "1rem",
}}
variant="outlined"
>
پاک کردن فیلترها
</Button>
</Grid>
</Grid>
</Grid>
{[1, 2, 3, 4, 5, 6].map((item) => (
<Paper className={classes.cardBaner} key={item}>
<AdvertisementBaner />
{item}
</Paper>
))}
</Layout>
);
};
export default ProjectsList;
|
define(['jquery', 'QDP'], function ($, QDP) {
"use strict";
// EVENT-ON:layout.started
QDP.on("layout.started", function () {
console.info("注册->系统运行后自动注册 - plugins-actions - 功能扩展插件:city、chart");
});
var plugins = [];
// EVENT-ON:generator.option.rendered
QDP.on('generator.option.rendered', function (eventArgs) {
// 释放之前使用过的plugin
$.each(plugins, function (index, plugin) {
if (plugin && typeof plugin.destory === 'function') {
plugin.destory();
}
});
plugins = [];
var options = eventArgs.args;
if (!options || !options.plugins) {
return;
}
$.each(options.plugins, function (index, plugin) {
let pluginName;
if (typeof plugin === 'string') {
pluginName = plugin;
} else {
pluginName = plugin.name;
}
switch (pluginName) {
case 'city':
if (selectedValue == -1) {
if (!options.type || options.type != 2) {
selectedValue = 2;
} else {
selectedValue = 3;
}
}
cityPlugin(options, plugin);
break;
case 'chart':
chartPlugin(options, plugin);
break;
}
});
});
// 图片上传和展示接口,APP自动升级接口
var _chartPlugin;
var resizeContainer = function () {
var windowHeight = $(window).outerHeight();
var breadcrumbHeight = $(".content-header").outerHeight();
// 20为.ajax-content的上填充合,padding-top:20px
$('#echarts-chart').height(windowHeight - breadcrumbHeight - 20);
}
var chartPlugin = function (options, pluginOptions) {
plugins.push({
'destory': function () {
$(window).off('resize', resizeContainer);
if (_chartPlugin && typeof _chartPlugin.destroy === 'function') {
_chartPlugin.destroy();
}
},
});
var btnChart = $("<button/>").addClass("btn-chart");
btnChart.html(' <i class="fa fa-line-chart"></i> 图表 ');
btnChart.on("click", function () {
QDP.form.openview({
map: true,
title: '图表',
url: QDP.config.chartpage,
callback: function () {
QDP.form.render();
$(window).on('resize', resizeContainer);
resizeContainer();
require(['plugins/plugins-chart'], plugin => {
_chartPlugin = plugin;
plugin.init('echarts-chart', pluginOptions.chart);
});
}
});
});
$('.view-action').prepend(btnChart);
}
var selectedValue = -1;
// var selectedValue = 3;
var cityPlugin = function (options, pluginOption) {
var select = $("<select/>");
select.width(200);
select.append($("<option/>").val(1).text('按省份查询'));
select.append($("<option/>").val(2).text('按地市查询'));
if (!pluginOption.type || pluginOption.type != 2) {
select.append($("<option/>").val(3).text('按区县查询'));
}
$('.content-toolbar').prepend(select);
select.select2();
select.val(selectedValue).trigger('change');
select.on('change', function () {
var value = $(this).val();
if (!value || value == selectedValue) {
return;
}
selectedValue = value;
var city_code = options.columns.find(function (p) { return p.name == 'city_code'; });
if (!city_code) city_code = {};
var county_code = options.columns.find(function (p) { return p.name == 'county_code'; });
if (!county_code) county_code = {};
switch (value) {
case "1":
city_code.display = false;
city_code.filter = false;
county_code.display = false;
county_code.filter = false;
break;
case "2":
city_code.display = true;
city_code.filter = true;
county_code.display = false;
county_code.filter = false;
break;
case "3":
city_code.display = true;
city_code.filter = true;
county_code.display = true;
county_code.filter = true;
break;
default:
return;
}
$('.ajax-content').load(QDP.config.listpage, function () {
$('.datetimepicker').remove();
$('.content-toolbar').empty();
QDP.generator.build(options);
});
});
}
});
|
(function(){
var componentBox = document.querySelectorAll('.component-container');
for (var i = 0; i < componentBox.length; i++) {
var codeBox = document.getElementById(componentBox[i].dataset.include);
var componentHTML = componentBox[i].innerHTML;
codeBox.innerHTML = componentHTML.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
})();
|
/*
* ProGade API
* Copyright 2014, Hans-Peter Wandura (ProGade)
* Last changes of this file: Aug 12 2014
*/
var PG_FOLDERUPDATE_ACTION_STATUS_STOPPED = 0;
var PG_FOLDERUPDATE_ACTION_STATUS_RUNNING = 1;
var PG_FOLDERUPDATE_NETWORK_REQUESTTYPE = 'PGFolderUpdateRequest';
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_FolderUpdate()
{
// Declarations...
this.iFolderIndex = 0;
this.iUpdatePercent = 0;
this.iFoldersSuccessed = 0;
this.iFoldersFailed = 0;
this.iFilesSuccessed = 0;
this.iFilesFailed = 0;
this.sProgressBarID = '';
this.sUpdateHistoryContainerID = '';
this.sCurrentActionContainerID = '';
this.fOnUpdateRefreshFunction = null;
this.fOnUpdateDoneFunction = null;
this.sUpdateScriptPath = 'update_folders.php';
this.asFolders = new Array();
this.iUpdateActionStatus = PG_FOLDERUPDATE_ACTION_STATUS_STOPPED;
// Construct...
this.setID({'sID': 'PGFolderUpdate'});
this.initClassBasics();
// Methods...
/*
@start method
@param asFolders [type]string[][/type]
[en]...[/en]
@param sUpdateScriptPath [type]string[/type]
[en]...[/en]
@param sProgressBarID [type]string[/type]
[en]...[/en]
*/
this.init = function(_asFolders, _sUpdateScriptPath, _sProgressBarID)
{
if (typeof(_sUpdateScriptPath) == 'undefined') {var _sUpdateScriptPath = null;}
if (typeof(_sProgressBarID) == 'undefined') {var _sProgressBarID = null;}
_sUpdateScriptPath = this.getRealParameter({'oParameters': _asFolders, 'sName': 'sUpdateScriptPath', 'xParameter': _sUpdateScriptPath});
_sProgressBarID = this.getRealParameter({'oParameters': _asFolders, 'sName': 'sProgressBarID', 'xParameter': _sProgressBarID});
_asFolders = this.getRealParameter({'oParameters': _asFolders, 'sName': 'asFolders', 'xParameter': _asFolders});
if (_sUpdateScriptPath != null) {this.sUpdateScriptPath = _sUpdateScriptPath;}
this.iUpdatePercent = 0;
this.iFolderIndex = 0;
this.iFoldersSuccessed = 0;
this.iFoldersFailed = 0;
this.iFilesSuccessed = 0;
this.iFilesFailed = 0;
this.asFolders = _asFolders;
this.sProgressBarID = _sProgressBarID;
}
/* @end method */
/*
@start method
@param sPath [needed][type]string[/type]
[en]...[/en]
*/
this.setUpdateScriptPath = function(_sPath)
{
_sPath = this.getRealParameter({'oParameters': _sPath, 'sName': 'sPath', 'xParameter': _sPath});
oPGFolderUpdate.sUpdateScriptPath = _sPath;
}
/* @end method */
/*
@start method
@param sContainerID [needed][type]string[/type]
[en]...[/en]
*/
this.setCurrentActionContainerID = function(_sContainerID)
{
_sContainerID = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sContainerID', 'xParameter': _sContainerID});
this.sCurrentActionContainerID = _sContainerID;
}
/* @end method */
/*
@start method
@return sContainerID [type]string[/type]
[en]...[/en]
*/
this.getCurrentActionContainerID = function() {return this.sCurrentActionContainerID;}
/* @end method */
/*
@start method
@param sContainerID [needed][type]string[/type]
[en]...[/en]
*/
this.setUpdateHistoryContainerID = function(_sContainerID)
{
_sContainerID = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sContainerID', 'xParameter': _sContainerID});
this.sUpdateHistoryContainerID = _sContainerID;
}
/* @end method */
/*
@start method
@return sContainerID [type]string[/type]
[en]...[/en]
*/
this.getUpdateHistoryContainerID = function() {return this.sUpdateHistoryContainerID;}
/* @end method */
/* @start method */
this.send = function()
{
var _sParameters = 'sRequestType='+PG_FOLDERUPDATE_NETWORK_REQUESTTYPE;
_sParameters += '&sDir='+oPGFolderUpdate.asFolders[oPGFolderUpdate.iFolderIndex-1];
this.networkSend({'sParameters': _sParameters, 'fOnResponse': oPGFolderUpdate.onResponse, 'sResponseFile': this.sUpdateScriptPath});
}
/* @end method */
/* @start method */
this.run = function()
{
if (oPGFolderUpdate.iUpdateActionStatus != PG_FOLDERUPDATE_ACTION_STATUS_RUNNING)
{
oPGFolderUpdate.iUpdateActionStatus = PG_FOLDERUPDATE_ACTION_STATUS_RUNNING;
oPGFolderUpdate.nextFolder();
}
}
/* @end method */
/* @start method */
this.stop = function() {oPGFolderUpdate.iUpdateActionStatus = PG_FOLDERUPDATE_ACTION_STATUS_STOPPED;}
/* @end method */
/*
@start method
@return iPercent [type]int[/type]
[en]...[/en]
*/
this.getPercent = function() {return oPGFolderUpdate.getPercentStatus();}
/* @end method */
/*
@start method
@return iPercent [type]int[/type]
[en]...[/en]
*/
this.getPercentStatus = function() {return oPGFolderUpdate.iUpdatePercent;}
/* @end method */
/*
@start method
@return iUpdateActionStatus [type]int[/type]
[en]...[/en]
*/
this.getActionStatus = function() {return oPGFolderUpdate.iUpdateActionStatus;}
/* @end method */
/*
@start method
@param oParameters [needed][type]object[/type]
[en]...[/en]
*/
this.onResponse = function(_oParameters)
{
if (_oParameters['PG_RequestType'] == PG_FOLDERUPDATE_NETWORK_REQUESTTYPE)
{
oPGFolderUpdate.iFoldersSuccessed += parseInt(_oParameters['PG_FolderUpdate_Successed']);
oPGFolderUpdate.iFoldersFailed += parseInt(_oParameters['PG_FolderUpdate_Failed']);
oPGFolderUpdate.iFilesSuccessed += parseInt(_oParameters['PG_FilesUpdate_Successed']);
oPGFolderUpdate.iFilesFailed += parseInt(_oParameters['PG_FilesUpdate_Failed']);
oPGFolderUpdate.nextFolder();
}
}
/* @end method */
/* @start method */
this.nextFolder = function()
{
if (oPGFolderUpdate.asFolders)
{
if (oPGFolderUpdate.iUpdateActionStatus == PG_FOLDERUPDATE_ACTION_STATUS_RUNNING) {oPGFolderUpdate.iFolderIndex++;}
if (oPGFolderUpdate.iFolderIndex <= oPGFolderUpdate.asFolders.length)
{
oPGFolderUpdate.iUpdatePercent = Math.ceil(((oPGFolderUpdate.iFolderIndex)*100) / oPGFolderUpdate.asFolders.length);
if (oPGFolderUpdate.sProgressBarID != '')
{
if (typeof(oPGProgressBar) != 'undefined')
{
oPGProgressBar.setPercent({'sProgressBarID': oPGFolderUpdate.sProgressBarID, 'iPercent': oPGFolderUpdate.iUpdatePercent});
}
}
if (oPGFolderUpdate.iFolderIndex == oPGFolderUpdate.asFolders.length)
{
if (oPGFolderUpdate.sCurrentActionContainerID != '')
{
var _oCurrentActionContainer = oPGFolderUpdate.oDocument.getElementById(oPGFolderUpdate.sCurrentActionContainerID);
if (_oCurrentActionContainer)
{
_oCurrentActionContainer.innerHTML = 'Folders update done';
}
}
if (oPGFolderUpdate.sUpdateHistoryContainerID != '')
{
var _oUpdateHistoryContainer = oPGFolderUpdate.oDocument.getElementById(oPGFolderUpdate.sUpdateHistoryContainerID);
if (_oUpdateHistoryContainer)
{
_oUpdateHistoryContainer.innerHTML += 'Folder "'+oPGFolderUpdate.asFolders[oPGFolderUpdate.iFolderIndex-1]+' done<br />';
// if ((oPGFolderUpdate.iFoldersSuccessed > 0) || (oPGFolderUpdate.iFoldersFailed > 0))
// {
_oUpdateHistoryContainer.innerHTML += '<br /><b>Folders:</b><br />';
_oUpdateHistoryContainer.innerHTML += '<span class="pg_failure">'+oPGFolderUpdate.iFoldersSuccessed+' successed</span><br />';
_oUpdateHistoryContainer.innerHTML += '<span class="warnung">'+oPGFolderUpdate.iFoldersFailed+' failed</span><br />';
// }
// if ((oPGFolderUpdate.iFilesSuccessed > 0) || (oPGFolderUpdate.iFilesFailed > 0))
// {
_oUpdateHistoryContainer.innerHTML += "<br /><b>Files:</b><br />";
_oUpdateHistoryContainer.innerHTML += '<span class="pg_failure">'+oPGFolderUpdate.iFilesSuccessed+' successed</span><br />';
_oUpdateHistoryContainer.innerHTML += '<span class="warnung">'+oPGFolderUpdate.iFilesFailed+' failed</span><br />';
// }
_oUpdateHistoryContainer.innerHTML += '<br /><b>Update done</b><br />';
}
}
if (oPGFolderUpdate.fOnUpdateDoneFunction) {oPGFolderUpdate.fOnUpdateDoneFunction();}
}
else
{
if (oPGFolderUpdate.sCurrentActionContainerID != '')
{
var _oCurrentActionContainer = oPGFolderUpdate.oDocument.getElementById(oPGFolderUpdate.sCurrentActionContainerID);
if (_oCurrentActionContainer)
{
_oCurrentActionContainer.innerHTML = 'Update folder: '+oPGFolderUpdate.asFolders[oPGFolderUpdate.iFolderIndex];
}
}
if (oPGFolderUpdate.sUpdateHistoryContainerID != '')
{
var _oUpdateHistoryContainer = oPGFolderUpdate.oDocument.getElementById(oPGFolderUpdate.sUpdateHistoryContainerID);
if (_oUpdateHistoryContainer)
{
if (oPGFolderUpdate.iFolderIndex > 0) {_oUpdateHistoryContainer.innerHTML += 'Folder "'+oPGFolderUpdate.asFolders[oPGFolderUpdate.iFolderIndex-1]+'" done<br />';}
}
}
if (oPGFolderUpdate.fOnUpdateRefreshFunction) {oPGFolderUpdate.fOnUpdateRefreshFunction();}
if (oPGFolderUpdate.iUpdateActionStatus == PG_FOLDERUPDATE_ACTION_STATUS_RUNNING) {oPGFolderUpdate.send();}
}
}
}
}
/* @end method */
/*
@start method
@param fFunction [needed][type]function[/type]
[en]...[/en]
*/
this.setOnUpdateRefreshFunction = function(_fFunction)
{
_fFunction = this.getRealParameter({'oParameters': _fFunction, 'sName': 'fFunction', 'xParameter': _fFunction});
this.fOnUpdateRefreshFunction = _fFunction;
}
/* @end method */
/*
@start method
@param fFunction [needed][type]function[/type]
[en]...[/en]
*/
this.setOnUpdateDoneFunction = function(_fFunction)
{
_fFunction = this.getRealParameter({'oParameters': _fFunction, 'sName': 'fFunction', 'xParameter': _fFunction});
this.fOnUpdateDoneFunction = _fFunction;
}
/* @end method */
/*
@start method
@param asFolders [needed][type]string[][/type]
[en]...[/en]
@param sUpdateScriptPath [type]string[/type]
[en]...[/en]
@param sFolderUpdateID [type]string[/type]
[en]...[/en]
@param bRunUpdate [type]bool[/type]
[en]...[/en]
@param iFoldersSuccessed [type]int[/type]
[en]...[/en]
@param iFoldersFailed [type]int[/type]
[en]...[/en]
@param iFilesSuccessed [type]int[/type]
[en]...[/en]
@param iFilesFailed [type]int[/type]
[en]...[/en]
*/
this.build = function(_asFolders, _sUpdateScriptPath, _sFolderUpdateID, _bRunUpdate, _iFoldersSuccessed, _iFoldersFailed, _iFilesSuccessed, _iFilesFailed)
{
if (typeof(_sUpdateScriptPath) == 'undefined') {var _sUpdateScriptPath = null;}
if (typeof(_sFolderUpdateID) == 'undefined') {var _sFolderUpdateID = null;}
if (typeof(_bRunUpdate) == 'undefined') {var _bRunUpdate = null;}
if (typeof(_iFoldersSuccessed) == 'undefined') {var _iFoldersSuccessed = null;}
if (typeof(_iFoldersFailed) == 'undefined') {var _iFoldersFailed = null;}
if (typeof(_iFilesSuccessed) == 'undefined') {var _iFilesSuccessed = null;}
if (typeof(_iFilesFailed) == 'undefined') {var _iFilesFailed = null;}
_sUpdateScriptPath = this.getRealParameter({'oParameters': _asFolders, 'sName': 'sUpdateScriptPath', 'xParameter': _sUpdateScriptPath});
_sFolderUpdateID = this.getRealParameter({'oParameters': _asFolders, 'sName': 'sFolderUpdateID', 'xParameter': _sFolderUpdateID});
_bRunUpdate = this.getRealParameter({'oParameters': _asFolders, 'sName': 'bRunUpdate', 'xParameter': _bRunUpdate});
_iFoldersSuccessed = this.getRealParameter({'oParameters': _asFolders, 'sName': 'iFoldersSuccessed', 'xParameter': _iFoldersSuccessed});
_iFoldersFailed = this.getRealParameter({'oParameters': _asFolders, 'sName': 'iFoldersFailed', 'xParameter': _iFoldersFailed});
_iFilesSuccessed = this.getRealParameter({'oParameters': _asFolders, 'sName': 'iFilesSuccessed', 'xParameter': _iFilesSuccessed});
_iFilesFailed = this.getRealParameter({'oParameters': _asFolders, 'sName': 'iFilesFailed', 'xParameter': _iFilesFailed});
_asFolders = this.getRealParameter({'oParameters': _asFolders, 'sName': 'asFolders', 'xParameter': _asFolders});
if (_sUpdateScriptPath == null) {_sUpdateScriptPath = this.sUpdateScriptPath;}
if (_sFolderUpdateID != null) {this.setID({'sID': _sFolderUpdateID});}
if (_bRunUpdate === null) {_bRunUpdate = false;}
if (_iFoldersSuccessed === null) {_iFoldersSuccessed = 0;}
if (_iFoldersFailed === null) {_iFoldersFailed = 0;}
if (_iFilesSuccessed === null) {_iFilesSuccessed = 0;}
if (_iFilesFailed === null) {_iFilesFailed = 0;}
var _sProgressBarID = this.getID()+'ProgressBar';
this.init(_asFolders, _sUpdateScriptPath, _sProgressBarID);
this.iFoldersSuccessed = _iFoldersSuccessed;
this.iFoldersFailed = _iFoldersFailed;
this.iFilesSuccessed = _iFilesSuccessed;
this.iFilesFailed = _iFilesFailed;
if (_bRunUpdate == true) {this.run();}
}
/* @end method */
}
/* @end class */
classPG_FolderUpdate.prototype = new classPG_ClassBasics();
var oPGFolderUpdate = new classPG_FolderUpdate();
|
// For any third party dependencies, like jQuery, place them in the lib folder.
// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.
// Start loading the main app file. Put all of
// your application logic in there.
//Load common code that includes config, then load the app logic for this page.
requirejs(['plugins/domReady','pollify/index'], function (dom,allshim){
requirejs(['./config'], function (common) {
requirejs(['app/home']);
});
});
|
import './serializers'
import './rendering'
import './transforms'
|
// Layouts
import LayoutRestaurante from '../Layouts/layoutRestaurante'
import LayoutSeguridad from '../Layouts/layoutSeguridad'
import LayoutSistema from '../Layouts/layoutSistema'
// Pages
import Login from '../Pages/Login/login';
//Menus Admin Restaurante
import MenuEspecialidades from '../Pages/AdminRestaurante/Menus/Especialidades';
import MainMenuAdminRes from '../Pages/AdminRestaurante/Menus/mainMenuAdminRestaurante'
import MenuListBebidas from '../Pages/AdminRestaurante/Menus/menuListBebidas'
//Forms AdminRestaurante
import InsertBebidaHelada from '../Pages/AdminRestaurante/Forms/AgregarBebidasHeladas';
import InsertLicor from '../Pages/AdminRestaurante/Forms/AgregarLicores';
import InsertGaseosa from '../Pages/AdminRestaurante/Forms/addGaseosas';
import InsertBebidaCaliente from '../Pages/AdminRestaurante/Forms/formBebCalientes';
import InsertVino from '../Pages/AdminRestaurante/Forms/formAddVinos';
import InsertMesa from '../Pages/AdminRestaurante/Forms/formAddMesa';
import InsertPuesto from '../Pages/AdminRestaurante/Forms/FormAddPuestos';
import InsertEspecial from '../Pages/AdminRestaurante/Forms/formAddEspeciales';
import InsertBuffet from '../Pages/AdminRestaurante/Forms/formAddBuffet';
import InsertEmpleado from '../Pages/AdminRestaurante/Forms/formAddEmpleados';
//Listas AdminRestaurante
import ListLicores from '../Pages/AdminRestaurante/Listas/listaLicores'
import ListMesas from '../Pages/AdminRestaurante/Listas/listaMesas'
import ListBebCalientes from '../Pages/AdminRestaurante/Listas/listBebCalientes'
import ListBuffet from '../Pages/AdminRestaurante/Listas/listBuffet'
import ListEmpleados from '../Pages/AdminRestaurante/Listas/listEmpleados'
import ListEspeciales from '../Pages/AdminRestaurante/Listas/listEspeciales'
import ListGaseosas from '../Pages/AdminRestaurante/Listas/listGaseosas'
import ListPuestos from '../Pages/AdminRestaurante/Listas/listPuestos'
import ListVinos from '../Pages/AdminRestaurante/Listas/listVinos'
import ListBebHeladas from '../Pages/AdminRestaurante/Listas/listaBebHeladas'
//Pages Seguridad
//Listas
import ListaUsuario from "../Pages/AdminSeguridad/Listas/ListaUsuarios/ListaUsuarios";
import ListaConsecutivos from "../Pages/AdminSeguridad/Listas/ListaConsecutivos/ListaConsecutivos";
import ListaCajas from "../Pages/AdminSeguridad/Listas/ListaCajas/ListaCajas";
import ListaPaises from "../Pages/AdminSeguridad/Listas/ListaPaises/ListaPaises";
import ListaUnidadesMedida from "../Pages/AdminSeguridad/Listas/ListaUnidadesMedida/ListaUnidadesMedida";
import ListaRoles from "../Pages/AdminSeguridad/Listas/ListaRoles/ListaRoles";
//Formularios de agregar en Admin Seguridad
import AgregarConsecutivos from "../Pages/AdminSeguridad/Forms/AgregarConsecutivos";
import AgregarPaises from "../Pages/AdminSeguridad/Forms/AgregarPaises";
import AgregarRoles from "../Pages/AdminSeguridad/Forms/AgregarRoles";
import AgregarUsuario from "../Pages/AdminSeguridad/Forms/AgregarUsuario";
import AgregarUnidadesMedidas from "../Pages/AdminSeguridad/Forms/AgregarUnidadesMedidas";
import VentanaSeguridad from "../Pages/AdminSeguridad/VentanaSeguridad/VentanaSeguridad";
//Pages AdminSistema
//Menus admin sistema
import VentanaProductos from '../Pages/AdminSistema/Menus/ventanaProductos'
import VentanaProveedores from '../Pages/AdminSistema/Menus/ventanaProveedores'
//Listas de admin sistema
import ListComestibles from '../Pages/AdminSistema/Lista/listComestibles'
import ListaDesechablesEmpaques from '../Pages/AdminSistema/Lista/listDesechablesEmpaques'
import ListEqUtencilios from '../Pages/AdminSistema/Lista/listEquiposUtencilios'
import ListLimpiezaHigiene from '../Pages/AdminSistema/Lista/listLimpiezaHigiene'
import ListMarcas from '../Pages/AdminSistema/Lista/listMarcas'
import ListProveedores from '../Pages/AdminSistema/Lista/ListProveedores'
import ListTecnologia from '../Pages/AdminSistema/Lista/listTecnologia'
//formulario de admin sistema
import AgregarComestibles from '../Pages/AdminSistema/Form/formAddComestibles'
import FormAddDesechablesEmpaques from '../Pages/AdminSistema/Form/formAddDesechablesEmpaques'
import FormAddEquiposUtencilios from '../Pages/AdminSistema/Form/formAddEquiposUtencilios'
import FormAddLimpiezaHigiene from '../Pages/AdminSistema/Form/formAddLimpiezaHigiene'
import FormAddListProveedores from '../Pages/AdminSistema/Form/formAddListProveedores'
import FormAddMarca from '../Pages/AdminSistema/Form/formAddMarca'
import FormAddTecnologia from '../Pages/AdminSistema/Form/formAddTecnologia'
//REPORTES
import reportesLicores from "../Pages/Reportes/Reporte Licores/ReporteLicores";
import reporteSeguridad from "../Pages/Reportes/Reporte Seguridad/ReporteSeguridad";
import reporteSistema from "../Pages/Reportes/Reporte Sistema/ReporteSistema";
import facturacionCliente from "../Pages/FacturacionCliente/FacturacionCliente";
//Apertura y Cierre de caja
import AperturaCaja from '../Pages/cajas/abrirCaja/abrirCaja.js';
import CerrarCajas from '../Pages/cajas/cerrarCaja/cerrarCaja.js';
//Restaurantes AdminRestaurante
import NotteDiFuoco from "../Pages/NotteDiFuoco/NotteDiFuoco";
import PiccolaStella from "../Pages/PiccolaStella/PiccolaStella";
import TurinAnivo from "../Pages/TurinAnivo/TurinAnivo";
import ListClienteMesa from "../Pages/AdminRestaurante/Listas/listClienteMesa";
const routes = [{
path: '/AdminRestaurante',
component: LayoutRestaurante,
exact: false,
routes: [
{
path: "/AdminRestaurante",
component: MainMenuAdminRes,
exact: true
},
{
path: "/AdminRestaurante/Especialidades",
component: MenuEspecialidades,
exact: true,
},
{
path: "/AdminRestaurante/ListEspeciales",
component: ListEspeciales,
exact: true
},
{
path: "/AdminRestaurante/AgregarBebidaHelada",
component: InsertBebidaHelada,
exact: true
},
{
path: "/AdminRestaurante/AgregarLicores",
component: InsertLicor,
exact: true
},
{
path: "/AdminRestaurante/AgregarBebidaGaseosa",
component: InsertGaseosa,
exact: true
},
{
path: "/AdminRestaurante/AgregarBebidaCaliente",
component: InsertBebidaCaliente,
exact: true
},
{
path: "/AdminRestaurante/AgregarVino",
component: InsertVino,
exact: true
},
{
path: "/AdminRestaurante/AgregarMesa",
component: InsertMesa,
exact: true
},
{
path: "/AdminRestaurante/AgregarPuestos",
component: InsertPuesto,
exact: true
},
{
path: "/AdminRestaurante/AgregarEspecialidades",
component: InsertEspecial,
exact: true
},
{
path: "/AdminRestaurante/AgregarBuffet",
component: InsertBuffet,
exact: true
},
{
path: "/AdminRestaurante/Agregarempleado",
component: InsertEmpleado,
exact: true
},
{
path: "/AdminRestaurante/MenuBebidas",
component: MenuListBebidas,
exact: true
},
{
path: "/AdminRestaurante/ListEmpleados",
component: ListEmpleados,
exact: true
},
{
path: "/AdminRestaurante/ListBuffet",
component: ListBuffet,
exact: true
},
{
path: "/AdminRestaurante/ListMesas",
component: ListMesas,
exact: true
},
{
path: "/AdminRestaurante/ListPuestos",
component: ListPuestos,
exact: true
},
{
path: "/AdminRestaurante/ListGaseosas",
component: ListGaseosas,
exact: true
},
{
path: "/AdminRestaurante/ListBebCalientes",
component: ListBebCalientes,
exact: true
},
{
path: "/AdminRestaurante/ListLicores",
component: ListLicores,
exact: true
},
{
path: "/AdminRestaurante/ListVinos",
component: ListVinos,
exact: true
},
{
path: "/AdminRestaurante/ListBebHeladas",
component: ListBebHeladas,
exact: true
},
{
path: "/AdminRestaurante/cerrarCaja",
component: CerrarCajas,
exact: true
},
{
path: "/AdminRestaurante/NotteDiFuoco",
component: NotteDiFuoco,
exact: true
},
{
path: "/AdminRestaurante/PiccolaStella",
component: PiccolaStella,
exact: true
},
{
path: "/AdminRestaurante/TurinAnivo",
component: TurinAnivo,
exact: true
},
{
path: "/AdminRestaurante/ListClienteMesa",
component: ListClienteMesa,
exact: true
}
]
},
{
path: "/abrirCaja",
component: AperturaCaja,
exact: true
},
{
path: '/',
component: Login,
exact: true
},
{
path: "/adminSeguridad",
exact: false,
component: LayoutSeguridad,
routes: [
{
path: "/adminSeguridad",
exact: true,
component: VentanaSeguridad
},
{
path: "/adminSeguridad/listaUsuarios",
exact: true,
component: ListaUsuario
},
{
path: "/adminSeguridad/listaConsecutivos",
exact: true,
component: ListaConsecutivos
},
{
path: "/adminSeguridad/listaCajas",
exact: true,
component: ListaCajas
},
{
path: "/adminSeguridad/listaPaises",
exact: true,
component: ListaPaises
},
{
path: "/adminSeguridad/listaUM",
exact: true,
component: ListaUnidadesMedida
},
{
path: "/adminSeguridad/listaRoles",
exact: true,
component: ListaRoles
},
{
path: "/adminSeguridad/addConsecutivo",
exact: true,
component: AgregarConsecutivos
},
{
path: "/adminSeguridad/addPais",
exact: true,
component: AgregarPaises
},
{
path: "/adminSeguridad/addRol",
exact: true,
component: AgregarRoles
},
{
path: "/adminSeguridad/addUsuario",
exact: true,
component: AgregarUsuario
},
{
path: "/adminSeguridad/addUnidadMedida",
exact: true,
component: AgregarUnidadesMedidas
}
]
},
{
path: '/AdminSistema',
component: LayoutSistema,
exact: false,
routes: [
{
path: "/AdminSistema",
component: VentanaProveedores,
exact: true
},
{
path: "/AdminSistema/MenuProductos",
component: VentanaProductos,
exact: true
},
{
path: "/AdminSistema/ListMarcas",
component: ListMarcas,
exact: true
},
{
path: "/AdminSistema/ListProveedores",
component: ListProveedores,
exact: true
},
{
path: "/AdminSistema/AgregarMarcas",
component: FormAddMarca,
exact: true
},
{
path: "/AdminSistema/AgregarProveedores",
component: FormAddListProveedores,
exact: true
},
{
path: "/AdminSistema/ListComestibles",
component: ListComestibles,
exact: true
},
{
path: "/AdminSistema/ListDesEmpaques",
component: ListaDesechablesEmpaques,
exact: true
},
{
path: "/AdminSistema/ListLimpHigiene",
component: ListLimpiezaHigiene,
exact: true
},
{
path: "/AdminSistema/ListTecnologia",
component: ListTecnologia,
exact: true
},
{
path: "/AdminSistema/ListEqUtencilios",
component: ListEqUtencilios,
exact: true
},
{
path: "/AdminSistema/FormComestibles",
component: AgregarComestibles,
exact: true
},
{
path: "/AdminSistema/FormDesEmpaques",
component: FormAddDesechablesEmpaques,
exact: true
},
{
path: "/AdminSistema/FormLimpHigiene",
component: FormAddLimpiezaHigiene,
exact: true
},
{
path: "/AdminSistema/FormTecnologia",
component: FormAddTecnologia,
exact: true
},
{
path: "/AdminSistema/FormEqutencilios",
component: FormAddEquiposUtencilios,
exact: true
}
]
},
{
path: "/reportesLicores",
component: LayoutSistema,
exact: false,
routes: [
{
path: "/reportesLicores",
component: reportesLicores,
exact: true
}
]
},
{
path: "/reporteSeguridad",
component: LayoutSeguridad,
exact: false,
routes: [
{
path: "/reporteSeguridad",
component: reporteSeguridad,
exact: true
}
]
},
{
path: "/reporteSistema",
component: LayoutSistema,
exact: false,
rouets: [
{
path: "/reporteSistema",
exact: true,
component: reporteSistema
}
]
},
{
path: "/facturacion",
component: facturacionCliente,
exact: false
}
];
export default routes;
|
/* eslint-disable no-undef */
import React, { Component } from 'react';
import './Map.css';
import _ from 'lodash';
class Map extends Component {
constructor(props) {
super(props);
// Key is referrer restricted to
// https://worldviewer.github.io/react-map-location/
this.APIkey = 'AIzaSyDwtT6k0iFxxUDIg0CdaHtS6U_eegLV5DE';
this.props = props;
this.initMap = this.initMap.bind(this);
this.initList = this.initList.bind(this);
this.getCoordinates = this.getCoordinates.bind(this);
this.panHandler = this.panHandler.bind(this);
}
componentWillMount() {
// Connect the initMap() function within this class to the global
// window context, so Google Maps can invoke it
window.initMap = this.initMap;
// Asynchronously load the Google Maps script, passing in the
// callback reference
this.loadJS('https://maps.googleapis.com/maps/api/js?key=' + this.APIkey + '&callback=initMap&libraries=geometry')
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && !this.props.active) {
this.getCoordinates(nextProps.active)
.then(coordinates => {
this.googleMap.panTo(coordinates);
this.props.unsetNearestPlaceHandler();
})
.catch((err) => {
console.log(err);
})
}
}
initMap() {
this.googleMap = new google.maps.Map(this.refs.map, {
center: {
lat: this.props.latitude,
lng: this.props.longitude
},
zoom: this.props.zoom
});
this.geocoder = new google.maps.Geocoder();
let panHandler = _.debounce(e => {
this.panHandler();
}, 400);
this.googleMap.addListener('center_changed', panHandler);
this.initList();
}
panHandler() {
let distances = [];
this.props.unsetExactPlaceHandler();
let promiseArray = this.props.places.map(place => {
return new Promise((resolve, reject) => {
resolve(distances.push({
name: place.name,
distance: google.maps.geometry.spherical.computeDistanceBetween(this.googleMap.getCenter(), place.coordinates)
}));
});
});
Promise.all(promiseArray)
.then(() => {
distances.sort((a, b) => a.distance - b.distance);
this.props.setNearestPlaceHandler(distances[0].name);
})
.catch((err) => {
console.log(err);
});
}
initList() {
let places = [];
let promiseArray = this.props.places.map(place => {
return new Promise((resolve, reject) => {
this.geocoder.geocode({ address: place.name }, (results, status) => {
if (status === google.maps.GeocoderStatus.OK) {
resolve(places.push({
name: place.name,
coordinates: results[0].geometry.location
}));
} else {
reject('Geocode unsuccessful during initialization of places.');
}
});
});
});
Promise.all(promiseArray)
.then(() => {
this.props.setPlaceCoordinatesHandler(places);
});
}
getCoordinates(address) {
return new Promise((resolve, reject) => {
this.geocoder.geocode({ address }, (results, status) => {
if (status === google.maps.GeocoderStatus.OK) {
if (this.marker) {
this.marker.setMap(null);
}
this.marker = new google.maps.Marker({
map: this.googleMap,
position: results[0].geometry.location
});
resolve(results[0].geometry.location);
} else {
reject('Geocode unsuccessful during distance calculation.');
}
});
})
}
loadJS(src) {
let ref = window.document.getElementsByTagName("script")[0];
let script = window.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}
render() {
return (
<div className="Map" id="map" ref="map"></div>
);
}
}
export default Map;
|
import { combineReducers } from "redux";
import authReducer from "./authReducer";
import errorReducer from "./errorReducer";
import profileReducer from "./profileReducer";
import dogReducer from "./dogReducer";
export default combineReducers({
auth: authReducer,
errors: errorReducer,
profile: profileReducer,
dog: dogReducer
});
|
import * as actionTypes from '../actions/actionTypes';
const initialState = {
orderReady: false,
orders : []
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.PURCHASE_INIT:
return {
...state, //Just in case I add some more fields.
orderReady: true
};
case actionTypes.PURCHASE_FIN:
return {
...state, //Just in case I add some more fields.
orderReady: false
};
case actionTypes.FETCH_ORDERS_START:
return {
...state,
//Set some flag to true.
};
case actionTypes.FETCH_ORDERS_SUCCESS:
return {
...state,
orders : action.orders
};
case actionTypes.FETCH_ORDERS_FAILED:
return {
...state,
//Set some error flag.
};
default: return state;
}
}
export default reducer;
|
var app = angular.module('shortURLApp',[]);
app.controller('shortAppCtrl', function($scope){
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.